-
Notifications
You must be signed in to change notification settings - Fork 31
/
block.go
69 lines (51 loc) · 1.36 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
package main
import (
"bytes"
"encoding/binary"
)
type Block struct {
VersionNumber uint32
PreviousHash []byte
Hash []byte
MerkleRoot []byte
Timestamp uint32
Bits uint32
Nonce uint32
TxCount int
Txs []*Transaction
Size int64
}
func (blk *Block) Serialize() []byte {
var out bytes.Buffer
uint32buffer := make([]byte, 4)
binary.LittleEndian.PutUint32(uint32buffer, blk.VersionNumber)
out.Write(uint32buffer)
out.Write(blk.PreviousHash)
out.Write(blk.MerkleRoot)
binary.LittleEndian.PutUint32(uint32buffer, blk.Timestamp)
out.Write(uint32buffer)
binary.LittleEndian.PutUint32(uint32buffer, blk.Bits)
out.Write(uint32buffer)
binary.LittleEndian.PutUint32(uint32buffer, blk.Nonce)
out.Write(uint32buffer)
return out.Bytes()
}
func CreateBlock(params *GenesisParams, tx *Transaction) *Block {
blk := new(Block)
blk.MerkleRoot = tx.Hash
blk.VersionNumber = 1
blk.PreviousHash = make([]byte, 32)
blk.MerkleRoot = tx.Hash
blk.Timestamp = params.Timestamp
blk.Nonce = params.Nonce
blk.Bits = params.Bits
blk.Txs = append(blk.Txs, tx)
return blk
}
func (blk *Block) ComputeHash() {
blk.Hash = ComputeSha256(ComputeSha256(blk.Serialize()))
}
// https://en.bitcoin.it/wiki/Block_hashing_algorithm
func ComputeBlockHash(blk *Block) []byte {
return ComputeSha256(ComputeSha256(blk.Serialize()))
}