Skip to content

Commit dec8bba

Browse files
VoR0220fjl
authored andcommitted
accounts/abi: improve type handling, add event support (#14743)
1 parent e929516 commit dec8bba

15 files changed

Lines changed: 903 additions & 847 deletions

‎accounts/abi/abi.go‎

Lines changed: 16 additions & 99 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,6 @@ import (
2020
"encoding/json"
2121
"fmt"
2222
"io"
23-
"reflect"
24-
"strings"
25-
26-
"github.com/ethereum/go-ethereum/common"
2723
)
2824

2925
// The ABI holds information about a contract's context and available
@@ -76,106 +72,27 @@ func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) {
7672
return append(method.Id(), arguments...), nil
7773
}
7874

79-
// these variable are used to determine certain types during type assertion for
80-
// assignment.
81-
var (
82-
r_interSlice = reflect.TypeOf([]interface{}{})
83-
r_hash = reflect.TypeOf(common.Hash{})
84-
r_bytes = reflect.TypeOf([]byte{})
85-
r_byte = reflect.TypeOf(byte(0))
86-
)
87-
8875
// Unpack output in v according to the abi specification
89-
func (abi ABI) Unpack(v interface{}, name string, output []byte) error {
90-
var method = abi.Methods[name]
91-
92-
if len(output) == 0 {
93-
return fmt.Errorf("abi: unmarshalling empty output")
94-
}
95-
96-
// make sure the passed value is a pointer
97-
valueOf := reflect.ValueOf(v)
98-
if reflect.Ptr != valueOf.Kind() {
99-
return fmt.Errorf("abi: Unpack(non-pointer %T)", v)
76+
func (abi ABI) Unpack(v interface{}, name string, output []byte) (err error) {
77+
if err = bytesAreProper(output); err != nil {
78+
return err
10079
}
101-
102-
var (
103-
value = valueOf.Elem()
104-
typ = value.Type()
105-
)
106-
107-
if len(method.Outputs) > 1 {
108-
switch value.Kind() {
109-
// struct will match named return values to the struct's field
110-
// names
111-
case reflect.Struct:
112-
for i := 0; i < len(method.Outputs); i++ {
113-
marshalledValue, err := toGoType(i, method.Outputs[i], output)
114-
if err != nil {
115-
return err
116-
}
117-
reflectValue := reflect.ValueOf(marshalledValue)
118-
119-
for j := 0; j < typ.NumField(); j++ {
120-
field := typ.Field(j)
121-
// TODO read tags: `abi:"fieldName"`
122-
if field.Name == strings.ToUpper(method.Outputs[i].Name[:1])+method.Outputs[i].Name[1:] {
123-
if err := set(value.Field(j), reflectValue, method.Outputs[i]); err != nil {
124-
return err
125-
}
126-
}
127-
}
128-
}
129-
case reflect.Slice:
130-
if !value.Type().AssignableTo(r_interSlice) {
131-
return fmt.Errorf("abi: cannot marshal tuple in to slice %T (only []interface{} is supported)", v)
132-
}
133-
134-
// if the slice already contains values, set those instead of the interface slice itself.
135-
if value.Len() > 0 {
136-
if len(method.Outputs) > value.Len() {
137-
return fmt.Errorf("abi: cannot marshal in to slices of unequal size (require: %v, got: %v)", len(method.Outputs), value.Len())
138-
}
139-
140-
for i := 0; i < len(method.Outputs); i++ {
141-
marshalledValue, err := toGoType(i, method.Outputs[i], output)
142-
if err != nil {
143-
return err
144-
}
145-
reflectValue := reflect.ValueOf(marshalledValue)
146-
if err := set(value.Index(i).Elem(), reflectValue, method.Outputs[i]); err != nil {
147-
return err
148-
}
149-
}
150-
return nil
151-
}
152-
153-
// create a new slice and start appending the unmarshalled
154-
// values to the new interface slice.
155-
z := reflect.MakeSlice(typ, 0, len(method.Outputs))
156-
for i := 0; i < len(method.Outputs); i++ {
157-
marshalledValue, err := toGoType(i, method.Outputs[i], output)
158-
if err != nil {
159-
return err
160-
}
161-
z = reflect.Append(z, reflect.ValueOf(marshalledValue))
162-
}
163-
value.Set(z)
164-
default:
165-
return fmt.Errorf("abi: cannot unmarshal tuple in to %v", typ)
166-
}
167-
80+
// since there can't be naming collisions with contracts and events,
81+
// we need to decide whether we're calling a method or an event
82+
var unpack unpacker
83+
if method, ok := abi.Methods[name]; ok {
84+
unpack = method
85+
} else if event, ok := abi.Events[name]; ok {
86+
unpack = event
16887
} else {
169-
marshalledValue, err := toGoType(0, method.Outputs[0], output)
170-
if err != nil {
171-
return err
172-
}
173-
if err := set(value, reflect.ValueOf(marshalledValue), method.Outputs[0]); err != nil {
174-
return err
175-
}
88+
return fmt.Errorf("abi: could not locate named method or event.")
17689
}
17790

178-
return nil
91+
// requires a struct to unpack into for a tuple return...
92+
if unpack.isTupleReturn() {
93+
return unpack.tupleUnpack(v, output)
94+
}
95+
return unpack.singleUnpack(v, output)
17996
}
18097

18198
func (abi *ABI) UnmarshalJSON(data []byte) error {

‎accounts/abi/abi_test.go‎

Lines changed: 1 addition & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -29,25 +29,6 @@ import (
2929
"github.com/ethereum/go-ethereum/crypto"
3030
)
3131

32-
// formatSilceOutput add padding to the value and adds a size
33-
func formatSliceOutput(v ...[]byte) []byte {
34-
off := common.LeftPadBytes(big.NewInt(int64(len(v))).Bytes(), 32)
35-
output := append(off, make([]byte, 0, len(v)*32)...)
36-
37-
for _, value := range v {
38-
output = append(output, common.LeftPadBytes(value, 32)...)
39-
}
40-
return output
41-
}
42-
43-
// quick helper padding
44-
func pad(input []byte, size int, left bool) []byte {
45-
if left {
46-
return common.LeftPadBytes(input, size)
47-
}
48-
return common.RightPadBytes(input, size)
49-
}
50-
5132
const jsondata = `
5233
[
5334
{ "type" : "function", "name" : "balance", "constant" : true },
@@ -191,7 +172,7 @@ func TestMethodSignature(t *testing.T) {
191172
t.Errorf("expected ids to match %x != %x", m.Id(), idexp)
192173
}
193174

194-
uintt, _ := NewType("uint")
175+
uintt, _ := NewType("uint256")
195176
m = Method{"foo", false, []Argument{{"bar", uintt, false}}, nil}
196177
exp = "foo(uint256)"
197178
if m.Sig() != exp {

‎accounts/abi/bind/bind_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -472,7 +472,7 @@ func TestBindings(t *testing.T) {
472472
t.Fatalf("failed to create temporary workspace: %v", err)
473473
}
474474
defer os.RemoveAll(ws)
475-
475+
476476
pkg := filepath.Join(ws, "bindtest")
477477
if err = os.MkdirAll(pkg, 0700); err != nil {
478478
t.Fatalf("failed to create package: %v", err)

‎accounts/abi/error.go‎

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -39,43 +39,43 @@ func formatSliceString(kind reflect.Kind, sliceSize int) string {
3939
// type in t.
4040
func sliceTypeCheck(t Type, val reflect.Value) error {
4141
if val.Kind() != reflect.Slice && val.Kind() != reflect.Array {
42-
return typeErr(formatSliceString(t.Kind, t.SliceSize), val.Type())
42+
return typeErr(formatSliceString(t.Kind, t.Size), val.Type())
4343
}
44-
if t.IsArray && val.Len() != t.SliceSize {
45-
return typeErr(formatSliceString(t.Elem.Kind, t.SliceSize), formatSliceString(val.Type().Elem().Kind(), val.Len()))
44+
45+
if t.T == ArrayTy && val.Len() != t.Size {
46+
return typeErr(formatSliceString(t.Elem.Kind, t.Size), formatSliceString(val.Type().Elem().Kind(), val.Len()))
4647
}
4748

48-
if t.Elem.IsSlice {
49+
if t.Elem.T == SliceTy {
4950
if val.Len() > 0 {
5051
return sliceTypeCheck(*t.Elem, val.Index(0))
5152
}
52-
} else if t.Elem.IsArray {
53+
} else if t.Elem.T == ArrayTy {
5354
return sliceTypeCheck(*t.Elem, val.Index(0))
5455
}
5556

5657
if elemKind := val.Type().Elem().Kind(); elemKind != t.Elem.Kind {
57-
return typeErr(formatSliceString(t.Elem.Kind, t.SliceSize), val.Type())
58+
return typeErr(formatSliceString(t.Elem.Kind, t.Size), val.Type())
5859
}
5960
return nil
6061
}
6162

6263
// typeCheck checks that the given reflection value can be assigned to the reflection
6364
// type in t.
6465
func typeCheck(t Type, value reflect.Value) error {
65-
if t.IsSlice || t.IsArray {
66+
if t.T == SliceTy || t.T == ArrayTy {
6667
return sliceTypeCheck(t, value)
6768
}
6869

6970
// Check base type validity. Element types will be checked later on.
7071
if t.Kind != value.Kind() {
7172
return typeErr(t.Kind, value.Kind())
73+
} else if t.T == FixedBytesTy && t.Size != value.Len() {
74+
return typeErr(t.Type, value.Type())
75+
} else {
76+
return nil
7277
}
73-
return nil
74-
}
7578

76-
// varErr returns a formatted error.
77-
func varErr(expected, got reflect.Kind) error {
78-
return typeErr(expected, got)
7979
}
8080

8181
// typeErr returns a formatted type casting error.

‎accounts/abi/event.go‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package abi
1818

1919
import (
2020
"fmt"
21+
"reflect"
2122
"strings"
2223

2324
"github.com/ethereum/go-ethereum/common"
@@ -44,3 +45,93 @@ func (e Event) Id() common.Hash {
4445
}
4546
return common.BytesToHash(crypto.Keccak256([]byte(fmt.Sprintf("%v(%v)", e.Name, strings.Join(types, ",")))))
4647
}
48+
49+
// unpacks an event return tuple into a struct of corresponding go types
50+
//
51+
// Unpacking can be done into a struct or a slice/array.
52+
func (e Event) tupleUnpack(v interface{}, output []byte) error {
53+
// make sure the passed value is a pointer
54+
valueOf := reflect.ValueOf(v)
55+
if reflect.Ptr != valueOf.Kind() {
56+
return fmt.Errorf("abi: Unpack(non-pointer %T)", v)
57+
}
58+
59+
var (
60+
value = valueOf.Elem()
61+
typ = value.Type()
62+
)
63+
64+
if value.Kind() != reflect.Struct {
65+
return fmt.Errorf("abi: cannot unmarshal tuple in to %v", typ)
66+
}
67+
68+
j := 0
69+
for i := 0; i < len(e.Inputs); i++ {
70+
input := e.Inputs[i]
71+
if input.Indexed {
72+
// can't read, continue
73+
continue
74+
} else if input.Type.T == ArrayTy {
75+
// need to move this up because they read sequentially
76+
j += input.Type.Size
77+
}
78+
marshalledValue, err := toGoType((i+j)*32, input.Type, output)
79+
if err != nil {
80+
return err
81+
}
82+
reflectValue := reflect.ValueOf(marshalledValue)
83+
84+
switch value.Kind() {
85+
case reflect.Struct:
86+
for j := 0; j < typ.NumField(); j++ {
87+
field := typ.Field(j)
88+
// TODO read tags: `abi:"fieldName"`
89+
if field.Name == strings.ToUpper(e.Inputs[i].Name[:1])+e.Inputs[i].Name[1:] {
90+
if err := set(value.Field(j), reflectValue, e.Inputs[i]); err != nil {
91+
return err
92+
}
93+
}
94+
}
95+
case reflect.Slice, reflect.Array:
96+
if value.Len() < i {
97+
return fmt.Errorf("abi: insufficient number of arguments for unpack, want %d, got %d", len(e.Inputs), value.Len())
98+
}
99+
v := value.Index(i)
100+
if v.Kind() != reflect.Ptr && v.Kind() != reflect.Interface {
101+
return fmt.Errorf("abi: cannot unmarshal %v in to %v", v.Type(), reflectValue.Type())
102+
}
103+
reflectValue := reflect.ValueOf(marshalledValue)
104+
if err := set(v.Elem(), reflectValue, e.Inputs[i]); err != nil {
105+
return err
106+
}
107+
default:
108+
return fmt.Errorf("abi: cannot unmarshal tuple in to %v", typ)
109+
}
110+
}
111+
return nil
112+
}
113+
114+
func (e Event) isTupleReturn() bool { return len(e.Inputs) > 1 }
115+
116+
func (e Event) singleUnpack(v interface{}, output []byte) error {
117+
// make sure the passed value is a pointer
118+
valueOf := reflect.ValueOf(v)
119+
if reflect.Ptr != valueOf.Kind() {
120+
return fmt.Errorf("abi: Unpack(non-pointer %T)", v)
121+
}
122+
123+
if e.Inputs[0].Indexed {
124+
return fmt.Errorf("abi: attempting to unpack indexed variable into element.")
125+
}
126+
127+
value := valueOf.Elem()
128+
129+
marshalledValue, err := toGoType(0, e.Inputs[0].Type, output)
130+
if err != nil {
131+
return err
132+
}
133+
if err := set(value, reflect.ValueOf(marshalledValue), e.Inputs[0]); err != nil {
134+
return err
135+
}
136+
return nil
137+
}

‎accounts/abi/event_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ func TestEventId(t *testing.T) {
3131
}{
3232
{
3333
definition: `[
34-
{ "type" : "event", "name" : "balance", "inputs": [{ "name" : "in", "type": "uint" }] },
34+
{ "type" : "event", "name" : "balance", "inputs": [{ "name" : "in", "type": "uint256" }] },
3535
{ "type" : "event", "name" : "check", "inputs": [{ "name" : "t", "type": "address" }, { "name": "b", "type": "uint256" }] }
3636
]`,
3737
expectations: map[string]common.Hash{

0 commit comments

Comments
 (0)