Skip to content

Commit 38ff815

Browse files
committed
Merge pull request bnb-chain#2003 from obscuren/abi-calling
accounts/abi: added output parsing & added call mechanism
2 parents 659d6b9 + a0bf2ea commit 38ff815

6 files changed

Lines changed: 243 additions & 88 deletions

File tree

‎accounts/abi/abi.go‎

Lines changed: 69 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -20,75 +20,17 @@ import (
2020
"encoding/json"
2121
"fmt"
2222
"io"
23-
"strings"
23+
"math"
2424

25-
"github.com/ethereum/go-ethereum/crypto"
25+
"github.com/ethereum/go-ethereum/common"
26+
"github.com/ethereum/go-ethereum/logger"
27+
"github.com/ethereum/go-ethereum/logger/glog"
2628
)
2729

28-
// Callable method given a `Name` and whether the method is a constant.
29-
// If the method is `Const` no transaction needs to be created for this
30-
// particular Method call. It can easily be simulated using a local VM.
31-
// For example a `Balance()` method only needs to retrieve something
32-
// from the storage and therefor requires no Tx to be send to the
33-
// network. A method such as `Transact` does require a Tx and thus will
34-
// be flagged `true`.
35-
// Input specifies the required input parameters for this gives method.
36-
type Method struct {
37-
Name string
38-
Const bool
39-
Inputs []Argument
40-
Return Type // not yet implemented
41-
}
42-
43-
// Returns the methods string signature according to the ABI spec.
44-
//
45-
// Example
46-
//
47-
// function foo(uint32 a, int b) = "foo(uint32,int256)"
48-
//
49-
// Please note that "int" is substitute for its canonical representation "int256"
50-
func (m Method) String() (out string) {
51-
out += m.Name
52-
types := make([]string, len(m.Inputs))
53-
i := 0
54-
for _, input := range m.Inputs {
55-
types[i] = input.Type.String()
56-
i++
57-
}
58-
out += "(" + strings.Join(types, ",") + ")"
59-
60-
return
61-
}
62-
63-
func (m Method) Id() []byte {
64-
return crypto.Sha3([]byte(m.String()))[:4]
65-
}
66-
67-
// Argument holds the name of the argument and the corresponding type.
68-
// Types are used when packing and testing arguments.
69-
type Argument struct {
70-
Name string
71-
Type Type
72-
}
73-
74-
func (a *Argument) UnmarshalJSON(data []byte) error {
75-
var extarg struct {
76-
Name string
77-
Type string
78-
}
79-
err := json.Unmarshal(data, &extarg)
80-
if err != nil {
81-
return fmt.Errorf("argument json err: %v", err)
82-
}
83-
84-
a.Type, err = NewType(extarg.Type)
85-
if err != nil {
86-
return err
87-
}
88-
a.Name = extarg.Name
89-
90-
return nil
91-
}
30+
// Executer is an executer method for performing state executions. It takes one
31+
// argument which is the input data and expects output data to be returned as
32+
// multiple 32 byte word length concatenated slice
33+
type Executer func(datain []byte) []byte
9234

9335
// The ABI holds information about a contract's context and available
9436
// invokable methods. It will allow you to type check function calls and
@@ -97,6 +39,18 @@ type ABI struct {
9739
Methods map[string]Method
9840
}
9941

42+
// JSON returns a parsed ABI interface and error if it failed.
43+
func JSON(reader io.Reader) (ABI, error) {
44+
dec := json.NewDecoder(reader)
45+
46+
var abi ABI
47+
if err := dec.Decode(&abi); err != nil {
48+
return ABI{}, err
49+
}
50+
51+
return abi, nil
52+
}
53+
10054
// tests, tests whether the given input would result in a successful
10155
// call. Checks argument list count and matches input to `input`.
10256
func (abi ABI) pack(name string, args ...interface{}) ([]byte, error) {
@@ -145,6 +99,55 @@ func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) {
14599
return packed, nil
146100
}
147101

