github.com/codingfuture/orig-energi3@v0.8.4/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 // unpack sets the unmarshalled value to go format. 106 // Note the dst here must be settable. 107 func unpack(t *Type, dst interface{}, src interface{}) error { 108 var ( 109 dstVal = reflect.ValueOf(dst).Elem() 110 srcVal = reflect.ValueOf(src) 111 ) 112 113 if t.T != TupleTy && !((t.T == SliceTy || t.T == ArrayTy) && t.Elem.T == TupleTy) { 114 return set(dstVal, srcVal) 115 } 116 117 switch t.T { 118 case TupleTy: 119 if dstVal.Kind() != reflect.Struct { 120 return fmt.Errorf("abi: invalid dst value for unpack, want struct, got %s", dstVal.Kind()) 121 } 122 fieldmap, err := mapArgNamesToStructFields(t.TupleRawNames, dstVal) 123 if err != nil { 124 return err 125 } 126 for i, elem := range t.TupleElems { 127 fname := fieldmap[t.TupleRawNames[i]] 128 field := dstVal.FieldByName(fname) 129 if !field.IsValid() { 130 return fmt.Errorf("abi: field %s can't found in the given value", t.TupleRawNames[i]) 131 } 132 if err := unpack(elem, field.Addr().Interface(), srcVal.Field(i).Interface()); err != nil { 133 return err 134 } 135 } 136 return nil 137 case SliceTy: 138 if dstVal.Kind() != reflect.Slice { 139 return fmt.Errorf("abi: invalid dst value for unpack, want slice, got %s", dstVal.Kind()) 140 } 141 slice := reflect.MakeSlice(dstVal.Type(), srcVal.Len(), srcVal.Len()) 142 for i := 0; i < slice.Len(); i++ { 143 if err := unpack(t.Elem, slice.Index(i).Addr().Interface(), srcVal.Index(i).Interface()); err != nil { 144 return err 145 } 146 } 147 dstVal.Set(slice) 148 case ArrayTy: 149 if dstVal.Kind() != reflect.Array { 150 return fmt.Errorf("abi: invalid dst value for unpack, want array, got %s", dstVal.Kind()) 151 } 152 array := reflect.New(dstVal.Type()).Elem() 153 for i := 0; i < array.Len(); i++ { 154 if err := unpack(t.Elem, array.Index(i).Addr().Interface(), srcVal.Index(i).Interface()); err != nil { 155 return err 156 } 157 } 158 dstVal.Set(array) 159 } 160 return nil 161 } 162 163 // unpackAtomic unpacks ( hexdata -> go ) a single value 164 func (arguments Arguments) unpackAtomic(v interface{}, marshalledValues interface{}) error { 165 if arguments.LengthNonIndexed() == 0 { 166 return nil 167 } 168 argument := arguments.NonIndexed()[0] 169 elem := reflect.ValueOf(v).Elem() 170 171 if elem.Kind() == reflect.Struct { 172 fieldmap, err := mapArgNamesToStructFields([]string{argument.Name}, elem) 173 if err != nil { 174 return err 175 } 176 field := elem.FieldByName(fieldmap[argument.Name]) 177 if !field.IsValid() { 178 return fmt.Errorf("abi: field %s can't be found in the given value", argument.Name) 179 } 180 return unpack(&argument.Type, field.Addr().Interface(), marshalledValues) 181 } 182 return unpack(&argument.Type, elem.Addr().Interface(), marshalledValues) 183 } 184 185 // unpackTuple unpacks ( hexdata -> go ) a batch of values. 186 func (arguments Arguments) unpackTuple(v interface{}, marshalledValues []interface{}) error { 187 var ( 188 value = reflect.ValueOf(v).Elem() 189 typ = value.Type() 190 kind = value.Kind() 191 ) 192 if err := requireUnpackKind(value, typ, kind, arguments); err != nil { 193 return err 194 } 195 196 // If the interface is a struct, get of abi->struct_field mapping 197 var abi2struct map[string]string 198 if kind == reflect.Struct { 199 var ( 200 argNames []string 201 err error 202 ) 203 for _, arg := range arguments.NonIndexed() { 204 argNames = append(argNames, arg.Name) 205 } 206 abi2struct, err = mapArgNamesToStructFields(argNames, value) 207 if err != nil { 208 return err 209 } 210 } 211 for i, arg := range arguments.NonIndexed() { 212 switch kind { 213 case reflect.Struct: 214 field := value.FieldByName(abi2struct[arg.Name]) 215 if !field.IsValid() { 216 return fmt.Errorf("abi: field %s can't be found in the given value", arg.Name) 217 } 218 if err := unpack(&arg.Type, field.Addr().Interface(), marshalledValues[i]); err != nil { 219 return err 220 } 221 case reflect.Slice, reflect.Array: 222 if value.Len() < i { 223 return fmt.Errorf("abi: insufficient number of arguments for unpack, want %d, got %d", len(arguments), value.Len()) 224 } 225 v := value.Index(i) 226 if err := requireAssignable(v, reflect.ValueOf(marshalledValues[i])); err != nil { 227 return err 228 } 229 if err := unpack(&arg.Type, v.Addr().Interface(), marshalledValues[i]); err != nil { 230 return err 231 } 232 default: 233 return fmt.Errorf("abi:[2] cannot unmarshal tuple in to %v", typ) 234 } 235 } 236 return nil 237 238 } 239 240 // UnpackValues can be used to unpack ABI-encoded hexdata according to the ABI-specification, 241 // without supplying a struct to unpack into. Instead, this method returns a list containing the 242 // values. An atomic argument will be a list with one element. 243 func (arguments Arguments) UnpackValues(data []byte) ([]interface{}, error) { 244 retval := make([]interface{}, 0, arguments.LengthNonIndexed()) 245 virtualArgs := 0 246 for index, arg := range arguments.NonIndexed() { 247 marshalledValue, err := toGoType((index+virtualArgs)*32, arg.Type, data) 248 if arg.Type.T == ArrayTy && !isDynamicType(arg.Type) { 249 // If we have a static array, like [3]uint256, these are coded as 250 // just like uint256,uint256,uint256. 251 // This means that we need to add two 'virtual' arguments when 252 // we count the index from now on. 253 // 254 // Array values nested multiple levels deep are also encoded inline: 255 // [2][3]uint256: uint256,uint256,uint256,uint256,uint256,uint256 256 // 257 // Calculate the full array size to get the correct offset for the next argument. 258 // Decrement it by 1, as the normal index increment is still applied. 259 virtualArgs += getTypeSize(arg.Type)/32 - 1 260 } else if arg.Type.T == TupleTy && !isDynamicType(arg.Type) { 261 // If we have a static tuple, like (uint256, bool, uint256), these are 262 // coded as just like uint256,bool,uint256 263 virtualArgs += getTypeSize(arg.Type)/32 - 1 264 } 265 if err != nil { 266 return nil, err 267 } 268 retval = append(retval, marshalledValue) 269 } 270 return retval, nil 271 } 272 273 // PackValues performs the operation Go format -> Hexdata 274 // It is the semantic opposite of UnpackValues 275 func (arguments Arguments) PackValues(args []interface{}) ([]byte, error) { 276 return arguments.Pack(args...) 277 } 278 279 // Pack performs the operation Go format -> Hexdata 280 func (arguments Arguments) Pack(args ...interface{}) ([]byte, error) { 281 // Make sure arguments match up and pack them 282 abiArgs := arguments 283 if len(args) != len(abiArgs) { 284 return nil, fmt.Errorf("argument count mismatch: %d for %d", len(args), len(abiArgs)) 285 } 286 // variable input is the output appended at the end of packed 287 // output. This is used for strings and bytes types input. 288 var variableInput []byte 289 290 // input offset is the bytes offset for packed output 291 inputOffset := 0 292 for _, abiArg := range abiArgs { 293 inputOffset += getTypeSize(abiArg.Type) 294 } 295 var ret []byte 296 for i, a := range args { 297 input := abiArgs[i] 298 // pack the input 299 packed, err := input.Type.pack(reflect.ValueOf(a)) 300 if err != nil { 301 return nil, err 302 } 303 // check for dynamic types 304 if isDynamicType(input.Type) { 305 // set the offset 306 ret = append(ret, packNum(reflect.ValueOf(inputOffset))...) 307 // calculate next offset 308 inputOffset += len(packed) 309 // append to variable input 310 variableInput = append(variableInput, packed...) 311 } else { 312 // append the packed value to the input 313 ret = append(ret, packed...) 314 } 315 } 316 // append the variable input at the end of the packed input 317 ret = append(ret, variableInput...) 318 319 return ret, nil 320 } 321 322 // ToCamelCase converts an under-score string to a camel-case string 323 func ToCamelCase(input string) string { 324 parts := strings.Split(input, "_") 325 for i, s := range parts { 326 if len(s) > 0 { 327 parts[i] = strings.ToUpper(s[:1]) + s[1:] 328 } 329 } 330 return strings.Join(parts, "") 331 }