github.com/cgcardona/r-subnet-evm@v0.1.5/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 // 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 // type TupleT struct { X *big.Int } 50 func ConvertType(in interface{}, proto interface{}) interface{} { 51 protoType := reflect.TypeOf(proto) 52 if reflect.TypeOf(in).ConvertibleTo(protoType) { 53 return reflect.ValueOf(in).Convert(protoType).Interface() 54 } 55 // Use set as a last ditch effort 56 if err := set(reflect.ValueOf(proto), reflect.ValueOf(in)); err != nil { 57 panic(err) 58 } 59 return proto 60 } 61 62 // indirect recursively dereferences the value until it either gets the value 63 // or finds a big.Int 64 func indirect(v reflect.Value) reflect.Value { 65 if v.Kind() == reflect.Ptr && v.Elem().Type() != reflect.TypeOf(big.Int{}) { 66 return indirect(v.Elem()) 67 } 68 return v 69 } 70 71 // reflectIntType returns the reflect using the given size and 72 // unsignedness. 73 func reflectIntType(unsigned bool, size int) reflect.Type { 74 if unsigned { 75 switch size { 76 case 8: 77 return reflect.TypeOf(uint8(0)) 78 case 16: 79 return reflect.TypeOf(uint16(0)) 80 case 32: 81 return reflect.TypeOf(uint32(0)) 82 case 64: 83 return reflect.TypeOf(uint64(0)) 84 } 85 } 86 switch size { 87 case 8: 88 return reflect.TypeOf(int8(0)) 89 case 16: 90 return reflect.TypeOf(int16(0)) 91 case 32: 92 return reflect.TypeOf(int32(0)) 93 case 64: 94 return reflect.TypeOf(int64(0)) 95 } 96 return reflect.TypeOf(&big.Int{}) 97 } 98 99 // mustArrayToByteSlice creates a new byte slice with the exact same size as value 100 // and copies the bytes in value to the new slice. 101 func mustArrayToByteSlice(value reflect.Value) reflect.Value { 102 slice := reflect.MakeSlice(reflect.TypeOf([]byte{}), value.Len(), value.Len()) 103 reflect.Copy(slice, value) 104 return slice 105 } 106 107 // set attempts to assign src to dst by either setting, copying or otherwise. 108 // 109 // set is a bit more lenient when it comes to assignment and doesn't force an as 110 // strict ruleset as bare `reflect` does. 111 func set(dst, src reflect.Value) error { 112 dstType, srcType := dst.Type(), src.Type() 113 switch { 114 case dstType.Kind() == reflect.Interface && dst.Elem().IsValid() && (dst.Elem().Type().Kind() == reflect.Ptr || dst.Elem().CanSet()): 115 return set(dst.Elem(), src) 116 case dstType.Kind() == reflect.Ptr && dstType.Elem() != reflect.TypeOf(big.Int{}): 117 return set(dst.Elem(), src) 118 case srcType.AssignableTo(dstType) && dst.CanSet(): 119 dst.Set(src) 120 case dstType.Kind() == reflect.Slice && srcType.Kind() == reflect.Slice && dst.CanSet(): 121 return setSlice(dst, src) 122 case dstType.Kind() == reflect.Array: 123 return setArray(dst, src) 124 case dstType.Kind() == reflect.Struct: 125 return setStruct(dst, src) 126 default: 127 return fmt.Errorf("abi: cannot unmarshal %v in to %v", src.Type(), dst.Type()) 128 } 129 return nil 130 } 131 132 // setSlice attempts to assign src to dst when slices are not assignable by default 133 // e.g. src: [][]byte -> dst: [][15]byte 134 // setSlice ignores if we cannot copy all of src' elements. 135 func setSlice(dst, src reflect.Value) error { 136 slice := reflect.MakeSlice(dst.Type(), src.Len(), src.Len()) 137 for i := 0; i < src.Len(); i++ { 138 if err := set(slice.Index(i), src.Index(i)); err != nil { 139 return err 140 } 141 } 142 if dst.CanSet() { 143 dst.Set(slice) 144 return nil 145 } 146 return errors.New("Cannot set slice, destination not settable") 147 } 148 149 func setArray(dst, src reflect.Value) error { 150 if src.Kind() == reflect.Ptr { 151 return set(dst, indirect(src)) 152 } 153 array := reflect.New(dst.Type()).Elem() 154 min := src.Len() 155 if src.Len() > dst.Len() { 156 min = dst.Len() 157 } 158 for i := 0; i < min; i++ { 159 if err := set(array.Index(i), src.Index(i)); err != nil { 160 return err 161 } 162 } 163 if dst.CanSet() { 164 dst.Set(array) 165 return nil 166 } 167 return errors.New("Cannot set array, destination not settable") 168 } 169 170 func setStruct(dst, src reflect.Value) error { 171 for i := 0; i < src.NumField(); i++ { 172 srcField := src.Field(i) 173 dstField := dst.Field(i) 174 if !dstField.IsValid() || !srcField.IsValid() { 175 return fmt.Errorf("Could not find src field: %v value: %v in destination", srcField.Type().Name(), srcField) 176 } 177 if err := set(dstField, srcField); err != nil { 178 return err 179 } 180 } 181 return nil 182 } 183 184 // mapArgNamesToStructFields maps a slice of argument names to struct fields. 185 // first round: for each Exportable field that contains a `abi:""` tag 186 // and this field name exists in the given argument name list, pair them together. 187 // second round: for each argument name that has not been already linked, 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 structFieldName := ToCamelCase(argName) 237 238 if structFieldName == "" { 239 return nil, fmt.Errorf("abi: purely underscored output cannot unpack to struct") 240 } 241 242 // this abi has already been paired, skip it... unless there exists another, yet unassigned 243 // struct field with the same field name. If so, raise an error: 244 // abi: [ { "name": "value" } ] 245 // struct { Value *big.Int , Value1 *big.Int `abi:"value"`} 246 if abi2struct[argName] != "" { 247 if abi2struct[argName] != structFieldName && 248 struct2abi[structFieldName] == "" && 249 value.FieldByName(structFieldName).IsValid() { 250 return nil, fmt.Errorf("abi: multiple variables maps to the same abi field '%s'", argName) 251 } 252 continue 253 } 254 255 // return an error if this struct field has already been paired. 256 if struct2abi[structFieldName] != "" { 257 return nil, fmt.Errorf("abi: multiple outputs mapping to the same struct field '%s'", structFieldName) 258 } 259 260 if value.FieldByName(structFieldName).IsValid() { 261 // pair them 262 abi2struct[argName] = structFieldName 263 struct2abi[structFieldName] = argName 264 } else { 265 // not paired, but annotate as used, to detect cases like 266 // abi : [ { "name": "value" }, { "name": "_value" } ] 267 // struct { Value *big.Int } 268 struct2abi[structFieldName] = argName 269 } 270 } 271 return abi2struct, nil 272 }