forked from septemhill/dpos-pbft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
block.go
91 lines (75 loc) · 1.82 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"bytes"
"crypto/sha256"
"encoding/gob"
"encoding/hex"
"time"
)
//Block B
type Block struct {
Version int64
Height int64
Timestamp int64
Forger string
PrevBlockHash string
Hash string
MerkleRoot string
Transactions []Transaction
}
//NewGenesisBlock g
func NewGenesisBlock() *Block {
b := &Block{
Version: 1,
Height: 0,
Timestamp: time.Now().Unix(),
Forger: "Septem",
PrevBlockHash: "0000000000000000000000000000000000000000000000000000000000000000",
MerkleRoot: "0000000000000000000000000000000000000000000000000000000000000000",
Transactions: make([]Transaction, 0),
}
b.CalculateHash()
return b
}
//GetHash return hash of block
func (b *Block) GetHash() string {
return b.Hash
}
//GetPrevBlockHash return previous block hash of block
func (b *Block) GetPrevBlockHash() string {
return b.PrevBlockHash
}
//GetHeight return height of block
func (b *Block) GetHeight() int64 {
return b.Height
}
//GetTransactions return transactions of block
func (b *Block) GetTransactions() []Transaction {
return b.Transactions
}
//GetTimestamp return timestamp of block
func (b *Block) GetTimestamp() int64 {
return b.Timestamp
}
//GetForger return forger of block
func (b *Block) GetForger() string {
return b.Forger
}
//CalculateMerkleRoot calculte block merkle root hash value
func (b *Block) CalculateMerkleRoot() {
}
//CalculateHash calculate block hash value
func (b *Block) CalculateHash() {
buff := bytes.NewBuffer(nil)
enc := gob.NewEncoder(buff)
b.CalculateMerkleRoot()
enc.Encode(b.Version)
enc.Encode(b.Height)
enc.Encode(b.Timestamp)
enc.Encode(b.Forger)
enc.Encode(b.PrevBlockHash)
enc.Encode(b.MerkleRoot)
enc.Encode(b.Transactions)
hash := sha256.Sum256(buff.Bytes())
b.Hash = hex.EncodeToString(hash[:])
}