Skip to content

Commit

Permalink
acounts/abi: refactor abi, generalize abi pack/unpack to Arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
holiman committed Dec 22, 2017
1 parent 81d4caf commit 73d4a57
Show file tree
Hide file tree
Showing 7 changed files with 260 additions and 251 deletions.
39 changes: 15 additions & 24 deletions accounts/abi/abi.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,25 +50,25 @@ func JSON(reader io.Reader) (ABI, error) {
// methods string signature. (signature = baz(uint32,string32))
func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) {
// Fetch the ABI of the requested method
var method Method

if name == "" {
method = abi.Constructor
} else {
m, exist := abi.Methods[name]
if !exist {
return nil, fmt.Errorf("method '%s' not found", name)
// constructor
arguments, err := abi.Constructor.Inputs.Pack(args...)
if err != nil {
return nil, err
}
method = m
return arguments, nil

}
arguments, err := method.pack(args...)
method, exist := abi.Methods[name]
if !exist {
return nil, fmt.Errorf("method '%s' not found", name)
}

arguments, err := method.Inputs.Pack(args...)
if err != nil {
return nil, err
}
// Pack up the method ID too if not a constructor and return
if name == "" {
return arguments, nil
}
return append(method.Id(), arguments...), nil
}

Expand All @@ -77,26 +77,17 @@ func (abi ABI) Unpack(v interface{}, name string, output []byte) (err error) {
if len(output) == 0 {
return fmt.Errorf("abi: unmarshalling empty output")
}

// since there can't be naming collisions with contracts and events,
// we need to decide whether we're calling a method or an event
var unpack unpacker
if method, ok := abi.Methods[name]; ok {
if len(output)%32 != 0 {
return fmt.Errorf("abi: improperly formatted output")
}
unpack = method
return method.Outputs.Unpack(v, output)
} else if event, ok := abi.Events[name]; ok {
unpack = event
} else {
return fmt.Errorf("abi: could not locate named method or event")
}

// requires a struct to unpack into for a tuple return...
if unpack.isTupleReturn() {
return unpack.tupleUnpack(v, output)
return event.Inputs.Unpack(v, output)
}
return unpack.singleUnpack(v, output)
return fmt.Errorf("abi: could not locate named method or event")
}

// UnmarshalJSON implements json.Unmarshaler interface
Expand Down
10 changes: 6 additions & 4 deletions accounts/abi/abi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import (
"fmt"
"log"
"math/big"
"reflect"
"strings"
"testing"

Expand Down Expand Up @@ -75,9 +74,12 @@ func TestReader(t *testing.T) {
}

// deep equal fails for some reason
t.Skip()
if !reflect.DeepEqual(abi, exp) {
t.Errorf("\nabi: %v\ndoes not match exp: %v", abi, exp)
//t.Skip()
// Check with String() instead
expS := fmt.Sprintf("%v",exp)
gotS := fmt.Sprintf("%v", abi)
if expS != gotS {
t.Errorf("\nGot abi: \n%v\ndoes not match expected \n%v", abi, exp)
}
}

Expand Down
161 changes: 161 additions & 0 deletions accounts/abi/argument.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ package abi
import (
"encoding/json"
"fmt"
"reflect"
"strings"
)

// Argument holds the name of the argument and the corresponding type.
Expand All @@ -29,6 +31,8 @@ type Argument struct {
Indexed bool // indexed is only used by events
}

type Arguments []Argument

// UnmarshalJSON implements json.Unmarshaler interface
func (a *Argument) UnmarshalJSON(data []byte) error {
var extarg struct {
Expand Down Expand Up @@ -60,3 +64,160 @@ func countNonIndexedArguments(args []Argument) int {
}
return out
}
func (a *Arguments) isTuple() bool {
return a != nil && len(*a) > 1
}

func (a *Arguments) Unpack(v interface{}, data []byte) error {
if a.isTuple() {
return a.unpackTuple(v, data)
}
return a.unpackAtomic(v, data)
}

func (a *Arguments) unpackTuple(v interface{}, output []byte) error {
// make sure the passed value is a pointer
valueOf := reflect.ValueOf(v)
if reflect.Ptr != valueOf.Kind() {
return fmt.Errorf("abi: Unpack(non-pointer %T)", v)
}

var (
value = valueOf.Elem()
typ = value.Type()
kind = value.Kind()
)
/* !TODO add this back
if err := requireUnpackKind(value, typ, kind, (*a), false); err != nil {
return err
}
*/
// `i` counts the nonindexed arguments.
// `j` counts the number of complex types.
// both `i` and `j` are used to to correctly compute `data` offset.

i, j := -1, 0
for _, arg := range(*a) {

if arg.Indexed {
// can't read, continue
continue
}
i++
marshalledValue, err := toGoType((i+j)*32, arg.Type, output)
if err != nil {
return err
}

if arg.Type.T == ArrayTy {
// combined index ('i' + 'j') need to be adjusted only by size of array, thus
// we need to decrement 'j' because 'i' was incremented
j += arg.Type.Size - 1
}

reflectValue := reflect.ValueOf(marshalledValue)

switch kind {
case reflect.Struct:
for j := 0; j < typ.NumField(); j++ {
field := typ.Field(j)
// TODO read tags: `abi:"fieldName"`
if field.Name == strings.ToUpper(arg.Name[:1])+arg.Name[1:] {
if err := set(value.Field(j), reflectValue, arg); err != nil {
return err
}
}
}
case reflect.Slice, reflect.Array:
if value.Len() < i {
return fmt.Errorf("abi: insufficient number of arguments for unpack, want %d, got %d", len(*a), value.Len())
}
v := value.Index(i)
if err := requireAssignable(v, reflectValue); err != nil {
return err
}
reflectValue := reflect.ValueOf(marshalledValue)
return set(v.Elem(), reflectValue, arg)
default:
return fmt.Errorf("abi:[2] cannot unmarshal tuple in to %v", typ)
}
}
return nil
}

func (a *Arguments) unpackAtomic(v interface{}, output []byte) error {
// make sure the passed value is a pointer
valueOf := reflect.ValueOf(v)
if reflect.Ptr != valueOf.Kind() {
return fmt.Errorf("abi: Unpack(non-pointer %T)", v)
}
arg := (*a)[0]
if arg.Indexed {
return fmt.Errorf("abi: attempting to unpack indexed variable into element.")
}

value := valueOf.Elem()

marshalledValue, err := toGoType(0, arg.Type, output)
if err != nil {
return err
}
if err := set(value, reflect.ValueOf(marshalledValue), arg); err != nil {
return err
}
return nil
}

func (arguments *Arguments) Pack(args ...interface{}) ([]byte, error) {
// Make sure arguments match up and pack them
if arguments == nil {
return nil, fmt.Errorf("arguments are nil, programmer error!")
}

abiArgs := *arguments
if len(args) != len(abiArgs) {
return nil, fmt.Errorf("argument count mismatch: %d for %d", len(args), len(abiArgs))
}

// variable input is the output appended at the end of packed
// output. This is used for strings and bytes types input.
var variableInput []byte

// input offset is the bytes offset for packed output
inputOffset := 0
for _, abiArg := range abiArgs {
if abiArg.Type.T == ArrayTy {
inputOffset += (32 * abiArg.Type.Size)
} else {
inputOffset += 32
}
}

var ret []byte
for i, a := range args {
input := abiArgs[i]
// pack the input
packed, err := input.Type.pack(reflect.ValueOf(a))
if err != nil {
return nil, err
}

// check for a slice type (string, bytes, slice)
if input.Type.requiresLengthPrefix() {
// calculate the offset
offset := inputOffset + len(variableInput)
// set the offset
ret = append(ret, packNum(reflect.ValueOf(offset))...)
// Append the packed output to the variable input. The variable input
// will be appended at the end of the input.
variableInput = append(variableInput, packed...)
} else {
// append the packed value to the input
ret = append(ret, packed...)
}
}
// append the variable input at the end of the packed input
ret = append(ret, variableInput...)

return ret, nil
}
89 changes: 1 addition & 88 deletions accounts/abi/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package abi

import (
"fmt"
"reflect"
"strings"

"github.com/ethereum/go-ethereum/common"
Expand All @@ -31,7 +30,7 @@ import (
type Event struct {
Name string
Anonymous bool
Inputs []Argument
Inputs Arguments
}

// Id returns the canonical representation of the event's signature used by the
Expand All @@ -45,89 +44,3 @@ func (e Event) Id() common.Hash {
}
return common.BytesToHash(crypto.Keccak256([]byte(fmt.Sprintf("%v(%v)", e.Name, strings.Join(types, ",")))))
}

// unpacks an event return tuple into a struct of corresponding go types
//
// Unpacking can be done into a struct or a slice/array.
func (e Event) tupleUnpack(v interface{}, output []byte) error {
// make sure the passed value is a pointer
valueOf := reflect.ValueOf(v)
if reflect.Ptr != valueOf.Kind() {
return fmt.Errorf("abi: Unpack(non-pointer %T)", v)
}

var (
value = valueOf.Elem()
typ = value.Type()
kind = value.Kind()
)
if err := requireUnpackKind(value, typ, kind, e.Inputs, true); err != nil {
return err
}

// `i` counts the nonindexed arguments.
// `j` counts the number of complex types.
// both `i` and `j` are used to to correctly compute `data` offset.
i, j := -1, 0
for _, input := range e.Inputs {
if input.Indexed {
// Indexed arguments are not packed into data
continue
}
i++
marshalledValue, err := toGoType((i+j)*32, input.Type, output)
if err != nil {
return err
}
if input.Type.T == ArrayTy {
// combined index ('i' + 'j') need to be adjusted only by size of array, thus
// we need to decrement 'j' because 'i' was incremented
j += input.Type.Size - 1
}
reflectValue := reflect.ValueOf(marshalledValue)

switch kind {
case reflect.Struct:
for j := 0; j < typ.NumField(); j++ {
field := typ.Field(j)
// TODO read tags: `abi:"fieldName"`
if field.Name == strings.ToUpper(input.Name[:1])+input.Name[1:] {
if err := set(value.Field(j), reflectValue, input); err != nil {
return err
}
}
}
case reflect.Slice, reflect.Array:
v := value.Index(i)
if err := requireAssignable(v, reflectValue); err != nil {
return err
}
if err := set(v.Elem(), reflectValue, input); err != nil {
return err
}
}
}
return nil
}

func (e Event) isTupleReturn() bool { return len(e.Inputs) > 1 }

func (e Event) singleUnpack(v interface{}, output []byte) error {
// make sure the passed value is a pointer
valueOf := reflect.ValueOf(v)
if reflect.Ptr != valueOf.Kind() {
return fmt.Errorf("abi: Unpack(non-pointer %T)", v)
}

if e.Inputs[0].Indexed {
return fmt.Errorf("abi: attempting to unpack indexed variable into element")
}

value := valueOf.Elem()

marshalledValue, err := toGoType(0, e.Inputs[0].Type, output)
if err != nil {
return err
}
return set(value, reflect.ValueOf(marshalledValue), e.Inputs[0])
}
Loading

0 comments on commit 73d4a57

Please sign in to comment.