github.com/n1ghtfa1l/go-vnt@v0.6.4-alpha.6/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  
   115  	// If the interface is a struct, get of abi->struct_field mapping
   116  
   117  	var abi2struct map[string]string
   118  	if kind == reflect.Struct {
   119  		var err error
   120  		abi2struct, err = mapAbiToStructFields(arguments, value)
   121  		if err != nil {
   122  			return err
   123  		}
   124  	}
   125  	for i, arg := range arguments.NonIndexed() {
   126  
   127  		reflectValue := reflect.ValueOf(marshalledValues[i])
   128  
   129  		switch kind {
   130  		case reflect.Struct:
   131  			if structField, ok := abi2struct[arg.Name]; ok {
   132  				if err := set(value.FieldByName(structField), reflectValue, arg); err != nil {
   133  					return err
   134  				}
   135  			}
   136  		case reflect.Slice, reflect.Array:
   137  			if value.Len() < i {
   138  				return fmt.Errorf("abi: insufficient number of arguments for unpack, want %d, got %d", len(arguments), value.Len())
   139  			}
   140  			v := value.Index(i)
   141  			if err := requireAssignable(v, reflectValue); err != nil {
   142  				return err
   143  			}
   144  
   145  			if err := set(v.Elem(), reflectValue, arg); err != nil {
   146  				return err
   147  			}
   148  		default:
   149  			return fmt.Errorf("abi:[2] cannot unmarshal tuple in to %v", typ)
   150  		}
   151  	}
   152  	return nil
   153  }
   154  
   155  // unpackAtomic unpacks ( hexdata -> go ) a single value
   156  func (arguments Arguments) unpackAtomic(v interface{}, marshalledValues []interface{}) error {
   157  	if len(marshalledValues) != 1 {
   158  		return fmt.Errorf("abi: wrong length, expected single value, got %d", len(marshalledValues))
   159  	}
   160  
   161  	elem := reflect.ValueOf(v).Elem()
   162  	kind := elem.Kind()
   163  	reflectValue := reflect.ValueOf(marshalledValues[0])
   164  
   165  	var abi2struct map[string]string
   166  	if kind == reflect.Struct {
   167  		var err error
   168  		if abi2struct, err = mapAbiToStructFields(arguments, elem); err != nil {
   169  			return err
   170  		}
   171  		arg := arguments.NonIndexed()[0]
   172  		if structField, ok := abi2struct[arg.Name]; ok {
   173  			return set(elem.FieldByName(structField), reflectValue, arg)
   174  		}
   175  		return nil
   176  	}
   177  	return set(elem, reflectValue, arguments.NonIndexed()[0])
   178  
   179  }
   180  
   181  // Computes the full size of an array;
   182  // i.e. counting nested arrays, which count towards size for unpacking.
   183  func getArraySize(arr *Type) int {
   184  	size := arr.Size
   185  	// Arrays can be nested, with each element being the same size
   186  	arr = arr.Elem
   187  	for arr.T == ArrayTy {
   188  		// Keep multiplying by elem.Size while the elem is an array.
   189  		size *= arr.Size
   190  		arr = arr.Elem
   191  	}
   192  	// Now we have the full array size, including its children.
   193  	return size
   194  }
   195  
   196  // UnpackValues can be used to unpack ABI-encoded hexdata according to the ABI-specification,
   197  // without supplying a struct to unpack into. Instead, this method returns a list containing the
   198  // values. An atomic argument will be a list with one element.
   199  func (arguments Arguments) UnpackValues(data []byte) ([]interface{}, error) {
   200  	retval := make([]interface{}, 0, arguments.LengthNonIndexed())
   201  	virtualArgs := 0
   202  	for index, arg := range arguments.NonIndexed() {
   203  		marshalledValue, err := toGoType((index+virtualArgs)*32, arg.Type, data)
   204  		if arg.Type.T == ArrayTy {
   205  			// If we have a static array, like [3]uint256, these are coded as
   206  			// just like uint256,uint256,uint256.
   207  			// This means that we need to add two 'virtual' arguments when
   208  			// we count the index from now on.
   209  			//
   210  			// Array values nested multiple levels deep are also encoded inline:
   211  			// [2][3]uint256: uint256,uint256,uint256,uint256,uint256,uint256
   212  			//
   213  			// Calculate the full array size to get the correct offset for the next argument.
   214  			// Decrement it by 1, as the normal index increment is still applied.
   215  			virtualArgs += getArraySize(&arg.Type) - 1
   216  		}
   217  		if err != nil {
   218  			return nil, err
   219  		}
   220  		retval = append(retval, marshalledValue)
   221  	}
   222  	return retval, nil
   223  }
   224  
   225  // PackValues performs the operation Go format -> Hexdata
   226  // It is the semantic opposite of UnpackValues
   227  func (arguments Arguments) PackValues(args []interface{}) ([]byte, error) {
   228  	return arguments.Pack(args...)
   229  }
   230  
   231  // Pack performs the operation Go format -> Hexdata
   232  func (arguments Arguments) Pack(args ...interface{}) ([]byte, error) {
   233  	// Make sure arguments match up and pack them
   234  	abiArgs := arguments
   235  	if len(args) != len(abiArgs) {
   236  		return nil, fmt.Errorf("argument count mismatch: %d for %d", len(args), len(abiArgs))
   237  	}
   238  	// variable input is the output appended at the end of packed
   239  	// output. This is used for strings and bytes types input.
   240  	var variableInput []byte
   241  
   242  	// input offset is the bytes offset for packed output
   243  	inputOffset := 0
   244  	for _, abiArg := range abiArgs {
   245  		if abiArg.Type.T == ArrayTy {
   246  			inputOffset += 32 * abiArg.Type.Size
   247  		} else {
   248  			inputOffset += 32
   249  		}
   250  	}
   251  	var ret []byte
   252  	for i, a := range args {
   253  		input := abiArgs[i]
   254  		// pack the input
   255  		packed, err := input.Type.pack(reflect.ValueOf(a))
   256  		if err != nil {
   257  			return nil, err
   258  		}
   259  		// check for a slice type (string, bytes, slice)
   260  		if input.Type.requiresLengthPrefix() {
   261  			// calculate the offset
   262  			offset := inputOffset + len(variableInput)
   263  			// set the offset
   264  			ret = append(ret, packNum(reflect.ValueOf(offset))...)
   265  			// Append the packed output to the variable input. The variable input
   266  			// will be appended at the end of the input.
   267  			variableInput = append(variableInput, packed...)
   268  		} else {
   269  			// append the packed value to the input
   270  			ret = append(ret, packed...)
   271  		}
   272  	}
   273  	// append the variable input at the end of the packed input
   274  	ret = append(ret, variableInput...)
   275  
   276  	return ret, nil
   277  }
   278  
   279  // capitalise makes the first character of a string upper case, also removing any
   280  // prefixing underscores from the variable names.
   281  func capitalise(input string) string {
   282  	for len(input) > 0 && input[0] == '_' {
   283  		input = input[1:]
   284  	}
   285  	if len(input) == 0 {
   286  		return ""
   287  	}
   288  	return strings.ToUpper(input[:1]) + input[1:]
   289  }