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