-
Notifications
You must be signed in to change notification settings - Fork 0
/
block.go
71 lines (55 loc) · 1.24 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
package blockchain
import (
"bytes"
"crypto/sha256"
"encoding/gob"
"time"
)
func NewBlock(transactions []*Transaction, prevBlockHash []byte) *Block {
block := &Block{
Timestamp: time.Now().UnixNano(),
Transactions: transactions,
PrevBlockHash: prevBlockHash,
Hash: []byte{},
Nonce: 0,
}
pow := NewProofOfWork(block)
nonce, hash := pow.Run()
block.Hash = hash[:]
block.Nonce = nonce
return block
}
type Block struct {
Timestamp int64
Transactions []*Transaction
PrevBlockHash []byte
Hash []byte
Nonce int
}
func (block *Block) Serialize() ([]byte, error) {
var result bytes.Buffer
encoder := gob.NewEncoder(&result)
if err := encoder.Encode(block); err != nil {
return nil, err
}
return result.Bytes(), nil
}
func (block *Block) HashTransactions() []byte {
var (
txHashes [][]byte
txHash [32]byte
)
for _, tx := range block.Transactions {
txHashes = append(txHashes, tx.Id)
}
txHash = sha256.Sum256(bytes.Join(txHashes, []byte{}))
return txHash[:]
}
func DeserializeBlock(raw []byte) (*Block, error) {
var block Block
decoder := gob.NewDecoder(bytes.NewReader(raw))
if err := decoder.Decode(&block); err != nil {
return nil, err
}
return &block, nil
}