github.com/ava-labs/subnet-evm@v0.6.4/accounts/abi/argument.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 2015 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 "encoding/json" 31 "errors" 32 "fmt" 33 "reflect" 34 "strings" 35 ) 36 37 // Argument holds the name of the argument and the corresponding type. 38 // Types are used when packing and testing arguments. 39 type Argument struct { 40 Name string 41 Type Type 42 Indexed bool // indexed is only used by events 43 } 44 45 type Arguments []Argument 46 47 type ArgumentMarshaling struct { 48 Name string 49 Type string 50 InternalType string 51 Components []ArgumentMarshaling 52 Indexed bool 53 } 54 55 // UnmarshalJSON implements json.Unmarshaler interface. 56 func (argument *Argument) UnmarshalJSON(data []byte) error { 57 var arg ArgumentMarshaling 58 err := json.Unmarshal(data, &arg) 59 if err != nil { 60 return fmt.Errorf("argument json err: %v", err) 61 } 62 63 argument.Type, err = NewType(arg.Type, arg.InternalType, arg.Components) 64 if err != nil { 65 return err 66 } 67 argument.Name = arg.Name 68 argument.Indexed = arg.Indexed 69 70 return nil 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(data []byte) ([]interface{}, error) { 91 if len(data) == 0 { 92 if len(arguments.NonIndexed()) != 0 { 93 return nil, errors.New("abi: attempting to unmarshall an empty string while arguments are expected") 94 } 95 return make([]interface{}, 0), nil 96 } 97 return arguments.UnpackValues(data) 98 } 99 100 // UnpackIntoMap performs the operation hexdata -> mapping of argument name to argument value. 101 func (arguments Arguments) UnpackIntoMap(v map[string]interface{}, data []byte) error { 102 // Make sure map is not nil 103 if v == nil { 104 return errors.New("abi: cannot unpack into a nil map") 105 } 106 if len(data) == 0 { 107 if len(arguments.NonIndexed()) != 0 { 108 return errors.New("abi: attempting to unmarshall an empty string while arguments are expected") 109 } 110 return nil // Nothing to unmarshal, return 111 } 112 marshalledValues, err := arguments.UnpackValues(data) 113 if err != nil { 114 return err 115 } 116 for i, arg := range arguments.NonIndexed() { 117 v[arg.Name] = marshalledValues[i] 118 } 119 return nil 120 } 121 122 // Copy performs the operation go format -> provided struct. 123 func (arguments Arguments) Copy(v interface{}, values []interface{}) error { 124 // make sure the passed value is arguments pointer 125 if reflect.Ptr != reflect.ValueOf(v).Kind() { 126 return fmt.Errorf("abi: Unpack(non-pointer %T)", v) 127 } 128 if len(values) == 0 { 129 if len(arguments.NonIndexed()) != 0 { 130 return errors.New("abi: attempting to copy no values while arguments are expected") 131 } 132 return nil // Nothing to copy, return 133 } 134 if arguments.isTuple() { 135 return arguments.copyTuple(v, values) 136 } 137 return arguments.copyAtomic(v, values[0]) 138 } 139 140 // unpackAtomic unpacks ( hexdata -> go ) a single value 141 func (arguments Arguments) copyAtomic(v interface{}, marshalledValues interface{}) error { 142 dst := reflect.ValueOf(v).Elem() 143 src := reflect.ValueOf(marshalledValues) 144 145 if dst.Kind() == reflect.Struct { 146 return set(dst.Field(0), src) 147 } 148 return set(dst, src) 149 } 150 151 // copyTuple copies a batch of values from marshalledValues to v. 152 func (arguments Arguments) copyTuple(v interface{}, marshalledValues []interface{}) error { 153 value := reflect.ValueOf(v).Elem() 154 nonIndexedArgs := arguments.NonIndexed() 155 156 switch value.Kind() { 157 case reflect.Struct: 158 argNames := make([]string, len(nonIndexedArgs)) 159 for i, arg := range nonIndexedArgs { 160 argNames[i] = arg.Name 161 } 162 var err error 163 abi2struct, err := mapArgNamesToStructFields(argNames, value) 164 if err != nil { 165 return err 166 } 167 for i, arg := range nonIndexedArgs { 168 field := value.FieldByName(abi2struct[arg.Name]) 169 if !field.IsValid() { 170 return fmt.Errorf("abi: field %s can't be found in the given value", arg.Name) 171 } 172 if err := set(field, reflect.ValueOf(marshalledValues[i])); err != nil { 173 return err 174 } 175 } 176 case reflect.Slice, reflect.Array: 177 if value.Len() < len(marshalledValues) { 178 return fmt.Errorf("abi: insufficient number of arguments for unpack, want %d, got %d", len(arguments), value.Len()) 179 } 180 for i := range nonIndexedArgs { 181 if err := set(value.Index(i), reflect.ValueOf(marshalledValues[i])); err != nil { 182 return err 183 } 184 } 185 default: 186 return fmt.Errorf("abi:[2] cannot unmarshal tuple in to %v", value.Type()) 187 } 188 return nil 189 } 190 191 // UnpackValues can be used to unpack ABI-encoded hexdata according to the ABI-specification, 192 // without supplying a struct to unpack into. Instead, this method returns a list containing the 193 // values. An atomic argument will be a list with one element. 194 func (arguments Arguments) UnpackValues(data []byte) ([]interface{}, error) { 195 nonIndexedArgs := arguments.NonIndexed() 196 retval := make([]interface{}, 0, len(nonIndexedArgs)) 197 virtualArgs := 0 198 for index, arg := range nonIndexedArgs { 199 marshalledValue, err := toGoType((index+virtualArgs)*32, arg.Type, data) 200 if err != nil { 201 return nil, err 202 } 203 if arg.Type.T == ArrayTy && !isDynamicType(arg.Type) { 204 // If we have a static array, like [3]uint256, these are coded as 205 // just like uint256,uint256,uint256. 206 // This means that we need to add two 'virtual' arguments when 207 // we count the index from now on. 208 // 209 // Array values nested multiple levels deep are also encoded inline: 210 // [2][3]uint256: uint256,uint256,uint256,uint256,uint256,uint256 211 // 212 // Calculate the full array size to get the correct offset for the next argument. 213 // Decrement it by 1, as the normal index increment is still applied. 214 virtualArgs += getTypeSize(arg.Type)/32 - 1 215 } else if arg.Type.T == TupleTy && !isDynamicType(arg.Type) { 216 // If we have a static tuple, like (uint256, bool, uint256), these are 217 // coded as just like uint256,bool,uint256 218 virtualArgs += getTypeSize(arg.Type)/32 - 1 219 } 220 retval = append(retval, marshalledValue) 221 } 222 return retval, nil 223 } 224 225 // PackValues performs the operation Go format -> Hexdata. 226 // It is the semantic opposite of UnpackValues. 227 func (arguments Arguments) PackValues(args []interface{}) ([]byte, error) { 228 return arguments.Pack(args...) 229 } 230 231 // Pack performs the operation Go format -> Hexdata. 232 func (arguments Arguments) Pack(args ...interface{}) ([]byte, error) { 233 // Make sure arguments match up and pack them 234 abiArgs := arguments 235 if len(args) != len(abiArgs) { 236 return nil, fmt.Errorf("argument count mismatch: got %d for %d", len(args), len(abiArgs)) 237 } 238 // variable input is the output appended at the end of packed 239 // output. This is used for strings and bytes types input. 240 var variableInput []byte 241 242 // input offset is the bytes offset for packed output 243 inputOffset := 0 244 for _, abiArg := range abiArgs { 245 inputOffset += getTypeSize(abiArg.Type) 246 } 247 var ret []byte 248 for i, a := range args { 249 input := abiArgs[i] 250 // pack the input 251 packed, err := input.Type.pack(reflect.ValueOf(a)) 252 if err != nil { 253 return nil, err 254 } 255 // check for dynamic types 256 if isDynamicType(input.Type) { 257 // set the offset 258 ret = append(ret, packNum(reflect.ValueOf(inputOffset))...) 259 // calculate next offset 260 inputOffset += len(packed) 261 // append to variable input 262 variableInput = append(variableInput, packed...) 263 } else { 264 // append the packed value to the input 265 ret = append(ret, packed...) 266 } 267 } 268 // append the variable input at the end of the packed input 269 ret = append(ret, variableInput...) 270 271 return ret, nil 272 } 273 274 // ToCamelCase converts an under-score string to a camel-case string 275 func ToCamelCase(input string) string { 276 parts := strings.Split(input, "_") 277 for i, s := range parts { 278 if len(s) > 0 { 279 parts[i] = strings.ToUpper(s[:1]) + s[1:] 280 } 281 } 282 return strings.Join(parts, "") 283 }