github.com/mprishchepo/go-ethereum@v1.9.7-0.20191031044858-21506be82b68/accounts/abi/argument.go (about)

     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  	"reflect"
    23  	"strings"
    24  )
    25  
    26  // Argument holds the name of the argument and the corresponding type.
    27  // Types are used when packing and testing arguments.
    28  type Argument struct {
    29  	Name    string
    30  	Type    Type
    31  	Indexed bool // indexed is only used by events
    32  }
    33  
    34  type Arguments []Argument
    35  
    36  type ArgumentMarshaling struct {
    37  	Name       string
    38  	Type       string
    39  	Components []ArgumentMarshaling
    40  	Indexed    bool
    41  }
    42  
    43  // UnmarshalJSON implements json.Unmarshaler interface
    44  func (argument *Argument) UnmarshalJSON(data []byte) error {
    45  	var arg ArgumentMarshaling
    46  	err := json.Unmarshal(data, &arg)
    47  	if err != nil {
    48  		return fmt.Errorf("argument json err: %v", err)
    49  	}
    50  
    51  	argument.Type, err = NewType(arg.Type, arg.Components)
    52  	if err != nil {
    53  		return err
    54  	}
    55  	argument.Name = arg.Name
    56  	argument.Indexed = arg.Indexed
    57  
    58  	return nil
    59  }
    60  
    61  // LengthNonIndexed returns the number of arguments when not counting 'indexed' ones. Only events
    62  // can ever have 'indexed' arguments, it should always be false on arguments for method input/output
    63  func (arguments Arguments) LengthNonIndexed() int {
    64  	out := 0
    65  	for _, arg := range arguments {
    66  		if !arg.Indexed {
    67  			out++
    68  		}
    69  	}
    70  	return out
    71  }
    72  
    73  // NonIndexed returns the arguments with indexed arguments filtered out
    74  func (arguments Arguments) NonIndexed() Arguments {
    75  	var ret []Argument
    76  	for _, arg := range arguments {
    77  		if !arg.Indexed {
    78  			ret = append(ret, arg)
    79  		}
    80  	}
    81  	return ret
    82  }
    83  
    84  // isTuple returns true for non-atomic constructs, like (uint,uint) or uint[]
    85  func (arguments Arguments) isTuple() bool {
    86  	return len(arguments) > 1
    87  }
    88  
    89  // Unpack performs the operation hexdata -> Go format
    90  func (arguments Arguments) Unpack(v interface{}, data []byte) error {
    91  	// make sure the passed value is arguments pointer
    92  	if reflect.Ptr != reflect.ValueOf(v).Kind() {
    93  		return fmt.Errorf("abi: Unpack(non-pointer %T)", v)
    94  	}
    95  	marshalledValues, err := arguments.UnpackValues(data)
    96  	if err != nil {
    97  		return err
    98  	}
    99  	if arguments.isTuple() {
   100  		return arguments.unpackTuple(v, marshalledValues)
   101  	}
   102  	return arguments.unpackAtomic(v, marshalledValues[0])
   103  }
   104  
   105  // UnpackIntoMap performs the operation hexdata -> mapping of argument name to argument value
   106  func (arguments Arguments) UnpackIntoMap(v map[string]interface{}, data []byte) error {
   107  	marshalledValues, err := arguments.UnpackValues(data)
   108  	if err != nil {
   109  		return err
   110  	}
   111  
   112  	return arguments.unpackIntoMap(v, marshalledValues)
   113  }
   114  
   115  // unpack sets the unmarshalled value to go format.
   116  // Note the dst here must be settable.
   117  func unpack(t *Type, dst interface{}, src interface{}) error {
   118  	var (
   119  		dstVal = reflect.ValueOf(dst).Elem()
   120  		srcVal = reflect.ValueOf(src)
   121  	)
   122  	tuple, typ := false, t
   123  	for {
   124  		if typ.T == SliceTy || typ.T == ArrayTy {
   125  			typ = typ.Elem
   126  			continue
   127  		}
   128  		tuple = typ.T == TupleTy
   129  		break
   130  	}
   131  	if !tuple {
   132  		return set(dstVal, srcVal)
   133  	}
   134  
   135  	// Dereferences interface or pointer wrapper
   136  	dstVal = indirectInterfaceOrPtr(dstVal)
   137  
   138  	switch t.T {
   139  	case TupleTy:
   140  		if dstVal.Kind() != reflect.Struct {
   141  			return fmt.Errorf("abi: invalid dst value for unpack, want struct, got %s", dstVal.Kind())
   142  		}
   143  		fieldmap, err := mapArgNamesToStructFields(t.TupleRawNames, dstVal)
   144  		if err != nil {
   145  			return err
   146  		}
   147  		for i, elem := range t.TupleElems {
   148  			fname := fieldmap[t.TupleRawNames[i]]
   149  			field := dstVal.FieldByName(fname)
   150  			if !field.IsValid() {
   151  				return fmt.Errorf("abi: field %s can't found in the given value", t.TupleRawNames[i])
   152  			}
   153  			if err := unpack(elem, field.Addr().Interface(), srcVal.Field(i).Interface()); err != nil {
   154  				return err
   155  			}
   156  		}
   157  		return nil
   158  	case SliceTy:
   159  		if dstVal.Kind() != reflect.Slice {
   160  			return fmt.Errorf("abi: invalid dst value for unpack, want slice, got %s", dstVal.Kind())
   161  		}
   162  		slice := reflect.MakeSlice(dstVal.Type(), srcVal.Len(), srcVal.Len())
   163  		for i := 0; i < slice.Len(); i++ {
   164  			if err := unpack(t.Elem, slice.Index(i).Addr().Interface(), srcVal.Index(i).Interface()); err != nil {
   165  				return err
   166  			}
   167  		}
   168  		dstVal.Set(slice)
   169  	case ArrayTy:
   170  		if dstVal.Kind() != reflect.Array {
   171  			return fmt.Errorf("abi: invalid dst value for unpack, want array, got %s", dstVal.Kind())
   172  		}
   173  		array := reflect.New(dstVal.Type()).Elem()
   174  		for i := 0; i < array.Len(); i++ {
   175  			if err := unpack(t.Elem, array.Index(i).Addr().Interface(), srcVal.Index(i).Interface()); err != nil {
   176  				return err
   177  			}
   178  		}
   179  		dstVal.Set(array)
   180  	}
   181  	return nil
   182  }
   183  
   184  // unpackIntoMap unpacks marshalledValues into the provided map[string]interface{}
   185  func (arguments Arguments) unpackIntoMap(v map[string]interface{}, marshalledValues []interface{}) error {
   186  	// Make sure map is not nil
   187  	if v == nil {
   188  		return fmt.Errorf("abi: cannot unpack into a nil map")
   189  	}
   190  
   191  	for i, arg := range arguments.NonIndexed() {
   192  		v[arg.Name] = marshalledValues[i]
   193  	}
   194  	return nil
   195  }
   196  
   197  // unpackAtomic unpacks ( hexdata -> go ) a single value
   198  func (arguments Arguments) unpackAtomic(v interface{}, marshalledValues interface{}) error {
   199  	if arguments.LengthNonIndexed() == 0 {
   200  		return nil
   201  	}
   202  	argument := arguments.NonIndexed()[0]
   203  	elem := reflect.ValueOf(v).Elem()
   204  
   205  	if elem.Kind() == reflect.Struct && argument.Type.T != TupleTy {
   206  		fieldmap, err := mapArgNamesToStructFields([]string{argument.Name}, elem)
   207  		if err != nil {
   208  			return err
   209  		}
   210  		field := elem.FieldByName(fieldmap[argument.Name])
   211  		if !field.IsValid() {
   212  			return fmt.Errorf("abi: field %s can't be found in the given value", argument.Name)
   213  		}
   214  		return unpack(&argument.Type, field.Addr().Interface(), marshalledValues)
   215  	}
   216  	return unpack(&argument.Type, elem.Addr().Interface(), marshalledValues)
   217  }
   218  
   219  // unpackTuple unpacks ( hexdata -> go ) a batch of values.
   220  func (arguments Arguments) unpackTuple(v interface{}, marshalledValues []interface{}) error {
   221  	var (
   222  		value = reflect.ValueOf(v).Elem()
   223  		typ   = value.Type()
   224  		kind  = value.Kind()
   225  	)
   226  	if err := requireUnpackKind(value, typ, kind, arguments); err != nil {
   227  		return err
   228  	}
   229  
   230  	// If the interface is a struct, get of abi->struct_field mapping
   231  	var abi2struct map[string]string
   232  	if kind == reflect.Struct {
   233  		var (
   234  			argNames []string
   235  			err      error
   236  		)
   237  		for _, arg := range arguments.NonIndexed() {
   238  			argNames = append(argNames, arg.Name)
   239  		}
   240  		abi2struct, err = mapArgNamesToStructFields(argNames, value)
   241  		if err != nil {
   242  			return err
   243  		}
   244  	}
   245  	for i, arg := range arguments.NonIndexed() {
   246  		switch kind {
   247  		case reflect.Struct:
   248  			field := value.FieldByName(abi2struct[arg.Name])
   249  			if !field.IsValid() {
   250  				return fmt.Errorf("abi: field %s can't be found in the given value", arg.Name)
   251  			}
   252  			if err := unpack(&arg.Type, field.Addr().Interface(), marshalledValues[i]); err != nil {
   253  				return err
   254  			}
   255  		case reflect.Slice, reflect.Array:
   256  			if value.Len() < i {
   257  				return fmt.Errorf("abi: insufficient number of arguments for unpack, want %d, got %d", len(arguments), value.Len())
   258  			}
   259  			v := value.Index(i)
   260  			if err := requireAssignable(v, reflect.ValueOf(marshalledValues[i])); err != nil {
   261  				return err
   262  			}
   263  			if err := unpack(&arg.Type, v.Addr().Interface(), marshalledValues[i]); err != nil {
   264  				return err
   265  			}
   266  		default:
   267  			return fmt.Errorf("abi:[2] cannot unmarshal tuple in to %v", typ)
   268  		}
   269  	}
   270  	return nil
   271  
   272  }
   273  
   274  // UnpackValues can be used to unpack ABI-encoded hexdata according to the ABI-specification,
   275  // without supplying a struct to unpack into. Instead, this method returns a list containing the
   276  // values. An atomic argument will be a list with one element.
   277  func (arguments Arguments) UnpackValues(data []byte) ([]interface{}, error) {
   278  	retval := make([]interface{}, 0, arguments.LengthNonIndexed())
   279  	virtualArgs := 0
   280  	for index, arg := range arguments.NonIndexed() {
   281  		marshalledValue, err := toGoType((index+virtualArgs)*32, arg.Type, data)
   282  		if arg.Type.T == ArrayTy && !isDynamicType(arg.Type) {
   283  			// If we have a static array, like [3]uint256, these are coded as
   284  			// just like uint256,uint256,uint256.
   285  			// This means that we need to add two 'virtual' arguments when
   286  			// we count the index from now on.
   287  			//
   288  			// Array values nested multiple levels deep are also encoded inline:
   289  			// [2][3]uint256: uint256,uint256,uint256,uint256,uint256,uint256
   290  			//
   291  			// Calculate the full array size to get the correct offset for the next argument.
   292  			// Decrement it by 1, as the normal index increment is still applied.
   293  			virtualArgs += getTypeSize(arg.Type)/32 - 1
   294  		} else if arg.Type.T == TupleTy && !isDynamicType(arg.Type) {
   295  			// If we have a static tuple, like (uint256, bool, uint256), these are
   296  			// coded as just like uint256,bool,uint256
   297  			virtualArgs += getTypeSize(arg.Type)/32 - 1
   298  		}
   299  		if err != nil {
   300  			return nil, err
   301  		}
   302  		retval = append(retval, marshalledValue)
   303  	}
   304  	return retval, nil
   305  }
   306  
   307  // PackValues performs the operation Go format -> Hexdata
   308  // It is the semantic opposite of UnpackValues
   309  func (arguments Arguments) PackValues(args []interface{}) ([]byte, error) {
   310  	return arguments.Pack(args...)
   311  }
   312  
   313  // Pack performs the operation Go format -> Hexdata
   314  func (arguments Arguments) Pack(args ...interface{}) ([]byte, error) {
   315  	// Make sure arguments match up and pack them
   316  	abiArgs := arguments
   317  	if len(args) != len(abiArgs) {
   318  		return nil, fmt.Errorf("argument count mismatch: %d for %d", len(args), len(abiArgs))
   319  	}
   320  	// variable input is the output appended at the end of packed
   321  	// output. This is used for strings and bytes types input.
   322  	var variableInput []byte
   323  
   324  	// input offset is the bytes offset for packed output
   325  	inputOffset := 0
   326  	for _, abiArg := range abiArgs {
   327  		inputOffset += getTypeSize(abiArg.Type)
   328  	}
   329  	var ret []byte
   330  	for i, a := range args {
   331  		input := abiArgs[i]
   332  		// pack the input
   333  		packed, err := input.Type.pack(reflect.ValueOf(a))
   334  		if err != nil {
   335  			return nil, err
   336  		}
   337  		// check for dynamic types
   338  		if isDynamicType(input.Type) {
   339  			// set the offset
   340  			ret = append(ret, packNum(reflect.ValueOf(inputOffset))...)
   341  			// calculate next offset
   342  			inputOffset += len(packed)
   343  			// append to variable input
   344  			variableInput = append(variableInput, packed...)
   345  		} else {
   346  			// append the packed value to the input
   347  			ret = append(ret, packed...)
   348  		}
   349  	}
   350  	// append the variable input at the end of the packed input
   351  	ret = append(ret, variableInput...)
   352  
   353  	return ret, nil
   354  }
   355  
   356  // ToCamelCase converts an under-score string to a camel-case string
   357  func ToCamelCase(input string) string {
   358  	parts := strings.Split(input, "_")
   359  	for i, s := range parts {
   360  		if len(s) > 0 {
   361  			parts[i] = strings.ToUpper(s[:1]) + s[1:]
   362  		}
   363  	}
   364  	return strings.Join(parts, "")
   365  }