-
Notifications
You must be signed in to change notification settings - Fork 7
/
decoder.go
1357 lines (1264 loc) · 44.9 KB
/
decoder.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
// ssz: Go Simple Serialize (SSZ) codec library
// Copyright 2024 ssz Authors
// SPDX-License-Identifier: BSD-3-Clause
package ssz
import (
"encoding/binary"
"fmt"
"io"
"math/big"
"math/bits"
"unsafe"
"github.com/holiman/uint256"
"github.com/prysmaticlabs/go-bitfield"
)
// Decoder is a wrapper around an io.Reader or a []byte buffer to implement SSZ
// decoding in a streaming or buffered way. It has the following behaviors:
//
// 1. The decoder does not buffer, simply reads from the wrapped input stream
// directly. If you need buffering, that is up to you.
//
// 2. The decoder does not return errors that were hit during reading from the
// underlying input stream from individual encoding methods. Since there
// is no expectation (in general) for failure, user code can be denser if
// error checking is done at the end. Internally, of course, an error will
// halt all future input operations.
//
// Internally there are a few implementation details that maintainers need to be
// aware of when modifying the code:
//
// 1. The decoder supports two modes of operation: streaming and buffered. Any
// high level Go code would achieve that with two decoder types implementing
// a common interface. Unfortunately, the DecodeXYZ methods are using Go's
// generic system, which is not supported on struct/interface *methods*. As
// such, `Decoder.DecodeUint64s[T ~uint64](ns []T)` style methods cannot be
// used, only `DecodeUint64s[T ~uint64](end *Decoder, ns []T)`. The latter
// form then requires each method internally to do some soft of type cast to
// handle different decoder implementations. To avoid runtime type asserts,
// we've opted for a combo decoder with 2 possible outputs and switching on
// which one is set. Elegant? No. Fast? Yes.
//
// 2. A lot of code snippets are repeated (e.g. encoding the offset, which is
// the exact same for all the different types, yet the code below has them
// copied verbatim). Unfortunately the Go compiler doesn't inline functions
// aggressively enough (neither does it allow explicitly directing it to),
// and in such tight loops, extra calls matter on performance.
type Decoder struct {
inReader io.Reader // Underlying input stream to read from (streaming mode)
inRead uint32 // Bytes already consumed from the reader (streaming mode)
inReads []uint32 // Stack of consumed bytes from outer calls (streaming mode)
inBuffer []byte // Underlying input buffer to read from (buffered mode)
inBufPtr uintptr // Starting pointer in the input buffer (buffered mode)
inBufPtrs []uintptr // Stack of starting pointers from outer calls (buffered mode)
inBufEnd uintptr // Ending pointer in the input buffer (buffered mode)
err error // Any write error to halt future encoding calls
codec *Codec // Self-referencing to pass DefineSSZ calls through (API trick)
sizer *Sizer // Self-referencing to pass SizeSSZ call through (API trick)
buf [32]byte // Integer conversion buffer
bufInt uint256.Int // Big.Int conversion buffer (not pointer, alloc free)
length uint32 // Message length being decoded
lengths []uint32 // Stack of lengths from outer calls
offset uint32 // Starting offset we expect, or last offset seen after
offsets []uint32 // Queue of offsets for dynamic size calculations
sizes []uint32 // Computed sizes for the dynamic objects
sizess [][]uint32 // Stack of computed sizes from outer calls
}
// DecodeBool parses a boolean.
func DecodeBool[T ~bool](dec *Decoder, v *T) {
if dec.err != nil {
return
}
if dec.inReader != nil {
_, dec.err = io.ReadFull(dec.inReader, dec.buf[:1])
if dec.err != nil {
return
}
switch dec.buf[0] {
case 0:
*v = false
case 1:
*v = true
default:
dec.err = fmt.Errorf("%w: found %#x", ErrInvalidBoolean, dec.buf[0])
}
dec.inRead += 1
} else {
if len(dec.inBuffer) < 1 {
dec.err = io.ErrUnexpectedEOF
return
}
switch dec.inBuffer[0] {
case 0:
*v = false
case 1:
*v = true
default:
dec.err = fmt.Errorf("%w: found %#x", ErrInvalidBoolean, dec.inBuffer[0])
}
dec.inBuffer = dec.inBuffer[1:]
}
}
// DecodeBoolPointerOnFork parses a boolean if present in a fork. If not, the
// boolean pointer is set to nil.
//
// This method is similar to DecodeBool, but will also initialize the pointer
// if it is not allocated yet.
func DecodeBoolPointerOnFork[T ~bool](dec *Decoder, v **T, filter ForkFilter) {
// If the field is not active in the current fork, clear out the output
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
*v = nil
return
}
// Otherwise fall back to the standard decoder
if *v == nil {
*v = new(T)
}
DecodeBool(dec, *v)
}
// DecodeUint8 parses a uint8.
func DecodeUint8[T ~uint8](dec *Decoder, n *T) {
if dec.err != nil {
return
}
if dec.inReader != nil {
_, dec.err = io.ReadFull(dec.inReader, dec.buf[:1])
*n = T(dec.buf[0])
dec.inRead += 1
} else {
if len(dec.inBuffer) < 1 {
dec.err = io.ErrUnexpectedEOF
return
}
*n = T(dec.inBuffer[0])
dec.inBuffer = dec.inBuffer[1:]
}
}
// DecodeUint8PointerOnFork parses a uint8 if present in a fork. If not, the
// uint8 pointer is set to nil.
//
// This method is similar to DecodeUint8, but will also initialize the pointer
// if it is not allocated yet.
func DecodeUint8PointerOnFork[T ~uint8](dec *Decoder, n **T, filter ForkFilter) {
// If the field is not active in the current fork, clear out the output
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
*n = nil
return
}
// Otherwise fall back to the standard decoder
if *n == nil {
*n = new(T)
}
DecodeUint8(dec, *n)
}
// DecodeUint16 parses a uint16.
func DecodeUint16[T ~uint16](dec *Decoder, n *T) {
if dec.err != nil {
return
}
if dec.inReader != nil {
_, dec.err = io.ReadFull(dec.inReader, dec.buf[:2])
*n = T(binary.LittleEndian.Uint16(dec.buf[:2]))
dec.inRead += 2
} else {
if len(dec.inBuffer) < 2 {
dec.err = io.ErrUnexpectedEOF
return
}
*n = T(binary.LittleEndian.Uint16(dec.inBuffer))
dec.inBuffer = dec.inBuffer[2:]
}
}
// DecodeUint16PointerOnFork parses a uint16 if present in a fork. If not, the
// uint16 pointer is set to nil.
//
// This method is similar to DecodeUint16, but will also initialize the pointer
// if it is not allocated yet.
func DecodeUint16PointerOnFork[T ~uint16](dec *Decoder, n **T, filter ForkFilter) {
// If the field is not active in the current fork, clear out the output
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
*n = nil
return
}
// Otherwise fall back to the standard decoder
if *n == nil {
*n = new(T)
}
DecodeUint16(dec, *n)
}
// DecodeUint32 parses a uint32.
func DecodeUint32[T ~uint32](dec *Decoder, n *T) {
if dec.err != nil {
return
}
if dec.inReader != nil {
_, dec.err = io.ReadFull(dec.inReader, dec.buf[:4])
*n = T(binary.LittleEndian.Uint32(dec.buf[:4]))
dec.inRead += 4
} else {
if len(dec.inBuffer) < 4 {
dec.err = io.ErrUnexpectedEOF
return
}
*n = T(binary.LittleEndian.Uint32(dec.inBuffer))
dec.inBuffer = dec.inBuffer[4:]
}
}
// DecodeUint32PointerOnFork parses a uint32 if present in a fork. If not, the
// uint32 pointer is set to nil.
//
// This method is similar to DecodeUint32, but will also initialize the pointer
// if it is not allocated yet.
func DecodeUint32PointerOnFork[T ~uint32](dec *Decoder, n **T, filter ForkFilter) {
// If the field is not active in the current fork, clear out the output
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
*n = nil
return
}
// Otherwise fall back to the standard decoder
if *n == nil {
*n = new(T)
}
DecodeUint32(dec, *n)
}
// DecodeUint64 parses a uint64.
func DecodeUint64[T ~uint64](dec *Decoder, n *T) {
if dec.err != nil {
return
}
if dec.inReader != nil {
_, dec.err = io.ReadFull(dec.inReader, dec.buf[:8])
*n = T(binary.LittleEndian.Uint64(dec.buf[:8]))
dec.inRead += 8
} else {
if len(dec.inBuffer) < 8 {
dec.err = io.ErrUnexpectedEOF
return
}
*n = T(binary.LittleEndian.Uint64(dec.inBuffer))
dec.inBuffer = dec.inBuffer[8:]
}
}
// DecodeUint64PointerOnFork parses a uint64 if present in a fork. If not, the
// uint64 pointer is set to nil.
//
// This method is similar to DecodeUint64, but will also initialize the pointer
// if it is not allocated yet.
func DecodeUint64PointerOnFork[T ~uint64](dec *Decoder, n **T, filter ForkFilter) {
// If the field is not active in the current fork, clear out the output
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
*n = nil
return
}
// Otherwise fall back to the standard decoder
if *n == nil {
*n = new(T)
}
DecodeUint64(dec, *n)
}
// DecodeUint256 parses a uint256.
func DecodeUint256(dec *Decoder, n **uint256.Int) {
if dec.err != nil {
return
}
if dec.inReader != nil {
_, dec.err = io.ReadFull(dec.inReader, dec.buf[:32])
if dec.err != nil {
return
}
dec.inRead += 32
if *n == nil {
*n = new(uint256.Int)
}
(*n).UnmarshalSSZ(dec.buf[:32])
} else {
if len(dec.inBuffer) < 32 {
dec.err = io.ErrUnexpectedEOF
return
}
if *n == nil {
*n = new(uint256.Int)
}
(*n).UnmarshalSSZ(dec.inBuffer[:32])
dec.inBuffer = dec.inBuffer[32:]
}
}
// DecodeUint256OnFork parses a uint256 if present in a fork.
func DecodeUint256OnFork(dec *Decoder, n **uint256.Int, filter ForkFilter) {
// If the field is not active in the current fork, clear out the output
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
*n = nil
return
}
// Otherwise fall back to the standard decoder
DecodeUint256(dec, n)
}
// DecodeUint256BigInt parses a uint256 into a big.Int.
func DecodeUint256BigInt(dec *Decoder, n **big.Int) {
if dec.err != nil {
return
}
if dec.inReader != nil {
_, dec.err = io.ReadFull(dec.inReader, dec.buf[:32])
if dec.err != nil {
return
}
dec.inRead += 32
dec.bufInt.UnmarshalSSZ(dec.buf[:32])
dec.bufInt.IntoBig(n)
} else {
if len(dec.inBuffer) < 32 {
dec.err = io.ErrUnexpectedEOF
return
}
dec.bufInt.UnmarshalSSZ(dec.inBuffer[:32])
dec.bufInt.IntoBig(n)
dec.inBuffer = dec.inBuffer[32:]
}
}
// DecodeUint256BigIntOnFork parses a uint256 into a big.Int if present in a fork.
func DecodeUint256BigIntOnFork(dec *Decoder, n **big.Int, filter ForkFilter) {
// If the field is not active in the current fork, clear out the output
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
*n = nil
return
}
// Otherwise fall back to the standard decoder
DecodeUint256BigInt(dec, n)
}
// DecodeStaticBytes parses a static binary blob.
func DecodeStaticBytes[T commonBytesLengths](dec *Decoder, blob *T) {
if dec.err != nil {
return
}
if dec.inReader != nil {
// The code below should have used `*blob[:]`, alas Go's generics compiler
// is missing that (i.e. a bug): https://github.com/golang/go/issues/51740
_, dec.err = io.ReadFull(dec.inReader, unsafe.Slice(&(*blob)[0], len(*blob)))
dec.inRead += uint32(len(*blob))
} else {
if len(dec.inBuffer) < len(*blob) {
dec.err = io.ErrUnexpectedEOF
return
}
// The code below should have used `*blob[:]`, alas Go's generics compiler
// is missing that (i.e. a bug): https://github.com/golang/go/issues/51740
copy(unsafe.Slice(&(*blob)[0], len(*blob)), dec.inBuffer)
dec.inBuffer = dec.inBuffer[len(*blob):]
}
}
// DecodeStaticBytesPointerOnFork parses a static binary blob if present in a fork.
// If not, the bytes are set to nil.
func DecodeStaticBytesPointerOnFork[T commonBytesLengths](dec *Decoder, blob **T, filter ForkFilter) {
// If the field is not active in the current fork, clear out the output
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
*blob = nil
return
}
// Otherwise fall back to the standard decoder
if *blob == nil {
*blob = new(T)
}
DecodeStaticBytes(dec, *blob)
}
// DecodeCheckedStaticBytes parses a static binary blob.
func DecodeCheckedStaticBytes(dec *Decoder, blob *[]byte, size uint64) {
if dec.err != nil {
return
}
// Expand the byte slice if needed and fill it with the data
if uint64(cap(*blob)) < size {
*blob = make([]byte, size)
} else {
*blob = (*blob)[:size]
}
if dec.inReader != nil {
_, dec.err = io.ReadFull(dec.inReader, *blob)
dec.inRead += uint32(size)
} else {
if uint64(len(dec.inBuffer)) < size {
dec.err = io.ErrUnexpectedEOF
return
}
copy(*blob, dec.inBuffer)
dec.inBuffer = dec.inBuffer[size:]
}
}
// DecodeDynamicBytesOffset parses the offset of a dynamic binary blob.
func DecodeDynamicBytesOffset(dec *Decoder, blob *[]byte) {
dec.decodeOffset(false)
}
// DecodeDynamicBytesOffsetOnFork parses the offset of dynamic binary blob if
// present in a fork.
func DecodeDynamicBytesOffsetOnFork(dec *Decoder, blob *[]byte, filter ForkFilter) {
// If the field is not active in the current fork, skip parsing the offset
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
return
}
// Otherwise fall back to the standard decoder
DecodeDynamicBytesOffset(dec, blob)
}
// DecodeDynamicBytesContent is the lazy data reader of DecodeDynamicBytesOffset.
func DecodeDynamicBytesContent(dec *Decoder, blob *[]byte, maxSize uint64) {
if dec.err != nil {
return
}
// Compute the length of the blob based on the seen offsets
size := dec.retrieveSize()
if uint64(size) > maxSize {
dec.err = fmt.Errorf("%w: decoded %d, max %d", ErrMaxLengthExceeded, size, maxSize)
return
}
// Expand the byte slice if needed and fill it with the data
if uint32(cap(*blob)) < size {
*blob = make([]byte, size)
} else {
*blob = (*blob)[:size]
}
// Inline:
//
// DecodeStaticBytes(dec, *(blob))
if dec.inReader != nil {
_, dec.err = io.ReadFull(dec.inReader, *blob)
dec.inRead += size
} else {
if uint32(len(dec.inBuffer)) < size {
dec.err = io.ErrUnexpectedEOF
return
}
copy(*blob, dec.inBuffer)
dec.inBuffer = dec.inBuffer[size:]
}
}
// DecodeDynamicBytesContentOnFork is the lazy data reader of DecodeDynamicBytesOffsetOnFork.
func DecodeDynamicBytesContentOnFork(dec *Decoder, blob *[]byte, maxSize uint64, filter ForkFilter) {
// If the field is not active in the current fork, clear out the output
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
*blob = nil
return
}
// Otherwise fall back to the standard decoder
DecodeDynamicBytesContent(dec, blob, maxSize)
}
// DecodeStaticObject parses a static ssz object.
func DecodeStaticObject[T newableStaticObject[U], U any](dec *Decoder, obj *T) {
if dec.err != nil {
return
}
if *obj == nil {
*obj = T(new(U))
}
(*obj).DefineSSZ(dec.codec)
}
// DecodeStaticObjectOnFork parses a static ssz object if present in a fork.
func DecodeStaticObjectOnFork[T newableStaticObject[U], U any](dec *Decoder, obj *T, filter ForkFilter) {
// If the field is not active in the current fork, clear out the output
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
*obj = nil
return
}
// Otherwise fall back to the standard decoder
DecodeStaticObject(dec, obj)
}
// DecodeDynamicObjectOffset parses a dynamic ssz object.
func DecodeDynamicObjectOffset[T newableDynamicObject[U], U any](dec *Decoder, obj *T) {
dec.decodeOffset(false)
}
// DecodeDynamicObjectOffsetOnFork parses a dynamic ssz object if present in a fork.
func DecodeDynamicObjectOffsetOnFork[T newableDynamicObject[U], U any](dec *Decoder, obj *T, filter ForkFilter) {
// If the field is not active in the current fork, skip parsing the offset
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
return
}
// Otherwise fall back to the standard decoder
DecodeDynamicObjectOffset(dec, obj)
}
// DecodeDynamicObjectContent is the lazy data reader of DecodeDynamicObjectOffset.
func DecodeDynamicObjectContent[T newableDynamicObject[U], U any](dec *Decoder, obj *T) {
if dec.err != nil {
return
}
// Compute the length of the object based on the seen offsets
size := dec.retrieveSize()
// Descend into a new data slot to track/verify a new sub-length
dec.descendIntoSlot(size)
defer dec.ascendFromSlot()
if *obj == nil {
*obj = T(new(U))
}
dec.startDynamics((*obj).SizeSSZ(dec.sizer, true))
(*obj).DefineSSZ(dec.codec)
dec.flushDynamics()
}
// DecodeDynamicObjectContentOnFork is the lazy data reader of DecodeDynamicObjectOffsetOnFork.
func DecodeDynamicObjectContentOnFork[T newableDynamicObject[U], U any](dec *Decoder, obj *T, filter ForkFilter) {
// If the field is not active in the current fork, clear out the output
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
*obj = nil
return
}
// Otherwise fall back to the standard decoder
DecodeDynamicObjectContent(dec, obj)
}
// DecodeArrayOfBits parses a static array of (packed) bits.
func DecodeArrayOfBits[T commonBitsLengths](dec *Decoder, bits *T, size uint64) {
if dec.err != nil {
return
}
// The code below should have used `*bits[:]`, alas Go's generics compiler
// is missing that (i.e. a bug): https://github.com/golang/go/issues/51740
bitvector := unsafe.Slice(&(*bits)[0], len(*bits))
if dec.inReader != nil {
_, dec.err = io.ReadFull(dec.inReader, bitvector)
if dec.err != nil {
return
}
dec.inRead += uint32(len(bitvector))
} else {
if len(dec.inBuffer) < len(bitvector) {
dec.err = io.ErrUnexpectedEOF
return
}
copy(bitvector, dec.inBuffer)
dec.inBuffer = dec.inBuffer[len(bitvector):]
}
// TODO(karalabe): This can probably be done more optimally...
for i := size; i < uint64(len(bitvector)<<3); i++ {
if bitvector[i>>3]&(1<<(i&0x7)) > 0 {
dec.err = fmt.Errorf("%w: bit %d set, size %d bits", ErrJunkInBitvector, i+1, size)
return
}
}
}
// DecodeArrayOfBitsPointerOnFork parses a static array of (packed) bits if present
// in a fork. If not, the bit array pointer is set to nil.
func DecodeArrayOfBitsPointerOnFork[T commonBitsLengths](dec *Decoder, bits **T, size uint64, filter ForkFilter) {
// If the field is not active in the current fork, clear out the output
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
*bits = nil
return
}
// Otherwise fall back to the standard decoder
if *bits == nil {
*bits = new(T)
}
DecodeArrayOfBits(dec, *bits, size)
}
// DecodeSliceOfBitsOffset parses a dynamic slice of (packed) bits.
func DecodeSliceOfBitsOffset(dec *Decoder, bitlist *bitfield.Bitlist) {
dec.decodeOffset(false)
}
// DecodeSliceOfBitsOffsetOnFork parses a dynamic slice of (packed) bits if present
// in a fork.
func DecodeSliceOfBitsOffsetOnFork(dec *Decoder, bitlist *bitfield.Bitlist, filter ForkFilter) {
// If the field is not active in the current fork, skip parsing the offset
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
return
}
// Otherwise fall back to the standard decoder
DecodeSliceOfBitsOffset(dec, bitlist)
}
// DecodeSliceOfBitsContent is the lazy data reader of DecodeSliceOfBitsOffset.
func DecodeSliceOfBitsContent(dec *Decoder, bitlist *bitfield.Bitlist, maxBits uint64) {
if dec.err != nil {
return
}
// Compute the length of the encoded bits based on the seen offsets
size := dec.retrieveSize()
if size == 0 {
dec.err = fmt.Errorf("%w: length bit missing", ErrJunkInBitlist)
return
}
// Verify that the byte size is reasonable, bits will need an extra step after decoding
if maxBytes := maxBits>>3 + 1; maxBytes < uint64(size) {
dec.err = fmt.Errorf("%w: decoded %d bytes, max %d bytes", ErrMaxItemsExceeded, size, maxBytes)
return
}
// Expand the slice if needed and read the bits
if uint32(cap(*bitlist)) < size {
*bitlist = make([]byte, size)
} else {
*bitlist = (*bitlist)[:size]
}
if dec.inReader != nil {
_, dec.err = io.ReadFull(dec.inReader, *bitlist)
if dec.err != nil {
return
}
dec.inRead += uint32(len(*bitlist))
} else {
if len(dec.inBuffer) < len(*bitlist) {
dec.err = io.ErrUnexpectedEOF
return
}
copy(*bitlist, dec.inBuffer)
dec.inBuffer = dec.inBuffer[len(*bitlist):]
}
// Verify that the length bit is at the correct position
high := (*bitlist)[len(*bitlist)-1]
if high == 0 {
dec.err = fmt.Errorf("%w: high byte unset", ErrJunkInBitlist)
return
}
if len := ((len(*bitlist) - 1) >> 3) + bits.Len8(high) - 1; uint64(len) > maxBits {
dec.err = fmt.Errorf("%w: decoded %d bits, max %d bits", ErrMaxItemsExceeded, len, maxBits)
return
}
}
// DecodeSliceOfBitsContentOnFork is the lazy data reader of DecodeSliceOfBitsOffsetOnFork.
func DecodeSliceOfBitsContentOnFork(dec *Decoder, bitlist *bitfield.Bitlist, maxBits uint64, filter ForkFilter) {
// If the field is not active in the current fork, clear out the output
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
*bitlist = nil
return
}
// Otherwise fall back to the standard decoder
DecodeSliceOfBitsContent(dec, bitlist, maxBits)
}
// DecodeArrayOfUint64s parses a static array of uint64s.
func DecodeArrayOfUint64s[T commonUint64sLengths](dec *Decoder, ns *T) {
if dec.err != nil {
return
}
// The code below should have used `*blob[:]`, alas Go's generics compiler
// is missing that (i.e. a bug): https://github.com/golang/go/issues/51740
nums := unsafe.Slice(&(*ns)[0], len(*ns))
if dec.inReader != nil {
for i := 0; i < len(nums); i++ {
_, dec.err = io.ReadFull(dec.inReader, dec.buf[:8])
if dec.err != nil {
return
}
nums[i] = binary.LittleEndian.Uint64(dec.buf[:8])
dec.inRead += 8
}
} else {
for i := 0; i < len(nums); i++ {
if len(dec.inBuffer) < 8 {
dec.err = io.ErrUnexpectedEOF
return
}
nums[i] = binary.LittleEndian.Uint64(dec.inBuffer)
dec.inBuffer = dec.inBuffer[8:]
}
}
}
// DecodeArrayOfUint64sPointerOnFork parses a static array of uint64s if present
// in a fork. If not, the bit array pointer is set to nil.
func DecodeArrayOfUint64sPointerOnFork[T commonUint64sLengths](dec *Decoder, ns **T, filter ForkFilter) {
// If the field is not active in the current fork, clear out the output
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
*ns = nil
return
}
// Otherwise fall back to the standard decoder
if *ns == nil {
*ns = new(T)
}
DecodeArrayOfUint64s(dec, *ns)
}
// DecodeSliceOfUint64sOffset parses a dynamic slice of uint64s.
func DecodeSliceOfUint64sOffset[T ~uint64](dec *Decoder, ns *[]T) {
dec.decodeOffset(false)
}
// DecodeSliceOfUint64sOffsetOnFork parses a dynamic slice of uint64s if present
// in a fork.
func DecodeSliceOfUint64sOffsetOnFork[T ~uint64](dec *Decoder, ns *[]T, filter ForkFilter) {
// If the field is not active in the current fork, skip parsing the offset
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
return
}
// Otherwise fall back to the standard decoder
DecodeSliceOfUint64sOffset(dec, ns)
}
// DecodeSliceOfUint64sContent is the lazy data reader of DecodeSliceOfUint64sOffset.
func DecodeSliceOfUint64sContent[T ~uint64](dec *Decoder, ns *[]T, maxItems uint64) {
if dec.err != nil {
return
}
// Compute the length of the encoded binaries based on the seen offsets
size := dec.retrieveSize()
if size == 0 {
// Empty slice, remove anything extra
if *ns == nil {
*ns = make([]T, 0) // Don't leave nil, init to empty
} else {
*ns = (*ns)[:0]
}
return
}
// Compute the number of items based on the item size of the type
if size&7 != 0 {
dec.err = fmt.Errorf("%w: length %d, item size %d", ErrDynamicStaticsIndivisible, size, 8)
return
}
itemCount := size >> 3
if uint64(itemCount) > maxItems {
dec.err = fmt.Errorf("%w: decoded %d, max %d", ErrMaxItemsExceeded, itemCount, maxItems)
return
}
// Expand the slice if needed and decode the objects
if uint32(cap(*ns)) < itemCount {
*ns = make([]T, itemCount)
} else {
*ns = (*ns)[:itemCount]
}
if dec.inReader != nil {
for i := uint32(0); i < itemCount; i++ {
_, dec.err = io.ReadFull(dec.inReader, dec.buf[:8])
if dec.err != nil {
return
}
(*ns)[i] = T(binary.LittleEndian.Uint64(dec.buf[:8]))
}
dec.inRead += 8 * itemCount
} else {
for i := uint32(0); i < itemCount; i++ {
if len(dec.inBuffer) < 8 {
dec.err = io.ErrUnexpectedEOF
return
}
(*ns)[i] = T(binary.LittleEndian.Uint64(dec.inBuffer))
dec.inBuffer = dec.inBuffer[8:]
}
}
}
// DecodeSliceOfUint64sContentOnFork is the lazy data reader of DecodeSliceOfUint64sOffsetOnFork.
func DecodeSliceOfUint64sContentOnFork[T ~uint64](dec *Decoder, ns *[]T, maxItems uint64, filter ForkFilter) {
// If the field is not active in the current fork, clear out the output
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
*ns = nil
return
}
// Otherwise fall back to the standard decoder
DecodeSliceOfUint64sContent(dec, ns, maxItems)
}
// DecodeArrayOfStaticBytes parses a static array of static binary blobs.
func DecodeArrayOfStaticBytes[T commonBytesArrayLengths[U], U commonBytesLengths](dec *Decoder, blobs *T) {
// The code below should have used `(*blobs)[:]`, alas Go's generics compiler
// is missing that (i.e. a bug): https://github.com/golang/go/issues/51740
DecodeUnsafeArrayOfStaticBytes(dec, unsafe.Slice(&(*blobs)[0], len(*blobs)))
}
// DecodeUnsafeArrayOfStaticBytes parses a static array of static binary blobs.
func DecodeUnsafeArrayOfStaticBytes[T commonBytesLengths](dec *Decoder, blobs []T) {
if dec.err != nil {
return
}
if dec.inReader != nil {
for i := 0; i < len(blobs); i++ {
// The code below should have used `(*blobs)[i][:]`, alas Go's generics compiler
// is missing that (i.e. a bug): https://github.com/golang/go/issues/51740
_, dec.err = io.ReadFull(dec.inReader, unsafe.Slice(&(blobs)[i][0], len((blobs)[i])))
if dec.err != nil {
return
}
dec.inRead += uint32(len((blobs)[i]))
}
} else {
for i := 0; i < len(blobs); i++ {
if len(dec.inBuffer) < len((blobs)[i]) {
dec.err = io.ErrUnexpectedEOF
return
}
// The code below should have used `blobs[i][:]`, alas Go's generics compiler
// is missing that (i.e. a bug): https://github.com/golang/go/issues/51740
copy(unsafe.Slice(&(blobs)[i][0], len((blobs)[i])), dec.inBuffer)
dec.inBuffer = dec.inBuffer[len((blobs)[i]):]
}
}
}
// DecodeCheckedArrayOfStaticBytes parses a static array of static binary blobs.
func DecodeCheckedArrayOfStaticBytes[T commonBytesLengths](dec *Decoder, blobs *[]T, size uint64) {
if dec.err != nil {
return
}
// Expand the byte-array slice if needed and fill it with the data
if uint64(cap(*blobs)) < size {
*blobs = make([]T, size)
} else {
*blobs = (*blobs)[:size]
}
if dec.inReader != nil {
for i := 0; i < len(*blobs); i++ {
// The code below should have used `(*blobs)[i][:]`, alas Go's generics compiler
// is missing that (i.e. a bug): https://github.com/golang/go/issues/51740
_, dec.err = io.ReadFull(dec.inReader, unsafe.Slice(&(*blobs)[i][0], len((*blobs)[i])))
if dec.err != nil {
return
}
dec.inRead += uint32(len((*blobs)[i]))
}
} else {
for i := 0; i < len(*blobs); i++ {
if len(dec.inBuffer) < len((*blobs)[i]) {
dec.err = io.ErrUnexpectedEOF
return
}
// The code below should have used `blobs[i][:]`, alas Go's generics compiler
// is missing that (i.e. a bug): https://github.com/golang/go/issues/51740
copy(unsafe.Slice(&(*blobs)[i][0], len((*blobs)[i])), dec.inBuffer)
dec.inBuffer = dec.inBuffer[len((*blobs)[i]):]
}
}
}
// DecodeSliceOfStaticBytesOffset parses a dynamic slice of static binary blobs.
func DecodeSliceOfStaticBytesOffset[T commonBytesLengths](dec *Decoder, blobs *[]T) {
dec.decodeOffset(false)
}
// DecodeSliceOfStaticBytesOffsetOnFork parses a dynamic slice of static binary
// blobs if present in a fork.
func DecodeSliceOfStaticBytesOffsetOnFork[T commonBytesLengths](dec *Decoder, blobs *[]T, filter ForkFilter) {
// If the field is not active in the current fork, skip parsing the offset
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
return
}
// Otherwise fall back to the standard decoder
DecodeSliceOfStaticBytesOffset(dec, blobs)
}
// DecodeSliceOfStaticBytesContent is the lazy data reader of DecodeSliceOfStaticBytesOffset.
func DecodeSliceOfStaticBytesContent[T commonBytesLengths](dec *Decoder, blobs *[]T, maxItems uint64) {
if dec.err != nil {
return
}
// Compute the length of the encoded binaries based on the seen offsets
size := dec.retrieveSize()
if size == 0 {
// Empty slice, remove anything extra
if *blobs == nil {
*blobs = make([]T, 0) // Don't leave nil, init to empty
} else {
*blobs = (*blobs)[:0]
}
return
}
// Compute the number of items based on the item size of the type
var sizer T // SizeSSZ is on *U, objects is static, so nil T is fine
itemSize := uint32(len(sizer))
if size%itemSize != 0 {
dec.err = fmt.Errorf("%w: length %d, item size %d", ErrDynamicStaticsIndivisible, size, itemSize)
return
}
itemCount := size / itemSize
if uint64(itemCount) > maxItems {
dec.err = fmt.Errorf("%w: decoded %d, max %d", ErrMaxItemsExceeded, itemCount, maxItems)
return
}
// Expand the slice if needed and decode the objects
if uint32(cap(*blobs)) < itemCount {
*blobs = make([]T, itemCount)
} else {
*blobs = (*blobs)[:itemCount]
}
// Descend into a new data slot to track/verify a new sub-length
dec.descendIntoSlot(size)
defer dec.ascendFromSlot()
if dec.inReader != nil {
for i := uint32(0); i < itemCount; i++ {
// The code below should have used `blobs[i][:]`, alas Go's generics compiler
// is missing that (i.e. a bug): https://github.com/golang/go/issues/51740
_, dec.err = io.ReadFull(dec.inReader, unsafe.Slice(&(*blobs)[i][0], len((*blobs)[i])))
if dec.err != nil {
return
}
dec.inRead += uint32(len((*blobs)[i]))
}
} else {
for i := uint32(0); i < itemCount; i++ {
if len(dec.inBuffer) < len((*blobs)[i]) {
dec.err = io.ErrUnexpectedEOF
return
}
// The code below should have used `blobs[i][:]`, alas Go's generics compiler
// is missing that (i.e. a bug): https://github.com/golang/go/issues/51740
copy(unsafe.Slice(&(*blobs)[i][0], len((*blobs)[i])), dec.inBuffer)
dec.inBuffer = dec.inBuffer[len((*blobs)[i]):]
}
}
}
// DecodeSliceOfStaticBytesContentOnFork is the lazy data reader of DecodeSliceOfStaticBytesOffsetOnFork.
func DecodeSliceOfStaticBytesContentOnFork[T commonBytesLengths](dec *Decoder, blobs *[]T, maxItems uint64, filter ForkFilter) {
// If the field is not active in the current fork, clear out the output
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
*blobs = nil
return
}
// Otherwise fall back to the standard decoder
DecodeSliceOfStaticBytesContent(dec, blobs, maxItems)
}
// DecodeSliceOfDynamicBytesOffset parses a dynamic slice of dynamic binary blobs.
func DecodeSliceOfDynamicBytesOffset(dec *Decoder, blobs *[][]byte) {
dec.decodeOffset(false)
}
// DecodeSliceOfDynamicBytesOffsetOnFork parses a dynamic slice of dynamic binary
// blobs if present in a fork.
func DecodeSliceOfDynamicBytesOffsetOnFork(dec *Decoder, blobs *[][]byte, filter ForkFilter) {
// If the field is not active in the current fork, skip parsing the offset
if dec.codec.fork < filter.Added || (filter.Removed > ForkUnknown && dec.codec.fork >= filter.Removed) {
return
}
// Otherwise fall back to the standard decoder
DecodeSliceOfDynamicBytesOffset(dec, blobs)
}
// DecodeSliceOfDynamicBytesContent is the lazy data reader of DecodeSliceOfDynamicBytesOffset.
func DecodeSliceOfDynamicBytesContent(dec *Decoder, blobs *[][]byte, maxItems uint64, maxSize uint64) {
if dec.err != nil {
return
}
// Compute the length of the blob slice based on the seen offsets and sanity
// check for empty slice or possibly bad data (too short to encode anything)
size := dec.retrieveSize()
if size == 0 {
// Empty slice, remove anything extra
if *blobs == nil {
*blobs = make([][]byte, 0) // Don't leave nil, init to empty
} else {
*blobs = (*blobs)[:0]
}
return
}
if size < 4 {
dec.err = fmt.Errorf("%w: %d bytes available", ErrShortCounterOffset, size)
return
}
// Descend into a new data slot to track/verify a new sub-length
dec.descendIntoSlot(size)
defer dec.ascendFromSlot()
// Since we're decoding a dynamic slice of dynamic objects (blobs here), the
// first offset will also act as a counter at to how many items there are in
// the list (x4 bytes for offsets being uint32).
dec.decodeOffset(true)
if dec.err != nil {
return
}
if dec.offset == 0 {