github.com/0xsequence/ethkit@v1.25.0/go-ethereum/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  	"errors"
    22  	"fmt"
    23  	"reflect"
    24  	"strings"
    25  )
    26  
    27  // Argument holds the name of the argument and the corresponding type.
    28  // Types are used when packing and testing arguments.
    29  type Argument struct {
    30  	Name    string
    31  	Type    Type
    32  	Indexed bool // indexed is only used by events
    33  }
    34  
    35  type Arguments []Argument
    36  
    37  type ArgumentMarshaling struct {
    38  	Name         string
    39  	Type         string
    40  	InternalType string
    41  	Components   []ArgumentMarshaling
    42  	Indexed      bool
    43  }
    44  
    45  // UnmarshalJSON implements json.Unmarshaler interface.
    46  func (argument *Argument) UnmarshalJSON(data []byte) error {
    47  	var arg ArgumentMarshaling
    48  	err := json.Unmarshal(data, &arg)
    49  	if err != nil {
    50  		return fmt.Errorf("argument json err: %v", err)
    51  	}
    52  
    53  	argument.Type, err = NewType(arg.Type, arg.InternalType, arg.Components)
    54  	if err != nil {
    55  		return err
    56  	}
    57  	argument.Name = arg.Name
    58  	argument.Indexed = arg.Indexed
    59  
    60  	return nil
    61  }
    62  
    63  // NonIndexed returns the arguments with indexed arguments filtered out.
    64  func (arguments Arguments) NonIndexed() Arguments {
    65  	var ret []Argument
    66  	for _, arg := range arguments {
    67  		if !arg.Indexed {
    68  			ret = append(ret, arg)
    69  		}
    70  	}
    71  	return ret
    72  }
    73  
    74  // isTuple returns true for non-atomic constructs, like (uint,uint) or uint[].
    75  func (arguments Arguments) isTuple() bool {
    76  	return len(arguments) > 1
    77  }
    78  
    79  // Unpack performs the operation hexdata -> Go format.
    80  func (arguments Arguments) Unpack(data []byte) ([]interface{}, error) {
    81  	if len(data) == 0 {
    82  		if len(arguments.NonIndexed()) != 0 {
    83  			return nil, errors.New("abi: attempting to unmarshall an empty string while arguments are expected")
    84  		}
    85  		return make([]interface{}, 0), nil
    86  	}
    87  	return arguments.UnpackValues(data)
    88  }
    89  
    90  // UnpackIntoMap performs the operation hexdata -> mapping of argument name to argument value.
    91  func (arguments Arguments) UnpackIntoMap(v map[string]interface{}, data []byte) error {
    92  	// Make sure map is not nil
    93  	if v == nil {
    94  		return errors.New("abi: cannot unpack into a nil map")
    95  	}
    96  	if len(data) == 0 {
    97  		if len(arguments.NonIndexed()) != 0 {
    98  			return errors.New("abi: attempting to unmarshall an empty string while arguments are expected")
    99  		}
   100  		return nil // Nothing to unmarshal, return
   101  	}
   102  	marshalledValues, err := arguments.UnpackValues(data)
   103  	if err != nil {
   104  		return err
   105  	}
   106  	for i, arg := range arguments.NonIndexed() {
   107  		v[arg.Name] = marshalledValues[i]
   108  	}
   109  	return nil
   110  }
   111  
   112  // Copy performs the operation go format -> provided struct.
   113  func (arguments Arguments) Copy(v interface{}, values []interface{}) error {
   114  	// make sure the passed value is arguments pointer
   115  	if reflect.Ptr != reflect.ValueOf(v).Kind() {
   116  		return fmt.Errorf("abi: Unpack(non-pointer %T)", v)
   117  	}
   118  	if len(values) == 0 {
   119  		if len(arguments.NonIndexed()) != 0 {
   120  			return errors.New("abi: attempting to copy no values while arguments are expected")
   121  		}
   122  		return nil // Nothing to copy, return
   123  	}
   124  	if arguments.isTuple() {
   125  		return arguments.copyTuple(v, values)
   126  	}
   127  	return arguments.copyAtomic(v, values[0])
   128  }
   129  
   130  // unpackAtomic unpacks ( hexdata -> go ) a single value
   131  func (arguments Arguments) copyAtomic(v interface{}, marshalledValues interface{}) error {
   132  	dst := reflect.ValueOf(v).Elem()
   133  	src := reflect.ValueOf(marshalledValues)
   134  
   135  	if dst.Kind() == reflect.Struct {
   136  		return set(dst.Field(0), src)
   137  	}
   138  	return set(dst, src)
   139  }
   140  
   141  // copyTuple copies a batch of values from marshalledValues to v.
   142  func (arguments Arguments) copyTuple(v interface{}, marshalledValues []interface{}) error {
   143  	value := reflect.ValueOf(v).Elem()
   144  	nonIndexedArgs := arguments.NonIndexed()
   145  
   146  	switch value.Kind() {
   147  	case reflect.Struct:
   148  		argNames := make([]string, len(nonIndexedArgs))
   149  		for i, arg := range nonIndexedArgs {
   150  			argNames[i] = arg.Name
   151  		}
   152  		var err error
   153  		abi2struct, err := mapArgNamesToStructFields(argNames, value)
   154  		if err != nil {
   155  			return err
   156  		}
   157  		for i, arg := range nonIndexedArgs {
   158  			field := value.FieldByName(abi2struct[arg.Name])
   159  			if !field.IsValid() {
   160  				return fmt.Errorf("abi: field %s can't be found in the given value", arg.Name)
   161  			}
   162  			if err := set(field, reflect.ValueOf(marshalledValues[i])); err != nil {
   163  				return err
   164  			}
   165  		}
   166  	case reflect.Slice, reflect.Array:
   167  		if value.Len() < len(marshalledValues) {
   168  			return fmt.Errorf("abi: insufficient number of arguments for unpack, want %d, got %d", len(arguments), value.Len())
   169  		}
   170  		for i := range nonIndexedArgs {
   171  			if err := set(value.Index(i), reflect.ValueOf(marshalledValues[i])); err != nil {
   172  				return err
   173  			}
   174  		}
   175  	default:
   176  		return fmt.Errorf("abi:[2] cannot unmarshal tuple in to %v", value.Type())
   177  	}
   178  	return nil
   179  }
   180  
   181  // UnpackValues can be used to unpack ABI-encoded hexdata according to the ABI-specification,
   182  // without supplying a struct to unpack into. Instead, this method returns a list containing the
   183  // values. An atomic argument will be a list with one element.
   184  func (arguments Arguments) UnpackValues(data []byte) ([]interface{}, error) {
   185  	nonIndexedArgs := arguments.NonIndexed()
   186  	retval := make([]interface{}, 0, len(nonIndexedArgs))
   187  	virtualArgs := 0
   188  	for index, arg := range nonIndexedArgs {
   189  		marshalledValue, err := toGoType((index+virtualArgs)*32, arg.Type, data)
   190  		if arg.Type.T == ArrayTy && !isDynamicType(arg.Type) {
   191  			// If we have a static array, like [3]uint256, these are coded as
   192  			// just like uint256,uint256,uint256.
   193  			// This means that we need to add two 'virtual' arguments when
   194  			// we count the index from now on.
   195  			//
   196  			// Array values nested multiple levels deep are also encoded inline:
   197  			// [2][3]uint256: uint256,uint256,uint256,uint256,uint256,uint256
   198  			//
   199  			// Calculate the full array size to get the correct offset for the next argument.
   200  			// Decrement it by 1, as the normal index increment is still applied.
   201  			virtualArgs += getTypeSize(arg.Type)/32 - 1
   202  		} else if arg.Type.T == TupleTy && !isDynamicType(arg.Type) {
   203  			// If we have a static tuple, like (uint256, bool, uint256), these are
   204  			// coded as just like uint256,bool,uint256
   205  			virtualArgs += getTypeSize(arg.Type)/32 - 1
   206  		}
   207  		if err != nil {
   208  			return nil, err
   209  		}
   210  		retval = append(retval, marshalledValue)
   211  	}
   212  	return retval, nil
   213  }
   214  
   215  // PackValues performs the operation Go format -> Hexdata.
   216  // It is the semantic opposite of UnpackValues.
   217  func (arguments Arguments) PackValues(args []interface{}) ([]byte, error) {
   218  	return arguments.Pack(args...)
   219  }
   220  
   221  // Pack performs the operation Go format -> Hexdata.
   222  func (arguments Arguments) Pack(args ...interface{}) ([]byte, error) {
   223  	// Make sure arguments match up and pack them
   224  	abiArgs := arguments
   225  	if len(args) != len(abiArgs) {
   226  		return nil, fmt.Errorf("argument count mismatch: got %d for %d", len(args), len(abiArgs))
   227  	}
   228  	// variable input is the output appended at the end of packed
   229  	// output. This is used for strings and bytes types input.
   230  	var variableInput []byte
   231  
   232  	// input offset is the bytes offset for packed output
   233  	inputOffset := 0
   234  	for _, abiArg := range abiArgs {
   235  		inputOffset += getTypeSize(abiArg.Type)
   236  	}
   237  	var ret []byte
   238  	for i, a := range args {
   239  		input := abiArgs[i]
   240  		// pack the input
   241  		packed, err := input.Type.pack(reflect.ValueOf(a))
   242  		if err != nil {
   243  			return nil, err
   244  		}
   245  		// check for dynamic types
   246  		if isDynamicType(input.Type) {
   247  			// set the offset
   248  			ret = append(ret, packNum(reflect.ValueOf(inputOffset))...)
   249  			// calculate next offset
   250  			inputOffset += len(packed)
   251  			// append to variable input
   252  			variableInput = append(variableInput, packed...)
   253  		} else {
   254  			// append the packed value to the input
   255  			ret = append(ret, packed...)
   256  		}
   257  	}
   258  	// append the variable input at the end of the packed input
   259  	ret = append(ret, variableInput...)
   260  
   261  	return ret, nil
   262  }
   263  
   264  // ToCamelCase converts an under-score string to a camel-case string
   265  func ToCamelCase(input string) string {
   266  	parts := strings.Split(input, "_")
   267  	for i, s := range parts {
   268  		if len(s) > 0 {
   269  			parts[i] = strings.ToUpper(s[:1]) + s[1:]
   270  		}
   271  	}
   272  	return strings.Join(parts, "")
   273  }