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