forked from streamingfast/eth-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoder.go
542 lines (459 loc) · 15 KB
/
encoder.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
// Copyright 2021 dfuse Platform Inc.
//
// 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 eth
import (
"encoding/hex"
"fmt"
"math/big"
"reflect"
"strings"
"go.uber.org/zap"
"golang.org/x/crypto/sha3"
)
type buffer []byte
func (b buffer) String() string {
return hex.EncodeToString([]byte(b))
}
type Encoder struct {
buffer []byte
}
func NewEncoder() *Encoder {
return &Encoder{}
}
func (e *Encoder) String() string {
return hex.EncodeToString(e.buffer)
}
func (e *Encoder) Buffer() []byte {
return e.buffer
}
func (e *Encoder) WriteMethodCall(method *MethodCall) error {
if len(method.Data) != len(method.MethodDef.Parameters) {
return fmt.Errorf("method is expecting %d parameters but %d were provided", len(method.MethodDef.Parameters), len(method.Data))
}
methodSignature := method.MethodDef.Signature()
err := e.write("method", nil, methodSignature)
if err != nil {
return fmt.Errorf("unable to write method in buffer: %w", err)
}
if tracer.Enabled() {
zlog.Debug("written method name in buffer",
zap.Stringer("buf", buffer(e.buffer)),
zap.String("method_name", methodSignature),
)
}
return e.writeParameters(4, method.MethodDef.Parameters, method.Data)
}
func (e *Encoder) WriteParameters(parameters []*MethodParameter, data []interface{}) error {
return e.writeParameters(0, parameters, data)
}
func (e *Encoder) writeParameters(methodSelectorOffset int, parameters []*MethodParameter, data []interface{}) error {
type arrayToInsert struct {
buffOffset uint64
typeName string
components []*StructComponent
value interface{}
}
slicesToInsert := []arrayToInsert{}
for idx, param := range parameters {
if isOffsetType(param.TypeName) {
slicesToInsert = append(slicesToInsert, arrayToInsert{
buffOffset: uint64(len(e.buffer)),
typeName: param.TypeName,
components: param.Components,
value: data[idx],
})
if tracer.Enabled() {
zlog.Debug("writting placeholder offset in buffer", zap.String("input_type", param.TypeName), zap.Int("input_idx", idx))
}
if err := e.write("uint64", nil, uint64(0)); err != nil {
return fmt.Errorf("unable to write slice placeholder: %w", err)
}
if tracer.Enabled() {
zlog.Debug("written slice placeholder in buffer",
zap.String("input_type", param.TypeName),
zap.Int("input_idx", idx),
)
}
continue
}
if err := e.write(param.TypeName, param.Components, data[idx]); err != nil {
return fmt.Errorf("unable to write input.%d %q in buffer: %w", idx, param.TypeName, err)
}
if tracer.Enabled() {
zlog.Debug("written input data in buffer",
zap.Stringer("buf", buffer(e.buffer)),
zap.String("input_type", param.TypeName),
zap.Int("input_idx", idx),
)
}
}
for sidx, slc := range slicesToInsert {
// Offset should not include the signatures' bytes if present, the `methodSelectorOffset` argument represents that
dataLength := uint64(len(e.buffer)) - uint64(methodSelectorOffset)
d, err := e.encodeUint(dataLength, 64)
if err != nil {
return fmt.Errorf("unable to encode slice offset: %w", err)
}
err = e.override(slc.buffOffset, d)
if err != nil {
return fmt.Errorf("unable to insert slice offset in buffer: %w", err)
}
if tracer.Enabled() {
zlog.Debug("inserted slice offset in buffer",
zap.String("input_type", slc.typeName),
zap.Int("slice_idx", sidx),
)
}
err = e.write(slc.typeName, slc.components, slc.value)
if err != nil {
return fmt.Errorf("unable to write slice in buffer: %w", err)
}
if tracer.Enabled() {
zlog.Debug("inserted slice in buffer",
zap.Stringer("buf", buffer(e.buffer)),
zap.String("input_tyewpe", slc.typeName),
zap.Int("slice_idx", sidx),
)
}
}
return nil
}
func (e *Encoder) Write(parameter *MethodParameter, in interface{}) error {
return e.write(parameter.TypeName, parameter.Components, in)
}
func (e *Encoder) write(typeName string, components []*StructComponent, in interface{}) error {
var isAnArray bool
isAnArray, resolvedTypeName := isArray(typeName)
if !isAnArray {
return e.writeElement(resolvedTypeName, components, in)
}
s := reflect.ValueOf(in)
switch s.Kind() {
case reflect.Slice:
if tracer.Enabled() {
zlog.Debug("writing length of array", zap.String("typeName", typeName), zap.Int("length", s.Len()))
}
err := e.writeElement("uint64", nil, uint64(s.Len()))
if err != nil {
return fmt.Errorf("cannot write slice %s size: %w", typeName, err)
}
if tracer.Enabled() {
zlog.Debug("writing elements of array", zap.String("typeName", typeName))
}
for i := 0; i < s.Len(); i++ {
err := e.writeElement(resolvedTypeName, components, s.Index(i).Interface())
if err != nil {
return fmt.Errorf("cannot write item from slice %s.%d: %w", typeName, i, err)
}
}
if tracer.Enabled() {
zlog.Debug("ended writing elements of array", zap.String("typeName", typeName))
}
return nil
}
return fmt.Errorf("type %q is not handled right now", typeName)
}
func (e *Encoder) writeElement(typeName string, components []*StructComponent, in interface{}) error {
if tracer.Enabled() {
zlog.Debug("writing element", zap.String("typeName", typeName), zap.Bool("has_components", len(components) > 0))
}
var d []byte
var err error
switch typeName {
case "bool":
d, err = e.encodeBool(in.(bool))
case "uint8":
d, err = e.encodeUintFromInterface(in, 8)
case "uint16":
d, err = e.encodeUintFromInterface(in, 16)
case "uint24":
d, err = e.encodeUintFromInterface(in, 24)
case "uint32":
d, err = e.encodeUintFromInterface(in, 32)
case "uint40":
d, err = e.encodeUintFromInterface(in, 40)
case "uint48":
d, err = e.encodeUintFromInterface(in, 48)
case "uint56":
d, err = e.encodeUintFromInterface(in, 56)
case "uint64":
d, err = e.encodeUintFromInterface(in, 64)
case "uint72", "uint80", "uint88", "uint96", "uint104", "uint112", "uint120", "uint128", "uint136", "uint144", "uint152", "uint160", "uint168", "uint176", "uint184", "uint192", "uint200", "uint208", "uint216", "uint224", "uint232", "uint240", "uint248", "uint256":
switch v := in.(type) {
case big.Int:
d, err = e.encodeBigInt(&v)
case *big.Int:
d, err = e.encodeBigInt(v)
default:
err = fmt.Errorf("type %q input should be big.Int or *big.Int, got %T", typeName, v)
}
case "method":
d, err = e.encodeMethod(in.(string))
case "address":
d, err = e.encodeAddress(in.(Address))
case "string":
d, err = e.encodeString(in.(string))
case "bytes":
d, err = e.encodeBytesFromInterface(in)
case "event":
d, err = e.encodeEvent(in.(string))
case "tuple":
return e.writeTuple("<unknown>", components, in)
default:
return fmt.Errorf("type %q is not handled right now", typeName)
}
if err != nil {
return err
}
if tracer.Enabled() {
zlog.Debug("appending to buffer", zap.String("typeName", typeName), zap.Int("actual_offset", len(e.buffer)), zap.Int("new_offset", len(e.buffer)+len(d)), zap.String("bytes", hex.EncodeToString(d)))
}
e.buffer = append(e.buffer, d...)
return nil
}
// writeTuple writes a tuple (defined as a `struct` in Solidity code) to the buffer. The components are the
// ordered definition of fields that form that structure. The `in` is the actual Go type that we should use
// to resolve the struct components. Here all the future types that we should handle:
//
// - Go struct and reflection to resolve the Go fields against the components
// - `map[string]interface{}`` to resolve the Go fields against the components
// - `[]interface{}`` to resolve the element against the components
//
// **Important** Right now, only []interface{} is supported.
func (e *Encoder) writeTuple(structName string, components []*StructComponent, in interface{}) error {
switch v := in.(type) {
case []interface{}:
return e.writeTupleFromSlice(structName, components, v)
case map[string]interface{}:
return e.writeTupleFromMap(structName, components, v)
default:
if in != nil {
rv := reflect.Indirect(reflect.ValueOf(in))
if rv.Kind() == reflect.Struct {
return e.writeTupleFromStruct(structName, components, rv)
}
}
return fmt.Errorf("invalid input type %T when encoding struct %s, only `[]interface{}` and `map[string]interface{}` are supported", v, structName)
}
}
func (e *Encoder) writeTupleFromSlice(structName string, components []*StructComponent, in []interface{}) error {
if len(in) != len(components) {
return fmt.Errorf(`input "[]interface{}" value has %d elements, but struct %q has %d fields`, len(in), structName, len(components))
}
for i, fieldIn := range in {
if err := e.writeComponent(structName, components[i], fieldIn); err != nil {
return err
}
}
return nil
}
func (e *Encoder) writeTupleFromMap(structName string, components []*StructComponent, in map[string]interface{}) error {
if len(in) != len(components) {
return fmt.Errorf(`input "map[string]interface{}" value has %d elements, but struct %q has %d fields`, len(in), structName, len(components))
}
for _, component := range components {
fieldIn, found := in[component.Name]
if !found {
return fmt.Errorf(`struct %q has a field %q but it was not found in input "map[string]interface{}" (keys %q)`, structName, component.Name, strings.Join(mapStringInterfaceKeys(in), ", "))
}
if err := e.writeComponent(structName, component, fieldIn); err != nil {
return err
}
}
return nil
}
func (e *Encoder) writeTupleFromStruct(structName string, components []*StructComponent, in reflect.Value) error {
fieldCount := in.NumField()
if fieldCount < len(components) {
return fmt.Errorf(`input %q value has only %d fields, but struct %q has %d fields`, in.Type().String(), fieldCount, structName, len(components))
}
writeCount := 0
for i := 0; i < fieldCount; i++ {
field := in.Field(i)
if !field.CanInterface() {
if tracer.Enabled() {
zlog.Debug("skipping struct field", zap.String("field", field.Type().Field(i).Name))
continue
}
}
if writeCount >= len(components) {
return fmt.Errorf(`input %q value with %d fields has more field to write than struct %q which has %d fields`, in.Type().String(), fieldCount, structName, len(components))
}
if err := e.writeComponent(structName, components[i], field.Interface()); err != nil {
return err
}
writeCount++
}
return nil
}
func (e *Encoder) writeComponent(structName string, component *StructComponent, in interface{}) error {
if tracer.Enabled() {
zlog.Debug("about to write struct component", zap.Stringer("component", component), zap.String("input_type", fmt.Sprintf("%T", in)))
}
if err := e.writeElement(component.Type, nil, in); err != nil {
return fmt.Errorf(`unable to write "%s#%s: %w"`, structName, component.Name, err)
}
return nil
}
func (e *Encoder) encodeBytesFromInterface(input interface{}) ([]byte, error) {
var bytes []byte
switch v := input.(type) {
case []byte:
bytes = v
case Hex:
bytes = []byte(v)
case Hash:
bytes = []byte(v)
}
return e.encodeBytes(bytes)
}
func (e *Encoder) encodeUintFromInterface(input interface{}, size uint64) ([]byte, error) {
switch v := input.(type) {
case uint8:
return e.encodeUint(uint64(v), size)
case uint16:
return e.encodeUint(uint64(v), size)
case uint32:
return e.encodeUint(uint64(v), size)
case uint64:
return e.encodeUint(uint64(v), size)
case Uint8:
return e.encodeUint(uint64(v), size)
case Uint16:
return e.encodeUint(uint64(v), size)
case Uint32:
return e.encodeUint(uint64(v), size)
case Uint64:
return e.encodeUint(uint64(v), size)
case *big.Int:
return e.encodeUint(v.Uint64(), size)
default:
return nil, fmt.Errorf("unsupported uint from type %T", input)
}
}
func (e *Encoder) encodeUint(input uint64, size uint64) ([]byte, error) {
byteCount := size / 8
buf := make([]byte, byteCount)
_ = buf[byteCount-1] // early bounds check to guarantee safety of writes below
for i := uint64(0); i < byteCount; i++ {
shift := (byteCount - 1 - i) * 8
buf[i] = byte(input >> shift)
}
return pad(buf), nil
}
func (e *Encoder) encodeBigInt(input *big.Int) ([]byte, error) {
return pad(input.Bytes()), nil
}
func (e *Encoder) encodeBool(input bool) ([]byte, error) {
var v *big.Int
if input {
v = big.NewInt(1)
} else {
v = big.NewInt(0)
}
return pad(v.Bytes()), nil
}
func (e *Encoder) encodeAddress(input Address) ([]byte, error) {
return pad(input), nil
}
func (e *Encoder) encodeMethod(input string) ([]byte, error) {
kec := sha3.NewLegacyKeccak256()
_, err := kec.Write([]byte(input))
if err != nil {
return nil, err
}
return kec.Sum(nil)[0:4], nil
}
func (e *Encoder) encodeBytes(input []byte) ([]byte, error) {
buf := make([]byte, 32+len(input))
l, err := e.encodeUint(uint64(len(input)), 64)
if err != nil {
return nil, fmt.Errorf("unable to encode string size: %w", err)
}
for i := 0; i < 32; i++ {
buf[i] = l[i]
}
for i := 0; i < len(input); i++ {
buf[32+i] = input[i]
}
return buf, nil
}
func (e *Encoder) encodeString(input string) ([]byte, error) {
// size: 32 bytes[length of the string] + num_char[1 char is 1 byte] + x
// where x pads the the number to fill the last 32 bytes
buf := make([]byte, (32 + len(input) + (32 - len(input)%32)))
l, err := e.encodeUint(uint64(len(input)), 64)
if err != nil {
return nil, fmt.Errorf("unable to encode string size: %w", err)
}
for i := 0; i < 32; i++ {
buf[i] = l[i]
}
for i := 0; i < len(input); i++ {
buf[32+i] = byte(input[i])
}
return buf, nil
}
func (e *Encoder) encodeEvent(input string) ([]byte, error) {
kec := sha3.NewLegacyKeccak256()
_, err := kec.Write([]byte(input))
if err != nil {
return nil, err
}
return kec.Sum(nil), nil
}
func (e *Encoder) override(offset uint64, data []byte) error {
if uint64(len(e.buffer)) < offset+uint64(len(data)) {
return fmt.Errorf("insuficient room in buffer with length %d to insert data with length %d at offset %d", len(e.buffer), len(data), offset)
}
for i := 0; i < len(data); i++ {
e.buffer[uint64(i)+offset] = data[i]
}
return nil
}
func pad(in []byte) []byte {
d := make([]byte, 32)
offset := 32 - len(in)
for i := 0; i < len(in); i++ {
d[i+offset] = in[i]
}
return d
}
func isOffsetType(typeName string) bool {
// First as they are probably the most probable type
if typeName == "bytes" || typeName == "string" {
return true
}
arr, _ := isArray(typeName)
return arr
}
func isArray(typeName string) (bool, string) {
check := strings.HasSuffix(typeName, "[]")
if check {
return true, strings.TrimRight(typeName, "[]")
}
return false, typeName
}
func mapStringInterfaceKeys(in map[string]interface{}) (out []string) {
if len(in) <= 0 {
return nil
}
i := 0
out = make([]string, len(in))
for k := range in {
out[i] = k
i++
}
return out
}