-
Notifications
You must be signed in to change notification settings - Fork 65
/
abi_type.go
727 lines (617 loc) · 14.1 KB
/
abi_type.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
/*-
*
* Hedera Go SDK
*
* Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use q 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 hedera
import (
"fmt"
"math/big"
"reflect"
"regexp"
"strconv"
"strings"
)
// batch of predefined reflect types
var (
boolT = reflect.TypeOf(bool(false))
uint8T = reflect.TypeOf(uint8(0))
uint16T = reflect.TypeOf(uint16(0))
uint32T = reflect.TypeOf(uint32(0))
uint64T = reflect.TypeOf(uint64(0))
int8T = reflect.TypeOf(int8(0))
int16T = reflect.TypeOf(int16(0))
int32T = reflect.TypeOf(int32(0))
int64T = reflect.TypeOf(int64(0))
addressT = reflect.TypeOf(Address{})
stringT = reflect.TypeOf("")
dynamicBytesT = reflect.SliceOf(reflect.TypeOf(byte(0)))
functionT = reflect.ArrayOf(24, reflect.TypeOf(byte(0)))
tupleT = reflect.TypeOf(map[string]interface{}{})
bigIntT = reflect.TypeOf(new(big.Int))
)
// AbiTypeKind represents the kind of abi type
type AbiTypeKind int
const (
// KindBool is a boolean
KindBool AbiTypeKind = iota
// KindUInt is an uint
KindUInt
// KindInt is an int
KindInt
// KindString is a string
KindString
// KindArray is an array
KindArray
// KindSlice is a slice
KindSlice
// KindAddress is an address
KindAddress
// KindBytes is a bytes array
KindBytes
// KindFixedBytes is a fixed bytes
KindFixedBytes
// KindFixedPoint is a fixed point
KindFixedPoint
// KindTuple is a tuple
KindTuple
// KindFunction is a function
KindFunction
)
func (k AbiTypeKind) String() string {
names := [...]string{
"Bool",
"Uint",
"Int",
"String",
"Array",
"Slice",
"Address",
"Bytes",
"FixedBytes",
"FixedPoint",
"Tuple",
"Function",
}
return names[k]
}
// TupleElem is an element of a tuple
type TupleElem struct {
Name string
Elem *Type
Indexed bool
}
// Type is an ABI type
type Type struct {
kind AbiTypeKind
size int
elem *Type
tuple []*TupleElem
t reflect.Type
itype string
}
func NewTupleType(inputs []*TupleElem) *Type {
return &Type{
kind: KindTuple,
tuple: inputs,
t: tupleT,
}
}
func NewTupleTypeFromArgs(inputs []*ArgumentStr) (*Type, error) {
elems := []*TupleElem{}
for _, i := range inputs {
typ, err := NewTypeFromArgument(i)
if err != nil {
return nil, err
}
elems = append(elems, &TupleElem{
Name: i.Name,
Elem: typ,
Indexed: i.Indexed,
})
}
return NewTupleType(elems), nil
}
// Decode decodes an object using this type
func (t *Type) Decode(input []byte) (interface{}, error) {
return Decode(t, input)
}
// DecodeStruct decodes an object using this type to the out param
func (t *Type) DecodeStruct(input []byte, out interface{}) error {
return DecodeStruct(t, input, out)
}
// InternalType returns the internal type
func (t *Type) InternalType() string {
return t.itype
}
// Encode encodes an object using this type
func (t *Type) Encode(v interface{}) ([]byte, error) {
return Encode(v, t)
}
// String returns the raw representation of the type
func (t *Type) String() string {
return t.Format(false)
}
// nolint
func (t *Type) Format(includeArgs bool) string {
switch t.kind {
case KindTuple:
rawAux := []string{}
for _, i := range t.TupleElems() {
name := i.Elem.Format(includeArgs)
if i.Indexed {
name += " indexed"
}
if includeArgs {
if i.Name != "" {
name += " " + i.Name
}
}
rawAux = append(rawAux, name)
}
return fmt.Sprintf("tuple(%s)", strings.Join(rawAux, ","))
case KindArray:
return fmt.Sprintf("%s[%d]", t.elem.Format(includeArgs), t.size)
case KindSlice:
return fmt.Sprintf("%s[]", t.elem.Format(includeArgs))
case KindBytes:
return "bytes"
case KindFixedBytes:
return fmt.Sprintf("bytes%d", t.size)
case KindString:
return "string"
case KindBool:
return "bool"
case KindAddress:
return "address"
case KindFunction:
return "function"
case KindUInt:
return fmt.Sprintf("uint%d", t.size)
case KindInt:
return fmt.Sprintf("int%d", t.size)
default:
panic(fmt.Errorf("BUG: abi type not found %s", t.kind.String()))
}
}
// Elem returns the elem value for slice and arrays
func (t *Type) Elem() *Type {
return t.elem
}
// Size returns the size of the type
func (t *Type) Size() int {
return t.size
}
// TupleElems returns the elems of the tuple
func (t *Type) TupleElems() []*TupleElem {
return t.tuple
}
// GoType returns the go type
func (t *Type) GoType() reflect.Type {
return t.t
}
// Kind returns the kind of the type
func (t *Type) Kind() AbiTypeKind {
return t.kind
}
func (t *Type) isVariableInput() bool {
return t.kind == KindSlice || t.kind == KindBytes || t.kind == KindString
}
func (t *Type) isDynamicType() bool {
if t.kind == KindTuple {
for _, elem := range t.tuple {
if elem.Elem.isDynamicType() {
return true
}
}
return false
}
return t.kind == KindString || t.kind == KindBytes || t.kind == KindSlice || (t.kind == KindArray && t.elem.isDynamicType())
}
func parseType(arg *ArgumentStr) (string, error) {
if !strings.HasPrefix(arg.Type, "tuple") {
return arg.Type, nil
}
if len(arg.Components) == 0 {
return "tuple()", nil
}
// parse the arg components from the tuple
str := []string{}
for _, i := range arg.Components {
aux, err := parseType(i)
if err != nil {
return "", err
}
if i.Indexed {
str = append(str, aux+" indexed "+i.Name)
} else {
str = append(str, aux+" "+i.Name)
}
}
return fmt.Sprintf("tuple(%s)%s", strings.Join(str, ","), strings.TrimPrefix(arg.Type, "tuple")), nil
}
// NewTypeFromArgument parses an abi type from an argument
func NewTypeFromArgument(arg *ArgumentStr) (*Type, error) {
str, err := parseType(arg)
if err != nil {
return nil, err
}
typ, err := NewType(str)
if err != nil {
return nil, err
}
// fill-in the `internalType` field into the type elems
err = fillIn(typ, arg)
if err != nil {
return nil, err
}
return typ, nil
}
func fillIn(typ *Type, arg *ArgumentStr) error {
typ.itype = arg.InternalType
if len(arg.Components) == 0 {
// no more items, nothing else to do
return nil
}
// tuple types in the ABI with slices are represented as
// tuple()[] or tuple()[2]. Thus, there might be element in the components
// section of the abi but the next item not be a tuple.
for {
kind := typ.kind
if kind == KindTuple {
break
}
if kind != KindArray && kind != KindSlice {
// error
return fmt.Errorf("array or slice not found")
}
typ = typ.Elem()
}
if len(arg.Components) != len(typ.tuple) {
// incorrect length
return fmt.Errorf("incorrect size")
}
for indx, i := range arg.Components {
err := fillIn(typ.tuple[indx].Elem, i)
if err != nil {
return err
}
}
return nil
}
// NewType parses a type in string format
func NewType(s string) (*Type, error) {
l := newLexer(s)
l.nextToken()
return readType(l)
}
func getTypeSize(t *Type) int {
if t.kind == KindArray && !t.elem.isDynamicType() {
if t.elem.kind == KindArray || t.elem.kind == KindTuple {
return t.size * getTypeSize(t.elem)
}
return t.size * 32
} else if t.kind == KindTuple && !t.isDynamicType() {
total := 0
for _, elem := range t.tuple {
total += getTypeSize(elem.Elem)
}
return total
}
return 32
}
var typeRegexp = regexp.MustCompile("^([[:alpha:]]+)([[:digit:]]*)$")
func expectedToken(t tokenType) error {
return fmt.Errorf("expected token %s", t.String())
}
func notExpectedToken(t tokenType) error {
return fmt.Errorf("token '%s' not expected", t.String())
}
// nolint
func readType(l *lexer) (*Type, error) {
var tt *Type
tok := l.nextToken()
isTuple := false
if tok.typ == tupleToken {
if l.nextToken().typ != lparenToken {
return nil, expectedToken(lparenToken)
}
isTuple = true
} else if tok.typ == lparenToken {
isTuple = true
}
if isTuple {
var next token
elems := []*TupleElem{}
for {
name := ""
indexed := false
elem, err := readType(l)
if err != nil {
if l.current.typ == rparenToken && len(elems) == 0 {
// empty tuple 'tuple()'
break
}
return nil, fmt.Errorf("failed to decode type: %v", err)
}
switch l.peek.typ {
case strToken:
l.nextToken()
name = l.current.literal
case indexedToken:
l.nextToken()
indexed = true
if l.peek.typ == strToken {
l.nextToken()
name = l.current.literal
}
}
elems = append(elems, &TupleElem{
Name: name,
Elem: elem,
Indexed: indexed,
})
next = l.nextToken()
if next.typ == commaToken {
continue
} else if next.typ == rparenToken {
break
} else {
return nil, notExpectedToken(next.typ)
}
}
tt = &Type{kind: KindTuple, tuple: elems, t: tupleT}
} else if tok.typ != strToken {
return nil, expectedToken(strToken)
} else {
// Check normal types
elem, err := decodeSimpleType(tok.literal)
if err != nil {
return nil, err
}
tt = elem
}
// check for arrays at the end of the type
for {
if l.peek.typ != lbracketToken {
break
}
l.nextToken()
n := l.nextToken()
var tAux *Type
if n.typ == rbracketToken {
tAux = &Type{kind: KindSlice, elem: tt, t: reflect.SliceOf(tt.t)}
} else if n.typ == numberToken {
size, err := strconv.ParseUint(n.literal, 10, 32)
if err != nil {
return nil, fmt.Errorf("failed to read array size '%s': %v", n.literal, err)
}
tAux = &Type{kind: KindArray, elem: tt, size: int(size), t: reflect.ArrayOf(int(size), tt.t)}
if l.nextToken().typ != rbracketToken {
return nil, expectedToken(rbracketToken)
}
} else {
return nil, notExpectedToken(n.typ)
}
tt = tAux
}
return tt, nil
}
func decodeSimpleType(str string) (*Type, error) {
match := typeRegexp.FindStringSubmatch(str)
if len(match) == 0 {
return nil, fmt.Errorf("type format is incorrect. Expected 'type''bytes' but found '%s'", str)
}
match = match[1:]
var err error
t := match[0]
bytes := 0
ok := false
if bytesStr := match[1]; bytesStr != "" {
bytes, err = strconv.Atoi(bytesStr)
if err != nil {
return nil, fmt.Errorf("failed to parse bytes '%s': %v", bytesStr, err)
}
ok = true
}
// int and uint without bytes default to 256, 'bytes' may
// have or not, the rest dont have bytes
if t == "int" || t == "uint" {
if !ok {
bytes = 256
}
} else if t != "bytes" && ok {
return nil, fmt.Errorf("type %s does not expect bytes", t)
}
switch t {
case "uint":
var k reflect.Type
switch bytes {
case 8:
k = uint8T
case 16:
k = uint16T
case 32:
k = uint32T
case 64:
k = uint64T
default:
if bytes%8 != 0 {
panic(fmt.Errorf("number of bytes has to be M mod 8"))
}
k = bigIntT
}
return &Type{kind: KindUInt, size: bytes, t: k}, nil
case "int":
var k reflect.Type
switch bytes {
case 8:
k = int8T
case 16:
k = int16T
case 32:
k = int32T
case 64:
k = int64T
default:
if bytes%8 != 0 {
panic(fmt.Errorf("number of bytes has to be M mod 8"))
}
k = bigIntT
}
return &Type{kind: KindInt, size: bytes, t: k}, nil
case "byte":
bytes = 1
fallthrough
case "bytes":
if bytes == 0 {
return &Type{kind: KindBytes, t: dynamicBytesT}, nil
}
return &Type{kind: KindFixedBytes, size: bytes, t: reflect.ArrayOf(bytes, reflect.TypeOf(byte(0)))}, nil
case "string":
return &Type{kind: KindString, t: stringT}, nil
case "bool":
return &Type{kind: KindBool, t: boolT}, nil
case "address":
return &Type{kind: KindAddress, t: addressT, size: 20}, nil
case "function":
return &Type{kind: KindFunction, size: 24, t: functionT}, nil
default:
return nil, fmt.Errorf("unknown type '%s'", t)
}
}
type tokenType int
const (
eofToken tokenType = iota
strToken
numberToken
tupleToken
lparenToken
rparenToken
lbracketToken
rbracketToken
commaToken
indexedToken
invalidToken
)
func (t tokenType) String() string {
names := [...]string{
"eof",
"string",
"number",
"tuple",
"(",
")",
"[",
"]",
",",
"indexed",
"<invalid>",
}
return names[t]
}
type token struct {
typ tokenType
literal string
}
type lexer struct {
input string
current token
peek token
position int
readPosition int
ch byte
}
func newLexer(input string) *lexer {
l := &lexer{input: input}
l.readChar()
return l
}
func (l *lexer) readChar() {
if l.readPosition >= len(l.input) {
l.ch = 0
} else {
l.ch = l.input[l.readPosition]
}
l.position = l.readPosition
l.readPosition++
}
func (l *lexer) nextToken() token {
l.current = l.peek
l.peek = l.nextTokenImpl()
return l.current
}
// nolint
func (l *lexer) nextTokenImpl() token {
var tok token
// skip whitespace
for l.ch == ' ' || l.ch == '\t' || l.ch == '\n' || l.ch == '\r' {
l.readChar()
}
switch l.ch {
case ',':
tok.typ = commaToken
case '(':
tok.typ = lparenToken
case ')':
tok.typ = rparenToken
case '[':
tok.typ = lbracketToken
case ']':
tok.typ = rbracketToken
case 0:
tok.typ = eofToken
default:
if isLetter(l.ch) {
tok.literal = l.readIdentifier()
if tok.literal == "tuple" {
tok.typ = tupleToken
} else if tok.literal == "indexed" {
tok.typ = indexedToken
} else {
tok.typ = strToken
}
return tok
} else if isDigit(l.ch) {
return token{numberToken, l.readNumber()}
} else {
tok.typ = invalidToken
}
}
l.readChar()
return tok
}
func (l *lexer) readIdentifier() string {
pos := l.position
for isLetter(l.ch) || isDigit(l.ch) {
l.readChar()
}
return l.input[pos:l.position]
}
func (l *lexer) readNumber() string {
position := l.position
for isDigit(l.ch) {
l.readChar()
}
return l.input[position:l.position]
}
func isDigit(ch byte) bool {
return '0' <= ch && ch <= '9'
}
func isLetter(ch byte) bool {
return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_'
}