github.com/niluplatform/go-nilu@v1.7.4-0.20200912082737-a0cb0776d52c/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  // UnmarshalJSON implements json.Unmarshaler interface
    37  func (argument *Argument) UnmarshalJSON(data []byte) error {
    38  	var extarg struct {
    39  		Name    string
    40  		Type    string
    41  		Indexed bool
    42  	}
    43  	err := json.Unmarshal(data, &extarg)
    44  	if err != nil {
    45  		return fmt.Errorf("argument json err: %v", err)
    46  	}
    47  
    48  	argument.Type, err = NewType(extarg.Type)
    49  	if err != nil {
    50  		return err
    51  	}
    52  	argument.Name = extarg.Name
    53  	argument.Indexed = extarg.Indexed
    54  
    55  	return nil
    56  }
    57  
    58  // LengthNonIndexed returns the number of arguments when not counting 'indexed' ones. Only events
    59  // can ever have 'indexed' arguments, it should always be false on arguments for method input/output
    60  func (arguments Arguments) LengthNonIndexed() int {
    61  	out := 0
    62  	for _, arg := range arguments {
    63  		if !arg.Indexed {
    64  			out++
    65  		}
    66  	}
    67  	return out
    68  }
    69  
    70  // NonIndexed returns the arguments with indexed arguments filtered out
    71  func (arguments Arguments) NonIndexed() Arguments {
    72  	var ret []Argument
    73  	for _, arg := range arguments {
    74  		if !arg.Indexed {
    75  			ret = append(ret, arg)
    76  		}
    77  	}
    78  	return ret
    79  }
    80  
    81  // isTuple returns true for non-atomic constructs, like (uint,uint) or uint[]
    82  func (arguments Arguments) isTuple() bool {
    83  	return len(arguments) > 1
    84  }
    85  
    86  // Unpack performs the operation hexdata -> Go format
    87  func (arguments Arguments) Unpack(v interface{}, data []byte) error {
    88  
    89  	// make sure the passed value is arguments pointer
    90  	if reflect.Ptr != reflect.ValueOf(v).Kind() {
    91  		return fmt.Errorf("abi: Unpack(non-pointer %T)", v)
    92  	}
    93  	marshalledValues, err := arguments.UnpackValues(data)
    94  	if err != nil {
    95  		return err
    96  	}
    97  	if arguments.isTuple() {
    98  		return arguments.unpackTuple(v, marshalledValues)
    99  	}
   100  	return arguments.unpackAtomic(v, marshalledValues)
   101  }
   102  
   103  func (arguments Arguments) unpackTuple(v interface{}, marshalledValues []interface{}) error {
   104  
   105  	var (
   106  		value = reflect.ValueOf(v).Elem()
   107  		typ   = value.Type()
   108  		kind  = value.Kind()
   109  	)
   110  
   111  	if err := requireUnpackKind(value, typ, kind, arguments); err != nil {
   112  		return err
   113  	}
   114  	// If the output interface is a struct, make sure names don't collide
   115  	if kind == reflect.Struct {
   116  		if err := requireUniqueStructFieldNames(arguments); err != nil {
   117  			return err
   118  		}
   119  	}
   120  	for i, arg := range arguments.NonIndexed() {
   121  
   122  		reflectValue := reflect.ValueOf(marshalledValues[i])
   123  
   124  		switch kind {
   125  		case reflect.Struct:
   126  			err := unpackStruct(value, reflectValue, arg)
   127  			if err != nil {
   128  				return err
   129  			}
   130  		case reflect.Slice, reflect.Array:
   131  			if value.Len() < i {
   132  				return fmt.Errorf("abi: insufficient number of arguments for unpack, want %d, got %d", len(arguments), value.Len())
   133  			}
   134  			v := value.Index(i)
   135  			if err := requireAssignable(v, reflectValue); err != nil {
   136  				return err
   137  			}
   138  
   139  			if err := set(v.Elem(), reflectValue, arg); err != nil {
   140  				return err
   141  			}
   142  		default:
   143  			return fmt.Errorf("abi:[2] cannot unmarshal tuple in to %v", typ)
   144  		}
   145  	}
   146  	return nil
   147  }
   148  
   149  // unpackAtomic unpacks ( hexdata -> go ) a single value
   150  func (arguments Arguments) unpackAtomic(v interface{}, marshalledValues []interface{}) error {
   151  	if len(marshalledValues) != 1 {
   152  		return fmt.Errorf("abi: wrong length, expected single value, got %d", len(marshalledValues))
   153  	}
   154  	elem := reflect.ValueOf(v).Elem()
   155  	kind := elem.Kind()
   156  	reflectValue := reflect.ValueOf(marshalledValues[0])
   157  
   158  	if kind == reflect.Struct {
   159  		//make sure names don't collide
   160  		if err := requireUniqueStructFieldNames(arguments); err != nil {
   161  			return err
   162  		}
   163  
   164  		return unpackStruct(elem, reflectValue, arguments[0])
   165  	}
   166  
   167  	return set(elem, reflectValue, arguments.NonIndexed()[0])
   168  
   169  }
   170  
   171  // Computes the full size of an array;
   172  // i.e. counting nested arrays, which count towards size for unpacking.
   173  func getArraySize(arr *Type) int {
   174  	size := arr.Size
   175  	// Arrays can be nested, with each element being the same size
   176  	arr = arr.Elem
   177  	for arr.T == ArrayTy {
   178  		// Keep multiplying by elem.Size while the elem is an array.
   179  		size *= arr.Size
   180  		arr = arr.Elem
   181  	}
   182  	// Now we have the full array size, including its children.
   183  	return size
   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  	retval := make([]interface{}, 0, arguments.LengthNonIndexed())
   191  	virtualArgs := 0
   192  	for index, arg := range arguments.NonIndexed() {
   193  		marshalledValue, err := toGoType((index+virtualArgs)*32, arg.Type, data)
   194  		if arg.Type.T == ArrayTy {
   195  			// If we have a static array, like [3]uint256, these are coded as
   196  			// just like uint256,uint256,uint256.
   197  			// This means that we need to add two 'virtual' arguments when
   198  			// we count the index from now on.
   199  			//
   200  			// Array values nested multiple levels deep are also encoded inline:
   201  			// [2][3]uint256: uint256,uint256,uint256,uint256,uint256,uint256
   202  			//
   203  			// Calculate the full array size to get the correct offset for the next argument.
   204  			// Decrement it by 1, as the normal index increment is still applied.
   205  			virtualArgs += getArraySize(&arg.Type) - 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: %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  		if abiArg.Type.T == ArrayTy {
   236  			inputOffset += 32 * abiArg.Type.Size
   237  		} else {
   238  			inputOffset += 32
   239  		}
   240  	}
   241  	var ret []byte
   242  	for i, a := range args {
   243  		input := abiArgs[i]
   244  		// pack the input
   245  		packed, err := input.Type.pack(reflect.ValueOf(a))
   246  		if err != nil {
   247  			return nil, err
   248  		}
   249  		// check for a slice type (string, bytes, slice)
   250  		if input.Type.requiresLengthPrefix() {
   251  			// calculate the offset
   252  			offset := inputOffset + len(variableInput)
   253  			// set the offset
   254  			ret = append(ret, packNum(reflect.ValueOf(offset))...)
   255  			// Append the packed output to the variable input. The variable input
   256  			// will be appended at the end of the 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  // capitalise makes the first character of a string upper case, also removing any
   270  // prefixing underscores from the variable names.
   271  func capitalise(input string) string {
   272  	for len(input) > 0 && input[0] == '_' {
   273  		input = input[1:]
   274  	}
   275  	if len(input) == 0 {
   276  		return ""
   277  	}
   278  	return strings.ToUpper(input[:1]) + input[1:]
   279  }
   280  
   281  //unpackStruct extracts each argument into its corresponding struct field
   282  func unpackStruct(value, reflectValue reflect.Value, arg Argument) error {
   283  	name := capitalise(arg.Name)
   284  	typ := value.Type()
   285  	for j := 0; j < typ.NumField(); j++ {
   286  		// TODO read tags: `abi:"fieldName"`
   287  		if typ.Field(j).Name == name {
   288  			if err := set(value.Field(j), reflectValue, arg); err != nil {
   289  				return err
   290  			}
   291  		}
   292  	}
   293  	return nil
   294  }