-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblock.go
More file actions
76 lines (67 loc) · 1.62 KB
/
Copy pathblock.go
File metadata and controls
76 lines (67 loc) · 1.62 KB
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/binary"
"encoding/gob"
"time"
)
// Block def block struct
type Block struct {
Version uint64
PrevHash []byte
MerkelRoot []byte
TimeStamp uint64
Difficulty uint64
Nonce uint64
// following data is not in real blockchain
Hash []byte
Transactions []*Transaction
}
func Uint64ToByte(num uint64) []byte {
var buffer bytes.Buffer
err1 := binary.Write(&buffer, binary.BigEndian, num)
HandleErr("Uint64ToByte binary.Write:\n", err1)
return buffer.Bytes()
}
func NewBlock(txs []*Transaction, prevBlockHash []byte) *Block {
block := Block{
Version: 00,
PrevHash: prevBlockHash,
MerkelRoot: []byte{},
TimeStamp: uint64(time.Now().Unix()),
Difficulty: 0,
Nonce: 0,
Hash: []byte{},
Transactions: txs,
}
block.MerkelRoot = block.MakeMerkelRoot()
pow := NewProofOfWork(&block)
// select nonce, keep hashing
hash, nonce := pow.Run()
block.Hash = hash
block.Nonce = nonce
return &block
}
func (block *Block) Serialize() []byte {
var buffer bytes.Buffer
encoder := gob.NewEncoder(&buffer)
err1 := encoder.Encode(&block)
HandleErr("Serialize encoder.Encode:\n", err1)
return buffer.Bytes()
}
func Deserialize(data []byte) Block {
decoder := gob.NewDecoder(bytes.NewReader(data))
var block Block
err1 := decoder.Decode(&block)
HandleErr("Deserialize decoder.Decode:\n", err1)
return block
}
func (block *Block) MakeMerkelRoot() []byte {
var info []byte
for _, tx := range block.Transactions {
info = append(info, tx.TXID...) // Splicing transaction hash
}
hash := sha256.Sum256(info)
return hash[:]
}