github.com/ava-labs/subnet-evm@v0.6.4/accounts/abi/reflect.go (about)

     1  // (c) 2019-2020, Ava Labs, Inc.
     2  //
     3  // This file is a derived work, based on the go-ethereum library whose original
     4  // notices appear below.
     5  //
     6  // It is distributed under a license compatible with the licensing terms of the
     7  // original code from which it is derived.
     8  //
     9  // Much love to the original authors for their work.
    10  // **********
    11  // Copyright 2016 The go-ethereum Authors
    12  // This file is part of the go-ethereum library.
    13  //
    14  // The go-ethereum library is free software: you can redistribute it and/or modify
    15  // it under the terms of the GNU Lesser General Public License as published by
    16  // the Free Software Foundation, either version 3 of the License, or
    17  // (at your option) any later version.
    18  //
    19  // The go-ethereum library is distributed in the hope that it will be useful,
    20  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    21  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    22  // GNU Lesser General Public License for more details.
    23  //
    24  // You should have received a copy of the GNU Lesser General Public License
    25  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    26  
    27  package abi
    28  
    29  import (
    30  	"errors"
    31  	"fmt"
    32  	"math/big"
    33  	"reflect"
    34  	"strings"
    35  )
    36  
    37  // ConvertType converts an interface of a runtime type into a interface of the
    38  // given type, e.g. turn this code:
    39  //
    40  //	var fields []reflect.StructField
    41  //
    42  //	fields = append(fields, reflect.StructField{
    43  //			Name: "X",
    44  //			Type: reflect.TypeOf(new(big.Int)),
    45  //			Tag:  reflect.StructTag("json:\"" + "x" + "\""),
    46  //	}
    47  //
    48  // into:
    49  //
    50  //	type TupleT struct { X *big.Int }
    51  func ConvertType(in interface{}, proto interface{}) interface{} {
    52  	protoType := reflect.TypeOf(proto)
    53  	if reflect.TypeOf(in).ConvertibleTo(protoType) {
    54  		return reflect.ValueOf(in).Convert(protoType).Interface()
    55  	}
    56  	// Use set as a last ditch effort
    57  	if err := set(reflect.ValueOf(proto), reflect.ValueOf(in)); err != nil {
    58  		panic(err)
    59  	}
    60  	return proto
    61  }
    62  
    63  // indirect recursively dereferences the value until it either gets the value
    64  // or finds a big.Int
    65  func indirect(v reflect.Value) reflect.Value {
    66  	if v.Kind() == reflect.Ptr && v.Elem().Type() != reflect.TypeOf(big.Int{}) {
    67  		return indirect(v.Elem())
    68  	}
    69  	return v
    70  }
    71  
    72  // reflectIntType returns the reflect using the given size and
    73  // unsignedness.
    74  func reflectIntType(unsigned bool, size int) reflect.Type {
    75  	if unsigned {
    76  		switch size {
    77  		case 8:
    78  			return reflect.TypeOf(uint8(0))
    79  		case 16:
    80  			return reflect.TypeOf(uint16(0))
    81  		case 32:
    82  			return reflect.TypeOf(uint32(0))
    83  		case 64:
    84  			return reflect.TypeOf(uint64(0))
    85  		}
    86  	}
    87  	switch size {
    88  	case 8:
    89  		return reflect.TypeOf(int8(0))
    90  	case 16:
    91  		return reflect.TypeOf(int16(0))
    92  	case 32:
    93  		return reflect.TypeOf(int32(0))
    94  	case 64:
    95  		return reflect.TypeOf(int64(0))
    96  	}
    97  	return reflect.TypeOf(&big.Int{})
    98  }
    99  
   100  // mustArrayToByteSlice creates a new byte slice with the exact same size as value
   101  // and copies the bytes in value to the new slice.
   102  func mustArrayToByteSlice(value reflect.Value) reflect.Value {
   103  	slice := reflect.MakeSlice(reflect.TypeOf([]byte{}), value.Len(), value.Len())
   104  	reflect.Copy(slice, value)
   105  	return slice
   106  }
   107  
   108  // set attempts to assign src to dst by either setting, copying or otherwise.
   109  //
   110  // set is a bit more lenient when it comes to assignment and doesn't force an as
   111  // strict ruleset as bare `reflect` does.
   112  func set(dst, src reflect.Value) error {
   113  	dstType, srcType := dst.Type(), src.Type()
   114  	switch {
   115  	case dstType.Kind() == reflect.Interface && dst.Elem().IsValid() && (dst.Elem().Type().Kind() == reflect.Ptr || dst.Elem().CanSet()):
   116  		return set(dst.Elem(), src)
   117  	case dstType.Kind() == reflect.Ptr && dstType.Elem() != reflect.TypeOf(big.Int{}):
   118  		return set(dst.Elem(), src)
   119  	case srcType.AssignableTo(dstType) && dst.CanSet():
   120  		dst.Set(src)
   121  	case dstType.Kind() == reflect.Slice && srcType.Kind() == reflect.Slice && dst.CanSet():
   122  		return setSlice(dst, src)
   123  	case dstType.Kind() == reflect.Array:
   124  		return setArray(dst, src)
   125  	case dstType.Kind() == reflect.Struct:
   126  		return setStruct(dst, src)
   127  	default:
   128  		return fmt.Errorf("abi: cannot unmarshal %v in to %v", src.Type(), dst.Type())
   129  	}
   130  	return nil
   131  }
   132  
   133  // setSlice attempts to assign src to dst when slices are not assignable by default
   134  // e.g. src: [][]byte -> dst: [][15]byte
   135  // setSlice ignores if we cannot copy all of src' elements.
   136  func setSlice(dst, src reflect.Value) error {
   137  	slice := reflect.MakeSlice(dst.Type(), src.Len(), src.Len())
   138  	for i := 0; i < src.Len(); i++ {
   139  		if err := set(slice.Index(i), src.Index(i)); err != nil {
   140  			return err
   141  		}
   142  	}
   143  	if dst.CanSet() {
   144  		dst.Set(slice)
   145  		return nil
   146  	}
   147  	return errors.New("Cannot set slice, destination not settable")
   148  }
   149  
   150  func setArray(dst, src reflect.Value) error {
   151  	if src.Kind() == reflect.Ptr {
   152  		return set(dst, indirect(src))
   153  	}
   154  	array := reflect.New(dst.Type()).Elem()
   155  	min := src.Len()
   156  	if src.Len() > dst.Len() {
   157  		min = dst.Len()
   158  	}
   159  	for i := 0; i < min; i++ {
   160  		if err := set(array.Index(i), src.Index(i)); err != nil {
   161  			return err
   162  		}
   163  	}
   164  	if dst.CanSet() {
   165  		dst.Set(array)
   166  		return nil
   167  	}
   168  	return errors.New("Cannot set array, destination not settable")
   169  }
   170  
   171  func setStruct(dst, src reflect.Value) error {
   172  	for i := 0; i < src.NumField(); i++ {
   173  		srcField := src.Field(i)
   174  		dstField := dst.Field(i)
   175  		if !dstField.IsValid() || !srcField.IsValid() {
   176  			return fmt.Errorf("Could not find src field: %v value: %v in destination", srcField.Type().Name(), srcField)
   177  		}
   178  		if err := set(dstField, srcField); err != nil {
   179  			return err
   180  		}
   181  	}
   182  	return nil
   183  }
   184  
   185  // mapArgNamesToStructFields maps a slice of argument names to struct fields.
   186  //
   187  // first round: for each Exportable field that contains a `abi:""` tag and this field name
   188  // exists in the given argument name list, pair them together.
   189  //
   190  // second round: for each argument name that has not been already linked, find what
   191  // variable is expected to be mapped into, if it exists and has not been used, pair them.
   192  //
   193  // Note this function assumes the given value is a struct value.
   194  func mapArgNamesToStructFields(argNames []string, value reflect.Value) (map[string]string, error) {
   195  	typ := value.Type()
   196  
   197  	abi2struct := make(map[string]string)
   198  	struct2abi := make(map[string]string)
   199  
   200  	// first round ~~~
   201  	for i := 0; i < typ.NumField(); i++ {
   202  		structFieldName := typ.Field(i).Name
   203  
   204  		// skip private struct fields.
   205  		if structFieldName[:1] != strings.ToUpper(structFieldName[:1]) {
   206  			continue
   207  		}
   208  		// skip fields that have no abi:"" tag.
   209  		tagName, ok := typ.Field(i).Tag.Lookup("abi")
   210  		if !ok {
   211  			continue
   212  		}
   213  		// check if tag is empty.
   214  		if tagName == "" {
   215  			return nil, fmt.Errorf("struct: abi tag in '%s' is empty", structFieldName)
   216  		}
   217  		// check which argument field matches with the abi tag.
   218  		found := false
   219  		for _, arg := range argNames {
   220  			if arg == tagName {
   221  				if abi2struct[arg] != "" {
   222  					return nil, fmt.Errorf("struct: abi tag in '%s' already mapped", structFieldName)
   223  				}
   224  				// pair them
   225  				abi2struct[arg] = structFieldName
   226  				struct2abi[structFieldName] = arg
   227  				found = true
   228  			}
   229  		}
   230  		// check if this tag has been mapped.
   231  		if !found {
   232  			return nil, fmt.Errorf("struct: abi tag '%s' defined but not found in abi", tagName)
   233  		}
   234  	}
   235  
   236  	// second round ~~~
   237  	for _, argName := range argNames {
   238  		structFieldName := ToCamelCase(argName)
   239  
   240  		if structFieldName == "" {
   241  			return nil, errors.New("abi: purely underscored output cannot unpack to struct")
   242  		}
   243  
   244  		// this abi has already been paired, skip it... unless there exists another, yet unassigned
   245  		// struct field with the same field name. If so, raise an error:
   246  		//    abi: [ { "name": "value" } ]
   247  		//    struct { Value  *big.Int , Value1 *big.Int `abi:"value"`}
   248  		if abi2struct[argName] != "" {
   249  			if abi2struct[argName] != structFieldName &&
   250  				struct2abi[structFieldName] == "" &&
   251  				value.FieldByName(structFieldName).IsValid() {
   252  				return nil, fmt.Errorf("abi: multiple variables maps to the same abi field '%s'", argName)
   253  			}
   254  			continue
   255  		}
   256  
   257  		// return an error if this struct field has already been paired.
   258  		if struct2abi[structFieldName] != "" {
   259  			return nil, fmt.Errorf("abi: multiple outputs mapping to the same struct field '%s'", structFieldName)
   260  		}
   261  
   262  		if value.FieldByName(structFieldName).IsValid() {
   263  			// pair them
   264  			abi2struct[argName] = structFieldName
   265  			struct2abi[structFieldName] = argName
   266  		} else {
   267  			// not paired, but annotate as used, to detect cases like
   268  			//   abi : [ { "name": "value" }, { "name": "_value" } ]
   269  			//   struct { Value *big.Int }
   270  			struct2abi[structFieldName] = argName
   271  		}
   272  	}
   273  	return abi2struct, nil
   274  }