-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerkle.go
394 lines (315 loc) · 7.06 KB
/
merkle.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package merkletree
import (
"bytes"
"encoding/json"
"errors"
"hash"
"sort"
"golang.org/x/crypto/sha3"
)
// HashProvider hash provider
type HashProvider func() hash.Hash
// IHashFunc hash interface
type IHashFunc interface {
Hash(msg []byte) ([]byte, error)
}
// ITree tree interface
type ITree interface {
BuildTree(opt ...OptionFunc) error
}
// HashFunc hash function
type HashFunc struct {
Provider HashProvider
}
// Hash returns message digest
func (h *HashFunc) Hash(msg []byte) ([]byte, error) {
provider := h.Provider()
if _, err := provider.Write(msg); err != nil {
return nil, err
}
return provider.Sum(nil), nil
}
// DefaultHashFunc returns default hash interface
func DefaultHashFunc() IHashFunc {
hashFunc := new(HashFunc)
hashFunc.Provider = sha3.NewLegacyKeccak256
return hashFunc
}
// Hash node hash
type Hash = []byte
// Tree merkle tree
type Tree [][]Hash
// Node merkle tree node
type Node struct {
Height int
Hash []byte
Left *Node
Right *Node
Payload []byte
}
// Leaf merkle tree leaf
type Leaf = Node
// Root merkle tree root
type Root = Node
// NewLeaf returns a new leaf
func NewLeaf() Leaf {
return Leaf{
Height: 0,
}
}
// Clone returns a clone of the leaf
func (node *Leaf) Clone() *Leaf {
if node == nil {
return nil
}
clone := NewLeaf()
clone.Height = node.Height
clone.Hash = node.Hash
clone.Left = node.Left
clone.Right = node.Right
clone.Payload = node.Payload
return &clone
}
// Marshal returns bytes of tree
func (node *Root) Marshal() ([]byte, error) {
return json.Marshal(node)
}
// Leaves merkle tree leaves
type Leaves []Leaf
// Length returns length of leaves
func (obj *Leaves) Length() int {
if obj == nil {
return 0
}
return len(*obj)
}
// IsEmpty returns if leaves if empty
func (obj *Leaves) IsEmpty() bool {
return obj.Length() == 0
}
// LastLeaf returns the last leaf
func (obj *Leaves) LastLeaf() *Leaf {
if obj == nil {
return nil
}
return &(*obj)[obj.Length()-1]
}
// BuildTree build tree by options, returns tree & root
func (obj *Leaves) BuildTree(opt ...OptionFunc) (*Tree, *Root, error) {
if obj == nil || obj.IsEmpty() {
return nil, nil, errors.New("not found leaf")
}
opts := NewOptions(opt...)
h := opts.HashFunc
if !opts.SkipHash {
if err := obj.Hash(h); err != nil {
return nil, nil, err
}
}
if obj.Length()%2 == 1 {
clone := obj.LastLeaf().Clone()
*obj = append(*obj, *clone)
}
tree, err := obj.initTree()
if err != nil {
return nil, nil, err
}
root, err := obj.buildBranch(*obj, tree, h)
if err != nil {
return nil, nil, err
}
return tree, root, nil
}
// Hash calc hash of leaves
func (obj *Leaves) Hash(h IHashFunc) error {
for i := 0; i < obj.Length(); i++ {
digest, err := h.Hash((*obj)[i].Payload)
if err != nil {
return err
}
(*obj)[i].Hash = digest
}
return nil
}
// Sort leaves by hash
func (obj *Leaves) Sort() {
sort.Sort(obj)
}
// Add leaf to leaves
func (obj *Leaves) Add(leaf *Leaf) {
if obj == nil || leaf == nil {
return
}
*obj = append(*obj, *leaf)
}
// Clone returns a clone of the leaves
func (obj *Leaves) Clone() *Leaves {
if obj == nil {
return nil
}
leaves := make(Leaves, 0)
for _, leaf := range *obj {
if clone := leaf.Clone(); clone != nil {
leaves = append(leaves, *clone)
}
}
if obj.Length() != leaves.Length() {
return nil
}
return &leaves
}
// initTree init a tree
func (obj *Leaves) initTree() (*Tree, error) {
if obj.Length() == 0 {
return nil, errors.New("not found")
}
tree := make(Tree, 1)
hashSet := make([]Hash, obj.Length())
for i := 0; i < obj.Length(); i++ {
hashSet[i] = (*obj)[i].Hash
}
tree[0] = hashSet
return &tree, nil
}
// buildBranch build branch, fill the tree & returns root
func (obj *Leaves) buildBranch(nodes []Node, tree *Tree, h IHashFunc) (*Root, error) {
var branches []Node
var hashSet []Hash
length := len(nodes)
for i := 0; i < length; i += 2 {
left, right := i, i+1
if length == i+1 {
right = i
}
digest, err := h.Hash(append(nodes[left].Hash, nodes[right].Hash...))
if err != nil {
return nil, err
}
branch := Node{
Height: nodes[left].Height + 1,
Hash: digest,
Left: &nodes[left],
Right: &nodes[right],
}
branches = append(branches, branch)
hashSet = append(hashSet, digest)
if length == 2 {
*tree = append(*tree, hashSet)
return &branch, nil
}
}
*tree = append(*tree, hashSet)
return obj.buildBranch(branches, tree, h)
}
/***************************
Y
^
|
+------------
2 | 0 | | |
+------------
1 | 0 | 1 | |
+------------
0 | 0 | 1 | 2 |
--+-----------------> X
| 0 1 2
***************************/
// Marshal returns bytes of tree
func (tree *Tree) Marshal() ([]byte, error) {
if tree == nil {
return nil, errors.New("tree is empty")
}
return json.Marshal(tree)
}
// Height returns height of tree
func (tree *Tree) Height() uint64 {
if tree == nil {
return 0
}
return uint64(len(*tree))
}
// Width returns width of tree by y
func (tree *Tree) Width(y uint64) uint64 {
if tree == nil || tree.Height() == 0 {
return 0
}
return uint64(len((*tree)[y]))
}
// Y returns value of 'y'
func (tree *Tree) Y() uint64 {
if tree == nil || tree.Height() == 0 {
return 0
}
return tree.Height() - 1
}
// X returns value of 'x'
func (tree *Tree) X(y uint64) uint64 {
if tree == nil || tree.Height() == 0 {
return 0
}
return tree.Width(y) - 1
}
// GetRootHash returns root hash
func (tree *Tree) GetRootHash() ([]byte, error) {
if tree == nil || tree.Height() == 0 {
return nil, errors.New("tree is empty")
}
return (*tree)[tree.Y()][0], nil
}
// GetHash returns hash by (y,x)
func (tree *Tree) GetHash(y uint64, x uint64) ([]byte, error) {
if tree == nil || tree.Height() == 0 {
return nil, errors.New("tree is empty")
} else if y > tree.Y() {
return nil, errors.New("invalid y")
} else if x > tree.X(y) {
return nil, errors.New("invalid x")
}
return (*tree)[y][x], nil
}
// Prove returns merkle proofs result
func (tree *Tree) Prove(merklePath *PoNs, unverifiedHash []byte, h IHashFunc) (bool, error) {
digest := unverifiedHash
for _, pon := range *merklePath {
brother, err := tree.GetHash(pon[0], pon[1])
if err != nil {
return false, err
}
if pon[1]%2 == 0 {
digest, err = h.Hash(append(brother, digest...))
} else {
digest, err = h.Hash(append(digest, brother...))
}
if err != nil {
return false, err
}
}
rootHash, err := tree.GetRootHash()
if err != nil {
return false, err
}
return bytes.Compare(rootHash, digest) == 0, nil
}
// PoN is position of node, PoN[0] is y, PoN[1] is x
type PoN [2]uint64
// PoNs is positions of nodes, from leaf to the root
type PoNs []PoN
// GetParent returns parent of node
func (pon PoN) GetParent() PoN {
return PoN{pon[0] + 1, pon[1] / 2}
}
// GetPath returns merkle path, pons is Positions Of Nodes
func (pons *PoNs) GetPath(height uint64, y uint64, x uint64) {
pon := PoN{y}
if x%2 == 0 {
pon[1] = x + 1
} else {
pon[1] = x - 1
}
if y == height-1 {
return
}
*pons = append(*pons, pon)
parent := pon.GetParent()
pons.GetPath(height, parent[0], parent[1])
}