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