This repository has been archived by the owner on Feb 20, 2023. It is now read-only.
/
block.go
257 lines (189 loc) · 4.58 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package blockchain
import (
"fmt"
"time"
"github.com/vmihailenco/msgpack"
)
type BlockHeader struct {
Height int64
Hash []byte
PrecHash []byte
MerkelHash []byte
Target []byte
Timestamp int64
Nonce int64
}
type Block struct {
Header BlockHeader
Transactions []Transaction
}
func NewBlock(bc *Blockchain) *Block {
block := &Block{
Header: BlockHeader{
Height: bc.headers[len(bc.headers)-1].Height + 1,
PrecHash: bc.headers[len(bc.headers)-1].Hash,
Timestamp: time.Now().Unix(),
Target: bc.lastTarget,
Hash: []byte{},
},
Transactions: bc.pendingTransactions,
}
cbTx := NewCoinBaseTransaction(bc)
block.Transactions = append([]Transaction{*cbTx}, block.Transactions...)
block.processMerkelTree()
return block
}
var originalBlock *Block
func OriginBlock(bc *Blockchain) *Block {
if originalBlock == nil {
originalBlock = &Block{
Header: BlockHeader{
Height: 0,
PrecHash: []byte{},
Timestamp: 0,
Target: bc.lastTarget,
Hash: []byte{},
},
Transactions: []Transaction{},
}
hash, _ := msgpack.Marshal(&originalBlock.Header)
newHash := NewHash(hash)
originalBlock.Header.Hash = newHash
}
return originalBlock
}
func (this *Block) Mine(stats *Stats, mustStop *bool) {
tmp, _ := msgpack.Marshal(this.Header)
newHash := NewHash(tmp)
for !*mustStop && compare(newHash, this.Header.Target) >= 0 {
this.Header.Nonce++
this.Header.Timestamp = time.Now().Unix()
var err error
tmp, err = msgpack.Marshal(&this.Header)
if err != nil {
fmt.Println("ERROR", err)
return
}
newHash = NewHash(tmp)
stats.lastHashes++
}
this.Header.Hash = newHash
}
func (this *Block) VerifyOld(bc *Blockchain) bool {
storedHeader := bc.headers[this.Header.Height]
if !this.verifyCommon(bc) {
return false
}
if compare(this.Header.Hash, storedHeader.Hash) != 0 {
bc.logger.Error("Block verify old: Hashes does not match with stored one")
return false
}
return true
}
func (this *Block) verifyCommon(bc *Blockchain) bool {
hash := this.Header.Hash
this.Header.Hash = []byte{}
tmp, _ := msgpack.Marshal(&this.Header)
newHash := NewHash(tmp)
this.Header.Hash = hash
if compare(newHash, hash) != 0 {
bc.logger.Error("Block verify: Hashes does not match")
return false
}
if len(this.Transactions[0].Ins) > 0 || len(this.Transactions[0].Outs) != 1 {
bc.logger.Error("Block verify: Bad coinbase transaction")
return false
}
for _, tx := range this.Transactions {
if !tx.Verify(bc) {
bc.logger.Error("Block verify: Bad transaction")
return false
}
}
if !this.verifyMerkelTree() {
bc.logger.Error("Block verify: Bad Merkel hash")
return false
}
return true
}
func (this *Block) Verify(bc *Blockchain) bool {
if this.Header.Height != bc.headers[len(bc.headers)-1].Height+1 {
bc.logger.Error("Block verify: Bad height")
return false
}
if !this.verifyCommon(bc) {
return false
}
if compare(bc.headers[len(bc.headers)-1].Hash, this.Header.PrecHash) != 0 {
bc.logger.Error("Block verify: Bad previous hash")
return false
}
if compare(bc.lastTarget, this.Header.Target) != 0 {
bc.logger.Error("Block verify: Bad target")
return false
}
if HasDoubleSpend(this.Transactions) {
bc.logger.Error("Block verify: Double spend")
return false
}
return true
}
func (this *Block) verifyMerkelTree() bool {
tree := [][]byte{}
for _, tx := range this.Transactions {
tree = append(tree, tx.Stamp.Hash)
}
for len(tree) > 1 {
tree = processOneMerkelTreeRow(tree)
}
return compare(this.Header.MerkelHash, tree[0]) == 0
}
func (this *Block) processMerkelTree() {
tree := [][]byte{}
for _, tx := range this.Transactions {
tree = append(tree, tx.Stamp.Hash)
}
for len(tree) > 1 {
tree = processOneMerkelTreeRow(tree)
}
this.Header.MerkelHash = tree[0]
}
func processOneMerkelTreeRow(row [][]byte) [][]byte {
res := [][]byte{}
for i := 0; i < len(row); {
addr1 := row[i]
addr2 := addr1
if i+1 < len(row) {
addr2 = row[i+1]
}
res = append(res, NewHash(append(addr1, addr2...)))
i += 2
}
return res
}
func HasDoubleSpend(transactions []Transaction) bool {
seen := make(map[string]int)
for _, tx := range transactions {
for _, in := range tx.Ins {
v, hasSeen := seen[string(in.PrevHash)]
if hasSeen && v == in.PrevIdx {
return true
}
seen[string(in.PrevHash)] = in.PrevIdx
}
}
return false
}
func compare(b1, b2 []byte) int {
if len(b1) > len(b2) {
return 1
} else if len(b2) > len(b1) {
return -1
}
for i, v := range b1 {
if v-b2[i] != 0 {
return int(v) - int(b2[i])
}
}
return 0
}