forked from laser/go-merkle-tree
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmerkletree.go
330 lines (267 loc) · 7.3 KB
/
merkletree.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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
package merkletree
import (
"bytes"
"errors"
"fmt"
"math"
)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// TYPES
////////
type Tree struct {
Root Node
Rows [][]Node
HashFunc func(isLeaf bool, block []byte) []byte
}
type Node interface {
GetHash() []byte
ToString(HashToStrFunc, int) string
}
type Branch struct {
Hash []byte
Left Node
Right Node
}
type Leaf struct {
Hash []byte
Data []byte
}
type ProofPart struct {
IsRight bool
Hash []byte
}
const (
ProofPartSerializeSize = 1 + 32
)
func (pf *ProofPart) Serialize() ([]byte, error) {
data := []byte{}
if pf.IsRight {
data = append(data, 1)
} else {
data = append(data, 0)
}
if len(pf.Hash) != 32 {
return nil, fmt.Errorf(
"ProofPart.Serailize: Hash size %d should equal %d", pf.Hash, 32)
}
data = append(data, pf.Hash...)
return data, nil
}
func (pf *ProofPart) Deserialize(data []byte) error {
if len(data) != ProofPartSerializeSize {
return fmt.Errorf(
"ProofPart.Deserialize: data length %d should equal %d",
len(data), ProofPartSerializeSize)
}
if data[0] == 0 {
pf.IsRight = false
} else {
pf.IsRight = true
}
pf.Hash = data[1:]
return nil
}
type Proof struct {
HashFunc func(isLeaf bool, xs []byte) []byte
// PathToRoot is a path from the LeafHash up to the root of the Merkle
// tree. Note that the LeafHash and the Root hash are not included in
// the this list. Rather, the list is everything in between these two
// items. To put it visually, below is how to think about a Merkle proof
// as it is described by this library:
//
// RootHash
// / \
// ... PathToRoot ...
// / \
// ... LeafHash ...
//
PathToRoot []*ProofPart
// LeafHash is the hash of an element at the lowest level of
// the Merkle tree. It is the hash of the element we want to
// prove actually exists in the tree.
LeafHash []byte
}
type HashToStrFunc func([]byte) string
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// CONSTRUCTORS
///////////////
func NewLeafFromHash(hash []byte) *Leaf {
return &Leaf{
Hash: hash,
Data: nil,
}
}
func NewLeaf(sumFunc func(bool, []byte) []byte, block []byte) *Leaf {
return &Leaf{
Hash: sumFunc(true, block),
Data: block,
}
}
func NewBranch(sumFunc func(bool, []byte) []byte, left Node, right Node) *Branch {
return &Branch{
Hash: sumFunc(false, append(left.GetHash(), right.GetHash()...)),
Left: left,
Right: right,
}
}
func NewTreeFromHashes(providedSumFunc func([]byte) []byte, hashes [][]byte) *Tree {
levels := int(math.Ceil(math.Log2(float64(len(hashes)+len(hashes)%2))) + 1)
sumFunc := func(isLeaf bool, xs []byte) []byte {
return providedSumFunc(xs)
}
// represents each row in the tree, where rows[0] is the base and rows[len(rows)-1] is the root
rows := make([][]Node, levels)
// build our base of leaves
for i := 0; i < len(hashes); i++ {
rows[0] = append(rows[0], NewLeafFromHash(hashes[i]))
}
// build upwards until we hit the root
for i := 1; i < levels; i++ {
prev := rows[i-1]
// each iteration creates a branch from a pair of values originating from the previous level
for j := 0; j < len(prev); j = j + 2 {
var l, r Node
// if we don't have enough to make a pair, duplicate the left
if j+1 >= len(prev) {
l = prev[j]
r = l
} else {
l = prev[j]
r = prev[j+1]
}
b := NewBranch(sumFunc, l, r)
rows[i] = append(rows[i], b)
}
}
return &Tree{
HashFunc: sumFunc,
Rows: rows,
Root: rows[len(rows)-1][0],
}
}
func NewTree(providedSumFunc func([]byte) []byte, blocks [][]byte) *Tree {
levels := int(math.Ceil(math.Log2(float64(len(blocks)+len(blocks)%2))) + 1)
// Note: The below code has been commented out and replaced because it causes
// the library to be incompatible with Bitcoin. This code is intended to make
// the library more resistant to pre-image attacks, but this is a very minor
// concern that Bitcoin doesn't worry about.
/*
sumFunc := func(isLeaf bool, xs []byte) []byte {
if isLeaf {
return providedSumFunc(append([]byte{0x00}, xs...))
}
return providedSumFunc(append([]byte{0x01}, xs...))
}
*/
sumFunc := func(isLeaf bool, xs []byte) []byte {
return providedSumFunc(xs)
}
// represents each row in the tree, where rows[0] is the base and rows[len(rows)-1] is the root
rows := make([][]Node, levels)
// build our base of leaves
for i := 0; i < len(blocks); i++ {
rows[0] = append(rows[0], NewLeaf(sumFunc, blocks[i]))
}
// build upwards until we hit the root
for i := 1; i < levels; i++ {
prev := rows[i-1]
// each iteration creates a branch from a pair of values originating from the previous level
for j := 0; j < len(prev); j = j + 2 {
var l, r Node
// if we don't have enough to make a pair, duplicate the left
if j+1 >= len(prev) {
l = prev[j]
r = l
} else {
l = prev[j]
r = prev[j+1]
}
b := NewBranch(sumFunc, l, r)
rows[i] = append(rows[i], b)
}
}
return &Tree{
HashFunc: sumFunc,
Rows: rows,
Root: rows[len(rows)-1][0],
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// METHODS
//////////
func (b *Branch) GetHash() []byte {
return b.Hash
}
func (l *Leaf) GetHash() []byte {
return l.Hash
}
func VerifyProof(leafHash []byte, pathToTarget []*ProofPart, target []byte) bool {
return VerifyProofCustomHash(leafHash, pathToTarget, target, Sha256DoubleHash)
}
func VerifyProofCustomHash(leafHash []byte, pathToTarget []*ProofPart, target []byte, hashFunc func([]byte) []byte) bool {
z := leafHash
for i := 0; i < len(pathToTarget); i++ {
if pathToTarget[i].IsRight {
z = hashFunc(append(z, pathToTarget[i].Hash...))
} else {
z = hashFunc(append(pathToTarget[i].Hash, z...))
}
}
return bytes.Equal(target, z)
}
func (t *Tree) getLeafIdxByChecksum(Hash []byte) int {
index := -1
for i := 0; i < len(t.Rows[0]); i++ {
if bytes.Equal(Hash, t.Rows[0][i].GetHash()) {
return i
}
}
return index
}
func (t *Tree) CreateProof(leafChecksum []byte) (*Proof, error) {
var parts []*ProofPart
index := t.getLeafIdxByChecksum(leafChecksum)
if index == -1 {
return nil, errors.New("LeafHash not found in receiver")
}
for i := 0; i < len(t.Rows)-1; i++ {
if index%2 == 1 {
// is right, so go back one to get left
parts = append(parts, &ProofPart{
IsRight: false,
Hash: t.Rows[i][index-1].GetHash(),
})
} else {
var Hash []byte
if (index + 1) < len(t.Rows[i]) {
Hash = t.Rows[i][index+1].GetHash()
} else {
Hash = t.Rows[i][index].GetHash()
}
// is left, so go one forward to get hash pair
parts = append(parts, &ProofPart{
IsRight: true,
Hash: Hash,
})
}
index = int(float64(index / 2))
}
return &Proof{
HashFunc: t.HashFunc,
PathToRoot: parts,
LeafHash: leafChecksum,
}, nil
}
func (p *Proof) Equals(o *Proof) bool {
if !bytes.Equal(p.LeafHash, o.LeafHash) {
return false
}
if len(p.PathToRoot) != len(o.PathToRoot) {
return false
}
ok := true
for i := 0; i < len(p.PathToRoot); i++ {
ok = ok && p.PathToRoot[i].IsRight && o.PathToRoot[i].IsRight && bytes.Equal(p.PathToRoot[i].Hash, o.PathToRoot[i].Hash)
}
return ok
}