github.com/amazechain/amc@v0.1.3/internal/avm/abi/reflect.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  	"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  // mustArrayToByteSlice 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 err := set(slice.Index(i), src.Index(i)); err != nil {
   129  			return err
   130  		}
   131  	}
   132  	if dst.CanSet() {
   133  		dst.Set(slice)
   134  		return nil
   135  	}
   136  	return errors.New("Cannot set slice, destination not settable")
   137  }
   138  
   139  func setArray(dst, src reflect.Value) error {
   140  	if src.Kind() == reflect.Ptr {
   141  		return set(dst, indirect(src))
   142  	}
   143  	array := reflect.New(dst.Type()).Elem()
   144  	min := src.Len()
   145  	if src.Len() > dst.Len() {
   146  		min = dst.Len()
   147  	}
   148  	for i := 0; i < min; i++ {
   149  		if err := set(array.Index(i), src.Index(i)); err != nil {
   150  			return err
   151  		}
   152  	}
   153  	if dst.CanSet() {
   154  		dst.Set(array)
   155  		return nil
   156  	}
   157  	return errors.New("Cannot set array, destination not settable")
   158  }
   159  
   160  func setStruct(dst, src reflect.Value) error {
   161  	for i := 0; i < src.NumField(); i++ {
   162  		srcField := src.Field(i)
   163  		dstField := dst.Field(i)
   164  		if !dstField.IsValid() || !srcField.IsValid() {
   165  			return fmt.Errorf("Could not find src field: %v value: %v in destination", srcField.Type().Name(), srcField)
   166  		}
   167  		if err := set(dstField, srcField); err != nil {
   168  			return err
   169  		}
   170  	}
   171  	return nil
   172  }
   173  
   174  // mapArgNamesToStructFields maps a slice of argument names to struct fields.
   175  // first round: for each Exportable field that contains a `abi:""` tag
   176  //
   177  //	and this field name exists in the given argument name list, pair them together.
   178  //
   179  // second round: for each argument name that has not been already linked,
   180  //
   181  //	find what variable is expected to be mapped into, if it exists and has not been
   182  //	used, pair them.
   183  //
   184  // Note this function assumes the given value is a struct value.
   185  func mapArgNamesToStructFields(argNames []string, value reflect.Value) (map[string]string, error) {
   186  	typ := value.Type()
   187  
   188  	abi2struct := make(map[string]string)
   189  	struct2abi := make(map[string]string)
   190  
   191  	// first round ~~~
   192  	for i := 0; i < typ.NumField(); i++ {
   193  		structFieldName := typ.Field(i).Name
   194  
   195  		// skip private struct fields.
   196  		if structFieldName[:1] != strings.ToUpper(structFieldName[:1]) {
   197  			continue
   198  		}
   199  		// skip fields that have no abi:"" tag.
   200  		tagName, ok := typ.Field(i).Tag.Lookup("abi")
   201  		if !ok {
   202  			continue
   203  		}
   204  		// check if tag is empty.
   205  		if tagName == "" {
   206  			return nil, fmt.Errorf("struct: abi tag in '%s' is empty", structFieldName)
   207  		}
   208  		// check which argument field matches with the abi tag.
   209  		found := false
   210  		for _, arg := range argNames {
   211  			if arg == tagName {
   212  				if abi2struct[arg] != "" {
   213  					return nil, fmt.Errorf("struct: abi tag in '%s' already mapped", structFieldName)
   214  				}
   215  				// pair them
   216  				abi2struct[arg] = structFieldName
   217  				struct2abi[structFieldName] = arg
   218  				found = true
   219  			}
   220  		}
   221  		// check if this tag has been mapped.
   222  		if !found {
   223  			return nil, fmt.Errorf("struct: abi tag '%s' defined but not found in abi", tagName)
   224  		}
   225  	}
   226  
   227  	// second round ~~~
   228  	for _, argName := range argNames {
   229  
   230  		structFieldName := ToCamelCase(argName)
   231  
   232  		if structFieldName == "" {
   233  			return nil, fmt.Errorf("abi: purely underscored output cannot unpack to struct")
   234  		}
   235  
   236  		// this abi has already been paired, skip it... unless there exists another, yet unassigned
   237  		// struct field with the same field name. If so, raise an error:
   238  		//    abi: [ { "name": "value" } ]
   239  		//    struct { Value  *big.Int , Value1 *big.Int `abi:"value"`}
   240  		if abi2struct[argName] != "" {
   241  			if abi2struct[argName] != structFieldName &&
   242  				struct2abi[structFieldName] == "" &&
   243  				value.FieldByName(structFieldName).IsValid() {
   244  				return nil, fmt.Errorf("abi: multiple variables maps to the same abi field '%s'", argName)
   245  			}
   246  			continue
   247  		}
   248  
   249  		// return an error if this struct field has already been paired.
   250  		if struct2abi[structFieldName] != "" {
   251  			return nil, fmt.Errorf("abi: multiple outputs mapping to the same struct field '%s'", structFieldName)
   252  		}
   253  
   254  		if value.FieldByName(structFieldName).IsValid() {
   255  			// pair them
   256  			abi2struct[argName] = structFieldName
   257  			struct2abi[structFieldName] = argName
   258  		} else {
   259  			// not paired, but annotate as used, to detect cases like
   260  			//   abi : [ { "name": "value" }, { "name": "_value" } ]
   261  			//   struct { Value *big.Int }
   262  			struct2abi[structFieldName] = argName
   263  		}
   264  	}
   265  	return abi2struct, nil
   266  }