-
Notifications
You must be signed in to change notification settings - Fork 65
/
abi_decode.go
422 lines (352 loc) · 8.68 KB
/
abi_decode.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
/*-
*
* 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 (
"encoding/binary"
"encoding/hex"
"fmt"
"math/big"
"reflect"
"strconv"
"strings"
"github.com/mitchellh/mapstructure"
)
// Decode decodes the input with a given type
func Decode(t *Type, input []byte) (interface{}, error) {
if len(input) == 0 {
return nil, fmt.Errorf("empty input")
}
val, _, err := decode(t, input)
return val, err
}
// DecodeStruct decodes the input with a type to a struct
func DecodeStruct(t *Type, input []byte, out interface{}) error {
val, err := Decode(t, input)
if err != nil {
return err
}
dc := &mapstructure.DecoderConfig{
Result: out,
WeaklyTypedInput: true,
TagName: "abi",
}
ms, err := mapstructure.NewDecoder(dc)
if err != nil {
return err
}
if err = ms.Decode(val); err != nil {
return err
}
return nil
}
func decode(t *Type, input []byte) (interface{}, []byte, error) {
var data []byte
var length int
var err error
// safe check, input should be at least 32 bytes
if len(input) < 32 {
return nil, nil, fmt.Errorf("incorrect length")
}
if t.isVariableInput() {
length, err = readLength(input)
if err != nil {
return nil, nil, err
}
} else {
data = input[:32]
}
switch t.kind {
case KindTuple:
return decodeTuple(t, input)
case KindSlice:
return decodeArraySlice(t, input[32:], length)
case KindArray:
return decodeArraySlice(t, input, t.size)
}
var val interface{}
switch t.kind {
case KindBool:
val, err = decodeBool(data)
case KindInt, KindUInt:
val = readInteger(t, data)
case KindString:
val = string(input[32 : 32+length])
case KindBytes:
val = input[32 : 32+length]
case KindAddress:
val, err = readAddr(data)
case KindFixedBytes:
val, err = readFixedBytes(t, data)
case KindFunction:
val, err = readFunctionType(t, data)
default:
return nil, nil, fmt.Errorf("decoding not available for type '%s'", t.kind)
}
return val, input[32:], err
}
var (
maxUint256 = big.NewInt(0).Add(
big.NewInt(0).Exp(big.NewInt(2), big.NewInt(256), nil),
big.NewInt(-1))
maxInt256 = big.NewInt(0).Add(
big.NewInt(0).Exp(big.NewInt(2), big.NewInt(255), nil),
big.NewInt(-1))
)
// Address is an Ethereum address
type Address [20]byte
func min(i, j int) int {
if i < j {
return i
}
return j
}
// BytesToAddress converts bytes to an address object
func BytesToAddress(b []byte) Address {
var a Address
size := len(b)
min := min(size, 20)
copy(a[20-min:], b[len(b)-min:])
return a
}
// Address implements the ethgo.Key interface Address method.
func (a Address) Address() Address {
return a
}
// UnmarshalText implements the unmarshal interface
func (a *Address) UnmarshalText(b []byte) error {
return unmarshalTextByte(a[:], b, 20)
}
// MarshalText implements the marshal interface
func (a Address) MarshalText() ([]byte, error) {
return []byte(a.String()), nil
}
// Bytes returns the bytes of the Address
func (a Address) Bytes() []byte {
return a[:]
}
func (a Address) String() string {
return a.checksumEncode()
}
func unmarshalTextByte(dst, src []byte, size int) error {
str := string(src)
str = strings.Trim(str, "\"")
if !strings.HasPrefix(str, "0x") {
return fmt.Errorf("0x prefix not found")
}
str = str[2:]
b, err := hex.DecodeString(str)
if err != nil {
return err
}
if len(b) != size {
return fmt.Errorf("length %d is not correct, expected %d", len(b), size)
}
copy(dst, b)
return nil
}
func (a Address) checksumEncode() string {
address := strings.ToLower(hex.EncodeToString(a[:]))
hash := hex.EncodeToString(Keccak256Hash([]byte(address)).Bytes())
ret := "0x"
for i := 0; i < len(address); i++ {
character := string(address[i])
num, _ := strconv.ParseInt(string(hash[i]), 16, 64)
if num > 7 {
ret += strings.ToUpper(character)
} else {
ret += character
}
}
return ret
}
func readAddr(b []byte) (Address, error) {
res := Address{}
if len(b) != 32 {
return res, fmt.Errorf("len is not correct")
}
copy(res[:], b[12:])
return res, nil
}
func readInteger(t *Type, b []byte) interface{} {
switch t.t.Kind() {
case reflect.Uint8:
return b[len(b)-1]
case reflect.Uint16:
return binary.BigEndian.Uint16(b[len(b)-2:])
case reflect.Uint32:
return binary.BigEndian.Uint32(b[len(b)-4:])
case reflect.Uint64:
return binary.BigEndian.Uint64(b[len(b)-8:])
case reflect.Int8:
return int8(b[len(b)-1])
case reflect.Int16:
return int16(binary.BigEndian.Uint16(b[len(b)-2:]))
case reflect.Int32:
return int32(binary.BigEndian.Uint32(b[len(b)-4:]))
case reflect.Int64:
return int64(binary.BigEndian.Uint64(b[len(b)-8:]))
default:
ret := new(big.Int).SetBytes(b)
if t.kind == KindUInt {
return ret
}
if ret.Cmp(maxInt256) > 0 {
ret.Add(maxUint256, big.NewInt(0).Neg(ret))
ret.Add(ret, big.NewInt(1))
ret.Neg(ret)
}
return ret
}
}
// nolint
func readFunctionType(t *Type, word []byte) ([24]byte, error) {
res := [24]byte{}
if !allZeros(word[24:32]) {
return res, fmt.Errorf("function type expects the last 8 bytes to be empty but found: %b", word[24:32])
}
copy(res[:], word[0:24])
return res, nil
}
// nolint
func readFixedBytes(t *Type, word []byte) (interface{}, error) {
array := reflect.New(t.t).Elem()
reflect.Copy(array, reflect.ValueOf(word[0:t.size]))
return array.Interface(), nil
}
func decodeTuple(t *Type, data []byte) (interface{}, []byte, error) {
res := make(map[string]interface{})
orig := data
origLen := len(orig)
for indx, arg := range t.tuple {
if len(data) < 32 {
return nil, nil, fmt.Errorf("incorrect length")
}
entry := data
if arg.Elem.isDynamicType() {
offset, err := readOffset(data, origLen)
if err != nil {
return nil, nil, err
}
entry = orig[offset:]
}
val, tail, err := decode(arg.Elem, entry)
if err != nil {
return nil, nil, err
}
if !arg.Elem.isDynamicType() {
data = tail
} else {
data = data[32:]
}
name := arg.Name
if name == "" {
name = strconv.Itoa(indx)
}
if _, ok := res[name]; !ok {
res[name] = val
} else {
return nil, nil, fmt.Errorf("tuple with repeated values")
}
}
return res, data, nil
}
func decodeArraySlice(t *Type, data []byte, size int) (interface{}, []byte, error) {
if size < 0 {
return nil, nil, fmt.Errorf("size is lower than zero")
}
if 32*size > len(data) {
return nil, nil, fmt.Errorf("size is too big")
}
var res reflect.Value
if t.kind == KindSlice {
res = reflect.MakeSlice(t.t, size, size)
} else if t.kind == KindArray {
res = reflect.New(t.t).Elem()
}
orig := data
origLen := len(orig)
for indx := 0; indx < size; indx++ {
isDynamic := t.elem.isDynamicType()
if len(data) < 32 {
return nil, nil, fmt.Errorf("incorrect length")
}
entry := data
if isDynamic {
offset, err := readOffset(data, origLen)
if err != nil {
return nil, nil, err
}
entry = orig[offset:]
}
val, tail, err := decode(t.elem, entry)
if err != nil {
return nil, nil, err
}
if !isDynamic {
data = tail
} else {
data = data[32:]
}
res.Index(indx).Set(reflect.ValueOf(val))
}
return res.Interface(), data, nil
}
func decodeBool(data []byte) (interface{}, error) {
switch data[31] {
case 0:
return false, nil
case 1:
return true, nil
default:
return false, fmt.Errorf("bad boolean")
}
}
func readOffset(data []byte, len int) (int, error) {
offsetBig := big.NewInt(0).SetBytes(data[0:32])
if offsetBig.BitLen() > 63 {
return 0, fmt.Errorf("offset larger than int64: %v", offsetBig.Int64())
}
offset := int(offsetBig.Int64())
if offset > len {
return 0, fmt.Errorf("offset insufficient %v require %v", len, offset)
}
return offset, nil
}
func readLength(data []byte) (int, error) {
lengthBig := big.NewInt(0).SetBytes(data[0:32])
if lengthBig.BitLen() > 63 {
return 0, fmt.Errorf("length larger than int64: %v", lengthBig.Int64())
}
length := int(lengthBig.Uint64())
// if we trim the length in the data there should be enough
// bytes to cover the length
if length > len(data)-32 {
return 0, fmt.Errorf("length insufficient %v require %v", len(data), length)
}
return length, nil
}
func allZeros(b []byte) bool {
for _, i := range b {
if i != 0 {
return false
}
}
return true
}