-
Notifications
You must be signed in to change notification settings - Fork 125
/
merkle_tree.go
352 lines (319 loc) · 9.2 KB
/
merkle_tree.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
// Copyright 2017 Cameron Bergoon
// Licensed under the MIT License, see LICENCE file for details.
package merkletree
import (
"bytes"
"crypto/sha256"
"errors"
"fmt"
"hash"
"math/big"
)
//Content represents the data that is stored and verified by the tree. A type that
//implements this interface can be used as an item in the tree.
type Content interface {
CalculateHash() ([]byte, error)
Equals(other Content) (bool, error)
}
//MerkleTree is the container for the tree. It holds a pointer to the root of the tree,
//a list of pointers to the leaf nodes, and the merkle root.
type MerkleTree struct {
Root *Node
merkleRoot []byte
Leafs []*Node
hashStrategy func() hash.Hash
sort bool
}
//Node represents a node, root, or leaf in the tree. It stores pointers to its immediate
//relationships, a hash, the content stored if it is a leaf, and other metadata.
type Node struct {
Tree *MerkleTree
Parent *Node
Left *Node
Right *Node
leaf bool
dup bool
Hash []byte
C Content
sort bool
}
// sortAppend sort and append the nodes to be compatible with OpenZepplin libraries
// https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/cryptography/MerkleProof.sol
func sortAppend(sort bool, a, b []byte) []byte {
if !sort {
return append(a, b...)
}
var aBig, bBig big.Int
aBig.SetBytes(a)
bBig.SetBytes(b)
if aBig.Cmp(&bBig) == -1 {
return append(a, b...)
}
return append(b, a...)
}
//verifyNode walks down the tree until hitting a leaf, calculating the hash at each level
//and returning the resulting hash of Node n.
func (n *Node) verifyNode(sort bool) ([]byte, error) {
if n.leaf {
return n.C.CalculateHash()
}
rightBytes, err := n.Right.verifyNode(sort)
if err != nil {
return nil, err
}
leftBytes, err := n.Left.verifyNode(sort)
if err != nil {
return nil, err
}
h := n.Tree.hashStrategy()
if _, err := h.Write(sortAppend(sort, leftBytes, rightBytes)); err != nil {
return nil, err
}
return h.Sum(nil), nil
}
//calculateNodeHash is a helper function that calculates the hash of the node.
func (n *Node) calculateNodeHash(sort bool) ([]byte, error) {
if n.leaf {
return n.C.CalculateHash()
}
h := n.Tree.hashStrategy()
if _, err := h.Write(sortAppend(sort, n.Left.Hash, n.Right.Hash)); err != nil {
return nil, err
}
return h.Sum(nil), nil
}
//NewTree creates a new Merkle Tree using the content cs.
func NewTree(cs []Content) (*MerkleTree, error) {
var defaultHashStrategy = sha256.New
t := &MerkleTree{
hashStrategy: defaultHashStrategy,
sort: false,
}
root, leafs, err := buildWithContent(cs, t)
if err != nil {
return nil, err
}
t.Root = root
t.Leafs = leafs
t.merkleRoot = root.Hash
return t, nil
}
//NewTreeWithHashStrategy creates a new Merkle Tree using the content cs using the provided hash
//strategy. Note that the hash type used in the type that implements the Content interface must
//match the hash type provided to the tree.
func NewTreeWithHashStrategy(cs []Content, hashStrategy func() hash.Hash) (*MerkleTree, error) {
t := &MerkleTree{
hashStrategy: hashStrategy,
sort: false,
}
root, leafs, err := buildWithContent(cs, t)
if err != nil {
return nil, err
}
t.Root = root
t.Leafs = leafs
t.merkleRoot = root.Hash
return t, nil
}
//NewTreeWithHashStrategySorted just like NewTreeWithHashStrategy
// but sorts the siblings before hashing, mostly to follow the OpenZepplin Merkle implementation
// https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/cryptography/MerkleProof.sol
func NewTreeWithHashStrategySorted(cs []Content, hashStrategy func() hash.Hash, sort bool) (*MerkleTree, error) {
t := &MerkleTree{
hashStrategy: hashStrategy,
sort: sort,
}
root, leafs, err := buildWithContent(cs, t)
if err != nil {
return nil, err
}
t.Root = root
t.Leafs = leafs
t.merkleRoot = root.Hash
return t, nil
}
// GetMerklePath: Get Merkle path and indexes(left leaf or right leaf)
func (m *MerkleTree) GetMerklePath(content Content) ([][]byte, []int64, error) {
for _, current := range m.Leafs {
ok, err := current.C.Equals(content)
if err != nil {
return nil, nil, err
}
if ok {
currentParent := current.Parent
var merklePath [][]byte
var index []int64
for currentParent != nil {
if bytes.Equal(currentParent.Left.Hash, current.Hash) {
merklePath = append(merklePath, currentParent.Right.Hash)
index = append(index, 1) // right leaf
} else {
merklePath = append(merklePath, currentParent.Left.Hash)
index = append(index, 0) // left leaf
}
current = currentParent
currentParent = currentParent.Parent
}
return merklePath, index, nil
}
}
return nil, nil, nil
}
//buildWithContent is a helper function that for a given set of Contents, generates a
//corresponding tree and returns the root node, a list of leaf nodes, and a possible error.
//Returns an error if cs contains no Contents.
func buildWithContent(cs []Content, t *MerkleTree) (*Node, []*Node, error) {
if len(cs) == 0 {
return nil, nil, errors.New("error: cannot construct tree with no content")
}
var leafs []*Node
for _, c := range cs {
hash, err := c.CalculateHash()
if err != nil {
return nil, nil, err
}
leafs = append(leafs, &Node{
Hash: hash,
C: c,
leaf: true,
Tree: t,
})
}
if len(leafs)%2 == 1 {
duplicate := &Node{
Hash: leafs[len(leafs)-1].Hash,
C: leafs[len(leafs)-1].C,
leaf: true,
dup: true,
Tree: t,
}
leafs = append(leafs, duplicate)
}
root, err := buildIntermediate(leafs, t)
if err != nil {
return nil, nil, err
}
return root, leafs, nil
}
//buildIntermediate is a helper function that for a given list of leaf nodes, constructs
//the intermediate and root levels of the tree. Returns the resulting root node of the tree.
func buildIntermediate(nl []*Node, t *MerkleTree) (*Node, error) {
var nodes []*Node
for i := 0; i < len(nl); i += 2 {
h := t.hashStrategy()
var left, right int = i, i + 1
if i+1 == len(nl) {
right = i
}
chash := sortAppend(t.sort, nl[left].Hash, nl[right].Hash)
if _, err := h.Write(chash); err != nil {
return nil, err
}
n := &Node{
Left: nl[left],
Right: nl[right],
Hash: h.Sum(nil),
Tree: t,
}
nodes = append(nodes, n)
nl[left].Parent = n
nl[right].Parent = n
if len(nl) == 2 {
return n, nil
}
}
return buildIntermediate(nodes, t)
}
//MerkleRoot returns the unverified Merkle Root (hash of the root node) of the tree.
func (m *MerkleTree) MerkleRoot() []byte {
return m.merkleRoot
}
//RebuildTree is a helper function that will rebuild the tree reusing only the content that
//it holds in the leaves.
func (m *MerkleTree) RebuildTree() error {
var cs []Content
for _, c := range m.Leafs {
cs = append(cs, c.C)
}
root, leafs, err := buildWithContent(cs, m)
if err != nil {
return err
}
m.Root = root
m.Leafs = leafs
m.merkleRoot = root.Hash
return nil
}
//RebuildTreeWith replaces the content of the tree and does a complete rebuild; while the root of
//the tree will be replaced the MerkleTree completely survives this operation. Returns an error if the
//list of content cs contains no entries.
func (m *MerkleTree) RebuildTreeWith(cs []Content) error {
root, leafs, err := buildWithContent(cs, m)
if err != nil {
return err
}
m.Root = root
m.Leafs = leafs
m.merkleRoot = root.Hash
return nil
}
//VerifyTree verify tree validates the hashes at each level of the tree and returns true if the
//resulting hash at the root of the tree matches the resulting root hash; returns false otherwise.
func (m *MerkleTree) VerifyTree() (bool, error) {
calculatedMerkleRoot, err := m.Root.verifyNode(m.sort)
if err != nil {
return false, err
}
if bytes.Compare(m.merkleRoot, calculatedMerkleRoot) == 0 {
return true, nil
}
return false, nil
}
//VerifyContent indicates whether a given content is in the tree and the hashes are valid for that content.
//Returns true if the expected Merkle Root is equivalent to the Merkle root calculated on the critical path
//for a given content. Returns true if valid and false otherwise.
func (m *MerkleTree) VerifyContent(content Content) (bool, error) {
for _, l := range m.Leafs {
ok, err := l.C.Equals(content)
if err != nil {
return false, err
}
if ok {
currentParent := l.Parent
for currentParent != nil {
h := m.hashStrategy()
rightBytes, err := currentParent.Right.calculateNodeHash(m.sort)
if err != nil {
return false, err
}
leftBytes, err := currentParent.Left.calculateNodeHash(m.sort)
if err != nil {
return false, err
}
if _, err := h.Write(sortAppend(m.sort, leftBytes, rightBytes)); err != nil {
return false, err
}
if bytes.Compare(h.Sum(nil), currentParent.Hash) != 0 {
return false, nil
}
currentParent = currentParent.Parent
}
return true, nil
}
}
return false, nil
}
//String returns a string representation of the node.
func (n *Node) String() string {
return fmt.Sprintf("%t %t %v %s", n.leaf, n.dup, n.Hash, n.C)
}
//String returns a string representation of the tree. Only leaf nodes are included
//in the output.
func (m *MerkleTree) String() string {
s := ""
for _, l := range m.Leafs {
s += fmt.Sprint(l)
s += "\n"
}
return s
}