github.com/humaniq/go-ethereum@v1.6.8-0.20171225131628-061223a13848/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  // isTuple returns true for non-atomic constructs, like (uint,uint) or uint[]
    71  func (arguments Arguments) isTuple() bool {
    72  	return len(arguments) > 1
    73  }
    74  
    75  // Unpack performs the operation hexdata -> Go format
    76  func (arguments Arguments) Unpack(v interface{}, data []byte) error {
    77  	if arguments.isTuple() {
    78  		return arguments.unpackTuple(v, data)
    79  	}
    80  	return arguments.unpackAtomic(v, data)
    81  }
    82  
    83  func (arguments Arguments) unpackTuple(v interface{}, output []byte) error {
    84  	// make sure the passed value is arguments pointer
    85  	valueOf := reflect.ValueOf(v)
    86  	if reflect.Ptr != valueOf.Kind() {
    87  		return fmt.Errorf("abi: Unpack(non-pointer %T)", v)
    88  	}
    89  
    90  	var (
    91  		value = valueOf.Elem()
    92  		typ   = value.Type()
    93  		kind  = value.Kind()
    94  	)
    95  
    96  	if err := requireUnpackKind(value, typ, kind, arguments); err != nil {
    97  		return err
    98  	}
    99  	// `i` counts the nonindexed arguments.
   100  	// `j` counts the number of complex types.
   101  	// both `i` and `j` are used to to correctly compute `data` offset.
   102  
   103  	i, j := -1, 0
   104  	for _, arg := range arguments {
   105  
   106  		if arg.Indexed {
   107  			// can't read, continue
   108  			continue
   109  		}
   110  		i++
   111  		marshalledValue, err := toGoType((i+j)*32, arg.Type, output)
   112  		if err != nil {
   113  			return err
   114  		}
   115  
   116  		if arg.Type.T == ArrayTy {
   117  			// combined index ('i' + 'j') need to be adjusted only by size of array, thus
   118  			// we need to decrement 'j' because 'i' was incremented
   119  			j += arg.Type.Size - 1
   120  		}
   121  
   122  		reflectValue := reflect.ValueOf(marshalledValue)
   123  
   124  		switch kind {
   125  		case reflect.Struct:
   126  			for j := 0; j < typ.NumField(); j++ {
   127  				field := typ.Field(j)
   128  				// TODO read tags: `abi:"fieldName"`
   129  				if field.Name == strings.ToUpper(arg.Name[:1])+arg.Name[1:] {
   130  					if err := set(value.Field(j), reflectValue, arg); err != nil {
   131  						return err
   132  					}
   133  				}
   134  			}
   135  		case reflect.Slice, reflect.Array:
   136  			if value.Len() < i {
   137  				return fmt.Errorf("abi: insufficient number of arguments for unpack, want %d, got %d", len(arguments), value.Len())
   138  			}
   139  			v := value.Index(i)
   140  			if err := requireAssignable(v, reflectValue); err != nil {
   141  				return err
   142  			}
   143  
   144  			if err := set(v.Elem(), reflectValue, arg); err != nil {
   145  				return err
   146  			}
   147  		default:
   148  			return fmt.Errorf("abi:[2] cannot unmarshal tuple in to %v", typ)
   149  		}
   150  	}
   151  	return nil
   152  }
   153  
   154  // unpackAtomic unpacks ( hexdata -> go ) a single value
   155  func (arguments Arguments) unpackAtomic(v interface{}, output []byte) error {
   156  	// make sure the passed value is arguments pointer
   157  	valueOf := reflect.ValueOf(v)
   158  	if reflect.Ptr != valueOf.Kind() {
   159  		return fmt.Errorf("abi: Unpack(non-pointer %T)", v)
   160  	}
   161  	arg := arguments[0]
   162  	if arg.Indexed {
   163  		return fmt.Errorf("abi: attempting to unpack indexed variable into element.")
   164  	}
   165  
   166  	value := valueOf.Elem()
   167  
   168  	marshalledValue, err := toGoType(0, arg.Type, output)
   169  	if err != nil {
   170  		return err
   171  	}
   172  	return set(value, reflect.ValueOf(marshalledValue), arg)
   173  }
   174  
   175  // Unpack performs the operation Go format -> Hexdata
   176  func (arguments Arguments) Pack(args ...interface{}) ([]byte, error) {
   177  	// Make sure arguments match up and pack them
   178  	abiArgs := arguments
   179  	if len(args) != len(abiArgs) {
   180  		return nil, fmt.Errorf("argument count mismatch: %d for %d", len(args), len(abiArgs))
   181  	}
   182  
   183  	// variable input is the output appended at the end of packed
   184  	// output. This is used for strings and bytes types input.
   185  	var variableInput []byte
   186  
   187  	// input offset is the bytes offset for packed output
   188  	inputOffset := 0
   189  	for _, abiArg := range abiArgs {
   190  		if abiArg.Type.T == ArrayTy {
   191  			inputOffset += (32 * abiArg.Type.Size)
   192  		} else {
   193  			inputOffset += 32
   194  		}
   195  	}
   196  
   197  	var ret []byte
   198  	for i, a := range args {
   199  		input := abiArgs[i]
   200  		// pack the input
   201  		packed, err := input.Type.pack(reflect.ValueOf(a))
   202  		if err != nil {
   203  			return nil, err
   204  		}
   205  
   206  		// check for a slice type (string, bytes, slice)
   207  		if input.Type.requiresLengthPrefix() {
   208  			// calculate the offset
   209  			offset := inputOffset + len(variableInput)
   210  			// set the offset
   211  			ret = append(ret, packNum(reflect.ValueOf(offset))...)
   212  			// Append the packed output to the variable input. The variable input
   213  			// will be appended at the end of the input.
   214  			variableInput = append(variableInput, packed...)
   215  		} else {
   216  			// append the packed value to the input
   217  			ret = append(ret, packed...)
   218  		}
   219  	}
   220  	// append the variable input at the end of the packed input
   221  	ret = append(ret, variableInput...)
   222  
   223  	return ret, nil
   224  }