github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/accounts/abi/reflect.go (about)

     1  //  Copyright 2018 The go-ethereum Authors
     2  //  Copyright 2019 The go-aigar Authors
     3  //  This file is part of the go-aigar library.
     4  //
     5  //  The go-aigar library is free software: you can redistribute it and/or modify
     6  //  it under the terms of the GNU Lesser General Public License as published by
     7  //  the Free Software Foundation, either version 3 of the License, or
     8  //  (at your option) any later version.
     9  //
    10  //  The go-aigar library is distributed in the hope that it will be useful,
    11  //  but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  //  GNU Lesser General Public License for more details.
    14  //
    15  //  You should have received a copy of the GNU Lesser General Public License
    16  //  along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package abi
    19  
    20  import (
    21  	"fmt"
    22  	"reflect"
    23  	"strings"
    24  )
    25  
    26  // indirect recursively dereferences the value until it either gets the value
    27  // or finds a big.Int
    28  func indirect(v reflect.Value) reflect.Value {
    29  	if v.Kind() == reflect.Ptr && v.Elem().Type() != derefbigT {
    30  		return indirect(v.Elem())
    31  	}
    32  	return v
    33  }
    34  
    35  // indirectInterfaceOrPtr recursively dereferences the value until value is not interface.
    36  func indirectInterfaceOrPtr(v reflect.Value) reflect.Value {
    37  	if (v.Kind() == reflect.Interface || v.Kind() == reflect.Ptr) && v.Elem().IsValid() {
    38  		return indirect(v.Elem())
    39  	}
    40  	return v
    41  }
    42  
    43  // reflectIntKind returns the reflect using the given size and
    44  // unsignedness.
    45  func reflectIntKindAndType(unsigned bool, size int) (reflect.Kind, reflect.Type) {
    46  	switch size {
    47  	case 8:
    48  		if unsigned {
    49  			return reflect.Uint8, uint8T
    50  		}
    51  		return reflect.Int8, int8T
    52  	case 16:
    53  		if unsigned {
    54  			return reflect.Uint16, uint16T
    55  		}
    56  		return reflect.Int16, int16T
    57  	case 32:
    58  		if unsigned {
    59  			return reflect.Uint32, uint32T
    60  		}
    61  		return reflect.Int32, int32T
    62  	case 64:
    63  		if unsigned {
    64  			return reflect.Uint64, uint64T
    65  		}
    66  		return reflect.Int64, int64T
    67  	}
    68  	return reflect.Ptr, bigT
    69  }
    70  
    71  // mustArrayToBytesSlice creates a new byte slice with the exact same size as value
    72  // and copies the bytes in value to the new slice.
    73  func mustArrayToByteSlice(value reflect.Value) reflect.Value {
    74  	slice := reflect.MakeSlice(reflect.TypeOf([]byte{}), value.Len(), value.Len())
    75  	reflect.Copy(slice, value)
    76  	return slice
    77  }
    78  
    79  // set attempts to assign src to dst by either setting, copying or otherwise.
    80  //
    81  // set is a bit more lenient when it comes to assignment and doesn't force an as
    82  // strict ruleset as bare `reflect` does.
    83  func set(dst, src reflect.Value) error {
    84  	dstType, srcType := dst.Type(), src.Type()
    85  	switch {
    86  	case dstType.Kind() == reflect.Interface && dst.Elem().IsValid():
    87  		return set(dst.Elem(), src)
    88  	case dstType.Kind() == reflect.Ptr && dstType.Elem() != derefbigT:
    89  		return set(dst.Elem(), src)
    90  	case srcType.AssignableTo(dstType) && dst.CanSet():
    91  		dst.Set(src)
    92  	case dstType.Kind() == reflect.Slice && srcType.Kind() == reflect.Slice:
    93  		return setSlice(dst, src)
    94  	default:
    95  		return fmt.Errorf("abi: cannot unmarshal %v in to %v", src.Type(), dst.Type())
    96  	}
    97  	return nil
    98  }
    99  
   100  // setSlice attempts to assign src to dst when slices are not assignable by default
   101  // e.g. src: [][]byte -> dst: [][15]byte
   102  func setSlice(dst, src reflect.Value) error {
   103  	slice := reflect.MakeSlice(dst.Type(), src.Len(), src.Len())
   104  	for i := 0; i < src.Len(); i++ {
   105  		v := src.Index(i)
   106  		reflect.Copy(slice.Index(i), v)
   107  	}
   108  
   109  	dst.Set(slice)
   110  	return nil
   111  }
   112  
   113  // requireAssignable assures that `dest` is a pointer and it's not an interface.
   114  func requireAssignable(dst, src reflect.Value) error {
   115  	if dst.Kind() != reflect.Ptr && dst.Kind() != reflect.Interface {
   116  		return fmt.Errorf("abi: cannot unmarshal %v into %v", src.Type(), dst.Type())
   117  	}
   118  	return nil
   119  }
   120  
   121  // requireUnpackKind verifies preconditions for unpacking `args` into `kind`
   122  func requireUnpackKind(v reflect.Value, t reflect.Type, k reflect.Kind,
   123  	args Arguments) error {
   124  
   125  	switch k {
   126  	case reflect.Struct:
   127  	case reflect.Slice, reflect.Array:
   128  		if minLen := args.LengthNonIndexed(); v.Len() < minLen {
   129  			return fmt.Errorf("abi: insufficient number of elements in the list/array for unpack, want %d, got %d",
   130  				minLen, v.Len())
   131  		}
   132  	default:
   133  		return fmt.Errorf("abi: cannot unmarshal tuple into %v", t)
   134  	}
   135  	return nil
   136  }
   137  
   138  // mapArgNamesToStructFields maps a slice of argument names to struct fields.
   139  // first round: for each Exportable field that contains a `abi:""` tag
   140  //   and this field name exists in the given argument name list, pair them together.
   141  // second round: for each argument name that has not been already linked,
   142  //   find what variable is expected to be mapped into, if it exists and has not been
   143  //   used, pair them.
   144  // Note this function assumes the given value is a struct value.
   145  func mapArgNamesToStructFields(argNames []string, value reflect.Value) (map[string]string, error) {
   146  	typ := value.Type()
   147  
   148  	abi2struct := make(map[string]string)
   149  	struct2abi := make(map[string]string)
   150  
   151  	// first round ~~~
   152  	for i := 0; i < typ.NumField(); i++ {
   153  		structFieldName := typ.Field(i).Name
   154  
   155  		// skip private struct fields.
   156  		if structFieldName[:1] != strings.ToUpper(structFieldName[:1]) {
   157  			continue
   158  		}
   159  		// skip fields that have no abi:"" tag.
   160  		var ok bool
   161  		var tagName string
   162  		if tagName, ok = typ.Field(i).Tag.Lookup("abi"); !ok {
   163  			continue
   164  		}
   165  		// check if tag is empty.
   166  		if tagName == "" {
   167  			return nil, fmt.Errorf("struct: abi tag in '%s' is empty", structFieldName)
   168  		}
   169  		// check which argument field matches with the abi tag.
   170  		found := false
   171  		for _, arg := range argNames {
   172  			if arg == tagName {
   173  				if abi2struct[arg] != "" {
   174  					return nil, fmt.Errorf("struct: abi tag in '%s' already mapped", structFieldName)
   175  				}
   176  				// pair them
   177  				abi2struct[arg] = structFieldName
   178  				struct2abi[structFieldName] = arg
   179  				found = true
   180  			}
   181  		}
   182  		// check if this tag has been mapped.
   183  		if !found {
   184  			return nil, fmt.Errorf("struct: abi tag '%s' defined but not found in abi", tagName)
   185  		}
   186  	}
   187  
   188  	// second round ~~~
   189  	for _, argName := range argNames {
   190  
   191  		structFieldName := ToCamelCase(argName)
   192  
   193  		if structFieldName == "" {
   194  			return nil, fmt.Errorf("abi: purely underscored output cannot unpack to struct")
   195  		}
   196  
   197  		// this abi has already been paired, skip it... unless there exists another, yet unassigned
   198  		// struct field with the same field name. If so, raise an error:
   199  		//    abi: [ { "name": "value" } ]
   200  		//    struct { Value  *big.Int , Value1 *big.Int `abi:"value"`}
   201  		if abi2struct[argName] != "" {
   202  			if abi2struct[argName] != structFieldName &&
   203  				struct2abi[structFieldName] == "" &&
   204  				value.FieldByName(structFieldName).IsValid() {
   205  				return nil, fmt.Errorf("abi: multiple variables maps to the same abi field '%s'", argName)
   206  			}
   207  			continue
   208  		}
   209  
   210  		// return an error if this struct field has already been paired.
   211  		if struct2abi[structFieldName] != "" {
   212  			return nil, fmt.Errorf("abi: multiple outputs mapping to the same struct field '%s'", structFieldName)
   213  		}
   214  
   215  		if value.FieldByName(structFieldName).IsValid() {
   216  			// pair them
   217  			abi2struct[argName] = structFieldName
   218  			struct2abi[structFieldName] = argName
   219  		} else {
   220  			// not paired, but annotate as used, to detect cases like
   221  			//   abi : [ { "name": "value" }, { "name": "_value" } ]
   222  			//   struct { Value *big.Int }
   223  			struct2abi[structFieldName] = argName
   224  		}
   225  	}
   226  	return abi2struct, nil
   227  }