-
Notifications
You must be signed in to change notification settings - Fork 16
/
map_debug.go
1464 lines (1214 loc) · 43.3 KB
/
map_debug.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
/*
* Atree - Scalable Arrays and Ordered Maps
*
* Copyright Flow Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package atree
import (
"bytes"
"errors"
"fmt"
"reflect"
"sort"
"strings"
"github.com/fxamacker/cbor/v2"
)
type MapStats struct {
Levels uint64
ElementCount uint64
MetaDataSlabCount uint64
DataSlabCount uint64
CollisionDataSlabCount uint64
StorableSlabCount uint64
}
func (s *MapStats) SlabCount() uint64 {
return s.DataSlabCount + s.MetaDataSlabCount + s.CollisionDataSlabCount + s.StorableSlabCount
}
// GetMapStats returns stats about the map slabs.
func GetMapStats(m *OrderedMap) (MapStats, error) {
level := uint64(0)
metaDataSlabCount := uint64(0)
dataSlabCount := uint64(0)
collisionDataSlabCount := uint64(0)
storableDataSlabCount := uint64(0)
nextLevelIDs := []SlabID{m.SlabID()}
for len(nextLevelIDs) > 0 {
ids := nextLevelIDs
nextLevelIDs = []SlabID(nil)
for _, id := range ids {
slab, err := getMapSlab(m.Storage, id)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by getMapSlab().
return MapStats{}, err
}
switch slab := slab.(type) {
case *MapDataSlab:
dataSlabCount++
elementGroups := []elements{slab.elements}
for len(elementGroups) > 0 {
var nestedElementGroups []elements
for _, group := range elementGroups {
for i := 0; i < int(group.Count()); i++ {
elem, err := group.Element(i)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by elements.Element().
return MapStats{}, err
}
switch e := elem.(type) {
case elementGroup:
nestedGroup := e
if !nestedGroup.Inline() {
collisionDataSlabCount++
}
nested, err := nestedGroup.Elements(m.Storage)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by elementGroup.Elements().
return MapStats{}, err
}
nestedElementGroups = append(nestedElementGroups, nested)
case *singleElement:
if _, ok := e.key.(SlabIDStorable); ok {
storableDataSlabCount++
}
if _, ok := e.value.(SlabIDStorable); ok {
storableDataSlabCount++
}
// This handles use case of inlined array or map value containing SlabID
ids := getSlabIDFromStorable(e.value, nil)
storableDataSlabCount += uint64(len(ids))
}
}
}
elementGroups = nestedElementGroups
}
case *MapMetaDataSlab:
metaDataSlabCount++
for _, storable := range slab.ChildStorables() {
id, ok := storable.(SlabIDStorable)
if !ok {
return MapStats{}, NewFatalError(fmt.Errorf("metadata slab's child storables are not of type SlabIDStorable"))
}
nextLevelIDs = append(nextLevelIDs, SlabID(id))
}
}
}
level++
}
return MapStats{
Levels: level,
ElementCount: m.Count(),
MetaDataSlabCount: metaDataSlabCount,
DataSlabCount: dataSlabCount,
CollisionDataSlabCount: collisionDataSlabCount,
StorableSlabCount: storableDataSlabCount,
}, nil
}
func PrintMap(m *OrderedMap) {
dumps, err := DumpMapSlabs(m)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(strings.Join(dumps, "\n"))
}
func DumpMapSlabs(m *OrderedMap) ([]string, error) {
var dumps []string
nextLevelIDs := []SlabID{m.SlabID()}
var overflowIDs []SlabID
var collisionSlabIDs []SlabID
level := 0
for len(nextLevelIDs) > 0 {
ids := nextLevelIDs
nextLevelIDs = []SlabID(nil)
for _, id := range ids {
slab, err := getMapSlab(m.Storage, id)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by getMapSlab().
return nil, err
}
switch slab := slab.(type) {
case *MapDataSlab:
dumps = append(dumps, fmt.Sprintf("level %d, %s", level+1, slab))
for i := 0; i < int(slab.elements.Count()); i++ {
elem, err := slab.elements.Element(i)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by elements.Element().
return nil, err
}
if group, ok := elem.(elementGroup); ok {
if !group.Inline() {
extSlab := group.(*externalCollisionGroup)
collisionSlabIDs = append(collisionSlabIDs, extSlab.slabID)
}
}
}
overflowIDs = getSlabIDFromStorable(slab, overflowIDs)
case *MapMetaDataSlab:
dumps = append(dumps, fmt.Sprintf("level %d, %s", level+1, slab))
for _, storable := range slab.ChildStorables() {
id, ok := storable.(SlabIDStorable)
if !ok {
return nil, NewFatalError(errors.New("metadata slab's child storables are not of type SlabIDStorable"))
}
nextLevelIDs = append(nextLevelIDs, SlabID(id))
}
}
}
level++
}
for _, id := range collisionSlabIDs {
slab, err := getMapSlab(m.Storage, id)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by getMapSlab().
return nil, err
}
dumps = append(dumps, fmt.Sprintf("collision: %s", slab.String()))
}
// overflowIDs include collisionSlabIDs
for _, id := range overflowIDs {
found := false
for _, cid := range collisionSlabIDs {
if id == cid {
found = true
break
}
}
if found {
continue
}
slab, found, err := m.Storage.Retrieve(id)
if err != nil {
// Wrap err as external error (if needed) because err is returned by SlabStorage interface.
return nil, wrapErrorfAsExternalErrorIfNeeded(err, fmt.Sprintf("failed to retrieve slab %s", id))
}
if !found {
return nil, NewSlabNotFoundErrorf(id, "slab not found during map slab dump")
}
dumps = append(dumps, slab.String())
}
return dumps, nil
}
func VerifyMap(m *OrderedMap, address Address, typeInfo TypeInfo, tic TypeInfoComparator, hip HashInputProvider, inlineEnabled bool) error {
return verifyMap(m, address, typeInfo, tic, hip, inlineEnabled, map[SlabID]struct{}{})
}
func verifyMap(m *OrderedMap, address Address, typeInfo TypeInfo, tic TypeInfoComparator, hip HashInputProvider, inlineEnabled bool, slabIDs map[SlabID]struct{}) error {
// Verify map address (independent of array inlined status)
if address != m.Address() {
return NewFatalError(fmt.Errorf("map address %v, got %v", address, m.Address()))
}
// Verify map value ID (independent of array inlined status)
err := verifyMapValueID(m)
if err != nil {
return err
}
// Verify map slab ID (dependent of array inlined status)
err = verifyMapSlabID(m)
if err != nil {
return err
}
// Verify map extra data
extraData := m.root.ExtraData()
if extraData == nil {
return NewFatalError(fmt.Errorf("root slab %d doesn't have extra data", m.root.SlabID()))
}
// Verify that extra data has correct type information
if typeInfo != nil && !tic(extraData.TypeInfo, typeInfo) {
return NewFatalError(
fmt.Errorf(
"root slab %d type information %v, want %v",
m.root.SlabID(),
extraData.TypeInfo,
typeInfo,
))
}
// Verify that extra data has seed
if extraData.Seed == 0 {
return NewFatalError(fmt.Errorf("root slab %d seed is uninitialized", m.root.SlabID()))
}
v := &mapVerifier{
storage: m.Storage,
address: address,
digesterBuilder: m.digesterBuilder,
tic: tic,
hip: hip,
inlineEnabled: inlineEnabled,
}
computedCount, dataSlabIDs, nextDataSlabIDs, firstKeys, err := v.verifySlab(
m.root, 0, nil, []SlabID{}, []SlabID{}, []Digest{}, slabIDs)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by verifySlab().
return err
}
// Verify that extra data has correct count
if computedCount != extraData.Count {
return NewFatalError(
fmt.Errorf(
"root slab %d count %d is wrong, want %d",
m.root.SlabID(),
extraData.Count,
computedCount,
))
}
// Verify next data slab ids
if !reflect.DeepEqual(dataSlabIDs[1:], nextDataSlabIDs) {
return NewFatalError(fmt.Errorf("chained next data slab ids %v are wrong, want %v",
nextDataSlabIDs, dataSlabIDs[1:]))
}
// Verify data slabs' first keys are sorted
if !sort.SliceIsSorted(firstKeys, func(i, j int) bool {
return firstKeys[i] < firstKeys[j]
}) {
return NewFatalError(fmt.Errorf("chained first keys %v are not sorted", firstKeys))
}
// Verify data slabs' first keys are unique
if len(firstKeys) > 1 {
prev := firstKeys[0]
for _, d := range firstKeys[1:] {
if prev == d {
return NewFatalError(fmt.Errorf("chained first keys %v are not unique", firstKeys))
}
prev = d
}
}
return nil
}
type mapVerifier struct {
storage SlabStorage
address Address
digesterBuilder DigesterBuilder
tic TypeInfoComparator
hip HashInputProvider
inlineEnabled bool
}
func (v *mapVerifier) verifySlab(
slab MapSlab,
level int,
headerFromParentSlab *MapSlabHeader,
dataSlabIDs []SlabID,
nextDataSlabIDs []SlabID,
firstKeys []Digest,
slabIDs map[SlabID]struct{},
) (
elementCount uint64,
_dataSlabIDs []SlabID,
_nextDataSlabIDs []SlabID,
_firstKeys []Digest,
err error,
) {
id := slab.Header().slabID
// Verify SlabID is unique
if _, exist := slabIDs[id]; exist {
return 0, nil, nil, nil, NewFatalError(fmt.Errorf("found duplicate slab ID %s", id))
}
slabIDs[id] = struct{}{}
// Verify slab address (independent of map inlined status)
if v.address != id.address {
return 0, nil, nil, nil, NewFatalError(fmt.Errorf("map slab address %v, got %v", v.address, id.address))
}
// Verify that inlined slab is not in storage
if slab.Inlined() {
_, exist, err := v.storage.Retrieve(id)
if err != nil {
// Wrap err as external error (if needed) because err is returned by Storage interface.
return 0, nil, nil, nil, wrapErrorAsExternalErrorIfNeeded(err)
}
if exist {
return 0, nil, nil, nil, NewFatalError(fmt.Errorf("inlined slab %s is in storage", id))
}
}
if level > 0 {
// Verify that non-root slab doesn't have extra data.
if slab.ExtraData() != nil {
return 0, nil, nil, nil, NewFatalError(fmt.Errorf("non-root slab %d has extra data", id))
}
// Verify that non-root slab doesn't underflow
if underflowSize, underflow := slab.IsUnderflow(); underflow {
return 0, nil, nil, nil, NewFatalError(fmt.Errorf("slab %d underflows by %d bytes", id, underflowSize))
}
}
// Verify that slab doesn't overflow
if slab.IsFull() {
return 0, nil, nil, nil, NewFatalError(fmt.Errorf("slab %d overflows", id))
}
// Verify that header is in sync with header from parent slab
if headerFromParentSlab != nil {
if !reflect.DeepEqual(*headerFromParentSlab, slab.Header()) {
return 0, nil, nil, nil, NewFatalError(
fmt.Errorf("slab %d header %+v is different from header %+v from parent slab",
id, slab.Header(), headerFromParentSlab))
}
}
switch slab := slab.(type) {
case *MapDataSlab:
return v.verifyDataSlab(slab, level, dataSlabIDs, nextDataSlabIDs, firstKeys, slabIDs)
case *MapMetaDataSlab:
return v.verifyMetaDataSlab(slab, level, dataSlabIDs, nextDataSlabIDs, firstKeys, slabIDs)
default:
return 0, nil, nil, nil, NewFatalError(fmt.Errorf("MapSlab is either *MapDataSlab or *MapMetaDataSlab, got %T", slab))
}
}
func (v *mapVerifier) verifyDataSlab(
dataSlab *MapDataSlab,
level int,
dataSlabIDs []SlabID,
nextDataSlabIDs []SlabID,
firstKeys []Digest,
slabIDs map[SlabID]struct{},
) (
elementCount uint64,
_dataSlabIDs []SlabID,
_nextDataSlabIDs []SlabID,
_firstKeys []Digest,
err error,
) {
id := dataSlab.header.slabID
if !dataSlab.IsData() {
return 0, nil, nil, nil, NewFatalError(fmt.Errorf("MapDataSlab %s is not data", id))
}
// Verify data slab's elements
elementCount, elementSize, err := v.verifyElements(id, dataSlab.elements, 0, nil, slabIDs)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by verifyElements().
return 0, nil, nil, nil, err
}
// Verify slab's first key
if dataSlab.elements.firstKey() != dataSlab.header.firstKey {
return 0, nil, nil, nil, NewFatalError(
fmt.Errorf("data slab %d header first key %d is wrong, want %d",
id, dataSlab.header.firstKey, dataSlab.elements.firstKey()))
}
// Verify that only root slab can be inlined
if dataSlab.Inlined() {
if level > 0 {
return 0, nil, nil, nil, NewFatalError(fmt.Errorf("non-root slab %s is inlined", id))
}
if dataSlab.extraData == nil {
return 0, nil, nil, nil, NewFatalError(fmt.Errorf("inlined slab %s doesn't have extra data", id))
}
if dataSlab.next != SlabIDUndefined {
return 0, nil, nil, nil, NewFatalError(fmt.Errorf("inlined slab %s has next slab ID", id))
}
}
// Verify that aggregated element size + slab prefix is the same as header.size
computedSize := uint32(mapDataSlabPrefixSize)
if level == 0 {
computedSize = uint32(mapRootDataSlabPrefixSize)
if dataSlab.Inlined() {
computedSize = uint32(inlinedMapDataSlabPrefixSize)
}
}
computedSize += elementSize
if computedSize != dataSlab.header.size {
return 0, nil, nil, nil, NewFatalError(
fmt.Errorf("data slab %d header size %d is wrong, want %d",
id, dataSlab.header.size, computedSize))
}
// Verify any size flag
if dataSlab.anySize {
return 0, nil, nil, nil, NewFatalError(
fmt.Errorf("data slab %d anySize %t is wrong, want false",
id, dataSlab.anySize))
}
// Verify collision group flag
if dataSlab.collisionGroup {
return 0, nil, nil, nil, NewFatalError(
fmt.Errorf("data slab %d collisionGroup %t is wrong, want false",
id, dataSlab.collisionGroup))
}
dataSlabIDs = append(dataSlabIDs, id)
if dataSlab.next != SlabIDUndefined {
nextDataSlabIDs = append(nextDataSlabIDs, dataSlab.next)
}
firstKeys = append(firstKeys, dataSlab.header.firstKey)
return elementCount, dataSlabIDs, nextDataSlabIDs, firstKeys, nil
}
func (v *mapVerifier) verifyMetaDataSlab(
metaSlab *MapMetaDataSlab,
level int,
dataSlabIDs []SlabID,
nextDataSlabIDs []SlabID,
firstKeys []Digest,
slabIDs map[SlabID]struct{},
) (
elementCount uint64,
_dataSlabIDs []SlabID,
_nextDataSlabIDs []SlabID,
_firstKeys []Digest,
err error,
) {
id := metaSlab.header.slabID
if metaSlab.IsData() {
return 0, nil, nil, nil, NewFatalError(fmt.Errorf("MapMetaDataSlab %s is data", id))
}
if metaSlab.Inlined() {
return 0, nil, nil, nil, NewFatalError(fmt.Errorf("MapMetaDataSlab %s can't be inlined", id))
}
if level == 0 {
// Verify that root slab has more than one child slabs
if len(metaSlab.childrenHeaders) < 2 {
return 0, nil, nil, nil, NewFatalError(
fmt.Errorf("root metadata slab %d has %d children, want at least 2 children ",
id, len(metaSlab.childrenHeaders)))
}
}
elementCount = 0
for i := 0; i < len(metaSlab.childrenHeaders); i++ {
h := metaSlab.childrenHeaders[i]
childSlab, err := getMapSlab(v.storage, h.slabID)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by getMapSlab().
return 0, nil, nil, nil, err
}
// Verify child slabs
count := uint64(0)
count, dataSlabIDs, nextDataSlabIDs, firstKeys, err =
v.verifySlab(childSlab, level+1, &h, dataSlabIDs, nextDataSlabIDs, firstKeys, slabIDs)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by verifySlab().
return 0, nil, nil, nil, err
}
elementCount += count
}
// Verify slab header first key
if metaSlab.childrenHeaders[0].firstKey != metaSlab.header.firstKey {
return 0, nil, nil, nil, NewFatalError(
fmt.Errorf("metadata slab %d header first key %d is wrong, want %d",
id, metaSlab.header.firstKey, metaSlab.childrenHeaders[0].firstKey))
}
// Verify that child slab's first keys are sorted.
sortedHKey := sort.SliceIsSorted(metaSlab.childrenHeaders, func(i, j int) bool {
return metaSlab.childrenHeaders[i].firstKey < metaSlab.childrenHeaders[j].firstKey
})
if !sortedHKey {
return 0, nil, nil, nil, NewFatalError(fmt.Errorf("metadata slab %d child slab's first key isn't sorted %+v", id, metaSlab.childrenHeaders))
}
// Verify that child slab's first keys are unique.
if len(metaSlab.childrenHeaders) > 1 {
prev := metaSlab.childrenHeaders[0].firstKey
for _, h := range metaSlab.childrenHeaders[1:] {
if prev == h.firstKey {
return 0, nil, nil, nil, NewFatalError(
fmt.Errorf("metadata slab %d child header first key isn't unique %v",
id, metaSlab.childrenHeaders))
}
prev = h.firstKey
}
}
// Verify slab header's size
computedSize := uint32(len(metaSlab.childrenHeaders)*mapSlabHeaderSize) + mapMetaDataSlabPrefixSize
if computedSize != metaSlab.header.size {
return 0, nil, nil, nil, NewFatalError(
fmt.Errorf("metadata slab %d header size %d is wrong, want %d",
id, metaSlab.header.size, computedSize))
}
return elementCount, dataSlabIDs, nextDataSlabIDs, firstKeys, nil
}
func (v *mapVerifier) verifyElements(
id SlabID,
elements elements,
digestLevel uint,
hkeyPrefixes []Digest,
slabIDs map[SlabID]struct{},
) (
elementCount uint64,
elementSize uint32,
err error,
) {
switch elems := elements.(type) {
case *hkeyElements:
return v.verifyHkeyElements(id, elems, digestLevel, hkeyPrefixes, slabIDs)
case *singleElements:
return v.verifySingleElements(id, elems, digestLevel, hkeyPrefixes, slabIDs)
default:
return 0, 0, NewFatalError(fmt.Errorf("slab %d has unknown elements type %T at digest level %d", id, elements, digestLevel))
}
}
func (v *mapVerifier) verifyHkeyElements(
id SlabID,
elements *hkeyElements,
digestLevel uint,
hkeyPrefixes []Digest,
slabIDs map[SlabID]struct{},
) (
elementCount uint64,
elementSize uint32,
err error,
) {
// Verify element's level
if digestLevel != elements.level {
return 0, 0, NewFatalError(
fmt.Errorf("data slab %d elements digest level %d is wrong, want %d",
id, elements.level, digestLevel))
}
// Verify number of hkeys is the same as number of elements
if len(elements.hkeys) != len(elements.elems) {
return 0, 0, NewFatalError(
fmt.Errorf("data slab %d hkeys count %d is wrong, want %d",
id, len(elements.hkeys), len(elements.elems)))
}
// Verify hkeys are sorted
if !sort.SliceIsSorted(elements.hkeys, func(i, j int) bool {
return elements.hkeys[i] < elements.hkeys[j]
}) {
return 0, 0, NewFatalError(fmt.Errorf("data slab %d hkeys is not sorted %v", id, elements.hkeys))
}
// Verify hkeys are unique
if len(elements.hkeys) > 1 {
prev := elements.hkeys[0]
for _, d := range elements.hkeys[1:] {
if prev == d {
return 0, 0, NewFatalError(fmt.Errorf("data slab %d hkeys is not unique %v", id, elements.hkeys))
}
prev = d
}
}
elementSize = uint32(hkeyElementsPrefixSize)
for i := 0; i < len(elements.elems); i++ {
e := elements.elems[i]
hkeys := make([]Digest, len(hkeyPrefixes)+1)
copy(hkeys, hkeyPrefixes)
hkeys[len(hkeys)-1] = elements.hkeys[i]
elementSize += digestSize
// Verify element size is <= inline size
if digestLevel == 0 {
if e.Size() > uint32(maxInlineMapElementSize) {
return 0, 0, NewFatalError(
fmt.Errorf("data slab %d element %s size %d is too large, want < %d",
id, e, e.Size(), maxInlineMapElementSize))
}
}
switch e := e.(type) {
case elementGroup:
group, err := e.Elements(v.storage)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by elementGroup.Elements().
return 0, 0, err
}
count, size, err := v.verifyElements(id, group, digestLevel+1, hkeys, slabIDs)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by verifyElements().
return 0, 0, err
}
if _, ok := e.(*inlineCollisionGroup); ok {
size += inlineCollisionGroupPrefixSize
} else {
size = externalCollisionGroupPrefixSize + 2 + 1 + 16
}
// Verify element group size
if size != e.Size() {
return 0, 0, NewFatalError(fmt.Errorf("data slab %d element %s size %d is wrong, want %d", id, e, e.Size(), size))
}
elementSize += e.Size()
elementCount += count
case *singleElement:
// Verify element
computedSize, maxDigestLevel, err := v.verifySingleElement(e, hkeys, slabIDs)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by verifySingleElement().
return 0, 0, fmt.Errorf("data slab %d: %w", id, err)
}
// Verify digest level
if digestLevel >= maxDigestLevel {
return 0, 0, NewFatalError(
fmt.Errorf("data slab %d, hkey elements %s: digest level %d is wrong, want < %d",
id, elements, digestLevel, maxDigestLevel))
}
elementSize += computedSize
elementCount++
default:
return 0, 0, NewFatalError(fmt.Errorf("data slab %d element type %T is wrong, want either elementGroup or *singleElement", id, e))
}
}
// Verify elements size
if elementSize != elements.Size() {
return 0, 0, NewFatalError(fmt.Errorf("data slab %d elements size %d is wrong, want %d", id, elements.Size(), elementSize))
}
return elementCount, elementSize, nil
}
func (v *mapVerifier) verifySingleElements(
id SlabID,
elements *singleElements,
digestLevel uint,
hkeyPrefixes []Digest,
slabIDs map[SlabID]struct{},
) (
elementCount uint64,
elementSize uint32,
err error,
) {
// Verify elements' level
if digestLevel != elements.level {
return 0, 0, NewFatalError(
fmt.Errorf("data slab %d elements level %d is wrong, want %d",
id, elements.level, digestLevel))
}
elementSize = singleElementsPrefixSize
for _, e := range elements.elems {
// Verify element
computedSize, maxDigestLevel, err := v.verifySingleElement(e, hkeyPrefixes, slabIDs)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by verifySingleElement().
return 0, 0, fmt.Errorf("data slab %d: %w", id, err)
}
// Verify element size is <= inline size
if e.Size() > uint32(maxInlineMapElementSize) {
return 0, 0, NewFatalError(
fmt.Errorf("data slab %d element %s size %d is too large, want < %d",
id, e, e.Size(), maxInlineMapElementSize))
}
// Verify digest level
if digestLevel != maxDigestLevel {
return 0, 0, NewFatalError(
fmt.Errorf("data slab %d single elements %s digest level %d is wrong, want %d",
id, elements, digestLevel, maxDigestLevel))
}
elementSize += computedSize
}
// Verify elements size
if elementSize != elements.Size() {
return 0, 0, NewFatalError(fmt.Errorf("slab %d elements size %d is wrong, want %d", id, elements.Size(), elementSize))
}
return uint64(len(elements.elems)), elementSize, nil
}
func (v *mapVerifier) verifySingleElement(
e *singleElement,
digests []Digest,
slabIDs map[SlabID]struct{},
) (
size uint32,
digestMaxLevel uint,
err error,
) {
// Verify key storable's size is less than size limit
if e.key.ByteSize() > uint32(maxInlineMapKeySize) {
return 0, 0, NewFatalError(
fmt.Errorf(
"map element key %s size %d exceeds size limit %d",
e.key, e.key.ByteSize(), maxInlineMapKeySize,
))
}
// Verify value storable's size is less than size limit
valueSizeLimit := maxInlineMapValueSize(uint64(e.key.ByteSize()))
if e.value.ByteSize() > uint32(valueSizeLimit) {
return 0, 0, NewFatalError(
fmt.Errorf(
"map element value %s size %d exceeds size limit %d",
e.value, e.value.ByteSize(), valueSizeLimit,
))
}
// Verify key
kv, err := e.key.StoredValue(v.storage)
if err != nil {
// Wrap err as external error (if needed) because err is returned by Stroable interface.
return 0, 0, wrapErrorfAsExternalErrorIfNeeded(err, fmt.Sprintf("element %s key can't be converted to value", e))
}
err = verifyValue(kv, v.address, nil, v.tic, v.hip, v.inlineEnabled, slabIDs)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by verifyValue().
return 0, 0, fmt.Errorf("element %s key isn't valid: %w", e, err)
}
// Verify value
vv, err := e.value.StoredValue(v.storage)
if err != nil {
// Wrap err as external error (if needed) because err is returned by Stroable interface.
return 0, 0, wrapErrorfAsExternalErrorIfNeeded(err, fmt.Sprintf("element %s value can't be converted to value", e))
}
switch e := e.value.(type) {
case SlabIDStorable:
// Verify not-inlined value > inline size, or can't be inlined
if v.inlineEnabled {
err = verifyNotInlinedValueStatusAndSize(vv, uint32(valueSizeLimit))
if err != nil {
return 0, 0, err
}
}
case *ArrayDataSlab:
// Verify inlined element's inlined status
if !e.Inlined() {
return 0, 0, NewFatalError(fmt.Errorf("inlined array inlined status is false"))
}
case *MapDataSlab:
// Verify inlined element's inlined status
if !e.Inlined() {
return 0, 0, NewFatalError(fmt.Errorf("inlined map inlined status is false"))
}
}
err = verifyValue(vv, v.address, nil, v.tic, v.hip, v.inlineEnabled, slabIDs)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by verifyValue().
return 0, 0, fmt.Errorf("element %s value isn't valid: %w", e, err)
}
// Verify size
computedSize := singleElementPrefixSize + e.key.ByteSize() + e.value.ByteSize()
if computedSize != e.Size() {
return 0, 0, NewFatalError(fmt.Errorf("element %s size %d is wrong, want %d", e, e.Size(), computedSize))
}
// Verify digest
digest, err := v.digesterBuilder.Digest(v.hip, kv)
if err != nil {
// Wrap err as external error (if needed) because err is returned by DigesterBuilder interface.
return 0, 0, wrapErrorfAsExternalErrorIfNeeded(err, "failed to create digester")
}
computedDigests, err := digest.DigestPrefix(digest.Levels())
if err != nil {
// Wrap err as external error (if needed) because err is returned by Digester interface.
return 0, 0, wrapErrorfAsExternalErrorIfNeeded(err, fmt.Sprintf("failed to generate digest prefix up to level %d", digest.Levels()))
}
if !reflect.DeepEqual(digests, computedDigests[:len(digests)]) {
return 0, 0, NewFatalError(fmt.Errorf("element %s digest %v is wrong, want %v", e, digests, computedDigests))
}
return computedSize, digest.Levels(), nil
}
func verifyValue(value Value, address Address, typeInfo TypeInfo, tic TypeInfoComparator, hip HashInputProvider, inlineEnabled bool, slabIDs map[SlabID]struct{}) error {
switch v := value.(type) {
case *Array:
return verifyArray(v, address, typeInfo, tic, hip, inlineEnabled, slabIDs)
case *OrderedMap:
return verifyMap(v, address, typeInfo, tic, hip, inlineEnabled, slabIDs)
}
return nil
}
// VerifyMapSerialization traverses ordered map tree and verifies serialization
// by encoding, decoding, and re-encoding slabs.
// It compares in-memory objects of original slab with decoded slab.
// It also compares encoded data of original slab with encoded data of decoded slab.
func VerifyMapSerialization(
m *OrderedMap,
cborDecMode cbor.DecMode,
cborEncMode cbor.EncMode,
decodeStorable StorableDecoder,
decodeTypeInfo TypeInfoDecoder,
compare StorableComparator,
) error {
// Skip verification of inlined map serialization.
if m.Inlined() {
return nil
}
v := &serializationVerifier{
storage: m.Storage,
cborDecMode: cborDecMode,
cborEncMode: cborEncMode,
decodeStorable: decodeStorable,
decodeTypeInfo: decodeTypeInfo,
compare: compare,
}
return v.verifyMapSlab(m.root)
}
func (v *serializationVerifier) verifyMapSlab(slab MapSlab) error {
id := slab.SlabID()
// Encode slab
data, err := EncodeSlab(slab, v.cborEncMode)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by Encode().
return err
}
// Decode encoded slab
decodedSlab, err := DecodeSlab(id, data, v.cborDecMode, v.decodeStorable, v.decodeTypeInfo)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by DecodeSlab().
return err
}
// Re-encode decoded slab
dataFromDecodedSlab, err := EncodeSlab(decodedSlab, v.cborEncMode)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by Encode().
return err
}
// Verify encoding is deterministic (encoded data of original slab is same as encoded data of decoded slab)
if !bytes.Equal(data, dataFromDecodedSlab) {
return NewFatalError(fmt.Errorf("encoded data of original slab %s is different from encoded data of decoded slab, got %v, want %v",
id, dataFromDecodedSlab, data))
}
// Extra check: encoded data size == header.size
// This check is skipped for slabs with inlined compact map because
// encoded size and slab size differ for inlined composites.
// For inlined composites, digests and field keys are encoded in
// compact map extra data section for reuse, and only compact map field
// values are encoded in non-extra data section.
// This reduces encoding size because compact map values of the same