This repository has been archived by the owner on Apr 9, 2024. It is now read-only.
/
block.go
68 lines (57 loc) · 1.4 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
package core
import (
"bytes"
"encoding/gob"
"time"
)
type Block struct {
Timestamp int64 `json:"timestamp"`
Nonce uint64 `json:"nonce"`
PrevBlockHash []byte `json:"prev_block_hash"`
Hash []byte `json:"hash"`
Transactions []*Transaction `json:"transactions"`
}
func (b Block) Serialize() ([]byte, error) {
var buff bytes.Buffer
encoder := gob.NewEncoder(&buff)
err := encoder.Encode(b)
return buff.Bytes(), err
}
func DeserializeBlock(encData []byte) (Block, error) {
block := Block{}
decoder := gob.NewDecoder(bytes.NewReader(encData))
err := decoder.Decode(&block)
return block, err
}
func (b *Block) HashTXs() ([]byte, error) {
var txs [][]byte
for _, tx := range b.Transactions {
serialData, err := tx.Serialize()
if err != nil {
return nil, err
}
txs = append(txs, serialData)
}
tree := NewMerkleTree(txs)
return tree.Root.Data, nil
}
func NewBlock(txs []*Transaction, prevBlockHash []byte) (Block, error) {
block := Block{
Timestamp: time.Now().Unix(),
Transactions: txs,
PrevBlockHash: prevBlockHash,
Nonce: 0,
Hash: []byte{},
}
pow := NewPoW(&block)
hash, nonce, err := pow.Run()
if err != nil {
return Block{}, err
}
block.Nonce = nonce
block.Hash = hash
return block, nil
}
func NewGenesisBlock(cbtx Transaction) (Block, error) {
return NewBlock([]*Transaction{&cbtx}, []byte{})
}