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