102+
// toGoType parses the input and casts it to the proper type defined by the ABI
103+
// argument in t.
104+
func toGoType(t Argument, input []byte) interface{} {
105+
switch t.Type.T {
106+
case IntTy:
107+
return common.BytesToBig(input)
108+
case UintTy:
109+
return common.BytesToBig(input)
110+
case BoolTy:
111+
return common.BytesToBig(input).Uint64() > 0
112+
case AddressTy:
113+
return common.BytesToAddress(input)
114+
case HashTy:
115+
return common.BytesToHash(input)
116+
}
117+
return nil
118+
}
119+
120+
// Call executes a call and attemps to parse the return values and returns it as
121+
// an interface. It uses the executer method to perform the actual call since
122+
// the abi knows nothing of the lower level calling mechanism.
123+
//
124+
// Call supports all abi types and includes multiple return values. When only
125+
// one item is returned a single interface{} will be returned, if a contract
126+
// method returns multiple values an []interface{} slice is returned.
127+
func (abi ABI) Call(executer Executer, name string, args ...interface{}) interface{} {
128+
callData, err := abi.Pack(name, args...)
129+
if err != nil {
130+
glog.V(logger.Debug).Infoln("pack error:", err)
131+
return nil
132+
}
133+
134+
output := executer(callData)
135+
136+
method := abi.Methods[name]
137+
ret := make([]interface{}, int(math.Max(float64(len(method.Outputs)), float64(len(output)/32))))
138+
for i := 0; i < len(ret); i += 32 {
139+
index := i / 32
140+
ret[index] = toGoType(method.Outputs[index], output[i:i+32])
141+
}
142+
143+
// return single interface
144+
if len(ret) == 1 {
145+
return ret[0]
146+
}
147+
148+
return ret
149+
}
150+
148151
func (abi *ABI) UnmarshalJSON(data []byte) error {
149152
var methods []Method
150153
if err := json.Unmarshal(data, &methods); err != nil {
@@ -158,14 +161,3 @@ func (abi *ABI) UnmarshalJSON(data []byte) error {
158161

159162
return nil
160163
}
161-
162-
func JSON(reader io.Reader) (ABI, error) {
163-
dec := json.NewDecoder(reader)
164-
165-
var abi ABI
166-
if err := dec.Decode(&abi); err != nil {
167-
return ABI{}, err
168-
}
169-
170-
return abi, nil
171-
}

‎accounts/abi/abi_test.go‎

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -92,12 +92,12 @@ func TestReader(t *testing.T) {
9292
exp := ABI{
9393
Methods: map[string]Method{
9494
"balance": Method{
95-
"balance", true, nil, Type{},
95+
"balance", true, nil, nil,
9696
},
9797
"send": Method{
9898
"send", false, []Argument{
9999
Argument{"amount", Uint256},
100-
}, Type{},
100+
}, nil,
101101
},
102102
},
103103
}
@@ -238,10 +238,10 @@ func TestTestAddress(t *testing.T) {
238238
func TestMethodSignature(t *testing.T) {
239239
String, _ := NewType("string")
240240
String32, _ := NewType("string32")
241-
m := Method{"foo", false, []Argument{Argument{"bar", String32}, Argument{"baz", String}}, Type{}}
241+
m := Method{"foo", false, []Argument{Argument{"bar", String32}, Argument{"baz", String}}, nil}
242242
exp := "foo(string32,string)"
243-
if m.String() != exp {
244-
t.Error("signature mismatch", exp, "!=", m.String())
243+
if m.Sig() != exp {
244+
t.Error("signature mismatch", exp, "!=", m.Sig())
245245
}
246246

247247
idexp := crypto.Sha3([]byte(exp))[:4]
@@ -250,10 +250,10 @@ func TestMethodSignature(t *testing.T) {
250250
}
251251

252252
uintt, _ := NewType("uint")
253-
m = Method{"foo", false, []Argument{Argument{"bar", uintt}}, Type{}}
253+
m = Method{"foo", false, []Argument{Argument{"bar", uintt}}, nil}
254254
exp = "foo(uint256)"
255-
if m.String() != exp {
256-
t.Error("signature mismatch", exp, "!=", m.String())
255+
if m.Sig() != exp {
256+
t.Error("signature mismatch", exp, "!=", m.Sig())
257257
}
258258
}
259259

@@ -393,3 +393,34 @@ func TestBytes(t *testing.T) {
393393
t.Error("expected error")
394394
}
395395
}
396+
397+
func TestReturn(t *testing.T) {
398+
const definition = `[
399+
{ "name" : "balance", "const" : true, "inputs" : [], "outputs" : [ { "name": "", "type": "hash" } ] },
400+
{ "name" : "name", "const" : true, "inputs" : [], "outputs" : [ { "name": "", "type": "address" } ] }
401+
402+
]`
403+
404+
abi, err := JSON(strings.NewReader(definition))
405+
if err != nil {
406+
t.Fatal(err)
407+
}
408+
409+
r := abi.Call(func([]byte) []byte {
410+
t := make([]byte, 32)
411+
t[0] = 1
412+
return t
413+
}, "balance")
414+
if _, ok := r.(common.Hash); !ok {
415+
t.Errorf("expected type common.Hash, got %T", r)
416+
}
417+
418+
r = abi.Call(func([]byte) []byte {
419+
t := make([]byte, 32)
420+
t[0] = 1
421+
return t
422+
}, "name")
423+
if _, ok := r.(common.Address); !ok {
424+
t.Errorf("expected type common.Address, got %T", r)
425+
}
426+
}

‎accounts/abi/argument.go‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// Copyright 2015 The go-ethereum Authors
2+
// This file is part of the go-ethereum library.
3+
//
4+
// The go-ethereum library is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU Lesser General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// The go-ethereum library is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU Lesser General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU Lesser General Public License
15+
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16+
17+
package abi
18+
19+
import (
20+
"encoding/json"
21+
"fmt"
22+
)
23+
24+
// Argument holds the name of the argument and the corresponding type.
25+
// Types are used when packing and testing arguments.
26+
type Argument struct {
27+
Name string
28+
Type Type
29+
}
30+
31+
func (a *Argument) UnmarshalJSON(data []byte) error {
32+
var extarg struct {
33+
Name string
34+
Type string
35+
}
36+
err := json.Unmarshal(data, &extarg)
37+
if err != nil {
38+
return fmt.Errorf("argument json err: %v", err)
39+
}
40+
41+
a.Type, err = NewType(extarg.Type)
42+
if err != nil {
43+
return err
44+
}
45+
a.Name = extarg.Name
46+
47+
return nil
48+
}

‎accounts/abi/method.go‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// Copyright 2015 The go-ethereum Authors
2+
// This file is part of the go-ethereum library.
3+
//
4+
// The go-ethereum library is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU Lesser General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// The go-ethereum library is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU Lesser General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU Lesser General Public License
15+
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16+
17+
package abi
18+
19+
import (
20+
"fmt"
21+
"strings"
22+
23+
"github.com/ethereum/go-ethereum/crypto"
24+
)
25+
26+
// Callable method given a `Name` and whether the method is a constant.
27+
// If the method is `Const` no transaction needs to be created for this
28+
// particular Method call. It can easily be simulated using a local VM.
29+
// For example a `Balance()` method only needs to retrieve something
30+
// from the storage and therefor requires no Tx to be send to the
31+
// network. A method such as `Transact` does require a Tx and thus will
32+
// be flagged `true`.
33+
// Input specifies the required input parameters for this gives method.
34+
type Method struct {
35+
Name string
36+
Const bool
37+
Inputs []Argument
38+
Outputs []Argument
39+
}
40+
41+
// Sig returns the methods string signature according to the ABI spec.
42+
//
43+
// Example
44+
//
45+
// function foo(uint32 a, int b) = "foo(uint32,int256)"
46+
//
47+
// Please note that "int" is substitute for its canonical representation "int256"
48+
func (m Method) Sig() string {
49+
types := make([]string, len(m.Inputs))
50+
i := 0
51+
for _, input := range m.Inputs {
52+
types[i] = input.Type.String()
53+
i++
54+
}
55+
return fmt.Sprintf("%v(%v)", m.Name, strings.Join(types, ","))
56+
}
57+
58+
func (m Method) String() string {
59+
inputs := make([]string, len(m.Inputs))
60+
for i, input := range m.Inputs {
61+
inputs[i] = fmt.Sprintf("%v %v", input.Name, input.Type)
62+
}
63+
outputs := make([]string, len(m.Outputs))
64+
for i, output := range m.Outputs {
65+
if len(output.Name) > 0 {
66+
outputs[i] = fmt.Sprintf("%v ", output.Name)
67+
}
68+
outputs[i] += output.Type.String()
69+
}
70+
71+
return fmt.Sprintf("function %v(%v) returns(%v)", m.Name, strings.Join(inputs, ", "), strings.Join(outputs, ", "))
72+
}
73+
74+
func (m Method) Id() []byte {
75+
return crypto.Sha3([]byte(m.Sig()))[:4]
76+
}

‎accounts/abi/numbers.go‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ var int8_t = reflect.TypeOf(int8(0))
3737
var int16_t = reflect.TypeOf(int16(0))
3838
var int32_t = reflect.TypeOf(int32(0))
3939
var int64_t = reflect.TypeOf(int64(0))
40+
var hash_t = reflect.TypeOf(common.Hash{})
41+
var address_t = reflect.TypeOf(common.Address{})
4042

4143
var uint_ts = reflect.TypeOf([]uint(nil))
4244
var uint8_ts = reflect.TypeOf([]uint8(nil))

0 commit comments

Comments
 (0)