github.com/MetalBlockchain/subnet-evm@v0.4.9/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
    39  // e.g. turn
    40  // var fields []reflect.StructField
    41  // fields = append(fields, reflect.StructField{
    42  // 		Name: "X",
    43  //		Type: reflect.TypeOf(new(big.Int)),
    44  //		Tag:  reflect.StructTag("json:\"" + "x" + "\""),
    45  // }
    46  // into
    47  // type TupleT struct { X *big.Int }
    48  func ConvertType(in interface{}, proto interface{}) interface{} {
    49  	protoType := reflect.TypeOf(proto)
    50  	if reflect.TypeOf(in).ConvertibleTo(protoType) {
    51  		return reflect.ValueOf(in).Convert(protoType).Interface()
    52  	}
    53  	// Use set as a last ditch effort
    54  	if err := set(reflect.ValueOf(proto), reflect.ValueOf(in)); err != nil {
    55  		panic(err)
    56  	}
    57  	return proto
    58  }
    59  
    60  // indirect recursively dereferences the value until it either gets the value
    61  // or finds a big.Int
    62  func indirect(v reflect.Value) reflect.Value {
    63  	if v.Kind() == reflect.Ptr && v.Elem().Type() != reflect.TypeOf(big.Int{}) {
    64  		return indirect(v.Elem())
    65  	}
    66  	return v
    67  }
    68  
    69  // reflectIntType returns the reflect using the given size and
    70  // unsignedness.
    71  func reflectIntType(unsigned bool, size int) reflect.Type {
    72  	if unsigned {
    73  		switch size {
    74  		case 8:
    75  			return reflect.TypeOf(uint8(0))
    76  		case 16:
    77  			return reflect.TypeOf(uint16(0))
    78  		case 32:
    79  			return reflect.TypeOf(uint32(0))
    80  		case 64:
    81  			return reflect.TypeOf(uint64(0))
    82  		}
    83  	}
    84  	switch size {
    85  	case 8:
    86  		return reflect.TypeOf(int8(0))
    87  	case 16:
    88  		return reflect.TypeOf(int16(0))
    89  	case 32:
    90  		return reflect.TypeOf(int32(0))
    91  	case 64:
    92  		return reflect.TypeOf(int64(0))
    93  	}
    94  	return reflect.TypeOf(&big.Int{})
    95  }
    96  
    97  // mustArrayToByteSlice creates a new byte slice with the exact same size as value
    98  // and copies the bytes in value to the new slice.
    99  func mustArrayToByteSlice(value reflect.Value) reflect.Value {
   100  	slice := reflect.MakeSlice(reflect.TypeOf([]byte{}), value.Len(), value.Len())
   101  	reflect.Copy(slice, value)
   102  	return slice
   103  }
   104  
   105  // set attempts to assign src to dst by either setting, copying or otherwise.
   106  //
   107  // set is a bit more lenient when it comes to assignment and doesn't force an as
   108  // strict ruleset as bare `reflect` does.
   109  func set(dst, src reflect.Value) error {
   110  	dstType, srcType := dst.Type(), src.Type()
   111  	switch {
   112  	case dstType.Kind() == reflect.Interface && dst.Elem().IsValid() && (dst.Elem().Type().Kind() == reflect.Ptr || dst.Elem().CanSet()):
   113  		return set(dst.Elem(), src)
   114  	case dstType.Kind() == reflect.Ptr && dstType.Elem() != reflect.TypeOf(big.Int{}):
   115  		return set(dst.Elem(), src)
   116  	case srcType.AssignableTo(dstType) && dst.CanSet():
   117  		dst.Set(src)
   118  	case dstType.Kind() == reflect.Slice && srcType.Kind() == reflect.Slice && dst.CanSet():
   119  		return setSlice(dst, src)
   120  	case dstType.Kind() == reflect.Array:
   121  		return setArray(dst, src)
   122  	case dstType.Kind() == reflect.Struct:
   123  		return setStruct(dst, src)
   124  	default:
   125  		return fmt.Errorf("abi: cannot unmarshal %v in to %v", src.Type(), dst.Type())
   126  	}
   127  	return nil
   128  }
   129  
   130  // setSlice attempts to assign src to dst when slices are not assignable by default
   131  // e.g. src: [][]byte -> dst: [][15]byte
   132  // setSlice ignores if we cannot copy all of src' elements.
   133  func setSlice(dst, src reflect.Value) error {
   134  	slice := reflect.MakeSlice(dst.Type(), src.Len(), src.Len())
   135  	for i := 0; i < src.Len(); i++ {
   136  		if err := set(slice.Index(i), src.Index(i)); err != nil {
   137  			return err
   138  		}
   139  	}
   140  	if dst.CanSet() {
   141  		dst.Set(slice)
   142  		return nil
   143  	}
   144  	return errors.New("Cannot set slice, destination not settable")
   145  }
   146  
   147  func setArray(dst, src reflect.Value) error {
   148  	if src.Kind() == reflect.Ptr {
   149  		return set(dst, indirect(src))
   150  	}
   151  	array := reflect.New(dst.Type()).Elem()
   152  	min := src.Len()
   153  	if src.Len() > dst.Len() {
   154  		min = dst.Len()
   155  	}
   156  	for i := 0; i < min; i++ {
   157  		if err := set(array.Index(i), src.Index(i)); err != nil {
   158  			return err
   159  		}
   160  	}
   161  	if dst.CanSet() {
   162  		dst.Set(array)
   163  		return nil
   164  	}
   165  	return errors.New("Cannot set array, destination not settable")
   166  }
   167  
   168  func setStruct(dst, src reflect.Value) error {
   169  	for i := 0; i < src.NumField(); i++ {
   170  		srcField := src.Field(i)
   171  		dstField := dst.Field(i)
   172  		if !dstField.IsValid() || !srcField.IsValid() {
   173  			return fmt.Errorf("Could not find src field: %v value: %v in destination", srcField.Type().Name(), srcField)
   174  		}
   175  		if err := set(dstField, srcField); err != nil {
   176  			return err
   177  		}
   178  	}
   179  	return nil
   180  }
   181  
   182  // mapArgNamesToStructFields maps a slice of argument names to struct fields.
   183  // first round: for each Exportable field that contains a `abi:""` tag
   184  //   and this field name exists in the given argument name list, pair them together.
   185  // second round: for each argument name that has not been already linked,
   186  //   find what variable is expected to be mapped into, if it exists and has not been
   187  //   used, pair them.
   188  // Note this function assumes the given value is a struct value.
   189  func mapArgNamesToStructFields(argNames []string, value reflect.Value) (map[string]string, error) {
   190  	typ := value.Type()
   191  
   192  	abi2struct := make(map[string]string)
   193  	struct2abi := make(map[string]string)
   194  
   195  	// first round ~~~
   196  	for i := 0; i < typ.NumField(); i++ {
   197  		structFieldName := typ.Field(i).Name
   198  
   199  		// skip private struct fields.
   200  		if structFieldName[:1] != strings.ToUpper(structFieldName[:1]) {
   201  			continue
   202  		}
   203  		// skip fields that have no abi:"" tag.
   204  		tagName, ok := typ.Field(i).Tag.Lookup("abi")
   205  		if !ok {
   206  			continue
   207  		}
   208  		// check if tag is empty.
   209  		if tagName == "" {
   210  			return nil, fmt.Errorf("struct: abi tag in '%s' is empty", structFieldName)
   211  		}
   212  		// check which argument field matches with the abi tag.
   213  		found := false
   214  		for _, arg := range argNames {
   215  			if arg == tagName {
   216  				if abi2struct[arg] != "" {
   217  					return nil, fmt.Errorf("struct: abi tag in '%s' already mapped", structFieldName)
   218  				}
   219  				// pair them
   220  				abi2struct[arg] = structFieldName
   221  				struct2abi[structFieldName] = arg
   222  				found = true
   223  			}
   224  		}
   225  		// check if this tag has been mapped.
   226  		if !found {
   227  			return nil, fmt.Errorf("struct: abi tag '%s' defined but not found in abi", tagName)
   228  		}
   229  	}
   230  
   231  	// second round ~~~
   232  	for _, argName := range argNames {
   233  		structFieldName := ToCamelCase(argName)
   234  
   235  		if structFieldName == "" {
   236  			return nil, fmt.Errorf("abi: purely underscored output cannot unpack to struct")
   237  		}
   238  
   239  		// this abi has already been paired, skip it... unless there exists another, yet unassigned
   240  		// struct field with the same field name. If so, raise an error:
   241  		//    abi: [ { "name": "value" } ]
   242  		//    struct { Value  *big.Int , Value1 *big.Int `abi:"value"`}
   243  		if abi2struct[argName] != "" {
   244  			if abi2struct[argName] != structFieldName &&
   245  				struct2abi[structFieldName] == "" &&
   246  				value.FieldByName(structFieldName).IsValid() {
   247  				return nil, fmt.Errorf("abi: multiple variables maps to the same abi field '%s'", argName)
   248  			}
   249  			continue
   250  		}
   251  
   252  		// return an error if this struct field has already been paired.
   253  		if struct2abi[structFieldName] != "" {
   254  			return nil, fmt.Errorf("abi: multiple outputs mapping to the same struct field '%s'", structFieldName)
   255  		}
   256  
   257  		if value.FieldByName(structFieldName).IsValid() {
   258  			// pair them
   259  			abi2struct[argName] = structFieldName
   260  			struct2abi[structFieldName] = argName
   261  		} else {
   262  			// not paired, but annotate as used, to detect cases like
   263  			//   abi : [ { "name": "value" }, { "name": "_value" } ]
   264  			//   struct { Value *big.Int }
   265  			struct2abi[structFieldName] = argName
   266  		}
   267  	}
   268  	return abi2struct, nil
   269  }