-
Notifications
You must be signed in to change notification settings - Fork 6
/
merkletree.go
982 lines (909 loc) · 26.1 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
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
package merkletree
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"math/big"
"sync"
cryptoUtils "github.com/iden3/go-iden3-crypto/utils"
)
const (
// proofFlagsLen is the byte length of the flags in the proof header
// (first 32 bytes).
proofFlagsLen = 2
numCharPrint = 8
// IndexLen indicates how many elements are used for the index.
IndexLen = 4
// DataLen indicates how many elements are used for the data.
DataLen = 8
)
var (
// ErrNodeKeyAlreadyExists is used when a node key already exists.
ErrNodeKeyAlreadyExists = errors.New("key already exists")
// ErrKeyNotFound is used when a key is not found in the MerkleTree.
ErrKeyNotFound = errors.New("Key not found in the MerkleTree")
// ErrNodeBytesBadSize is used when the data of a node has an incorrect
// size and can't be parsed.
ErrNodeBytesBadSize = errors.New("node data has incorrect size in the DB")
// ErrReachedMaxLevel is used when a traversal of the MT reaches the
// maximum level.
ErrReachedMaxLevel = errors.New("reached maximum level of the merkle tree")
// ErrInvalidNodeFound is used when an invalid node is found and can't
// be parsed.
ErrInvalidNodeFound = errors.New("found an invalid node in the DB")
// ErrInvalidProofBytes is used when a serialized proof is invalid.
ErrInvalidProofBytes = errors.New("the serialized proof is invalid")
// ErrInvalidDBValue is used when a value in the key value DB is
// invalid (for example, it doen't contain a byte header and a []byte
// body of at least len=1.
ErrInvalidDBValue = errors.New("the value in the DB is invalid")
// ErrEntryIndexAlreadyExists is used when the entry index already
// exists in the tree.
ErrEntryIndexAlreadyExists = errors.New("the entry index already exists in the tree")
// ErrNotWritable is used when the MerkleTree is not writable and a
// write function is called
ErrNotWritable = errors.New("Merkle Tree not writable")
)
// MerkleTree is the struct with the main elements of the MerkleTree
type MerkleTree struct {
sync.RWMutex
db Storage
rootKey *Hash
writable bool
maxLevels int
}
// NewMerkleTree loads a new MerkleTree. If in the storage already exists one
// will open that one, if not, will create a new one.
func NewMerkleTree(ctx context.Context, storage Storage,
maxLevels int) (*MerkleTree, error) {
mt := MerkleTree{db: storage, maxLevels: maxLevels, writable: true}
root, err := mt.db.GetRoot(ctx)
if err == ErrNotFound {
mt.rootKey = &HashZero
err = mt.db.SetRoot(ctx, mt.rootKey)
if err != nil {
return nil, err
}
return &mt, nil
} else if err != nil {
return nil, err
}
mt.rootKey = root
return &mt, nil
}
// Root returns the MerkleRoot
func (mt *MerkleTree) Root() *Hash {
return mt.rootKey
}
// MaxLevels returns the MT maximum level
func (mt *MerkleTree) MaxLevels() int {
return mt.maxLevels
}
// Snapshot returns a read-only copy of the MerkleTree
func (mt *MerkleTree) Snapshot(
ctx context.Context, rootKey *Hash) (*MerkleTree, error) {
mt.RLock()
defer mt.RUnlock()
_, err := mt.GetNode(ctx, rootKey)
if err != nil {
return nil, err
}
return &MerkleTree{
db: mt.db,
maxLevels: mt.maxLevels,
rootKey: rootKey,
writable: false}, nil
}
// Add adds a Key & Value into the MerkleTree. Where the `k` determines the
// path from the Root to the Leaf.
func (mt *MerkleTree) Add(ctx context.Context, k, v *big.Int) error {
// verify that the MerkleTree is writable
if !mt.writable {
return ErrNotWritable
}
kHash, err := NewHashFromBigInt(k)
if err != nil {
return fmt.Errorf("can't create hash from Key: %w", err)
}
vHash, err := NewHashFromBigInt(v)
if err != nil {
return fmt.Errorf("can't create hash from Value: %w", err)
}
mt.Lock()
defer mt.Unlock()
newNodeLeaf := NewNodeLeaf(kHash, vHash)
path := getPath(mt.maxLevels, kHash[:])
newRootKey, err := mt.addLeaf(ctx, newNodeLeaf, mt.rootKey, 0, path)
if err != nil {
return err
}
mt.rootKey = newRootKey
return mt.db.SetRoot(ctx, mt.rootKey)
}
// AddEntry adds the Entry to the MerkleTree
func (mt *MerkleTree) AddEntry(ctx context.Context, e *Entry) error {
// verify that the MerkleTree is writable
if !mt.writable {
return ErrNotWritable
}
// verify that the ElemBytes are valid and fit inside the mimc7 field.
if !CheckEntryInField(*e) {
return errors.New("Elements not inside the Finite Field over R")
}
mt.Lock()
defer mt.Unlock()
hIndex, err := e.HIndex()
if err != nil {
return err
}
hValue, err := e.HValue()
if err != nil {
return err
}
newNodeLeaf := NewNodeLeaf(hIndex, hValue)
path := getPath(mt.maxLevels, hIndex[:])
newRootKey, err := mt.addLeaf(ctx, newNodeLeaf, mt.rootKey, 0, path)
if err != nil {
return err
}
mt.rootKey = newRootKey
return mt.db.SetRoot(ctx, mt.rootKey)
}
// AddAndGetCircomProof does an Add, and returns a CircomProcessorProof
func (mt *MerkleTree) AddAndGetCircomProof(ctx context.Context,
k, v *big.Int) (*CircomProcessorProof, error) {
var cp CircomProcessorProof
cp.Fnc = 2
cp.OldRoot = mt.rootKey
gotK, gotV, _, err := mt.Get(ctx, k)
if err != nil && err != ErrKeyNotFound {
return nil, err
}
cp.OldKey, err = NewHashFromBigInt(gotK)
if err != nil {
return nil, err
}
cp.OldValue, err = NewHashFromBigInt(gotV)
if err != nil {
return nil, err
}
if bytes.Equal(cp.OldKey[:], HashZero[:]) {
cp.IsOld0 = true
}
_, _, siblings, err := mt.Get(ctx, k)
if err != nil && err != ErrKeyNotFound {
return nil, err
}
cp.Siblings = CircomSiblingsFromSiblings(siblings, mt.maxLevels)
err = mt.Add(ctx, k, v)
if err != nil {
return nil, err
}
cp.NewKey, err = NewHashFromBigInt(k)
if err != nil {
return nil, err
}
cp.NewValue, err = NewHashFromBigInt(v)
if err != nil {
return nil, err
}
cp.NewRoot = mt.rootKey
return &cp, nil
}
// pushLeaf recursively pushes an existing oldLeaf down until its path diverges
// from newLeaf, at which point both leafs are stored, all while updating the
// path.
func (mt *MerkleTree) pushLeaf(ctx context.Context, newLeaf *Node,
oldLeaf *Node, lvl int, pathNewLeaf []bool,
pathOldLeaf []bool) (*Hash, error) {
if lvl > mt.maxLevels-2 {
return nil, ErrReachedMaxLevel
}
var newNodeMiddle *Node
if pathNewLeaf[lvl] == pathOldLeaf[lvl] { // We need to go deeper!
nextKey, err := mt.pushLeaf(ctx, newLeaf, oldLeaf, lvl+1,
pathNewLeaf, pathOldLeaf)
if err != nil {
return nil, err
}
if pathNewLeaf[lvl] { // go right
newNodeMiddle = NewNodeMiddle(&HashZero, nextKey)
} else { // go left
newNodeMiddle = NewNodeMiddle(nextKey, &HashZero)
}
return mt.addNode(context.TODO(), newNodeMiddle)
}
oldLeafKey, err := oldLeaf.Key()
if err != nil {
return nil, err
}
newLeafKey, err := newLeaf.Key()
if err != nil {
return nil, err
}
if pathNewLeaf[lvl] {
newNodeMiddle = NewNodeMiddle(oldLeafKey, newLeafKey)
} else {
newNodeMiddle = NewNodeMiddle(newLeafKey, oldLeafKey)
}
// We can add newLeaf now. We don't need to add oldLeaf because it's
// already in the tree.
_, err = mt.addNode(ctx, newLeaf)
if err != nil {
return nil, err
}
return mt.addNode(ctx, newNodeMiddle)
}
// addLeaf recursively adds a newLeaf in the MT while updating the path.
func (mt *MerkleTree) addLeaf(ctx context.Context, newLeaf *Node, key *Hash,
lvl int, path []bool) (*Hash, error) {
var err error
var nextKey *Hash
if lvl > mt.maxLevels-1 {
return nil, ErrReachedMaxLevel
}
n, err := mt.GetNode(ctx, key)
if err != nil {
return nil, err
}
switch n.Type {
case NodeTypeEmpty:
// We can add newLeaf now
return mt.addNode(ctx, newLeaf)
case NodeTypeLeaf:
nKey := n.Entry[0]
// Check if leaf node found contains the leaf node we are
// trying to add
newLeafKey := newLeaf.Entry[0]
if bytes.Equal(nKey[:], newLeafKey[:]) {
return nil, ErrEntryIndexAlreadyExists
}
pathOldLeaf := getPath(mt.maxLevels, nKey[:])
// We need to push newLeaf down until its path diverges from
// n's path
return mt.pushLeaf(ctx, newLeaf, n, lvl, path, pathOldLeaf)
case NodeTypeMiddle:
// We need to go deeper, continue traversing the tree, left or
// right depending on path
var newNodeMiddle *Node
if path[lvl] { // go right
nextKey, err = mt.addLeaf(ctx, newLeaf, n.ChildR, lvl+1, path)
newNodeMiddle = NewNodeMiddle(n.ChildL, nextKey)
} else { // go left
nextKey, err = mt.addLeaf(ctx, newLeaf, n.ChildL, lvl+1, path)
newNodeMiddle = NewNodeMiddle(nextKey, n.ChildR)
}
if err != nil {
return nil, err
}
// Update the node to reflect the modified child
return mt.addNode(ctx, newNodeMiddle)
default:
return nil, ErrInvalidNodeFound
}
}
// addNode adds a node into the MT. Empty nodes are not stored in the tree;
// they are all the same and assumed to always exist.
func (mt *MerkleTree) addNode(ctx context.Context, n *Node) (*Hash, error) {
// verify that the MerkleTree is writable
if !mt.writable {
return nil, ErrNotWritable
}
if n.Type == NodeTypeEmpty {
return n.Key()
}
k, err := n.Key()
if err != nil {
return nil, err
}
//v := n.Value()
// Check that the node key doesn't already exist
if _, err := mt.db.Get(ctx, k[:]); err == nil {
return k, nil
}
return k, mt.db.Put(ctx, k[:], n)
}
// updateNode updates an existing node in the MT. Empty nodes are not stored
// in the tree; they are all the same and assumed to always exist.
func (mt *MerkleTree) updateNode(ctx context.Context, n *Node) (*Hash, error) {
// verify that the MerkleTree is writable
if !mt.writable {
return nil, ErrNotWritable
}
if n.Type == NodeTypeEmpty {
return n.Key()
}
k, err := n.Key()
if err != nil {
return nil, err
}
//v := n.Value()
err = mt.db.Put(ctx, k[:], n)
return k, err
}
// Get returns the value of the leaf for the given key
func (mt *MerkleTree) Get(ctx context.Context,
k *big.Int) (*big.Int, *big.Int, []*Hash, error) {
kHash, err := NewHashFromBigInt(k)
if err != nil {
return nil, nil, nil, fmt.Errorf("can't create hash from Key: %w", err)
}
path := getPath(mt.maxLevels, kHash[:])
nextKey := mt.rootKey
siblings := []*Hash{}
for i := 0; i < mt.maxLevels; i++ {
n, err := mt.GetNode(ctx, nextKey)
if err != nil {
return nil, nil, nil, err
}
switch n.Type {
case NodeTypeEmpty:
return big.NewInt(0), big.NewInt(0), siblings, ErrKeyNotFound
case NodeTypeLeaf:
if bytes.Equal(kHash[:], n.Entry[0][:]) {
return n.Entry[0].BigInt(), n.Entry[1].BigInt(), siblings, nil
}
return n.Entry[0].BigInt(), n.Entry[1].BigInt(), siblings, ErrKeyNotFound
case NodeTypeMiddle:
if path[i] {
nextKey = n.ChildR
siblings = append(siblings, n.ChildL)
} else {
nextKey = n.ChildL
siblings = append(siblings, n.ChildR)
}
default:
return nil, nil, nil, ErrInvalidNodeFound
}
}
return nil, nil, nil, ErrReachedMaxLevel
}
// Update updates the value of a specified key in the MerkleTree, and updates
// the path from the leaf to the Root with the new values. Returns the
// CircomProcessorProof.
func (mt *MerkleTree) Update(ctx context.Context,
k, v *big.Int) (*CircomProcessorProof, error) {
// verify that the MerkleTree is writable
if !mt.writable {
return nil, ErrNotWritable
}
// verify that k & v are valid and fit inside the Finite Field.
if !cryptoUtils.CheckBigIntInField(k) {
return nil, errors.New("Key not inside the Finite Field")
}
if !cryptoUtils.CheckBigIntInField(v) {
return nil, errors.New("Key not inside the Finite Field")
}
mt.Lock()
defer mt.Unlock()
kHash, err := NewHashFromBigInt(k)
if err != nil {
return nil, err
}
vHash, err := NewHashFromBigInt(v)
if err != nil {
return nil, err
}
path := getPath(mt.maxLevels, kHash[:])
var cp CircomProcessorProof
cp.Fnc = 1
cp.OldRoot = mt.rootKey
cp.OldKey = kHash
cp.NewKey = kHash
cp.NewValue = vHash
nextKey := mt.rootKey
siblings := []*Hash{}
for i := 0; i < mt.maxLevels; i++ {
n, err := mt.GetNode(ctx, nextKey)
if err != nil {
return nil, err
}
switch n.Type {
case NodeTypeEmpty:
return nil, ErrKeyNotFound
case NodeTypeLeaf:
if bytes.Equal(kHash[:], n.Entry[0][:]) {
cp.OldValue = n.Entry[1]
cp.Siblings = CircomSiblingsFromSiblings(siblings, mt.maxLevels)
// update leaf and upload to the root
newNodeLeaf := NewNodeLeaf(kHash, vHash)
_, err := mt.updateNode(ctx, newNodeLeaf)
if err != nil {
return nil, err
}
newRootKey, err :=
mt.recalculatePathUntilRoot(path, newNodeLeaf, siblings)
if err != nil {
return nil, err
}
mt.rootKey = newRootKey
err = mt.db.SetRoot(ctx, mt.rootKey)
if err != nil {
return nil, err
}
cp.NewRoot = newRootKey
return &cp, nil
}
return nil, ErrKeyNotFound
case NodeTypeMiddle:
if path[i] {
nextKey = n.ChildR
siblings = append(siblings, n.ChildL)
} else {
nextKey = n.ChildL
siblings = append(siblings, n.ChildR)
}
default:
return nil, ErrInvalidNodeFound
}
}
return nil, ErrKeyNotFound
}
// Delete removes the specified Key from the MerkleTree and updates the path
// from the deleted key to the Root with the new values. This method removes
// the key from the MerkleTree, but does not remove the old nodes from the
// key-value database; this means that if the tree is accessed by an old Root
// where the key was not deleted yet, the key will still exist. If is desired
// to remove the key-values from the database that are not under the current
// Root, an option could be to dump all the leaves (using mt.DumpLeafs) and
// import them in a new MerkleTree in a new database (using
// mt.ImportDumpedLeafs), but this will loose all the Root history of the
// MerkleTree
func (mt *MerkleTree) Delete(ctx context.Context, k *big.Int) error {
// verify that the MerkleTree is writable
if !mt.writable {
return ErrNotWritable
}
mt.Lock()
defer mt.Unlock()
kHash, err := NewHashFromBigInt(k)
if err != nil {
return err
}
path := getPath(mt.maxLevels, kHash[:])
nextKey := mt.rootKey
siblings := []*Hash{}
for i := 0; i < mt.maxLevels; i++ {
n, err := mt.GetNode(ctx, nextKey)
if err != nil {
return err
}
switch n.Type {
case NodeTypeEmpty:
return ErrKeyNotFound
case NodeTypeLeaf:
if bytes.Equal(kHash[:], n.Entry[0][:]) {
// remove and go up with the sibling
err = mt.rmAndUpload(ctx, path, kHash, siblings)
return err
}
return ErrKeyNotFound
case NodeTypeMiddle:
if path[i] {
nextKey = n.ChildR
siblings = append(siblings, n.ChildL)
} else {
nextKey = n.ChildL
siblings = append(siblings, n.ChildR)
}
default:
return ErrInvalidNodeFound
}
}
return ErrKeyNotFound
}
// rmAndUpload removes the key, and goes up until the root updating all the
// nodes with the new values.
func (mt *MerkleTree) rmAndUpload(ctx context.Context, path []bool, kHash *Hash,
siblings []*Hash) error {
if len(siblings) == 0 {
mt.rootKey = &HashZero
err := mt.db.SetRoot(ctx, mt.rootKey)
return err
}
toUpload := siblings[len(siblings)-1]
if len(siblings) < 2 {
mt.rootKey = siblings[0]
err := mt.db.SetRoot(ctx, mt.rootKey)
if err != nil {
return err
}
}
//When deleting a leaf node that is on the same level as middleNode,
//need to nullify the leaf node instead of removing it from the tree.
nearestSibling, err := mt.db.Get(ctx, toUpload[:])
if err != nil {
return err
}
if nearestSibling.Type == NodeTypeMiddle {
var newNode *Node
if path[len(siblings)-1] {
newNode = NewNodeMiddle(toUpload, &HashZero)
} else {
newNode = NewNodeMiddle(&HashZero, toUpload)
}
_, err = mt.addNode(ctx, newNode)
if err != nil {
return err
}
newRootKey, err := mt.recalculatePathUntilRoot(path, newNode,
siblings[:len(siblings)-1])
if err != nil {
return err
}
mt.rootKey = newRootKey
err = mt.db.SetRoot(ctx, mt.rootKey)
if err != nil {
return err
}
return nil
}
for i := len(siblings) - 2; i >= 0; i-- {
if !bytes.Equal(siblings[i][:], HashZero[:]) {
var newNode *Node
if path[i] {
newNode = NewNodeMiddle(siblings[i], toUpload)
} else {
newNode = NewNodeMiddle(toUpload, siblings[i])
}
_, err := mt.addNode(context.TODO(), newNode)
if err != nil {
return err
}
// go up until the root
newRootKey, err := mt.recalculatePathUntilRoot(path, newNode,
siblings[:i])
if err != nil {
return err
}
mt.rootKey = newRootKey
err = mt.db.SetRoot(ctx, mt.rootKey)
if err != nil {
return err
}
break
}
// if i==0 (root position), stop and store the sibling of the
// deleted leaf as root
if i == 0 {
mt.rootKey = toUpload
err := mt.db.SetRoot(ctx, mt.rootKey)
if err != nil {
return err
}
break
}
}
return nil
}
// recalculatePathUntilRoot recalculates the nodes until the Root
func (mt *MerkleTree) recalculatePathUntilRoot(path []bool, node *Node,
siblings []*Hash) (*Hash, error) {
for i := len(siblings) - 1; i >= 0; i-- {
nodeKey, err := node.Key()
if err != nil {
return nil, err
}
if path[i] {
node = NewNodeMiddle(siblings[i], nodeKey)
} else {
node = NewNodeMiddle(nodeKey, siblings[i])
}
_, err = mt.addNode(context.TODO(), node)
if err != nil {
return nil, err
}
}
// return last node added, which is the root
nodeKey, err := node.Key()
return nodeKey, err
}
// GetNode gets a node by key from the MT. Empty nodes are not stored in the
// tree; they are all the same and assumed to always exist.
func (mt *MerkleTree) GetNode(ctx context.Context, key *Hash) (*Node, error) {
if bytes.Equal(key[:], HashZero[:]) {
return NewNodeEmpty(), nil
}
n, err := mt.db.Get(ctx, key[:])
if err != nil {
return nil, err
}
return n, nil
}
// getPath returns the binary path, from the root to the leaf.
func getPath(numLevels int, k []byte) []bool {
path := make([]bool, numLevels)
for n := 0; n < numLevels; n++ {
path[n] = TestBit(k[:], uint(n))
}
return path
}
// NodeAux contains the auxiliary node used in a non-existence proof.
type NodeAux struct {
Key *Hash `json:"key"`
Value *Hash `json:"value"`
}
// CircomSiblingsFromSiblings returns the full siblings compatible with circom
func CircomSiblingsFromSiblings(siblings []*Hash, levels int) []*Hash {
// Add the rest of empty levels to the siblings
for i := len(siblings); i < levels+1; i++ {
siblings = append(siblings, &HashZero)
}
return siblings
}
// CircomProcessorProof defines the ProcessorProof compatible with circom. Is
// the data of the proof between the transition from one state to another.
type CircomProcessorProof struct {
OldRoot *Hash `json:"oldRoot"`
NewRoot *Hash `json:"newRoot"`
Siblings []*Hash `json:"siblings"`
OldKey *Hash `json:"oldKey"`
OldValue *Hash `json:"oldValue"`
NewKey *Hash `json:"newKey"`
NewValue *Hash `json:"newValue"`
IsOld0 bool `json:"isOld0"`
// 0: NOP, 1: Update, 2: Insert, 3: Delete
Fnc int `json:"fnc"`
}
// String returns a human readable string representation of the
// CircomProcessorProof
func (p CircomProcessorProof) String() string {
buf := bytes.NewBufferString("{")
fmt.Fprintf(buf, " OldRoot: %v,\n", p.OldRoot)
fmt.Fprintf(buf, " NewRoot: %v,\n", p.NewRoot)
fmt.Fprintf(buf, " Siblings: [\n ")
for _, s := range p.Siblings {
fmt.Fprintf(buf, "%v, ", s)
}
fmt.Fprintf(buf, "\n ],\n")
fmt.Fprintf(buf, " OldKey: %v,\n", p.OldKey)
fmt.Fprintf(buf, " OldValue: %v,\n", p.OldValue)
fmt.Fprintf(buf, " NewKey: %v,\n", p.NewKey)
fmt.Fprintf(buf, " NewValue: %v,\n", p.NewValue)
fmt.Fprintf(buf, " IsOld0: %v,\n", p.IsOld0)
fmt.Fprintf(buf, "}\n")
return buf.String()
}
// CircomVerifierProof defines the VerifierProof compatible with circom. Is the
// data of the proof that a certain leaf exists in the MerkleTree.
type CircomVerifierProof struct {
Root *Hash `json:"root"`
Siblings []*Hash `json:"siblings"`
OldKey *Hash `json:"oldKey"`
OldValue *Hash `json:"oldValue"`
IsOld0 bool `json:"isOld0"`
Key *Hash `json:"key"`
Value *Hash `json:"value"`
Fnc int `json:"fnc"` // 0: inclusion, 1: non inclusion
}
// GenerateCircomVerifierProof returns the CircomVerifierProof for a certain
// key in the MerkleTree. If the rootKey is nil, the current merkletree root
// is used.
func (mt *MerkleTree) GenerateCircomVerifierProof(ctx context.Context,
k *big.Int, rootKey *Hash) (*CircomVerifierProof, error) {
cp, err := mt.GenerateSCVerifierProof(ctx, k, rootKey)
if err != nil {
return nil, err
}
cp.Siblings = CircomSiblingsFromSiblings(cp.Siblings, mt.maxLevels)
return cp, nil
}
// GenerateSCVerifierProof returns the CircomVerifierProof for a certain key in
// the MerkleTree with the Siblings without the extra 0 needed at the circom
// circuits, which makes it straight forward to verifiy inside a Smart
// Contract. If the rootKey is nil, the current merkletree root is used.
func (mt *MerkleTree) GenerateSCVerifierProof(ctx context.Context, k *big.Int,
rootKey *Hash) (*CircomVerifierProof, error) {
if rootKey == nil {
rootKey = mt.Root()
}
p, v, err := mt.GenerateProof(ctx, k, rootKey)
if err != nil && err != ErrKeyNotFound {
return nil, err
}
var cp CircomVerifierProof
cp.Root = rootKey
cp.Siblings = p.AllSiblings()
if p.NodeAux != nil {
cp.OldKey = p.NodeAux.Key
cp.OldValue = p.NodeAux.Value
} else {
cp.OldKey = &HashZero
cp.OldValue = &HashZero
}
cp.Key, err = NewHashFromBigInt(k)
if err != nil {
return nil, err
}
cp.Value, err = NewHashFromBigInt(v)
if err != nil {
return nil, err
}
if p.Existence {
cp.Fnc = 0 // inclusion
} else {
cp.Fnc = 1 // non inclusion
}
return &cp, nil
}
// GenerateProof generates the proof of existence (or non-existence) of an
// Entry's hash Index for a Merkle Tree given the root.
// If the rootKey is nil, the current merkletree root is used
func (mt *MerkleTree) GenerateProof(ctx context.Context, k *big.Int,
rootKey *Hash) (*Proof, *big.Int, error) {
p := &Proof{}
var siblingKey *Hash
kHash, err := NewHashFromBigInt(k)
if err != nil {
return nil, nil, err
}
path := getPath(mt.maxLevels, kHash[:])
if rootKey == nil {
rootKey = mt.Root()
}
nextKey := rootKey
for p.depth = 0; p.depth < uint(mt.maxLevels); p.depth++ {
n, err := mt.GetNode(ctx, nextKey)
if err != nil {
return nil, nil, err
}
switch n.Type {
case NodeTypeEmpty:
return p, big.NewInt(0), nil
case NodeTypeLeaf:
if bytes.Equal(kHash[:], n.Entry[0][:]) {
p.Existence = true
return p, n.Entry[1].BigInt(), nil
}
// We found a leaf whose entry didn't match hIndex
p.NodeAux = &NodeAux{Key: n.Entry[0], Value: n.Entry[1]}
return p, n.Entry[1].BigInt(), nil
case NodeTypeMiddle:
if path[p.depth] {
nextKey = n.ChildR
siblingKey = n.ChildL
} else {
nextKey = n.ChildL
siblingKey = n.ChildR
}
default:
return nil, nil, ErrInvalidNodeFound
}
if !bytes.Equal(siblingKey[:], HashZero[:]) {
SetBitBigEndian(p.notempties[:], p.depth)
p.siblings = append(p.siblings, siblingKey)
}
}
return nil, nil, ErrKeyNotFound
}
// walk is a helper recursive function to iterate over all tree branches
func (mt *MerkleTree) walk(ctx context.Context,
key *Hash, f func(*Node)) error {
n, err := mt.GetNode(ctx, key)
if err != nil {
return err
}
switch n.Type {
case NodeTypeEmpty:
f(n)
case NodeTypeLeaf:
f(n)
case NodeTypeMiddle:
f(n)
if err := mt.walk(ctx, n.ChildL, f); err != nil {
return err
}
if err := mt.walk(ctx, n.ChildR, f); err != nil {
return err
}
default:
return ErrInvalidNodeFound
}
return nil
}
// Walk iterates over all the branches of a MerkleTree with the given rootKey
// if rootKey is nil, it will get the current RootKey of the current state of
// the MerkleTree. For each node, it calls the f function given in the
// parameters. See some examples of the Walk function usage in the
// merkletree.go and merkletree_test.go
func (mt *MerkleTree) Walk(ctx context.Context, rootKey *Hash,
f func(*Node)) error {
if rootKey == nil {
rootKey = mt.Root()
}
err := mt.walk(ctx, rootKey, f)
return err
}
// GraphViz uses Walk function to generate a string GraphViz representation of
// the tree and writes it to w
func (mt *MerkleTree) GraphViz(ctx context.Context, w io.Writer,
rootKey *Hash) error {
fmt.Fprintf(w, `digraph hierarchy {
node [fontname=Monospace,fontsize=10,shape=box]
`)
cnt := 0
var errIn error
err := mt.Walk(ctx, rootKey, func(n *Node) {
k, err := n.Key()
if err != nil {
errIn = err
}
switch n.Type {
case NodeTypeEmpty:
case NodeTypeLeaf:
fmt.Fprintf(w, "\"%v\" [style=filled];\n", k.String())
case NodeTypeMiddle:
lr := [2]string{n.ChildL.String(), n.ChildR.String()}
emptyNodes := ""
for i := range lr {
if lr[i] == "0" {
lr[i] = fmt.Sprintf("empty%v", cnt)
emptyNodes += fmt.Sprintf("\"%v\" [style=dashed,label=0];\n",
lr[i])
cnt++
}
}
fmt.Fprintf(w, "\"%v\" -> {\"%v\" \"%v\"}\n", k.String(), lr[0],
lr[1])
fmt.Fprint(w, emptyNodes)
default:
}
})
fmt.Fprintf(w, "}\n")
if errIn != nil {
return errIn
}
return err
}
// PrintGraphViz prints directly the GraphViz() output
func (mt *MerkleTree) PrintGraphViz(ctx context.Context, rootKey *Hash) error {
if rootKey == nil {
rootKey = mt.Root()
}
w := bytes.NewBufferString("")
fmt.Fprintf(w,
"--------\nGraphViz of the MerkleTree with RootKey "+rootKey.BigInt().String()+"\n")
err := mt.GraphViz(ctx, w, nil)
if err != nil {
return err
}
fmt.Fprintf(w,
"End of GraphViz of the MerkleTree with RootKey "+rootKey.BigInt().String()+"\n--------\n")
fmt.Println(w)
return nil
}
// DumpLeafs returns all the Leafs that exist under the given Root. If no Root
// is given (nil), it uses the current Root of the MerkleTree.
func (mt *MerkleTree) DumpLeafs(ctx context.Context,
rootKey *Hash) ([]byte, error) {
var buf bytes.Buffer
err := mt.Walk(ctx, rootKey, func(n *Node) {
if n.Type == NodeTypeLeaf {
buf.Grow(len(n.Entry[0]) + len(n.Entry[1]))
buf.Write(n.Entry[0][:])
buf.Write(n.Entry[1][:])
}
})
return buf.Bytes(), err
}
// ImportDumpedLeafs parses and adds to the MerkleTree the dumped list of leafs
// from the DumpLeafs function.
func (mt *MerkleTree) ImportDumpedLeafs(ctx context.Context, b []byte) error {
hashLn := len(Hash{})
nodeLn := hashLn * 2
if len(b)%nodeLn != 0 {
return errors.New("invalid input length")
}
for i := 0; i < len(b); i += nodeLn {
var leftHash, rightHash Hash
copy(leftHash[:], b[i:i+hashLn])
copy(rightHash[:], b[i+hashLn:i+(hashLn*2)])
err := mt.Add(ctx, leftHash.BigInt(), rightHash.BigInt())
if err != nil {
return err
}
}
return nil
}