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