github.com/nitinawathare/ethereumassignment3@v0.0.0-20211021213010-f07344c2b868/go-ethereum/accounts/abi/argument.go (about) 1 // Copyright 2015 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 "encoding/json" 21 "fmt" 22 "reflect" 23 "strings" 24 ) 25 26 // Argument holds the name of the argument and the corresponding type. 27 // Types are used when packing and testing arguments. 28 type Argument struct { 29 Name string 30 Type Type 31 Indexed bool // indexed is only used by events 32 } 33 34 type Arguments []Argument 35 36 type ArgumentMarshaling struct { 37 Name string 38 Type string 39 Components []ArgumentMarshaling 40 Indexed bool 41 } 42 43 // UnmarshalJSON implements json.Unmarshaler interface 44 func (argument *Argument) UnmarshalJSON(data []byte) error { 45 var arg ArgumentMarshaling 46 err := json.Unmarshal(data, &arg) 47 if err != nil { 48 return fmt.Errorf("argument json err: %v", err) 49 } 50 51 argument.Type, err = NewType(arg.Type, arg.Components) 52 if err != nil { 53 return err 54 } 55 argument.Name = arg.Name 56 argument.Indexed = arg.Indexed 57 58 return nil 59 } 60 61 // LengthNonIndexed returns the number of arguments when not counting 'indexed' ones. Only events 62 // can ever have 'indexed' arguments, it should always be false on arguments for method input/output 63 func (arguments Arguments) LengthNonIndexed() int { 64 out := 0 65 for _, arg := range arguments { 66 if !arg.Indexed { 67 out++ 68 } 69 } 70 return out 71 } 72 73 // NonIndexed returns the arguments with indexed arguments filtered out 74 func (arguments Arguments) NonIndexed() Arguments { 75 var ret []Argument 76 for _, arg := range arguments { 77 if !arg.Indexed { 78 ret = append(ret, arg) 79 } 80 } 81 return ret 82 } 83 84 // isTuple returns true for non-atomic constructs, like (uint,uint) or uint[] 85 func (arguments Arguments) isTuple() bool { 86 return len(arguments) > 1 87 } 88 89 // Unpack performs the operation hexdata -> Go format 90 func (arguments Arguments) Unpack(v interface{}, data []byte) error { 91 // make sure the passed value is arguments pointer 92 if reflect.Ptr != reflect.ValueOf(v).Kind() { 93 return fmt.Errorf("abi: Unpack(non-pointer %T)", v) 94 } 95 marshalledValues, err := arguments.UnpackValues(data) 96 if err != nil { 97 return err 98 } 99 if arguments.isTuple() { 100 return arguments.unpackTuple(v, marshalledValues) 101 } 102 return arguments.unpackAtomic(v, marshalledValues[0]) 103 } 104 105 // UnpackIntoMap performs the operation hexdata -> mapping of argument name to argument value 106 func (arguments Arguments) UnpackIntoMap(v map[string]interface{}, data []byte) error { 107 marshalledValues, err := arguments.UnpackValues(data) 108 if err != nil { 109 return err 110 } 111 112 return arguments.unpackIntoMap(v, marshalledValues) 113 } 114 115 // unpack sets the unmarshalled value to go format. 116 // Note the dst here must be settable. 117 func unpack(t *Type, dst interface{}, src interface{}) error { 118 var ( 119 dstVal = reflect.ValueOf(dst).Elem() 120 srcVal = reflect.ValueOf(src) 121 ) 122 123 if t.T != TupleTy && !((t.T == SliceTy || t.T == ArrayTy) && t.Elem.T == TupleTy) { 124 return set(dstVal, srcVal) 125 } 126 127 switch t.T { 128 case TupleTy: 129 if dstVal.Kind() != reflect.Struct { 130 return fmt.Errorf("abi: invalid dst value for unpack, want struct, got %s", dstVal.Kind()) 131 } 132 fieldmap, err := mapArgNamesToStructFields(t.TupleRawNames, dstVal) 133 if err != nil { 134 return err 135 } 136 for i, elem := range t.TupleElems { 137 fname := fieldmap[t.TupleRawNames[i]] 138 field := dstVal.FieldByName(fname) 139 if !field.IsValid() { 140 return fmt.Errorf("abi: field %s can't found in the given value", t.TupleRawNames[i]) 141 } 142 if err := unpack(elem, field.Addr().Interface(), srcVal.Field(i).Interface()); err != nil { 143 return err 144 } 145 } 146 return nil 147 case SliceTy: 148 if dstVal.Kind() != reflect.Slice { 149 return fmt.Errorf("abi: invalid dst value for unpack, want slice, got %s", dstVal.Kind()) 150 } 151 slice := reflect.MakeSlice(dstVal.Type(), srcVal.Len(), srcVal.Len()) 152 for i := 0; i < slice.Len(); i++ { 153 if err := unpack(t.Elem, slice.Index(i).Addr().Interface(), srcVal.Index(i).Interface()); err != nil { 154 return err 155 } 156 } 157 dstVal.Set(slice) 158 case ArrayTy: 159 if dstVal.Kind() != reflect.Array { 160 return fmt.Errorf("abi: invalid dst value for unpack, want array, got %s", dstVal.Kind()) 161 } 162 array := reflect.New(dstVal.Type()).Elem() 163 for i := 0; i < array.Len(); i++ { 164 if err := unpack(t.Elem, array.Index(i).Addr().Interface(), srcVal.Index(i).Interface()); err != nil { 165 return err 166 } 167 } 168 dstVal.Set(array) 169 } 170 return nil 171 } 172 173 // unpackIntoMap unpacks marshalledValues into the provided map[string]interface{} 174 func (arguments Arguments) unpackIntoMap(v map[string]interface{}, marshalledValues []interface{}) error { 175 // Make sure map is not nil 176 if v == nil { 177 return fmt.Errorf("abi: cannot unpack into a nil map") 178 } 179 180 for i, arg := range arguments.NonIndexed() { 181 v[arg.Name] = marshalledValues[i] 182 } 183 return nil 184 } 185 186 // unpackAtomic unpacks ( hexdata -> go ) a single value 187 func (arguments Arguments) unpackAtomic(v interface{}, marshalledValues interface{}) error { 188 if arguments.LengthNonIndexed() == 0 { 189 return nil 190 } 191 argument := arguments.NonIndexed()[0] 192 elem := reflect.ValueOf(v).Elem() 193 194 if elem.Kind() == reflect.Struct { 195 fieldmap, err := mapArgNamesToStructFields([]string{argument.Name}, elem) 196 if err != nil { 197 return err 198 } 199 field := elem.FieldByName(fieldmap[argument.Name]) 200 if !field.IsValid() { 201 return fmt.Errorf("abi: field %s can't be found in the given value", argument.Name) 202 } 203 return unpack(&argument.Type, field.Addr().Interface(), marshalledValues) 204 } 205 return unpack(&argument.Type, elem.Addr().Interface(), marshalledValues) 206 } 207 208 // unpackTuple unpacks ( hexdata -> go ) a batch of values. 209 func (arguments Arguments) unpackTuple(v interface{}, marshalledValues []interface{}) error { 210 var ( 211 value = reflect.ValueOf(v).Elem() 212 typ = value.Type() 213 kind = value.Kind() 214 ) 215 if err := requireUnpackKind(value, typ, kind, arguments); err != nil { 216 return err 217 } 218 219 // If the interface is a struct, get of abi->struct_field mapping 220 var abi2struct map[string]string 221 if kind == reflect.Struct { 222 var ( 223 argNames []string 224 err error 225 ) 226 for _, arg := range arguments.NonIndexed() { 227 argNames = append(argNames, arg.Name) 228 } 229 abi2struct, err = mapArgNamesToStructFields(argNames, value) 230 if err != nil { 231 return err 232 } 233 } 234 for i, arg := range arguments.NonIndexed() { 235 switch kind { 236 case reflect.Struct: 237 field := value.FieldByName(abi2struct[arg.Name]) 238 if !field.IsValid() { 239 return fmt.Errorf("abi: field %s can't be found in the given value", arg.Name) 240 } 241 if err := unpack(&arg.Type, field.Addr().Interface(), marshalledValues[i]); err != nil { 242 return err 243 } 244 case reflect.Slice, reflect.Array: 245 if value.Len() < i { 246 return fmt.Errorf("abi: insufficient number of arguments for unpack, want %d, got %d", len(arguments), value.Len()) 247 } 248 v := value.Index(i) 249 if err := requireAssignable(v, reflect.ValueOf(marshalledValues[i])); err != nil { 250 return err 251 } 252 if err := unpack(&arg.Type, v.Addr().Interface(), marshalledValues[i]); err != nil { 253 return err 254 } 255 default: 256 return fmt.Errorf("abi:[2] cannot unmarshal tuple in to %v", typ) 257 } 258 } 259 return nil 260 261 } 262 263 // UnpackValues can be used to unpack ABI-encoded hexdata according to the ABI-specification, 264 // without supplying a struct to unpack into. Instead, this method returns a list containing the 265 // values. An atomic argument will be a list with one element. 266 func (arguments Arguments) UnpackValues(data []byte) ([]interface{}, error) { 267 retval := make([]interface{}, 0, arguments.LengthNonIndexed()) 268 virtualArgs := 0 269 for index, arg := range arguments.NonIndexed() { 270 marshalledValue, err := toGoType((index+virtualArgs)*32, arg.Type, data) 271 if arg.Type.T == ArrayTy && !isDynamicType(arg.Type) { 272 // If we have a static array, like [3]uint256, these are coded as 273 // just like uint256,uint256,uint256. 274 // This means that we need to add two 'virtual' arguments when 275 // we count the index from now on. 276 // 277 // Array values nested multiple levels deep are also encoded inline: 278 // [2][3]uint256: uint256,uint256,uint256,uint256,uint256,uint256 279 // 280 // Calculate the full array size to get the correct offset for the next argument. 281 // Decrement it by 1, as the normal index increment is still applied. 282 virtualArgs += getTypeSize(arg.Type)/32 - 1 283 } else if arg.Type.T == TupleTy && !isDynamicType(arg.Type) { 284 // If we have a static tuple, like (uint256, bool, uint256), these are 285 // coded as just like uint256,bool,uint256 286 virtualArgs += getTypeSize(arg.Type)/32 - 1 287 } 288 if err != nil { 289 return nil, err 290 } 291 retval = append(retval, marshalledValue) 292 } 293 return retval, nil 294 } 295 296 // PackValues performs the operation Go format -> Hexdata 297 // It is the semantic opposite of UnpackValues 298 func (arguments Arguments) PackValues(args []interface{}) ([]byte, error) { 299 return arguments.Pack(args...) 300 } 301 302 // Pack performs the operation Go format -> Hexdata 303 func (arguments Arguments) Pack(args ...interface{}) ([]byte, error) { 304 // Make sure arguments match up and pack them 305 abiArgs := arguments 306 if len(args) != len(abiArgs) { 307 return nil, fmt.Errorf("argument count mismatch: %d for %d", len(args), len(abiArgs)) 308 } 309 // variable input is the output appended at the end of packed 310 // output. This is used for strings and bytes types input. 311 var variableInput []byte 312 313 // input offset is the bytes offset for packed output 314 inputOffset := 0 315 for _, abiArg := range abiArgs { 316 inputOffset += getTypeSize(abiArg.Type) 317 } 318 var ret []byte 319 for i, a := range args { 320 input := abiArgs[i] 321 // pack the input 322 packed, err := input.Type.pack(reflect.ValueOf(a)) 323 if err != nil { 324 return nil, err 325 } 326 // check for dynamic types 327 if isDynamicType(input.Type) { 328 // set the offset 329 ret = append(ret, packNum(reflect.ValueOf(inputOffset))...) 330 // calculate next offset 331 inputOffset += len(packed) 332 // append to variable input 333 variableInput = append(variableInput, packed...) 334 } else { 335 // append the packed value to the input 336 ret = append(ret, packed...) 337 } 338 } 339 // append the variable input at the end of the packed input 340 ret = append(ret, variableInput...) 341 342 return ret, nil 343 } 344 345 // ToCamelCase converts an under-score string to a camel-case string 346 func ToCamelCase(input string) string { 347 parts := strings.Split(input, "_") 348 for i, s := range parts { 349 if len(s) > 0 { 350 parts[i] = strings.ToUpper(s[:1]) + s[1:] 351 } 352 } 353 return strings.Join(parts, "") 354 }