-
Notifications
You must be signed in to change notification settings - Fork 67
/
tree_test.go
1882 lines (1638 loc) · 55.7 KB
/
tree_test.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"
"crypto/rand"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"io"
mRandV1 "math/rand"
mRand "math/rand/v2"
"reflect"
"runtime"
"sort"
"strings"
"testing"
"testing/quick"
"time"
"github.com/davecgh/go-spew/spew"
)
// a 32 byte value, as expected in the tree structure
var testValue = []byte("0123456789abcdef0123456789abcdef")
var (
zeroKeyTest, _ = hex.DecodeString("0000000000000000000000000000000000000000000000000000000000000000")
oneKeyTest, _ = hex.DecodeString("0000000000000000000000000000000000000000000000000000000000000001")
forkOneKeyTest, _ = hex.DecodeString("0001000000000000000000000000000000000000000000000000000000000001")
fourtyKeyTest, _ = hex.DecodeString("4000000000000000000000000000000000000000000000000000000000000000")
ffx32KeyTest, _ = hex.DecodeString("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
)
func TestInsertIntoRoot(t *testing.T) {
t.Parallel()
root := New()
if err := root.Insert(zeroKeyTest, testValue, nil); err != nil {
t.Fatalf("error inserting: %v", err)
}
leaf, ok := root.(*InternalNode).children[0].(*LeafNode)
if !ok {
t.Fatalf("invalid leaf node type %v", root.(*InternalNode).children[0])
}
if !bytes.Equal(leaf.values[zeroKeyTest[StemSize]], testValue) {
t.Fatalf("did not find correct value in trie %x != %x", testValue, leaf.values[zeroKeyTest[StemSize]])
}
}
func TestInsertTwoLeaves(t *testing.T) {
t.Parallel()
root := New()
if err := root.Insert(zeroKeyTest, testValue, nil); err != nil {
t.Fatalf("error inserting: %v", err)
}
if err := root.Insert(ffx32KeyTest, testValue, nil); err != nil {
t.Fatalf("error inserting: %v", err)
}
leaf0, ok := root.(*InternalNode).children[0].(*LeafNode)
if !ok {
t.Fatalf("invalid leaf node type %v", root.(*InternalNode).children[0])
}
leaff, ok := root.(*InternalNode).children[255].(*LeafNode)
if !ok {
t.Fatalf("invalid leaf node type %v", root.(*InternalNode).children[255])
}
if !bytes.Equal(leaf0.values[zeroKeyTest[StemSize]], testValue) {
t.Fatalf("did not find correct value in trie %x != %x", testValue, leaf0.values[zeroKeyTest[StemSize]])
}
if !bytes.Equal(leaff.values[255], testValue) {
t.Fatalf("did not find correct value in trie %x != %x", testValue, leaff.values[ffx32KeyTest[StemSize]])
}
}
func TestInsertTwoLeavesLastLevel(t *testing.T) {
t.Parallel()
root := New()
if err := root.Insert(zeroKeyTest, testValue, nil); err != nil {
t.Fatalf("error inserting: %v", err)
}
if err := root.Insert(oneKeyTest, testValue, nil); err != nil {
t.Fatalf("error inserting: %v", err)
}
leaf, ok := root.(*InternalNode).children[0].(*LeafNode)
if !ok {
t.Fatalf("invalid leaf node type %v", root.(*InternalNode).children[0])
}
if !bytes.Equal(leaf.values[1], testValue) {
t.Fatalf("did not find correct value in trie %x != %x", testValue, leaf.values[1])
}
if !bytes.Equal(leaf.values[0], testValue) {
t.Fatalf("did not find correct value in trie %x != %x", testValue, leaf.values[0])
}
}
func TestGetTwoLeaves(t *testing.T) {
t.Parallel()
root := New()
if err := root.Insert(zeroKeyTest, testValue, nil); err != nil {
t.Fatalf("error inserting: %v", err)
}
if err := root.Insert(ffx32KeyTest, testValue, nil); err != nil {
t.Fatalf("error inserting: %v", err)
}
val, err := root.Get(zeroKeyTest, nil)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(val, testValue) {
t.Fatalf("got a different value from the tree than expected %x != %x", val, testValue)
}
val, err = root.Get(oneKeyTest, nil)
if err != nil {
t.Fatalf("wrong error type, expected %v, got %v", nil, err)
}
if val != nil {
t.Fatalf("Get returned value %x for a non-existing key", val)
}
if val != nil {
t.Fatalf("got a different value from the tree than expected %x != nil", val)
}
}
func TestOffset2key8BitsWide(t *testing.T) {
t.Parallel()
key, _ := hex.DecodeString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")
for i := byte(0); i < KeySize; i++ {
childId := offset2key(key, i)
if childId != i {
t.Fatalf("error getting child number in key %d != %d", childId, i)
}
}
}
func TestFlush1kLeaves(t *testing.T) {
t.Parallel()
n := 1000
keys := randomKeysSorted(t, n)
flushCh := make(chan VerkleNode)
flush := func(_ []byte, node VerkleNode) {
flushCh <- node
}
go func() {
root := New()
for _, k := range keys {
if err := root.Insert(k, fourtyKeyTest, nil); err != nil {
panic(err)
}
}
root.(*InternalNode).Flush(flush)
close(flushCh)
}()
count := 0
leaves := 0
for n := range flushCh {
_, isLeaf := n.(*LeafNode)
_, isInternal := n.(*InternalNode)
if !isLeaf && !isInternal {
t.Fatal("invalid node type received, expected leaf")
}
if isLeaf {
leaves++
}
count++
}
if leaves != n {
t.Fatalf("number of flushed leaves incorrect. Expected %d got %d\n", n, leaves)
}
}
func TestCopy(t *testing.T) {
t.Parallel()
key1, _ := hex.DecodeString("0105000000000000000000000000000000000000000000000000000000000000")
key2, _ := hex.DecodeString("0107000000000000000000000000000000000000000000000000000000000000")
key3, _ := hex.DecodeString("0405000000000000000000000000000000000000000000000000000000000000")
tree := New()
if err := tree.Insert(key1, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
if err := tree.Insert(key2, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
tree.Commit()
copied := tree.Copy()
if err := tree.Insert(key3, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
if tree.Commit().Equal(copied.Commit()) {
t.Fatal("inserting the copy into the original tree updated the copy's commitment")
}
if err := copied.Insert(key3, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into the copy failed: %v", err)
}
if !tree.Commitment().Equal(copied.Commit()) {
t.Fatalf("differing final commitments %x != %x", tree.Commitment().Bytes(), copied.Commitment().Bytes())
}
}
func TestCachedCommitment(t *testing.T) {
t.Parallel()
key1, _ := hex.DecodeString("0105000000000000000000000000000000000000000000000000000000000000")
key2, _ := hex.DecodeString("0107000000000000000000000000000000000000000000000000000000000000")
key3, _ := hex.DecodeString("0405000000000000000000000000000000000000000000000000000000000000")
key4, _ := hex.DecodeString("0407000000000000000000000000000000000000000000000000000000000000")
tree := New()
if err := tree.Insert(key1, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
if err := tree.Insert(key2, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
if err := tree.Insert(key3, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
oldRoot := tree.Commit().Bytes()
oldInternal := tree.(*InternalNode).children[4].(*LeafNode).commitment.Bytes()
if tree.(*InternalNode).commitment == nil {
t.Error("root has not cached commitment")
}
if err := tree.Insert(key4, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into key4 failed: %v", err)
}
tree.Commit()
if tree.(*InternalNode).Commitment().Bytes() == oldRoot {
t.Error("root has stale commitment")
}
if tree.(*InternalNode).children[4].(*InternalNode).commitment.Bytes() == oldInternal {
t.Error("internal node has stale commitment")
}
if tree.(*InternalNode).children[1].(*InternalNode).commitment == nil {
t.Error("internal node has mistakenly cleared cached commitment")
}
}
func TestDelLeaf(t *testing.T) { // skipcq: GO-R1005
t.Parallel()
key1, _ := hex.DecodeString("0105000000000000000000000000000000000000000000000000000000000000")
key1p, _ := hex.DecodeString("0105000000000000000000000000000000000000000000000000000000000001") // same Cn group as key1
key1pp, _ := hex.DecodeString("0105000000000000000000000000000000000000000000000000000000000081") // Other Cn group as key1
key2, _ := hex.DecodeString("0107000000000000000000000000000000000000000000000000000000000000")
key3, _ := hex.DecodeString("0405000000000000000000000000000000000000000000000000000000000000")
tree := New()
if err := tree.Insert(key1, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
if err := tree.Insert(key1p, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
if err := tree.Insert(key1pp, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
if err := tree.Insert(key2, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
var init Point
init.Set(tree.Commit())
if err := tree.Insert(key3, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
if _, err := tree.Delete(key3, nil); err != nil {
t.Error(err)
}
// the pre and post deletion hashes should be different,
// as deleting a value means replacing it with a 0 in verkle
// trees.
postHash := tree.Commit()
if !init.Equal(postHash) {
t.Errorf("deleting leaf resulted in unexpected tree %x %x", init.Bytes(), postHash.Bytes())
}
res, err := tree.Get(key3, nil)
if err != nil {
t.Error(err)
}
if len(res) > 0 {
t.Error("leaf hasnt been deleted")
}
if _, err := tree.Delete(key1pp, nil); err != nil {
t.Fatal(err)
}
res, err = tree.Get(key1pp, nil)
if err != nil {
t.Error(err)
}
if len(res) > 0 {
t.Error("leaf hasnt been deleted")
}
if _, err := tree.Delete(key1p, nil); err != nil {
t.Fatal(err)
}
res, err = tree.Get(key1p, nil)
if err != nil {
t.Error(err)
}
if len(res) > 0 {
t.Error("leaf hasnt been deleted")
}
}
func TestDeleteAtStem(t *testing.T) {
t.Parallel()
key1, _ := hex.DecodeString("0105000000000000000000000000000000000000000000000000000000000000")
key1p, _ := hex.DecodeString("0105000000000000000000000000000000000000000000000000000000000001") // same Cn group as key1
key1pp, _ := hex.DecodeString("0105000000000000000000000000000000000000000000000000000000000081") // Other Cn group as key1
key2, _ := hex.DecodeString("0107000000000000000000000000000000000000000000000000000000000000")
tree := New()
if err := tree.Insert(key1, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
if err := tree.Insert(key1p, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
if err := tree.Insert(key1pp, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
if err := tree.Insert(key2, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
var init Point
init.Set(tree.Commit())
if _, err := tree.(*InternalNode).DeleteAtStem(key1[:31], nil); err != err {
t.Error(err)
}
res, err := tree.Get(key1, nil)
if err != nil {
t.Error(err)
}
if len(res) > 0 {
t.Error("leaf hasnt been deleted")
}
res, err = tree.Get(key1pp, nil)
if err != nil {
t.Error(err)
}
if len(res) > 0 {
t.Error("leaf hasnt been deleted")
}
if _, err := tree.(*InternalNode).DeleteAtStem(zeroKeyTest[:31], nil); err != errDeleteMissing {
t.Fatal(err)
}
}
func TestDeleteNonExistent(t *testing.T) {
t.Parallel()
key1, _ := hex.DecodeString("0105000000000000000000000000000000000000000000000000000000000000")
key2, _ := hex.DecodeString("0107000000000000000000000000000000000000000000000000000000000000")
key3, _ := hex.DecodeString("0405000000000000000000000000000000000000000000000000000000000000")
tree := New()
if err := tree.Insert(key1, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into key1 failed: %v", err)
}
if err := tree.Insert(key2, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into key2 failed: %v", err)
}
if _, err := tree.Delete(key3, nil); err != nil {
t.Error("should not fail when deleting a non-existent key")
}
}
func TestDeletePrune(t *testing.T) { // skipcq: GO-R1005
t.Parallel()
key1, _ := hex.DecodeString("0105000000000000000000000000000000000000000000000000000000000000")
key2, _ := hex.DecodeString("0107000000000000000000000000000000000000000000000000000000000000")
key3, _ := hex.DecodeString("0405000000000000000000000000000000000000000000000000000000000000")
key4, _ := hex.DecodeString("0407000000000000000000000000000000000000000000000000000000000000")
key5, _ := hex.DecodeString("04070000000000000000000000000000000000000000000000000000000000FF")
tree := New()
if err := tree.Insert(key1, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into key1 failed: %v", err)
}
if err := tree.Insert(key2, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into key2 failed: %v", err)
}
var hashPostKey2, hashPostKey4, completeTreeHash Point
hashPostKey2.Set(tree.Commit())
if err := tree.Insert(key3, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into key3 failed: %v", err)
}
if err := tree.Insert(key4, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into key4 failed: %v", err)
}
hashPostKey4.Set(tree.Commit())
if err := tree.Insert(key5, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into key5 failed: %v", err)
}
completeTreeHash.Set(tree.Commit()) // hash when the tree has received all its keys
// Delete key5.
if _, err := tree.Delete(key5, nil); err != nil {
t.Error(err)
}
postHash := tree.Commit()
// Check that the deletion updated the root hash and that it's not
// the same as the pre-deletion hash.
if completeTreeHash.Equal(postHash) {
t.Fatalf("deletion did not update the hash %x == %x", completeTreeHash, postHash)
}
// The post deletion hash should be the same as the post key4 hash.
if !hashPostKey4.Equal(postHash) {
t.Error("deleting leaf #5 resulted in unexpected tree")
}
res, err := tree.Get(key5, nil)
if err != nil {
t.Error(err)
}
if len(res) > 0 {
t.Error("leaf #5 hasn't been deleted")
}
// Delete key4 and key3.
if _, err := tree.Delete(key4, nil); err != nil {
t.Error(err)
}
if _, err := tree.Delete(key3, nil); err != nil {
t.Error(err)
}
postHash = tree.Commit()
// The post deletion hash should be different from the post key2 hash.
if !hashPostKey2.Equal(postHash) {
t.Error("deleting leaf #3 resulted in unexpected tree")
}
res, err = tree.Get(key3, nil)
if err != nil {
t.Error(err)
}
if len(res) > 0 {
t.Error("leaf hasnt been deleted")
}
}
// A test that inserts 3 keys in a tree, and then replaces two of them with
// their hashed values. It then tries to delete the hashed values, which should
// fail.
func TestDeleteHash(t *testing.T) {
//TODO: fix this test when we take a final decision about FlushAtDepth API.
t.SkipNow()
key1, _ := hex.DecodeString("0105000000000000000000000000000000000000000000000000000000000000")
key2, _ := hex.DecodeString("0107000000000000000000000000000000000000000000000000000000000000")
key3, _ := hex.DecodeString("0405000000000000000000000000000000000000000000000000000000000000")
tree := New()
if err := tree.Insert(key1, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into key1 failed: %v", err)
}
if err := tree.Insert(key2, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into key2 failed: %v", err)
}
if err := tree.Insert(key3, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into key3 failed: %v", err)
}
tree.(*InternalNode).FlushAtDepth(0, func(path []byte, vn VerkleNode) {})
tree.Commit()
if _, err := tree.Delete(key2, nil); err != errDeleteHash {
t.Fatalf("did not report the correct error while deleting from a hash: %v", err)
}
}
func TestDeleteUnequalPath(t *testing.T) {
t.Parallel()
key1, _ := hex.DecodeString("0105000000000000000000000000000000000000000000000000000000000000")
key2, _ := hex.DecodeString("0107000000000000000000000000000000000000000000000000000000000000")
key3, _ := hex.DecodeString("0405000000000000000000000000000000000000000000000000000000000000")
tree := New()
if err := tree.Insert(key1, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into key1 failed: %v", err)
}
if err := tree.Insert(key3, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into key3 failed: %v", err)
}
tree.Commit()
if _, err := tree.Delete(key2, nil); err != nil {
t.Fatalf("errored during the deletion of non-existing key, err =%v", err)
}
}
func TestDeleteResolve(t *testing.T) {
//TODO: fix this test when we take a final decision about FlushAtDepth API.
t.SkipNow()
key1, _ := hex.DecodeString("0105000000000000000000000000000000000000000000000000000000000000")
key2, _ := hex.DecodeString("0107000000000000000000000000000000000000000000000000000000000000")
key3, _ := hex.DecodeString("0405000000000000000000000000000000000000000000000000000000000000")
tree := New()
savedNodes := make(map[string]VerkleNode)
saveNode := func(path []byte, node VerkleNode) {
savedNodes[string(path)] = node
}
if err := tree.Insert(key1, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into key1 failed: %v", err)
}
if err := tree.Insert(key2, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into key2 failed: %v", err)
}
if err := tree.Insert(key3, fourtyKeyTest, nil); err != nil {
t.Fatalf("inserting into key3 failed: %v", err)
}
tree.(*InternalNode).FlushAtDepth(0, saveNode)
tree.Commit()
var called bool
_, err := tree.Delete(key2, func(path []byte) ([]byte, error) {
called = true
if node, ok := savedNodes[string(path)]; ok {
return node.Serialize()
}
t.Fatal("could not find node")
return nil, fmt.Errorf("node not found")
})
if !called {
t.Fatal("should have called the resolve function")
}
if err != nil {
t.Fatalf("error deleting key: %v", err)
}
}
func TestConcurrentTrees(t *testing.T) {
t.Parallel()
tree := New()
err := tree.Insert(zeroKeyTest, fourtyKeyTest, nil)
if err != nil {
t.Fatal(err)
}
expected := tree.Commit()
threads := 2
ch := make(chan *Point)
builder := func() {
tree := New()
if err := tree.Insert(zeroKeyTest, fourtyKeyTest, nil); err != nil {
panic(err)
}
ch <- tree.Commit()
}
for i := 0; i < threads; i++ {
go builder()
}
for i := 0; i < threads; i++ {
root := <-ch
if !root.Equal(expected) {
t.Error("Incorrect root")
}
}
}
func BenchmarkCommitLeaves(b *testing.B) {
benchmarkCommitNLeaves(b, 1000)
benchmarkCommitNLeaves(b, 10000)
}
func BenchmarkCommitFullNode(b *testing.B) {
nChildren := 256
keys := make([][]byte, nChildren)
for i := 0; i < nChildren; i++ {
key := make([]byte, KeySize)
key[0] = uint8(i)
keys[i] = key
}
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
root := New()
for _, k := range keys {
if err := root.Insert(k, fourtyKeyTest, nil); err != nil {
b.Fatal(err)
}
}
root.Commit()
}
}
func benchmarkCommitNLeaves(b *testing.B, n int) {
type kv struct {
k []byte
v []byte
}
kvs := make([]kv, n)
sortedKVs := make([]kv, n)
for i := 0; i < n; i++ {
key := make([]byte, KeySize)
val := make([]byte, KeySize)
if _, err := rand.Read(key); err != nil {
b.Fatalf("failed to generate random key: %v", err)
}
if _, err := rand.Read(val); err != nil {
b.Fatalf("failed to generate random value: %v", err)
}
kvs[i] = kv{k: key, v: val}
sortedKVs[i] = kv{k: key, v: val}
}
// InsertOrder assumes keys are sorted
sortKVs := func(src []kv) {
sort.Slice(src, func(i, j int) bool { return bytes.Compare(src[i].k, src[j].k) < 0 })
}
sortKVs(sortedKVs)
b.Run(fmt.Sprintf("insert/leaves/%d", n), func(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
root := New()
for _, el := range kvs {
if err := root.Insert(el.k, el.v, nil); err != nil {
b.Error(err)
}
}
root.Commit()
}
})
}
func BenchmarkModifyLeaves(b *testing.B) {
n := 200000
toEdit := 10000
val := []byte{0}
keys := make([][]byte, n)
root := New()
for i := 0; i < n; i++ {
key := make([]byte, KeySize)
if _, err := rand.Read(key); err != nil {
b.Fatalf("failed to generate random key: %v", err)
}
keys[i] = key
if err := root.Insert(key, val, nil); err != nil {
b.Fatalf("inserting into key1 failed: %v", err)
}
}
root.Commit()
b.ResetTimer()
b.ReportAllocs()
val = make([]byte, 4)
for i := 0; i < b.N; i++ {
binary.BigEndian.PutUint32(val, uint32(i))
for j := 0; j < toEdit; j++ {
k := keys[mRand.IntN(n)]
if err := root.Insert(k, val, nil); err != nil {
b.Error(err)
}
}
root.Commit()
}
}
func randomKeys(t *testing.T, n int) [][]byte {
keys := make([][]byte, n)
for i := 0; i < n; i++ {
key := make([]byte, KeySize)
if _, err := rand.Read(key); err != nil {
t.Fatalf("failed to generate random key: %v", err)
}
keys[i] = key
}
return keys
}
func randomKeysSorted(t *testing.T, n int) [][]byte {
keys := randomKeys(t, n)
sort.Slice(keys, func(i, j int) bool { return bytes.Compare(keys[i], keys[j]) < 0 })
return keys
}
func TestNodeSerde(t *testing.T) {
t.Parallel()
tree := New()
if err := tree.Insert(zeroKeyTest, testValue, nil); err != nil {
t.Fatalf("inserting into key1 failed: %v", err)
}
if err := tree.Insert(fourtyKeyTest, testValue, nil); err != nil {
t.Fatalf("inserting into key2 failed: %v", err)
}
origComm := tree.Commit().BytesUncompressedTrusted()
root := tree.(*InternalNode)
// Serialize all the nodes
leaf0 := (root.children[0]).(*LeafNode)
ls0, err := leaf0.Serialize()
if err != nil {
t.Error(err)
}
leaf64 := (root.children[64]).(*LeafNode)
ls64, err := leaf64.Serialize()
if err != nil {
t.Error(err)
}
rs, err := root.Serialize()
if err != nil {
t.Error(err)
}
// Now deserialize and re-construct tree
res, err := ParseNode(ls0, 1)
if err != nil {
t.Fatal(err)
}
resLeaf0 := res.(*LeafNode)
res, err = ParseNode(ls64, 1)
if err != nil {
t.Fatal(err)
}
resLeaf64 := res.(*LeafNode)
res, err = ParseNode(rs, 0)
if err != nil {
t.Fatal(err)
}
resRoot := res.(*InternalNode)
resRoot.children[0] = resLeaf0
resRoot.children[64] = resLeaf64
if !isInternalEqual(root, resRoot) {
t.Fatalf("parsed node not equal, %x != %x", root.commitment.BytesUncompressedTrusted(), resRoot.commitment.BytesUncompressedTrusted())
}
if resRoot.Commitment().BytesUncompressedTrusted() != origComm {
t.Fatal("invalid deserialized commitment")
}
}
func isInternalEqual(a, b *InternalNode) bool {
for i := 0; i < NodeWidth; i++ {
c := a.children[i]
switch c.(type) {
case Empty:
if _, ok := b.children[i].(Empty); !ok {
return false
}
case HashedNode:
if _, ok := b.children[i].(HashedNode); !ok {
return false
}
case *LeafNode:
ln, ok := b.children[i].(*LeafNode)
if !ok {
return false
}
if !isLeafEqual(c.(*LeafNode), ln) {
return false
}
case *InternalNode:
in, ok := b.children[i].(*InternalNode)
if !ok {
return false
}
if !isInternalEqual(c.(*InternalNode), in) {
return false
}
}
}
return true
}
func isLeafEqual(a, b *LeafNode) bool {
if !bytes.Equal(a.stem, b.stem) {
return false
}
for i, v := range a.values {
if !bytes.Equal(v, b.values[i]) {
return false
}
}
return true
}
func TestGetResolveFromHash(t *testing.T) {
//TODO: fix this test when we take a final decision about FlushAtDepth API.
t.SkipNow()
var count uint
dummyError := errors.New("dummy")
var serialized []byte
getter := func([]byte) ([]byte, error) {
count++
return serialized, nil
}
failingGetter := func([]byte) ([]byte, error) {
return nil, dummyError
}
flush := func(_ []byte, n VerkleNode) {
s, err := n.Serialize()
if err != nil {
panic(err)
}
serialized = append(serialized, s...)
}
root := New()
if err := root.Insert(zeroKeyTest, zeroKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
if err := root.Insert(fourtyKeyTest, zeroKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
root.(*InternalNode).FlushAtDepth(0, flush)
if err := root.Insert(oneKeyTest, zeroKeyTest, nil); err != errInsertIntoHash {
t.Fatal(err)
}
data, err := root.Get(zeroKeyTest, nil)
if !errors.Is(err, errReadFromInvalid) || len(data) != 0 {
t.Fatal(err)
}
data, err = root.Get(zeroKeyTest, failingGetter)
if !errors.Is(err, dummyError) || len(data) != 0 {
t.Fatal(err)
}
data, err = root.Get(zeroKeyTest, getter)
if err != nil {
t.Fatalf("error resolving hash: %v", err)
}
if count != 1 {
t.Fatalf("error getting the correct number of nodes: 1 != %d", count)
}
if !bytes.Equal(data, zeroKeyTest) {
t.Fatalf("invalid result: %x != %x", zeroKeyTest, len(data))
}
if hsh := root.Hash(); hsh == nil {
t.Fatalf("root hash can't be nil")
}
}
func TestGetKey(t *testing.T) {
t.Parallel()
root := &LeafNode{stem: fourtyKeyTest}
for i := 0; i < NodeWidth; i++ {
k := root.Key(i)
if !bytes.Equal(KeyToStem(k), KeyToStem(fourtyKeyTest)) {
t.Fatal("invalid stem")
}
if int(k[StemSize]) != i {
t.Fatal("invalid selector")
}
}
}
func TestInsertIntoHashedNode(t *testing.T) {
//TODO: fix this test when we take a final decision about FlushAtDepth API.
t.SkipNow()
root := New()
if err := root.Insert(zeroKeyTest, zeroKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
root.(*InternalNode).FlushAtDepth(0, func(_ []byte, n VerkleNode) {})
if err := root.Insert(fourtyKeyTest, zeroKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
if err := root.Insert(zeroKeyTest, zeroKeyTest, nil); err != errInsertIntoHash {
t.Fatalf("incorrect error type: %v", err)
}
resolver := func(h []byte) ([]byte, error) {
values := make([][]byte, NodeWidth)
values[0] = zeroKeyTest
node, _ := NewLeafNode(KeyToStem(zeroKeyTest), values)
return node.Serialize()
}
if err := root.Copy().Insert(zeroKeyTest, zeroKeyTest, resolver); err != nil {
t.Fatalf("error in node resolution: %v", err)
}
// Check that the proper error is raised if the RLP data is invalid and the
// node can not be parsed.
invalidRLPResolver := func(h []byte) ([]byte, error) {
values := make([][]byte, NodeWidth)
values[0] = zeroKeyTest
node, _ := NewLeafNode(KeyToStem(zeroKeyTest), values)
rlp, _ := node.Serialize()
return rlp[:len(rlp)-10], nil
}
if err := root.Copy().Insert(zeroKeyTest, zeroKeyTest, invalidRLPResolver); !errors.Is(err, errSerializedPayloadTooShort) {
t.Fatalf("error detecting a decoding error after resolution: %v", err)
}
randomResolverError := errors.New("'clef' was mispronounced")
// Check that the proper error is raised if the resolver returns an error
erroringResolver := func(h []byte) ([]byte, error) {
return nil, randomResolverError
}
if err := root.Copy().Insert(zeroKeyTest, zeroKeyTest, erroringResolver); !errors.Is(err, randomResolverError) {
t.Fatalf("error detecting a resolution error: %v", err)
}
}
func TestToDot(t *testing.T) {
root := New()
if err := root.Insert(zeroKeyTest, zeroKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
// TODO fix the issue with FlushAtDepth so that we can also try to verify the display of hashed nodes
// root.(*InternalNode).FlushAtDepth(0, func(_ []byte, n VerkleNode) {}) // Hash the leaf to ensure HashedNodes display correctly
if err := root.Insert(fourtyKeyTest, zeroKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
fourtytwoKeyTest, _ := hex.DecodeString("4020000000000000000000000000000000000000000000000000000000000000")
if err := root.Insert(fourtytwoKeyTest, zeroKeyTest, nil); err != nil {
t.Fatalf("inserting into the original failed: %v", err)
}
fmt.Println(ToDot(root))
// ensure the ToDot output contains a single HashedNode
// TODO see other TODO above
// if !strings.Contains(ToDot(root), "hash00") {
// t.Error("ToDot output does not contain a HashedNode")