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