-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdecoder.go
775 lines (675 loc) · 17.6 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
package bin
import (
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"math"
"reflect"
"strings"
"unicode/utf8"
"go.uber.org/zap"
)
var TypeSize = struct {
Bool int
Byte int
Int8 int
Int16 int
Uint8 int
Uint16 int
Uint32 int
Uint64 int
Uint128 int
Float32 int
Float64 int
PublicKey int
Signature int
Tstamp int
BlockTimestamp int
CurrencyName int
}{
Byte: 1,
Bool: 1,
Int8: 1,
Int16: 2,
Uint8: 1,
Uint16: 2,
Uint32: 4,
Uint64: 8,
Uint128: 16,
Float32: 4,
Float64: 8,
}
// Decoder implements the EOS unpacking, similar to FC_BUFFER
type Decoder struct {
data []byte
pos int
currentFieldOpt *option
}
func NewDecoder(data []byte) *Decoder {
return &Decoder{
data: data,
}
}
func (d *Decoder) Decode(v interface{}) (err error) {
return d.decodeWithOption(v, nil)
}
func (d *Decoder) decodeWithOption(v interface{}, option *option) (err error) {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Ptr {
return &InvalidDecoderError{reflect.TypeOf(v)}
}
// We decode rv not rv.Elem because the Unmarshaler interface
// test must be applied at the top level of the value.
err = d.decode(rv, option)
if err != nil {
return err
}
return nil
}
func (d *Decoder) decode(rv reflect.Value, opt *option) (err error) {
if opt == nil {
opt = newDefaultOption()
}
d.currentFieldOpt = opt
unmarshaler, rv := indirect(rv, opt.isOptional())
if traceEnabled {
zlog.Debug("decode: type",
zap.Stringer("value_kind", rv.Kind()),
zap.Bool("has_unmarshaler", (unmarshaler != nil)),
zap.Reflect("options", opt),
)
}
if opt.isOptional() {
isPresent, e := d.ReadByte()
if e != nil {
err = fmt.Errorf("decode: %t isPresent, %s", rv.Type(), e)
return
}
if isPresent == 0 {
if traceEnabled {
zlog.Debug("decode: skipping optional value", zap.Stringer("type", rv.Kind()))
}
rv.Set(reflect.Zero(rv.Type()))
return
}
// we have ptr here we should not go get the element
unmarshaler, rv = indirect(rv, false)
}
if unmarshaler != nil {
if traceEnabled {
zlog.Debug("decode: using UnmarshalBinary method to decode type")
}
return unmarshaler.UnmarshalBinary(d)
}
rt := rv.Type()
switch rv.Kind() {
case reflect.String:
s, e := d.ReadString()
if e != nil {
err = e
return
}
rv.SetString(s)
return
case reflect.Uint8:
var n byte
n, err = d.ReadByte()
rv.SetUint(uint64(n))
return
case reflect.Int8:
var n int8
n, err = d.ReadInt8()
rv.SetInt(int64(n))
return
case reflect.Int16:
var n int16
n, err = d.ReadInt16(opt.Order)
rv.SetInt(int64(n))
return
case reflect.Int32:
var n int32
n, err = d.ReadInt32(opt.Order)
rv.SetInt(int64(n))
return
case reflect.Int64:
var n int64
n, err = d.ReadInt64(opt.Order)
rv.SetInt(int64(n))
return
case reflect.Uint16:
var n uint16
n, err = d.ReadUint16(opt.Order)
rv.SetUint(uint64(n))
return
case reflect.Uint32:
var n uint32
n, err = d.ReadUint32(opt.Order)
rv.SetUint(uint64(n))
return
case reflect.Uint64:
var n uint64
n, err = d.ReadUint64(opt.Order)
rv.SetUint(n)
return
case reflect.Float32:
var n float32
n, err = d.ReadFloat32(opt.Order)
rv.SetFloat(float64(n))
return
case reflect.Float64:
var n float64
n, err = d.ReadFloat64(opt.Order)
rv.SetFloat(n)
return
case reflect.Bool:
var r bool
r, err = d.ReadBool()
rv.SetBool(r)
return
}
switch rt.Kind() {
case reflect.Array:
length := rt.Len()
if traceEnabled {
zlog.Debug("decoding: reading array", zap.Int("length", length))
}
for i := 0; i < length; i++ {
if err = d.decode(rv.Index(i), opt); err != nil {
return
}
}
return
case reflect.Slice:
var l int
if opt.hasSizeOfSlice() {
l = opt.getSizeOfSlice()
} else {
length, err := d.ReadUvarint64()
if err != nil {
return err
}
l = int(length)
}
if traceEnabled {
zlog.Debug("reading slice", zap.Int("len", l), typeField("type", rv))
}
rv.Set(reflect.MakeSlice(rt, l, l))
for i := 0; i < l; i++ {
if err = d.decode(rv.Index(i), opt); err != nil {
return
}
}
case reflect.Struct:
if err = d.decodeStruct(rt, rv); err != nil {
return
}
default:
return fmt.Errorf("decode: unsupported type %q", rt)
}
return
}
func (d *Decoder) decodeStruct(rt reflect.Type, rv reflect.Value) (err error) {
l := rv.NumField()
if traceEnabled {
zlog.Debug("decode: struct", zap.Int("fields", l), zap.Stringer("type", rv.Kind()))
}
sizeOfMap := map[string]int{}
seenBinaryExtensionField := false
for i := 0; i < l; i++ {
structField := rt.Field(i)
fieldTag := parseFieldTag(structField.Tag)
if fieldTag.Skip {
if traceEnabled {
zlog.Debug("decode: skipping struct field with skip flag",
zap.String("struct_field_name", structField.Name),
)
}
continue
}
if !fieldTag.BinaryExtension && seenBinaryExtensionField {
panic(fmt.Sprintf("the `bin:\"binary_extension\"` tags must be packed together at the end of struct fields, problematic field %q", structField.Name))
}
if fieldTag.BinaryExtension {
seenBinaryExtensionField = true
// FIXME: This works only if what is in `d.data` is the actual full data buffer that
// needs to be decoded. If there is for example two structs in the buffer, this
// will not work as we would continue into the next struct.
//
// But at the same time, does it make sense otherwise? What would be the inference
// rule in the case of extra bytes available? Continue decoding and revert if it's
// not working? But how to detect valid errors?
if len(d.data[d.pos:]) <= 0 {
continue
}
}
v := rv.Field(i)
if !v.CanSet() {
// This means that the field cannot be set, to fix this
// we need to create a pointer to said field
if !v.CanAddr() {
// we cannot create a point to field skipping
if traceEnabled {
zlog.Debug("skipping struct field that cannot be addressed",
zap.String("struct_field_name", structField.Name),
zap.Stringer("struct_value_type", v.Kind()),
)
}
return fmt.Errorf("unable to decode a none setup struc field %q with type %q", structField.Name, v.Kind())
}
v = v.Addr()
}
if !v.CanSet() {
if traceEnabled {
zlog.Debug("skipping struct field that cannot be addressed",
zap.String("struct_field_name", structField.Name),
zap.Stringer("struct_value_type", v.Kind()),
)
}
continue
}
option := &option{
OptionalField: fieldTag.Optional,
Order: fieldTag.Order,
}
if s, ok := sizeOfMap[structField.Name]; ok {
option.setSizeOfSlice(s)
}
if traceEnabled {
zlog.Debug("decode: struct field",
zap.Stringer("struct_field_value_type", v.Kind()),
zap.String("struct_field_name", structField.Name),
zap.Reflect("struct_field_tags", fieldTag),
zap.Reflect("struct_field_option", option),
)
}
if err = d.decode(v, option); err != nil {
return
}
if fieldTag.SizeOf != nil {
size := sizeof(structField.Type, v)
for _, sizeOfField := range fieldTag.SizeOf {
if traceEnabled {
zlog.Debug("setting size of field",
zap.String("field_name", sizeOfField),
zap.Int("size", size),
)
}
sizeOfMap[sizeOfField] = size
}
}
}
return
}
func sizeof(t reflect.Type, v reflect.Value) int {
switch t.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return int(v.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
n := int(v.Uint())
// all the builtin array length types are native int
// so this guards against weird truncation
if n < 0 {
return 0
}
return n
default:
panic(fmt.Sprintf("sizeof field "))
}
}
var ErrVarIntBufferSize = errors.New("varint: invalid buffer size")
func (d *Decoder) ReadUvarint64() (uint64, error) {
l, read := binary.Uvarint(d.data[d.pos:])
if read <= 0 {
return l, ErrVarIntBufferSize
}
if traceEnabled {
zlog.Debug("decode: read uvarint64", zap.Uint64("val", l))
}
d.pos += read
return l, nil
}
func (d *Decoder) ReadVarint64() (out int64, err error) {
l, read := binary.Varint(d.data[d.pos:])
if read <= 0 {
return l, ErrVarIntBufferSize
}
if traceEnabled {
zlog.Debug("decode: read varint", zap.Int64("val", l))
}
d.pos += read
return l, nil
}
func (d *Decoder) ReadVarint32() (out int32, err error) {
n, err := d.ReadVarint64()
if err != nil {
return out, err
}
out = int32(n)
if traceEnabled {
zlog.Debug("decode: read varint32", zap.Int32("val", out))
}
return
}
func (d *Decoder) ReadUvarint32() (out uint32, err error) {
n, err := d.ReadUvarint64()
if err != nil {
return out, err
}
out = uint32(n)
if traceEnabled {
zlog.Debug("decode: read uvarint32", zap.Uint32("val", out))
}
return
}
func (d *Decoder) ReadVarint16() (out int16, err error) {
n, err := d.ReadVarint64()
if err != nil {
return out, err
}
out = int16(n)
if traceEnabled {
zlog.Debug("decode: read varint16", zap.Int16("val", out))
}
return
}
func (d *Decoder) ReadUvarint16() (out uint16, err error) {
n, err := d.ReadUvarint64()
if err != nil {
return out, err
}
out = uint16(n)
if traceEnabled {
zlog.Debug("decode: read uvarint16", zap.Uint16("val", out))
}
return
}
func (d *Decoder) ReadByteArray() (out []byte, err error) {
l, err := d.ReadUvarint64()
if err != nil {
return nil, err
}
if len(d.data) < d.pos+int(l) {
return nil, fmt.Errorf("byte array: varlen=%d, missing %d bytes", l, d.pos+int(l)-len(d.data))
}
out = d.data[d.pos : d.pos+int(l)]
d.pos += int(l)
if traceEnabled {
zlog.Debug("decode: read byte array", zap.Stringer("hex", HexBytes(out)))
}
return
}
func (d *Decoder) ReadByte() (out byte, err error) {
if d.Remaining() < TypeSize.Byte {
err = fmt.Errorf("required [1] byte, remaining [%d]", d.Remaining())
return
}
out = d.data[d.pos]
d.pos++
if traceEnabled {
zlog.Debug("decode: read byte", zap.Uint8("byte", out), zap.String("hex", hex.EncodeToString([]byte{out})))
}
return
}
func (d *Decoder) ReadBool() (out bool, err error) {
if d.Remaining() < TypeSize.Bool {
err = fmt.Errorf("bool required [%d] byte, remaining [%d]", TypeSize.Bool, d.Remaining())
return
}
b, err := d.ReadByte()
if err != nil {
err = fmt.Errorf("readBool, %s", err)
}
out = b != 0
if traceEnabled {
zlog.Debug("decode: read bool", zap.Bool("val", out))
}
return
}
func (d *Decoder) ReadUint8() (out uint8, err error) {
out, err = d.ReadByte()
return
}
func (d *Decoder) ReadInt8() (out int8, err error) {
b, err := d.ReadByte()
out = int8(b)
if traceEnabled {
zlog.Debug("decode: read int8", zap.Int8("val", out))
}
return
}
func (d *Decoder) ReadUint16(order binary.ByteOrder) (out uint16, err error) {
if d.Remaining() < TypeSize.Uint16 {
err = fmt.Errorf("uint16 required [%d] bytes, remaining [%d]", TypeSize.Uint16, d.Remaining())
return
}
out = order.Uint16(d.data[d.pos:])
d.pos += TypeSize.Uint16
if traceEnabled {
zlog.Debug("decode: read uint16", zap.Uint16("val", out))
}
return
}
func (d *Decoder) ReadInt16(order binary.ByteOrder) (out int16, err error) {
n, err := d.ReadUint16(order)
out = int16(n)
if traceEnabled {
zlog.Debug("decode: read int16", zap.Int16("val", out))
}
return
}
func (d *Decoder) ReadInt64(order binary.ByteOrder) (out int64, err error) {
n, err := d.ReadUint64(order)
out = int64(n)
if traceEnabled {
zlog.Debug("decode: read int64", zap.Int64("val", out))
}
return
}
func (d *Decoder) ReadUint32(order binary.ByteOrder) (out uint32, err error) {
if d.Remaining() < TypeSize.Uint32 {
err = fmt.Errorf("uint32 required [%d] bytes, remaining [%d]", TypeSize.Uint32, d.Remaining())
return
}
out = order.Uint32(d.data[d.pos:])
d.pos += TypeSize.Uint32
if traceEnabled {
zlog.Debug("decode: read uint32", zap.Uint32("val", out))
}
return
}
func (d *Decoder) ReadInt32(order binary.ByteOrder) (out int32, err error) {
n, err := d.ReadUint32(order)
out = int32(n)
if traceEnabled {
zlog.Debug("decode: read int32", zap.Int32("val", out))
}
return
}
func (d *Decoder) ReadUint64(order binary.ByteOrder) (out uint64, err error) {
if d.Remaining() < TypeSize.Uint64 {
err = fmt.Errorf("decode: uint64 required [%d] bytes, remaining [%d]", TypeSize.Uint64, d.Remaining())
return
}
data := d.data[d.pos : d.pos+TypeSize.Uint64]
out = order.Uint64(data)
d.pos += TypeSize.Uint64
if traceEnabled {
zlog.Debug("decode: read uint64", zap.Uint64("val", out), zap.Stringer("hex", HexBytes(data)))
}
return
}
func (d *Decoder) ReadInt128(order binary.ByteOrder) (out Int128, err error) {
v, err := d.ReadUint128(order)
if err != nil {
return
}
return Int128(v), nil
}
func (d *Decoder) ReadUint128(order binary.ByteOrder) (out Uint128, err error) {
if d.Remaining() < TypeSize.Uint128 {
err = fmt.Errorf("uint128 required [%d] bytes, remaining [%d]", TypeSize.Uint128, d.Remaining())
return
}
data := d.data[d.pos : d.pos+TypeSize.Uint128]
if order == binary.LittleEndian {
out.Lo = order.Uint64(data)
out.Hi = order.Uint64(data[8:])
} else {
out.Lo = order.Uint64(data[8:])
out.Hi = order.Uint64(data)
}
d.pos += TypeSize.Uint128
if traceEnabled {
zlog.Debug("decode: read uint128", zap.Stringer("hex", out), zap.Uint64("hi", out.Hi), zap.Uint64("lo", out.Lo))
}
return
}
func (d *Decoder) ReadFloat32(order binary.ByteOrder) (out float32, err error) {
if d.Remaining() < TypeSize.Float32 {
err = fmt.Errorf("float32 required [%d] bytes, remaining [%d]", TypeSize.Float32, d.Remaining())
return
}
n := order.Uint32(d.data[d.pos:])
out = math.Float32frombits(n)
d.pos += TypeSize.Float32
if traceEnabled {
zlog.Debug("decode: read float32", zap.Float32("val", out))
}
return
}
func (d *Decoder) ReadFloat64(order binary.ByteOrder) (out float64, err error) {
if d.Remaining() < TypeSize.Float64 {
err = fmt.Errorf("float64 required [%d] bytes, remaining [%d]", TypeSize.Float64, d.Remaining())
return
}
n := order.Uint64(d.data[d.pos:])
out = math.Float64frombits(n)
d.pos += TypeSize.Float64
if traceEnabled {
zlog.Debug("decode: read Float64", zap.Float64("val", out))
}
return
}
func (d *Decoder) ReadFloat128(order binary.ByteOrder) (out Float128, err error) {
value, err := d.ReadUint128(order)
if err != nil {
return out, fmt.Errorf("float128: %s", err)
}
return Float128(value), nil
}
func (d *Decoder) SafeReadUTF8String() (out string, err error) {
data, err := d.ReadByteArray()
out = strings.Map(fixUtf, string(data))
if traceEnabled {
zlog.Debug("read safe UTF8 string", zap.String("val", out))
}
return
}
func fixUtf(r rune) rune {
if r == utf8.RuneError {
return '�'
}
return r
}
func (d *Decoder) ReadString() (out string, err error) {
data, err := d.ReadByteArray()
out = string(data)
if traceEnabled {
zlog.Debug("read string", zap.String("val", out))
}
return
}
func (d *Decoder) SkipBytes(count uint) error {
if uint(d.Remaining()) < count {
return fmt.Errorf("request to skip %d but only %d bytes remain", count, d.Remaining())
}
d.pos += int(count)
return nil
}
func (d *Decoder) SetPosition(idx uint) error {
if int(idx) < len(d.data) {
d.pos = int(idx)
return nil
}
return fmt.Errorf("request to set position to %d outsize of buffer (buffer size %d)", idx, len(d.data))
}
func (d *Decoder) Position() uint {
return uint(d.pos)
}
func (d *Decoder) Remaining() int {
return len(d.data) - d.pos
}
func (d *Decoder) HasRemaining() bool {
return d.Remaining() > 0
}
// indirect walks down v allocating pointers as needed,
// until it gets to a non-pointer.
// if it encounters an Unmarshaler, indirect stops and returns that.
// if decodingNull is true, indirect stops at the last pointer so it can be set to nil.
//
// *Note* This is a copy of `encoding/json/decoder.go#indirect` of Golang 1.14.
//
// See here: https://github.com/golang/go/blob/go1.14.2/src/encoding/json/decode.go#L439
func indirect(v reflect.Value, decodingNull bool) (UnmarshalerBinary, reflect.Value) {
// Issue #24153 indicates that it is generally not a guaranteed property
// that you may round-trip a reflect.Value by calling Value.Addr().Elem()
// and expect the value to still be settable for values derived from
// unexported embedded struct fields.
//
// The logic below effectively does this when it first addresses the value
// (to satisfy possible pointer methods) and continues to dereference
// subsequent pointers as necessary.
//
// After the first round-trip, we set v back to the original value to
// preserve the original RW flags contained in reflect.Value.
v0 := v
haveAddr := false
// If v is a named type and is addressable,
// start with its address, so that if the type has pointer methods,
// we find them.
if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() {
haveAddr = true
v = v.Addr()
}
for {
// Load value from interface, but only if the result will be
// usefully addressable.
if v.Kind() == reflect.Interface && !v.IsNil() {
e := v.Elem()
if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) {
haveAddr = false
v = e
continue
}
}
if v.Kind() != reflect.Ptr {
break
}
if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() {
break
}
// Prevent infinite loop if v is an interface pointing to its own address:
// var v interface{}
// v = &v
if v.Elem().Kind() == reflect.Interface && v.Elem().Elem() == v {
v = v.Elem()
break
}
if v.IsNil() {
v.Set(reflect.New(v.Type().Elem()))
}
if v.Type().NumMethod() > 0 && v.CanInterface() {
if u, ok := v.Interface().(UnmarshalerBinary); ok {
return u, reflect.Value{}
}
}
if haveAddr {
v = v0 // restore original value after round-trip Value.Addr().Elem()
haveAddr = false
} else {
v = v.Elem()
}
}
return nil, v
}