-
Notifications
You must be signed in to change notification settings - Fork 0
/
Block.go
76 lines (60 loc) · 1.61 KB
/
Block.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package main
import (
"bytes"
"crypto/sha256"
"encoding/gob"
"log"
"time"
)
type Block struct {
Timestamp int64
PrevBlockHash []byte
// Data []byte
Transactions []*Transaction
Hash []byte
Nonce int
}
// setHash is to hash the headers of the block which are the all the information in a block
// 把整个区块都加密了: 所以第一步先把时间变成byte格式, 然后连接所有信息组成header
// func (b *Block) setHash() {
// timestamp := []byte(strconv.FormatInt(b.Timestamp, 10)) //convert int to byte
// headers := bytes.Join([][]byte{b.PrevBlockHash, b.Data, timestamp}, []byte{})
// hash := sha256.Sum256(headers)
// b.Hash = hash[:] // [:] bytes to slice: [32]byte -> []byte
// }
func NewBlock(prevBlockHash []byte, Txs []*Transaction) *Block {
block := &Block{time.Now().Unix(), prevBlockHash, Txs, []byte{}, 0}
// block.setHash()
pow := NewProofOfWork(block)
nonce, hash := pow.Run()
block.Hash = hash[:]
block.Nonce = nonce
return block
}
func (b *Block) serialize() []byte {
var result bytes.Buffer
encoder := gob.NewEncoder(&result)
err := encoder.Encode(b)
if err != nil {
log.Panic(err)
}
return result.Bytes()
}
func DeserializeBlock(d []byte) *Block {
var block Block
decoder := gob.NewDecoder(bytes.NewReader(d))
err := decoder.Decode(&block)
if err != nil {
log.Panic(err)
}
return &block
}
func (b *Block) HashTransactions() []byte {
var txHashes [][]byte
var txHash [32]byte
for _, tx := range b.Transactions {
txHashes = append(txHashes, tx.ID)
}
txHash = sha256.Sum256(bytes.Join(txHashes, []byte{}))
return txHash[:]
}