github.com/klaytn/klaytn@v1.12.1/accounts/abi/reflect.go (about)

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