This commit is contained in:
Robert Zaremba 2017-12-22 13:07:19 +00:00 committed by GitHub
commit 47bfc3dfb0
10 changed files with 380 additions and 162 deletions

View file

@ -89,7 +89,7 @@ func (abi ABI) Unpack(v interface{}, name string, output []byte) (err error) {
} else if event, ok := abi.Events[name]; ok { } else if event, ok := abi.Events[name]; ok {
unpack = event unpack = event
} else { } else {
return fmt.Errorf("abi: could not locate named method or event.") return fmt.Errorf("abi: could not locate named method or event")
} }
// requires a struct to unpack into for a tuple return... // requires a struct to unpack into for a tuple return...
@ -99,6 +99,7 @@ func (abi ABI) Unpack(v interface{}, name string, output []byte) (err error) {
return unpack.singleUnpack(v, output) return unpack.singleUnpack(v, output)
} }
// UnmarshalJSON implements json.Unmarshaler interface
func (abi *ABI) UnmarshalJSON(data []byte) error { func (abi *ABI) UnmarshalJSON(data []byte) error {
var fields []struct { var fields []struct {
Type string Type string

View file

@ -29,6 +29,7 @@ type Argument struct {
Indexed bool // indexed is only used by events Indexed bool // indexed is only used by events
} }
// UnmarshalJSON implements json.Unmarshaler interface
func (a *Argument) UnmarshalJSON(data []byte) error { func (a *Argument) UnmarshalJSON(data []byte) error {
var extarg struct { var extarg struct {
Name string Name string
@ -49,3 +50,13 @@ func (a *Argument) UnmarshalJSON(data []byte) error {
return nil return nil
} }
func countNonIndexedArguments(args []Argument) int {
out := 0
for i := range args {
if !args[i].Indexed {
out++
}
}
return out
}

View file

@ -59,19 +59,22 @@ func (e Event) tupleUnpack(v interface{}, output []byte) error {
var ( var (
value = valueOf.Elem() value = valueOf.Elem()
typ = value.Type() typ = value.Type()
kind = value.Kind()
) )
if err := requireUnpackKind(value, typ, kind, e.Inputs, true); err != nil {
if value.Kind() != reflect.Struct { return err
return fmt.Errorf("abi: cannot unmarshal tuple in to %v", typ)
} }
j := 0 // `i` counts the nonindexed arguments.
for i := 0; i < len(e.Inputs); i++ { // `j` counts the number of complex types.
input := e.Inputs[i] // both `i` and `j` are used to to correctly compute `data` offset.
i, j := -1, 0
for _, input := range e.Inputs {
if input.Indexed { if input.Indexed {
// can't read, continue // Indexed arguments are not packed into data
continue continue
} }
i++
marshalledValue, err := toGoType((i+j)*32, input.Type, output) marshalledValue, err := toGoType((i+j)*32, input.Type, output)
if err != nil { if err != nil {
return err return err
@ -83,31 +86,25 @@ func (e Event) tupleUnpack(v interface{}, output []byte) error {
} }
reflectValue := reflect.ValueOf(marshalledValue) reflectValue := reflect.ValueOf(marshalledValue)
switch value.Kind() { switch kind {
case reflect.Struct: case reflect.Struct:
for j := 0; j < typ.NumField(); j++ { for j := 0; j < typ.NumField(); j++ {
field := typ.Field(j) field := typ.Field(j)
// TODO read tags: `abi:"fieldName"` // TODO read tags: `abi:"fieldName"`
if field.Name == strings.ToUpper(e.Inputs[i].Name[:1])+e.Inputs[i].Name[1:] { if field.Name == strings.ToUpper(input.Name[:1])+input.Name[1:] {
if err := set(value.Field(j), reflectValue, e.Inputs[i]); err != nil { if err := set(value.Field(j), reflectValue, input); err != nil {
return err return err
} }
} }
} }
case reflect.Slice, reflect.Array: case reflect.Slice, reflect.Array:
if value.Len() < i {
return fmt.Errorf("abi: insufficient number of arguments for unpack, want %d, got %d", len(e.Inputs), value.Len())
}
v := value.Index(i) v := value.Index(i)
if v.Kind() != reflect.Ptr && v.Kind() != reflect.Interface { if err := requireAssignable(v, reflectValue); err != nil {
return fmt.Errorf("abi: cannot unmarshal %v in to %v", v.Type(), reflectValue.Type()) return err
} }
reflectValue := reflect.ValueOf(marshalledValue) if err := set(v.Elem(), reflectValue, input); err != nil {
if err := set(v.Elem(), reflectValue, e.Inputs[i]); err != nil {
return err return err
} }
default:
return fmt.Errorf("abi: cannot unmarshal tuple in to %v", typ)
} }
} }
return nil return nil
@ -123,7 +120,7 @@ func (e Event) singleUnpack(v interface{}, output []byte) error {
} }
if e.Inputs[0].Indexed { if e.Inputs[0].Indexed {
return fmt.Errorf("abi: attempting to unpack indexed variable into element.") return fmt.Errorf("abi: attempting to unpack indexed variable into element")
} }
value := valueOf.Elem() value := valueOf.Elem()
@ -132,8 +129,5 @@ func (e Event) singleUnpack(v interface{}, output []byte) error {
if err != nil { if err != nil {
return err return err
} }
if err := set(value, reflect.ValueOf(marshalledValue), e.Inputs[0]); err != nil { return set(value, reflect.ValueOf(marshalledValue), e.Inputs[0])
return err
}
return nil
} }

View file

@ -18,15 +18,52 @@ package abi
import ( import (
"bytes" "bytes"
"encoding/hex"
"encoding/json"
"math/big"
"reflect" "reflect"
"strings" "strings"
"testing" "testing"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
var jsonEventTransfer = []byte(`{
"anonymous": false,
"inputs": [
{
"indexed": true, "name": "from", "type": "address"
}, {
"indexed": true, "name": "to", "type": "address"
}, {
"indexed": false, "name": "value", "type": "uint256"
}],
"name": "Transfer",
"type": "event"
}`)
var jsonEventPledge = []byte(`{
"anonymous": false,
"inputs": [{
"indexed": false, "name": "who", "type": "address"
}, {
"indexed": false, "name": "wad", "type": "uint128"
}, {
"indexed": false, "name": "currency", "type": "bytes3"
}],
"name": "Pledge",
"type": "event"
}`)
// 1000000
var transferData1 = "00000000000000000000000000000000000000000000000000000000000f4240"
// "0x00Ce0d46d924CC8437c806721496599FC3FFA268", 2218516807680, "usd"
var pledgeData1 = "00000000000000000000000000ce0d46d924cc8437c806721496599fc3ffa2680000000000000000000000000000000000000000000000000000020489e800007573640000000000000000000000000000000000000000000000000000000000"
func TestEventId(t *testing.T) { func TestEventId(t *testing.T) {
var table = []struct { var table = []struct {
definition string definition string
@ -77,3 +114,130 @@ func TestEventMultiValueWithArrayUnpack(t *testing.T) {
require.Equal(t, [2]uint8{1, 2}, rst.Value1) require.Equal(t, [2]uint8{1, 2}, rst.Value1)
require.Equal(t, uint8(3), rst.Value2) require.Equal(t, uint8(3), rst.Value2)
} }
func TestEventTupleUnpack(t *testing.T) {
type EventTransfer struct {
Value *big.Int
}
type EventPledge struct {
Who common.Address
Wad *big.Int
Currency [3]byte
}
type BadEventPledge struct {
Who string
Wad int
Currency [3]byte
}
bigint := new(big.Int)
bigintExpected := big.NewInt(1000000)
bigintExpected2 := big.NewInt(2218516807680)
addr := common.HexToAddress("0x00Ce0d46d924CC8437c806721496599FC3FFA268")
var testCases = []struct {
data string
dest interface{}
expected interface{}
jsonLog []byte
error string
name string
}{{
transferData1,
&EventTransfer{},
&EventTransfer{Value: bigintExpected},
jsonEventTransfer,
"",
"Can unpack ERC20 Transfer event into structure",
}, {
transferData1,
&[]interface{}{&bigint},
&[]interface{}{&bigintExpected},
jsonEventTransfer,
"",
"Can unpack ERC20 Transfer event into slice",
}, {
pledgeData1,
&EventPledge{},
&EventPledge{
addr,
bigintExpected2,
[3]byte{'u', 's', 'd'}},
jsonEventPledge,
"",
"Can unpack Pledge event into structure",
}, {
pledgeData1,
&[]interface{}{&common.Address{}, &bigint, &[3]byte{}},
&[]interface{}{
&addr,
&bigintExpected2,
&[3]byte{'u', 's', 'd'}},
jsonEventPledge,
"",
"Can unpack Pledge event into slice",
}, {
pledgeData1,
&[3]interface{}{&common.Address{}, &bigint, &[3]byte{}},
&[3]interface{}{
&addr,
&bigintExpected2,
&[3]byte{'u', 's', 'd'}},
jsonEventPledge,
"",
"Can unpack Pledge event into an array",
}, {
pledgeData1,
&[]interface{}{new(int), 0, 0},
&[]interface{}{},
jsonEventPledge,
"abi: cannot unmarshal common.Address in to int",
"Can not unpack Pledge event into slice with wrong types",
}, {
pledgeData1,
&BadEventPledge{},
&BadEventPledge{},
jsonEventPledge,
"abi: cannot unmarshal common.Address in to string",
"Can not unpack Pledge event into struct with wrong filed types",
}, {
pledgeData1,
&[]interface{}{common.Address{}, new(big.Int)},
&[]interface{}{},
jsonEventPledge,
"abi: insufficient number of elements in the list/array for unpack, want 3, got 2",
"Can not unpack Pledge event into too short slice",
}, {
pledgeData1,
new(map[string]interface{}),
&[]interface{}{},
jsonEventPledge,
"abi: cannot unmarshal tuple into map[string]interface {}",
"Can not unpack Pledge event into map",
}}
for _, tc := range testCases {
assert := assert.New(t)
tc := tc
t.Run(tc.name, func(t *testing.T) {
err := unpackTestEventData(tc.dest, tc.data, tc.jsonLog, assert)
if tc.error == "" {
assert.Nil(err, "Should be able to unpack event data.")
assert.Equal(tc.expected, tc.dest)
} else {
assert.EqualError(err, tc.error)
}
})
}
}
func unpackTestEventData(dest interface{}, hexData string, jsonEvent []byte, assert *assert.Assertions) error {
data, err := hex.DecodeString(hexData)
assert.NoError(err, "Hex data should be a correct hex-string")
var e Event
assert.NoError(json.Unmarshal(jsonEvent, &e), "Should be able to unmarshal event ABI")
a := ABI{Events: map[string]Event{"e": e}}
return a.Unpack(dest, "e", data)
}

View file

@ -24,7 +24,7 @@ import (
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
) )
// Callable method given a `Name` and whether the method is a constant. // Method represents a callable given a `Name` and whether the method is a constant.
// If the method is `Const` no transaction needs to be created for this // If the method is `Const` no transaction needs to be created for this
// particular Method call. It can easily be simulated using a local VM. // particular Method call. It can easily be simulated using a local VM.
// For example a `Balance()` method only needs to retrieve something // For example a `Balance()` method only needs to retrieve something
@ -91,7 +91,7 @@ func (method Method) pack(args ...interface{}) ([]byte, error) {
// unpacks a method return tuple into a struct of corresponding go types // unpacks a method return tuple into a struct of corresponding go types
// //
// Unpacking can be done into a struct or a slice/array. // Unpacking can be done into a struct or a slice/array.
func (method Method) tupleUnpack(v interface{}, output []byte) error { func (method Method) tupleUnpack(v interface{}, outputSlice []byte) error {
// make sure the passed value is a pointer // make sure the passed value is a pointer
valueOf := reflect.ValueOf(v) valueOf := reflect.ValueOf(v)
if reflect.Ptr != valueOf.Kind() { if reflect.Ptr != valueOf.Kind() {
@ -101,47 +101,44 @@ func (method Method) tupleUnpack(v interface{}, output []byte) error {
var ( var (
value = valueOf.Elem() value = valueOf.Elem()
typ = value.Type() typ = value.Type()
kind = value.Kind()
) )
if err := requireUnpackKind(value, typ, kind, method.Outputs, false); err != nil {
return err
}
j := 0 j := 0
for i := 0; i < len(method.Outputs); i++ { for i, output := range method.Outputs {
toUnpack := method.Outputs[i] marshalledValue, err := toGoType((i+j)*32, output.Type, outputSlice)
marshalledValue, err := toGoType((i+j)*32, toUnpack.Type, output)
if err != nil { if err != nil {
return err return err
} }
if toUnpack.Type.T == ArrayTy { if output.Type.T == ArrayTy {
// combined index ('i' + 'j') need to be adjusted only by size of array, thus // combined index ('i' + 'j') need to be adjusted only by size of array, thus
// we need to decrement 'j' because 'i' was incremented // we need to decrement 'j' because 'i' was incremented
j += toUnpack.Type.Size - 1 j += output.Type.Size - 1
} }
reflectValue := reflect.ValueOf(marshalledValue) reflectValue := reflect.ValueOf(marshalledValue)
switch value.Kind() { switch kind {
case reflect.Struct: case reflect.Struct:
for j := 0; j < typ.NumField(); j++ { for j := 0; j < typ.NumField(); j++ {
field := typ.Field(j) field := typ.Field(j)
// TODO read tags: `abi:"fieldName"` // TODO read tags: `abi:"fieldName"`
if field.Name == strings.ToUpper(method.Outputs[i].Name[:1])+method.Outputs[i].Name[1:] { if field.Name == strings.ToUpper(output.Name[:1])+output.Name[1:] {
if err := set(value.Field(j), reflectValue, method.Outputs[i]); err != nil { if err := set(value.Field(j), reflectValue, output); err != nil {
return err return err
} }
} }
} }
case reflect.Slice, reflect.Array: case reflect.Slice, reflect.Array:
if value.Len() < i {
return fmt.Errorf("abi: insufficient number of arguments for unpack, want %d, got %d", len(method.Outputs), value.Len())
}
v := value.Index(i) v := value.Index(i)
if v.Kind() != reflect.Ptr && v.Kind() != reflect.Interface { if err := requireAssignable(v, reflectValue); err != nil {
return fmt.Errorf("abi: cannot unmarshal %v in to %v", v.Type(), reflectValue.Type()) return err
} }
reflectValue := reflect.ValueOf(marshalledValue) if err := set(v.Elem(), reflectValue, output); err != nil {
if err := set(v.Elem(), reflectValue, method.Outputs[i]); err != nil {
return err return err
} }
default:
return fmt.Errorf("abi: cannot unmarshal tuple in to %v", typ)
} }
} }
return nil return nil
@ -162,10 +159,7 @@ func (method Method) singleUnpack(v interface{}, output []byte) error {
if err != nil { if err != nil {
return err return err
} }
if err := set(value, reflect.ValueOf(marshalledValue), method.Outputs[0]); err != nil { return set(value, reflect.ValueOf(marshalledValue), method.Outputs[0])
return err
}
return nil
} }
// Sig returns the methods string signature according to the ABI spec. // Sig returns the methods string signature according to the ABI spec.
@ -175,35 +169,35 @@ func (method Method) singleUnpack(v interface{}, output []byte) error {
// function foo(uint32 a, int b) = "foo(uint32,int256)" // function foo(uint32 a, int b) = "foo(uint32,int256)"
// //
// Please note that "int" is substitute for its canonical representation "int256" // Please note that "int" is substitute for its canonical representation "int256"
func (m Method) Sig() string { func (method Method) Sig() string {
types := make([]string, len(m.Inputs)) types := make([]string, len(method.Inputs))
i := 0 i := 0
for _, input := range m.Inputs { for _, input := range method.Inputs {
types[i] = input.Type.String() types[i] = input.Type.String()
i++ i++
} }
return fmt.Sprintf("%v(%v)", m.Name, strings.Join(types, ",")) return fmt.Sprintf("%v(%v)", method.Name, strings.Join(types, ","))
} }
func (m Method) String() string { func (method Method) String() string {
inputs := make([]string, len(m.Inputs)) inputs := make([]string, len(method.Inputs))
for i, input := range m.Inputs { for i, input := range method.Inputs {
inputs[i] = fmt.Sprintf("%v %v", input.Name, input.Type) inputs[i] = fmt.Sprintf("%v %v", input.Name, input.Type)
} }
outputs := make([]string, len(m.Outputs)) outputs := make([]string, len(method.Outputs))
for i, output := range m.Outputs { for i, output := range method.Outputs {
if len(output.Name) > 0 { if len(output.Name) > 0 {
outputs[i] = fmt.Sprintf("%v ", output.Name) outputs[i] = fmt.Sprintf("%v ", output.Name)
} }
outputs[i] += output.Type.String() outputs[i] += output.Type.String()
} }
constant := "" constant := ""
if m.Const { if method.Const {
constant = "constant " constant = "constant "
} }
return fmt.Sprintf("function %v(%v) %sreturns(%v)", m.Name, strings.Join(inputs, ", "), constant, strings.Join(outputs, ", ")) return fmt.Sprintf("function %v(%v) %sreturns(%v)", method.Name, strings.Join(inputs, ", "), constant, strings.Join(outputs, ", "))
} }
func (m Method) Id() []byte { func (method Method) Id() []byte {
return crypto.Keccak256([]byte(m.Sig()))[:4] return crypto.Keccak256([]byte(method.Sig()))[:4]
} }

View file

@ -48,9 +48,8 @@ func packElement(t Type, reflectValue reflect.Value) []byte {
case BoolTy: case BoolTy:
if reflectValue.Bool() { if reflectValue.Bool() {
return math.PaddedBigBytes(common.Big1, 32) return math.PaddedBigBytes(common.Big1, 32)
} else {
return math.PaddedBigBytes(common.Big0, 32)
} }
return math.PaddedBigBytes(common.Big0, 32)
case BytesTy: case BytesTy:
if reflectValue.Kind() == reflect.Array { if reflectValue.Kind() == reflect.Array {
reflectValue = mustArrayToByteSlice(reflectValue) reflectValue = mustArrayToByteSlice(reflectValue)

View file

@ -85,3 +85,32 @@ func set(dst, src reflect.Value, output Argument) error {
} }
return nil return nil
} }
// requireUnpackKind verifies preconditions for unpacking `args` into `kind`
func requireUnpackKind(v reflect.Value, t reflect.Type, k reflect.Kind,
args []Argument, ignoreIndexed bool) error {
switch k {
case reflect.Struct:
case reflect.Slice, reflect.Array:
minLen := len(args)
if ignoreIndexed {
minLen = countNonIndexedArguments(args)
}
if v.Len() < minLen {
return fmt.Errorf("abi: insufficient number of elements in the list/array for unpack, want %d, got %d",
minLen, v.Len())
}
default:
return fmt.Errorf("abi: cannot unmarshal tuple into %v", t)
}
return nil
}
// requireAssignable assures that `dest` is a pointer and it's not an interface.
func requireAssignable(dst, src reflect.Value) error {
if dst.Kind() != reflect.Ptr && dst.Kind() != reflect.Interface {
return fmt.Errorf("abi: cannot unmarshal %v into %v", src.Type(), dst.Type())
}
return nil
}

View file

@ -24,6 +24,7 @@ import (
"strings" "strings"
) )
// Type enumerator
const ( const (
IntTy byte = iota IntTy byte = iota
UintTy UintTy
@ -100,7 +101,7 @@ func NewType(t string) (typ Type, err error) {
return Type{}, fmt.Errorf("invalid formatting of array type") return Type{}, fmt.Errorf("invalid formatting of array type")
} }
return typ, err return typ, err
} else { }
// parse the type and size of the abi-type. // parse the type and size of the abi-type.
parsedType := typeRegex.FindAllStringSubmatch(t, -1)[0] parsedType := typeRegex.FindAllStringSubmatch(t, -1)[0]
// varSize is the size of the variable // varSize is the size of the variable
@ -119,9 +120,7 @@ func NewType(t string) (typ Type, err error) {
} }
} }
// varType is the parsed abi type // varType is the parsed abi type
varType := parsedType[1] switch varType := parsedType[1]; varType {
switch varType {
case "int": case "int":
typ.Kind, typ.Type = reflectIntKindAndType(false, varSize) typ.Kind, typ.Type = reflectIntKindAndType(false, varSize)
typ.Size = varSize typ.Size = varSize
@ -162,7 +161,6 @@ func NewType(t string) (typ Type, err error) {
default: default:
return Type{}, fmt.Errorf("unsupported arg type: %s", t) return Type{}, fmt.Errorf("unsupported arg type: %s", t)
} }
}
return return
} }

View file

@ -79,7 +79,7 @@ func readBool(word []byte) (bool, error) {
// This enforces that standard by always presenting it as a 24-array (address + sig = 24 bytes) // This enforces that standard by always presenting it as a 24-array (address + sig = 24 bytes)
func readFunctionType(t Type, word []byte) (funcTy [24]byte, err error) { func readFunctionType(t Type, word []byte) (funcTy [24]byte, err error) {
if t.T != FunctionTy { if t.T != FunctionTy {
return [24]byte{}, fmt.Errorf("abi: invalid type in call to make function type byte array.") return [24]byte{}, fmt.Errorf("abi: invalid type in call to make function type byte array")
} }
if garbage := binary.BigEndian.Uint64(word[24:32]); garbage != 0 { if garbage := binary.BigEndian.Uint64(word[24:32]); garbage != 0 {
err = fmt.Errorf("abi: got improperly encoded function type, got %v", word) err = fmt.Errorf("abi: got improperly encoded function type, got %v", word)
@ -92,7 +92,7 @@ func readFunctionType(t Type, word []byte) (funcTy [24]byte, err error) {
// through reflection, creates a fixed array to be read from // through reflection, creates a fixed array to be read from
func readFixedBytes(t Type, word []byte) (interface{}, error) { func readFixedBytes(t Type, word []byte) (interface{}, error) {
if t.T != FixedBytesTy { if t.T != FixedBytesTy {
return nil, fmt.Errorf("abi: invalid type in call to make fixed byte array.") return nil, fmt.Errorf("abi: invalid type in call to make fixed byte array")
} }
// convert // convert
array := reflect.New(t.Type).Elem() array := reflect.New(t.Type).Elem()

View file

@ -27,6 +27,7 @@ import (
"testing" "testing"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/stretchr/testify/require"
) )
type unpackTest struct { type unpackTest struct {
@ -286,56 +287,83 @@ func TestUnpack(t *testing.T) {
} }
} }
func TestMultiReturnWithStruct(t *testing.T) { type methodMultiOutput struct {
Int *big.Int
String string
}
func methodMultiReturn(require *require.Assertions) (ABI, []byte, methodMultiOutput) {
const definition = `[ const definition = `[
{ "name" : "multi", "constant" : false, "outputs": [ { "name": "Int", "type": "uint256" }, { "name": "String", "type": "string" } ] }]` { "name" : "multi", "constant" : false, "outputs": [ { "name": "Int", "type": "uint256" }, { "name": "String", "type": "string" } ] }]`
var expected = methodMultiOutput{big.NewInt(1), "hello"}
abi, err := JSON(strings.NewReader(definition)) abi, err := JSON(strings.NewReader(definition))
if err != nil { require.NoError(err)
t.Fatal(err)
}
// using buff to make the code readable // using buff to make the code readable
buff := new(bytes.Buffer) buff := new(bytes.Buffer)
buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040")) buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040"))
buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000005")) buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000005"))
stringOut := "hello" buff.Write(common.RightPadBytes([]byte(expected.String), 32))
buff.Write(common.RightPadBytes([]byte(stringOut), 32)) return abi, buff.Bytes(), expected
}
var inter struct { func TestMethodMultiReturn(t *testing.T) {
Int *big.Int type reversed struct {
String string
}
err = abi.Unpack(&inter, "multi", buff.Bytes())
if err != nil {
t.Error(err)
}
if inter.Int == nil || inter.Int.Cmp(big.NewInt(1)) != 0 {
t.Error("expected Int to be 1 got", inter.Int)
}
if inter.String != stringOut {
t.Error("expected String to be", stringOut, "got", inter.String)
}
var reversed struct {
String string String string
Int *big.Int Int *big.Int
} }
err = abi.Unpack(&reversed, "multi", buff.Bytes()) abi, data, expected := methodMultiReturn(require.New(t))
if err != nil { bigint := new(big.Int)
t.Error(err) var testCases = []struct {
dest interface{}
expected interface{}
error string
name string
}{{
&methodMultiOutput{},
&expected,
"",
"Can unpack into structure",
}, {
&reversed{},
&reversed{expected.String, expected.Int},
"",
"Can unpack into reversed structure",
}, {
&[]interface{}{&bigint, new(string)},
&[]interface{}{&expected.Int, &expected.String},
"",
"Can unpack into a slice",
}, {
&[2]interface{}{&bigint, new(string)},
&[2]interface{}{&expected.Int, &expected.String},
"",
"Can unpack into an array",
}, {
&[]interface{}{new(int), new(int)},
&[]interface{}{&expected.Int, &expected.String},
"abi: cannot unmarshal *big.Int in to int",
"Can not unpack into a slice with wrong types",
}, {
&[]interface{}{new(int)},
&[]interface{}{},
"abi: insufficient number of elements in the list/array for unpack, want 2, got 1",
"Can not unpack into a slice with wrong types",
}}
for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
require := require.New(t)
err := abi.Unpack(tc.dest, "multi", data)
if tc.error == "" {
require.Nil(err, "Should be able to unpack method outputs.")
require.Equal(tc.expected, tc.dest)
} else {
require.EqualError(err, tc.error)
} }
})
if reversed.Int == nil || reversed.Int.Cmp(big.NewInt(1)) != 0 {
t.Error("expected Int to be 1 got", reversed.Int)
}
if reversed.String != stringOut {
t.Error("expected String to be", stringOut, "got", reversed.String)
} }
} }