github.com/amazechain/amc@v0.1.3/internal/avm/abi/argument.go (about)

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