-
Notifications
You must be signed in to change notification settings - Fork 66
/
tree.go
1912 lines (1689 loc) · 53.6 KB
/
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
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
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This is free and unencumbered software released into the public domain.
//
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.
//
// In jurisdictions that recognize copyright laws, the author or authors
// of this software dedicate any and all copyright interest in the
// software to the public domain. We make this dedication for the benefit
// of the public at large and to the detriment of our heirs and
// successors. We intend this dedication to be an overt act of
// relinquishment in perpetuity of all present and future rights to this
// software under copyright law.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
// For more information, please refer to <https://unlicense.org>
package verkle
import (
"bytes"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"runtime"
"sync"
"github.com/crate-crypto/go-ipa/banderwagon"
)
type (
NodeFlushFn func([]byte, VerkleNode)
NodeResolverFn func([]byte) ([]byte, error)
)
type keylist [][]byte
func (kl keylist) Len() int {
return len(kl)
}
func (kl keylist) Less(i, j int) bool {
return bytes.Compare(kl[i], kl[j]) == -1
}
func (kl keylist) Swap(i, j int) {
kl[i], kl[j] = kl[j], kl[i]
}
type Stem []byte
func KeyToStem(key []byte) Stem {
if len(key) < StemSize {
panic(fmt.Errorf("key length (%d) is shorter than the expected stem size (%d)", len(key), StemSize))
}
return Stem(key[:StemSize])
}
type VerkleNode interface {
// Insert or Update value into the tree
Insert([]byte, []byte, NodeResolverFn) error
// Delete a leaf with the given key
Delete([]byte, NodeResolverFn) (bool, error)
// Get value at a given key
Get([]byte, NodeResolverFn) ([]byte, error)
// Commit computes the commitment of the node. The
// result (the curve point) is cached.
Commit() *Point
// Commitment is a getter for the cached commitment
// to this node.
Commitment() *Point
// Hash returns the field representation of the commitment.
Hash() *Fr
// GetProofItems collects the various proof elements, and
// returns them breadth-first. On top of that, it returns
// one "extension status" per stem, and an alternate stem
// if the key is missing but another stem has been found.
GetProofItems(keylist, NodeResolverFn) (*ProofElements, []byte, []Stem, error)
// Serialize encodes the node to RLP.
Serialize() ([]byte, error)
// Copy a node and its children
Copy() VerkleNode
// toDot returns a string representing this subtree in DOT language
toDot(string, string) string
setDepth(depth byte)
}
// ProofElements gathers the elements needed to build a proof.
type ProofElements struct {
Cis []*Point
Zis []byte
Yis []*Fr
Fis [][]Fr
ByPath map[string]*Point // Gather commitments by path
Vals [][]byte // list of values read from the tree
// dedups flags the presence of each (Ci,zi) tuple
dedups map[*Point]map[byte]struct{}
}
// Merge merges the elements of two proofs and removes duplicates.
func (pe *ProofElements) Merge(other *ProofElements) {
// Build the local map if it's missing
if pe.dedups == nil {
pe.dedups = make(map[*Point]map[byte]struct{})
for i, ci := range pe.Cis {
if _, ok := pe.dedups[ci]; !ok {
pe.dedups[ci] = make(map[byte]struct{})
}
pe.dedups[ci][pe.Zis[i]] = struct{}{}
}
}
for i, ci := range other.Cis {
if _, ok := pe.dedups[ci]; !ok {
// First time this commitment has been seen, create
// the map and flatten the zi.
pe.dedups[ci] = make(map[byte]struct{})
}
if _, ok := pe.dedups[ci][other.Zis[i]]; ok {
// duplicate, skip
continue
}
pe.dedups[ci][other.Zis[i]] = struct{}{}
pe.Cis = append(pe.Cis, ci)
pe.Zis = append(pe.Zis, other.Zis[i])
pe.Yis = append(pe.Yis, other.Yis[i])
if pe.Fis != nil {
pe.Fis = append(pe.Fis, other.Fis[i])
}
}
for path, C := range other.ByPath {
if _, ok := pe.ByPath[path]; !ok {
pe.ByPath[path] = C
}
}
pe.Vals = append(pe.Vals, other.Vals...)
}
const (
// These types will distinguish internal
// and leaf nodes when decoding from RLP.
internalType byte = 1
leafType byte = 2
eoAccountType byte = 3
singleSlotType byte = 4
)
type (
// Represents an internal node at any level
InternalNode struct {
// List of child nodes of this internal node.
children []VerkleNode
// node depth in the tree, in bits
depth byte
// Cache the commitment value
commitment *Point
cow map[byte]*Point
}
LeafNode struct {
stem Stem
values [][]byte
commitment *Point
c1, c2 *Point
depth byte
// IsPOAStub indicates if this LeafNode is a proof of absence
// for a steam that isn't present in the tree. This flag is only
// true in the context of a stateless tree.
isPOAStub bool
}
)
func (n *InternalNode) toExportable() *ExportableInternalNode {
comm := n.commitment.Bytes()
exportable := &ExportableInternalNode{
Children: make([]interface{}, NodeWidth),
Commitment: comm[:],
}
for i := range exportable.Children {
switch child := n.children[i].(type) {
case Empty:
exportable.Children[i] = nil
case HashedNode:
exportable.Children[i] = n.commitment.Bytes()
case *InternalNode:
exportable.Children[i] = child.toExportable()
case *LeafNode:
exportable.Children[i] = &ExportableLeafNode{
Stem: child.stem,
Values: child.values,
C: child.commitment.Bytes(),
C1: child.c1.Bytes(),
}
default:
panic("unexportable type")
}
}
return exportable
}
// Turn an internal node into a JSON string
func (n *InternalNode) ToJSON() ([]byte, error) {
return json.Marshal(n.toExportable())
}
func newInternalNode(depth byte) VerkleNode {
node := new(InternalNode)
node.children = make([]VerkleNode, NodeWidth)
for idx := range node.children {
node.children[idx] = Empty(struct{}{})
}
node.depth = depth
node.commitment = new(Point).SetIdentity()
return node
}
// New creates a new tree root
func New() VerkleNode {
return newInternalNode(0)
}
func NewStatelessInternal(depth byte, comm *Point) VerkleNode {
node := &InternalNode{
children: make([]VerkleNode, NodeWidth),
depth: depth,
commitment: comm,
}
for idx := range node.children {
node.children[idx] = UnknownNode(struct{}{})
}
return node
}
// New creates a new leaf node
func NewLeafNode(stem Stem, values [][]byte) (*LeafNode, error) {
cfg := GetConfig()
// C1.
var c1poly [NodeWidth]Fr
var c1 *Point
count, err := fillSuffixTreePoly(c1poly[:], values[:NodeWidth/2])
if err != nil {
return nil, err
}
containsEmptyCodeHash := c1poly[EmptyCodeHashFirstHalfIdx].Equal(&EmptyCodeHashFirstHalfValue) &&
c1poly[EmptyCodeHashSecondHalfIdx].Equal(&EmptyCodeHashSecondHalfValue)
if containsEmptyCodeHash {
// Clear out values of the cached point.
c1poly[EmptyCodeHashFirstHalfIdx] = FrZero
c1poly[EmptyCodeHashSecondHalfIdx] = FrZero
// Calculate the remaining part of c1 and add to the base value.
partialc1 := cfg.CommitToPoly(c1poly[:], NodeWidth-count-2)
c1 = new(Point)
c1.Add(&EmptyCodeHashPoint, partialc1)
} else {
c1 = cfg.CommitToPoly(c1poly[:], NodeWidth-count)
}
// C2.
var c2poly [NodeWidth]Fr
count, err = fillSuffixTreePoly(c2poly[:], values[NodeWidth/2:])
if err != nil {
return nil, err
}
c2 := cfg.CommitToPoly(c2poly[:], NodeWidth-count)
// Root commitment preparation for calculation.
stem = stem[:StemSize] // enforce a 31-byte length
var poly [NodeWidth]Fr
poly[0].SetUint64(1)
if err := StemFromLEBytes(&poly[1], stem); err != nil {
return nil, err
}
if err := banderwagon.BatchMapToScalarField([]*Fr{&poly[2], &poly[3]}, []*Point{c1, c2}); err != nil {
return nil, fmt.Errorf("batch mapping to scalar fields: %s", err)
}
return &LeafNode{
// depth will be 0, but the commitment calculation
// does not need it, and so it won't be free.
values: values,
stem: stem,
commitment: cfg.CommitToPoly(poly[:], NodeWidth-4),
c1: c1,
c2: c2,
}, nil
}
// NewLeafNodeWithNoComms create a leaf node but does not compute its
// commitments. The created node's commitments are intended to be
// initialized with `SetTrustedBytes` in a deserialization context.
func NewLeafNodeWithNoComms(stem Stem, values [][]byte) *LeafNode {
return &LeafNode{
// depth will be 0, but the commitment calculation
// does not need it, and so it won't be free.
values: values,
stem: stem,
}
}
// Children return the children of the node. The returned slice is
// internal to the tree, so callers *must* consider it readonly.
func (n *InternalNode) Children() []VerkleNode {
return n.children
}
// SetChild *replaces* the child at the given index with the given node.
func (n *InternalNode) SetChild(i int, c VerkleNode) error {
if i >= NodeWidth {
return errors.New("child index higher than node width")
}
n.children[i] = c
return nil
}
func (n *InternalNode) cowChild(index byte) {
if n.cow == nil {
n.cow = make(map[byte]*Point)
}
if n.cow[index] == nil {
n.cow[index] = new(Point)
n.cow[index].Set(n.children[index].Commitment())
}
}
func (n *InternalNode) Insert(key []byte, value []byte, resolver NodeResolverFn) error {
values := make([][]byte, NodeWidth)
values[key[StemSize]] = value
return n.InsertValuesAtStem(KeyToStem(key), values, resolver)
}
func (n *InternalNode) InsertValuesAtStem(stem Stem, values [][]byte, resolver NodeResolverFn) error {
nChild := offset2key(stem, n.depth) // index of the child pointed by the next byte in the key
switch child := n.children[nChild].(type) {
case UnknownNode:
return errMissingNodeInStateless
case Empty:
n.cowChild(nChild)
var err error
n.children[nChild], err = NewLeafNode(stem, values)
if err != nil {
return err
}
n.children[nChild].setDepth(n.depth + 1)
case HashedNode:
if resolver == nil {
return errInsertIntoHash
}
serialized, err := resolver(stem[:n.depth+1])
if err != nil {
return fmt.Errorf("verkle tree: error resolving node %x at depth %d: %w", stem, n.depth, err)
}
resolved, err := ParseNode(serialized, n.depth+1)
if err != nil {
return fmt.Errorf("verkle tree: error parsing resolved node %x: %w", stem, err)
}
n.children[nChild] = resolved
n.cowChild(nChild)
// recurse to handle the case of a LeafNode child that
// splits.
return n.InsertValuesAtStem(stem, values, resolver)
case *LeafNode:
if equalPaths(child.stem, stem) {
// We can't insert any values into a POA leaf node.
if child.isPOAStub {
return errIsPOAStub
}
n.cowChild(nChild)
return child.insertMultiple(stem, values)
}
n.cowChild(nChild)
// A new branch node has to be inserted. Depending
// on the next word in both keys, a recursion into
// the moved leaf node can occur.
nextWordInExistingKey := offset2key(child.stem, n.depth+1)
newBranch := newInternalNode(n.depth + 1).(*InternalNode)
newBranch.cowChild(nextWordInExistingKey)
n.children[nChild] = newBranch
newBranch.children[nextWordInExistingKey] = child
child.depth += 1
nextWordInInsertedKey := offset2key(stem, n.depth+1)
if nextWordInInsertedKey == nextWordInExistingKey {
return newBranch.InsertValuesAtStem(stem, values, resolver)
}
// Next word differs, so this was the last level.
// Insert it directly into its final slot.
leaf, err := NewLeafNode(stem, values)
if err != nil {
return err
}
leaf.setDepth(n.depth + 2)
newBranch.cowChild(nextWordInInsertedKey)
newBranch.children[nextWordInInsertedKey] = leaf
case *InternalNode:
n.cowChild(nChild)
return child.InsertValuesAtStem(stem, values, resolver)
default: // It should be an UknownNode.
return errUnknownNodeType
}
return nil
}
// CreatePath inserts a given stem in the tree, placing it as
// described by stemInfo. Its third parameters is the list of
// commitments that have not been assigned a node. It returns
// the same list, save the commitments that were consumed
// during this call.
func (n *InternalNode) CreatePath(path []byte, stemInfo stemInfo, comms []*Point, values [][]byte) ([]*Point, error) { // skipcq: GO-R1005
if len(path) == 0 {
return comms, errors.New("invalid path")
}
// path is 1 byte long, the leaf node must be created
if len(path) == 1 {
switch stemInfo.stemType & 3 {
case extStatusAbsentEmpty:
// Set child to Empty so that, in a stateless context,
// a node known to be absent is differentiated from an
// unknown node.
n.children[path[0]] = Empty{}
case extStatusAbsentOther:
if len(comms) == 0 {
return comms, fmt.Errorf("missing commitment for stem %x", stemInfo.stem)
}
if len(stemInfo.stem) != StemSize {
return comms, fmt.Errorf("invalid stem size %d", len(stemInfo.stem))
}
// insert poa stem
newchild := &LeafNode{
commitment: comms[0],
stem: stemInfo.stem,
values: nil,
depth: n.depth + 1,
isPOAStub: true,
}
n.children[path[0]] = newchild
comms = comms[1:]
case extStatusPresent:
if len(comms) == 0 {
return comms, fmt.Errorf("missing commitment for stem %x", stemInfo.stem)
}
if len(stemInfo.stem) != StemSize {
return comms, fmt.Errorf("invalid stem size %d", len(stemInfo.stem))
}
// insert stem
newchild := &LeafNode{
commitment: comms[0],
stem: stemInfo.stem,
values: values,
depth: n.depth + 1,
}
n.children[path[0]] = newchild
comms = comms[1:]
if stemInfo.has_c1 {
if len(comms) == 0 {
return comms, fmt.Errorf("missing commitment for stem %x", stemInfo.stem)
}
newchild.c1 = comms[0]
comms = comms[1:]
} else {
newchild.c1 = new(Point)
}
if stemInfo.has_c2 {
if len(comms) == 0 {
return comms, fmt.Errorf("missing commitment for stem %x", stemInfo.stem)
}
newchild.c2 = comms[0]
comms = comms[1:]
} else {
newchild.c2 = new(Point)
}
for b, value := range stemInfo.values {
newchild.values[b] = value
}
default:
return comms, fmt.Errorf("invalid stem type %d", stemInfo.stemType)
}
return comms, nil
}
switch child := n.children[path[0]].(type) {
case UnknownNode:
// create the child node if missing
n.children[path[0]] = NewStatelessInternal(n.depth+1, comms[0])
comms = comms[1:]
case *InternalNode:
// nothing else to do
case *LeafNode:
return comms, fmt.Errorf("error rebuilding the tree from a proof: stem %x leads to an already-existing leaf node at depth %x", stemInfo.stem, n.depth)
default:
return comms, fmt.Errorf("error rebuilding the tree from a proof: stem %x leads to an unsupported node type %v", stemInfo.stem, child)
}
// This should only be used in the context of
// stateless nodes, so panic if another node
// type is found.
child := n.children[path[0]].(*InternalNode)
// recurse
return child.CreatePath(path[1:], stemInfo, comms, values)
}
// GetValuesAtStem returns the all NodeWidth values of the stem.
// The returned slice is internal to the tree, so it *must* be considered readonly
// for callers.
func (n *InternalNode) GetValuesAtStem(stem Stem, resolver NodeResolverFn) ([][]byte, error) {
nchild := offset2key(stem, n.depth) // index of the child pointed by the next byte in the key
switch child := n.children[nchild].(type) {
case UnknownNode:
return nil, errMissingNodeInStateless
case Empty:
return nil, nil
case HashedNode:
if resolver == nil {
return nil, fmt.Errorf("hashed node %x at depth %d along stem %x could not be resolved: %w", child.Commitment().Bytes(), n.depth, stem, errReadFromInvalid)
}
serialized, err := resolver(stem[:n.depth+1])
if err != nil {
return nil, fmt.Errorf("resolving node %x at depth %d: %w", stem, n.depth, err)
}
resolved, err := ParseNode(serialized, n.depth+1)
if err != nil {
return nil, fmt.Errorf("verkle tree: error parsing resolved node %x: %w", stem, err)
}
n.children[nchild] = resolved
// recurse to handle the case of a LeafNode child that
// splits.
return n.GetValuesAtStem(stem, resolver)
case *LeafNode:
if equalPaths(child.stem, stem) {
// We can't return the values since it's a POA leaf node, so we know nothing
// about its values.
if child.isPOAStub {
return nil, errIsPOAStub
}
return child.values, nil
}
return nil, nil
case *InternalNode:
return child.GetValuesAtStem(stem, resolver)
default:
return nil, errUnknownNodeType
}
}
func (n *InternalNode) Delete(key []byte, resolver NodeResolverFn) (bool, error) {
nChild := offset2key(key, n.depth)
switch child := n.children[nChild].(type) {
case Empty:
return false, nil
case HashedNode:
if resolver == nil {
return false, errDeleteHash
}
payload, err := resolver(key[:n.depth+1])
if err != nil {
return false, err
}
// deserialize the payload and set it as the child
c, err := ParseNode(payload, n.depth+1)
if err != nil {
return false, err
}
n.children[nChild] = c
return n.Delete(key, resolver)
default:
n.cowChild(nChild)
del, err := child.Delete(key, resolver)
if err != nil {
return false, err
}
// delete the entire child if instructed to by
// the recursive algorigthm.
if del {
n.children[nChild] = Empty{}
// Check if all children are gone, if so
// signal that this node should be deleted
// as well.
for _, c := range n.children {
if _, ok := c.(Empty); !ok {
return false, nil
}
}
return true, nil
}
return false, nil
}
}
// DeleteAtStem delete a full stem. Unlike Delete, it will error out if the stem that is to
// be deleted does not exist in the tree, because it's meant to be used by rollback code,
// that should only delete things that exist.
func (n *InternalNode) DeleteAtStem(key []byte, resolver NodeResolverFn) (bool, error) {
nChild := offset2key(key, n.depth)
switch child := n.children[nChild].(type) {
case Empty:
return false, errDeleteMissing
case HashedNode:
if resolver == nil {
return false, errDeleteHash
}
payload, err := resolver(key[:n.depth+1])
if err != nil {
return false, err
}
// deserialize the payload and set it as the child
c, err := ParseNode(payload, n.depth+1)
if err != nil {
return false, err
}
n.children[nChild] = c
return n.DeleteAtStem(key, resolver)
case *LeafNode:
if !bytes.Equal(child.stem, key[:31]) {
return false, errDeleteMissing
}
n.cowChild(nChild)
n.children[nChild] = Empty{}
// Check if all children are gone, if so
// signal that this node should be deleted
// as well.
for _, c := range n.children {
if _, ok := c.(Empty); !ok {
return false, nil
}
}
return true, nil
case *InternalNode:
n.cowChild(nChild)
del, err := child.DeleteAtStem(key, resolver)
if err != nil {
return false, err
}
// delete the entire child if instructed to by
// the recursive algorigthm.
if del {
n.children[nChild] = Empty{}
// Check if all children are gone, if so
// signal that this node should be deleted
// as well.
for _, c := range n.children {
if _, ok := c.(Empty); !ok {
return false, nil
}
}
return true, nil
}
return false, nil
default:
// only unknown nodes are left
return false, errDeleteUnknown
}
}
// Flush hashes the children of an internal node and replaces them
// with HashedNode. It also sends the current node on the flush channel.
func (n *InternalNode) Flush(flush NodeFlushFn) {
//
var (
path []byte
flushAndCapturePath = func(p []byte, vn VerkleNode) {
// wrap the flush function into a function that will
// capture the path of the first leaf being flushed,
// so that it can be used as the path to call `flush`.
if len(path) == 0 {
path = p[:n.depth]
}
flush(p, vn)
}
)
n.Commit()
for i, child := range n.children {
if c, ok := child.(*InternalNode); ok {
c.Commit()
c.Flush(flushAndCapturePath)
n.children[i] = HashedNode{}
} else if c, ok := child.(*LeafNode); ok {
c.Commit()
flushAndCapturePath(c.stem[:n.depth+1], n.children[i])
n.children[i] = HashedNode{}
}
}
flush(path, n)
}
// FlushAtDepth goes over all internal nodes of a given depth, and
// flushes them to disk. Its purpose it to free up space if memory
// is running scarce.
func (n *InternalNode) FlushAtDepth(depth uint8, flush NodeFlushFn) {
for i, child := range n.children {
// Skip non-internal nodes
c, ok := child.(*InternalNode)
if !ok {
if c, ok := child.(*LeafNode); ok {
c.Commit()
flush(c.stem[:c.depth], c)
n.children[i] = HashedNode{}
}
continue
}
// Not deep enough, recurse
if n.depth < depth {
c.FlushAtDepth(depth, flush)
continue
}
child.Commit()
c.Flush(flush)
n.children[i] = HashedNode{}
}
}
func (n *InternalNode) Get(key []byte, resolver NodeResolverFn) ([]byte, error) {
if len(key) != StemSize+1 {
return nil, fmt.Errorf("invalid key length, expected %d, got %d", StemSize+1, len(key))
}
stemValues, err := n.GetValuesAtStem(KeyToStem(key), resolver)
if err != nil {
return nil, err
}
// If the stem results in an empty node, return nil.
if stemValues == nil {
return nil, nil
}
// Return nil as a signal that the value isn't
// present in the tree. This matches the behavior
// of SecureTrie in Geth.
return stemValues[key[StemSize]], nil
}
func (n *InternalNode) Hash() *Fr {
var hash Fr
n.Commitment().MapToScalarField(&hash)
return &hash
}
func (n *InternalNode) Commitment() *Point {
if n.commitment == nil {
panic("nil commitment")
}
return n.commitment
}
func (n *InternalNode) fillLevels(levels [][]*InternalNode) {
levels[int(n.depth)] = append(levels[int(n.depth)], n)
for idx := range n.cow {
child := n.children[idx]
if childInternalNode, ok := child.(*InternalNode); ok && len(childInternalNode.cow) > 0 {
childInternalNode.fillLevels(levels)
}
}
}
func (n *InternalNode) Commit() *Point {
if len(n.cow) == 0 {
return n.commitment
}
internalNodeLevels := make([][]*InternalNode, StemSize)
n.fillLevels(internalNodeLevels)
for level := len(internalNodeLevels) - 1; level >= 0; level-- {
nodes := internalNodeLevels[level]
if len(nodes) == 0 {
continue
}
minBatchSize := 4
if len(nodes) <= minBatchSize {
if err := commitNodesAtLevel(nodes); err != nil {
// TODO: make Commit() return an error
panic(err)
}
} else {
var wg sync.WaitGroup
numBatches := runtime.NumCPU()
batchSize := (len(nodes) + numBatches - 1) / numBatches
if batchSize < minBatchSize {
batchSize = minBatchSize
}
for i := 0; i < len(nodes); i += batchSize {
start := i
end := i + batchSize
if end > len(nodes) {
end = len(nodes)
}
wg.Add(1)
go func() {
defer wg.Done()
if err := commitNodesAtLevel(nodes[start:end]); err != nil {
// TODO: make Commit() return an error
panic(err)
}
}()
}
wg.Wait()
}
}
return n.commitment
}
func commitNodesAtLevel(nodes []*InternalNode) error {
points := make([]*Point, 0, 1024)
cowIndexes := make([]int, 0, 1024)
// For each internal node, we collect in `points` all the ones we need to map to a field element.
// That is, for each touched children in a node, we collect the old and new commitment to do the diff updating
// later.
for _, node := range nodes {
for idx, nodeChildComm := range node.cow {
points = append(points, nodeChildComm)
points = append(points, node.children[idx].Commitment())
cowIndexes = append(cowIndexes, int(idx))
}
}
// We generate `frs` which will contain the result for each element in `points`.
frs := make([]*Fr, len(points))
for i := range frs {
frs[i] = &Fr{}
}
// Do a single batch calculation for all the points in this level.
if err := banderwagon.BatchMapToScalarField(frs, points); err != nil {
return fmt.Errorf("batch mapping to scalar fields: %s", err)
}
// We calculate the difference between each (new commitment - old commitment) pair, and store it
// in the same slice to avoid allocations.
for i := 0; i < len(frs); i += 2 {
frs[i/2].Sub(frs[i+1], frs[i])
}
// Now `frs` have half of the elements, and these are the Frs differences to update commitments.
frs = frs[:len(frs)/2]
// Now we iterate on the nodes, and use this calculated differences to update their commitment.
var frsIdx int
var cowIndex int
for _, node := range nodes {
poly := make([]Fr, NodeWidth)
for i := 0; i < len(node.cow); i++ {
poly[cowIndexes[cowIndex]] = *frs[frsIdx]
frsIdx++
cowIndex++
}
node.cow = nil
node.commitment.Add(node.commitment, cfg.CommitToPoly(poly, 0))
}
return nil
}
// groupKeys groups a set of keys based on their byte at a given depth.
func groupKeys(keys keylist, depth byte) []keylist {
// special case: no key
if len(keys) == 0 {
return []keylist{}
}
// special case: only one key left
if len(keys) == 1 {
return []keylist{keys}
}
// there are at least two keys left in the list at this depth
groups := make([]keylist, 0, len(keys))
firstkey, lastkey := 0, 1
for ; lastkey < len(keys); lastkey++ {
key := keys[lastkey]
keyidx := offset2key(key, depth)
previdx := offset2key(keys[lastkey-1], depth)
if keyidx != previdx {
groups = append(groups, keys[firstkey:lastkey])
firstkey = lastkey
}
}
groups = append(groups, keys[firstkey:lastkey])
return groups
}
func (n *InternalNode) GetProofItems(keys keylist, resolver NodeResolverFn) (*ProofElements, []byte, []Stem, error) {
var (
groups = groupKeys(keys, n.depth)
pe = &ProofElements{
Cis: []*Point{},
Zis: []byte{},
Yis: []*Fr{}, // Should be 0
Fis: [][]Fr{},
ByPath: map[string]*Point{},
}
esses []byte = nil // list of extension statuses
poass []Stem // list of proof-of-absence stems
)
// fill in the polynomial for this node
var fi [NodeWidth]Fr
var fiPtrs [NodeWidth]*Fr
var points [NodeWidth]*Point
for i, child := range n.children {
fiPtrs[i] = &fi[i]
if child != nil {
var c VerkleNode
if _, ok := child.(HashedNode); ok {
childpath := make([]byte, n.depth+1)
copy(childpath[:n.depth+1], keys[0][:n.depth])
childpath[n.depth] = byte(i)
if resolver == nil {
return nil, nil, nil, fmt.Errorf("no resolver for path %x", childpath)
}
serialized, err := resolver(childpath)
if err != nil {
return nil, nil, nil, fmt.Errorf("error resolving for path %x: %w", childpath, err)
}
c, err = ParseNode(serialized, n.depth+1)
if err != nil {
return nil, nil, nil, err
}
n.children[i] = c
} else {
c = child
}
points[i] = c.Commitment()
} else {
// TODO: add a test case to cover this scenario.
points[i] = new(Point)
}
}
if err := banderwagon.BatchMapToScalarField(fiPtrs[:], points[:]); err != nil {
return nil, nil, nil, fmt.Errorf("batch mapping to scalar fields: %s", err)
}
for _, group := range groups {
childIdx := offset2key(group[0], n.depth)
// Build the list of elements for this level
var yi Fr
yi.Set(&fi[childIdx])
pe.Cis = append(pe.Cis, n.commitment)