github.com/CommerciumBlockchain/go-commercium@v0.0.0-20220709212705-b46438a77516/accounts/abi/argument.go (about) 1 // Copyright 2022 Commercium 2 // Copyright 2015 The go-ethereum Authors 3 // This file is part of the go-ethereum library. 4 // 5 // The go-ethereum library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-ethereum library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 17 18 package abi 19 20 import ( 21 "encoding/json" 22 "fmt" 23 "reflect" 24 "strings" 25 ) 26 27 // Argument holds the name of the argument and the corresponding type. 28 // Types are used when packing and testing arguments. 29 type Argument struct { 30 Name string 31 Type Type 32 Indexed bool // indexed is only used by events 33 } 34 35 type Arguments []Argument 36 37 type ArgumentMarshaling struct { 38 Name string 39 Type string 40 InternalType string 41 Components []ArgumentMarshaling 42 Indexed bool 43 } 44 45 // UnmarshalJSON implements json.Unmarshaler interface. 46 func (argument *Argument) UnmarshalJSON(data []byte) error { 47 var arg ArgumentMarshaling 48 err := json.Unmarshal(data, &arg) 49 if err != nil { 50 return fmt.Errorf("argument json err: %v", err) 51 } 52 53 argument.Type, err = NewType(arg.Type, arg.InternalType, arg.Components) 54 if err != nil { 55 return err 56 } 57 argument.Name = arg.Name 58 argument.Indexed = arg.Indexed 59 60 return nil 61 } 62 63 // NonIndexed returns the arguments with indexed arguments filtered out. 64 func (arguments Arguments) NonIndexed() Arguments { 65 var ret []Argument 66 for _, arg := range arguments { 67 if !arg.Indexed { 68 ret = append(ret, arg) 69 } 70 } 71 return ret 72 } 73 74 // isTuple returns true for non-atomic constructs, like (uint,uint) or uint[]. 75 func (arguments Arguments) isTuple() bool { 76 return len(arguments) > 1 77 } 78 79 // Unpack performs the operation hexdata -> Go format. 80 func (arguments Arguments) Unpack(data []byte) ([]interface{}, error) { 81 if len(data) == 0 { 82 if len(arguments) != 0 { 83 return nil, fmt.Errorf("abi: attempting to unmarshall an empty string while arguments are expected") 84 } 85 // Nothing to unmarshal, return default variables 86 nonIndexedArgs := arguments.NonIndexed() 87 defaultVars := make([]interface{}, len(nonIndexedArgs)) 88 for index, arg := range nonIndexedArgs { 89 defaultVars[index] = reflect.New(arg.Type.GetType()) 90 } 91 return defaultVars, nil 92 } 93 return arguments.UnpackValues(data) 94 } 95 96 // UnpackIntoMap performs the operation hexdata -> mapping of argument name to argument value. 97 func (arguments Arguments) UnpackIntoMap(v map[string]interface{}, data []byte) error { 98 // Make sure map is not nil 99 if v == nil { 100 return fmt.Errorf("abi: cannot unpack into a nil map") 101 } 102 if len(data) == 0 { 103 if len(arguments) != 0 { 104 return fmt.Errorf("abi: attempting to unmarshall an empty string while arguments are expected") 105 } 106 return nil // Nothing to unmarshal, return 107 } 108 marshalledValues, err := arguments.UnpackValues(data) 109 if err != nil { 110 return err 111 } 112 for i, arg := range arguments.NonIndexed() { 113 v[arg.Name] = marshalledValues[i] 114 } 115 return nil 116 } 117 118 // Copy performs the operation go format -> provided struct. 119 func (arguments Arguments) Copy(v interface{}, values []interface{}) error { 120 // make sure the passed value is arguments pointer 121 if reflect.Ptr != reflect.ValueOf(v).Kind() { 122 return fmt.Errorf("abi: Unpack(non-pointer %T)", v) 123 } 124 if len(values) == 0 { 125 if len(arguments) != 0 { 126 return fmt.Errorf("abi: attempting to copy no values while %d arguments are expected", len(arguments)) 127 } 128 return nil // Nothing to copy, return 129 } 130 if arguments.isTuple() { 131 return arguments.copyTuple(v, values) 132 } 133 return arguments.copyAtomic(v, values[0]) 134 } 135 136 // unpackAtomic unpacks ( hexdata -> go ) a single value 137 func (arguments Arguments) copyAtomic(v interface{}, marshalledValues interface{}) error { 138 dst := reflect.ValueOf(v).Elem() 139 src := reflect.ValueOf(marshalledValues) 140 141 if dst.Kind() == reflect.Struct && src.Kind() != reflect.Struct { 142 return set(dst.Field(0), src) 143 } 144 return set(dst, src) 145 } 146 147 // copyTuple copies a batch of values from marshalledValues to v. 148 func (arguments Arguments) copyTuple(v interface{}, marshalledValues []interface{}) error { 149 value := reflect.ValueOf(v).Elem() 150 nonIndexedArgs := arguments.NonIndexed() 151 152 switch value.Kind() { 153 case reflect.Struct: 154 argNames := make([]string, len(nonIndexedArgs)) 155 for i, arg := range nonIndexedArgs { 156 argNames[i] = arg.Name 157 } 158 var err error 159 abi2struct, err := mapArgNamesToStructFields(argNames, value) 160 if err != nil { 161 return err 162 } 163 for i, arg := range nonIndexedArgs { 164 field := value.FieldByName(abi2struct[arg.Name]) 165 if !field.IsValid() { 166 return fmt.Errorf("abi: field %s can't be found in the given value", arg.Name) 167 } 168 if err := set(field, reflect.ValueOf(marshalledValues[i])); err != nil { 169 return err 170 } 171 } 172 case reflect.Slice, reflect.Array: 173 if value.Len() < len(marshalledValues) { 174 return fmt.Errorf("abi: insufficient number of arguments for unpack, want %d, got %d", len(arguments), value.Len()) 175 } 176 for i := range nonIndexedArgs { 177 if err := set(value.Index(i), reflect.ValueOf(marshalledValues[i])); err != nil { 178 return err 179 } 180 } 181 default: 182 return fmt.Errorf("abi:[2] cannot unmarshal tuple in to %v", value.Type()) 183 } 184 return nil 185 } 186 187 // UnpackValues can be used to unpack ABI-encoded hexdata according to the ABI-specification, 188 // without supplying a struct to unpack into. Instead, this method returns a list containing the 189 // values. An atomic argument will be a list with one element. 190 func (arguments Arguments) UnpackValues(data []byte) ([]interface{}, error) { 191 nonIndexedArgs := arguments.NonIndexed() 192 retval := make([]interface{}, 0, len(nonIndexedArgs)) 193 virtualArgs := 0 194 for index, arg := range nonIndexedArgs { 195 marshalledValue, err := toGoType((index+virtualArgs)*32, arg.Type, data) 196 if arg.Type.T == ArrayTy && !isDynamicType(arg.Type) { 197 // If we have a static array, like [3]uint256, these are coded as 198 // just like uint256,uint256,uint256. 199 // This means that we need to add two 'virtual' arguments when 200 // we count the index from now on. 201 // 202 // Array values nested multiple levels deep are also encoded inline: 203 // [2][3]uint256: uint256,uint256,uint256,uint256,uint256,uint256 204 // 205 // Calculate the full array size to get the correct offset for the next argument. 206 // Decrement it by 1, as the normal index increment is still applied. 207 virtualArgs += getTypeSize(arg.Type)/32 - 1 208 } else if arg.Type.T == TupleTy && !isDynamicType(arg.Type) { 209 // If we have a static tuple, like (uint256, bool, uint256), these are 210 // coded as just like uint256,bool,uint256 211 virtualArgs += getTypeSize(arg.Type)/32 - 1 212 } 213 if err != nil { 214 return nil, err 215 } 216 retval = append(retval, marshalledValue) 217 } 218 return retval, nil 219 } 220 221 // PackValues performs the operation Go format -> Hexdata. 222 // It is the semantic opposite of UnpackValues. 223 func (arguments Arguments) PackValues(args []interface{}) ([]byte, error) { 224 return arguments.Pack(args...) 225 } 226 227 // Pack performs the operation Go format -> Hexdata. 228 func (arguments Arguments) Pack(args ...interface{}) ([]byte, error) { 229 // Make sure arguments match up and pack them 230 abiArgs := arguments 231 if len(args) != len(abiArgs) { 232 return nil, fmt.Errorf("argument count mismatch: got %d for %d", len(args), len(abiArgs)) 233 } 234 // variable input is the output appended at the end of packed 235 // output. This is used for strings and bytes types input. 236 var variableInput []byte 237 238 // input offset is the bytes offset for packed output 239 inputOffset := 0 240 for _, abiArg := range abiArgs { 241 inputOffset += getTypeSize(abiArg.Type) 242 } 243 var ret []byte 244 for i, a := range args { 245 input := abiArgs[i] 246 // pack the input 247 packed, err := input.Type.pack(reflect.ValueOf(a)) 248 if err != nil { 249 return nil, err 250 } 251 // check for dynamic types 252 if isDynamicType(input.Type) { 253 // set the offset 254 ret = append(ret, packNum(reflect.ValueOf(inputOffset))...) 255 // calculate next offset 256 inputOffset += len(packed) 257 // append to variable input 258 variableInput = append(variableInput, packed...) 259 } else { 260 // append the packed value to the input 261 ret = append(ret, packed...) 262 } 263 } 264 // append the variable input at the end of the packed input 265 ret = append(ret, variableInput...) 266 267 return ret, nil 268 } 269 270 // ToCamelCase converts an under-score string to a camel-case string 271 func ToCamelCase(input string) string { 272 parts := strings.Split(input, "_") 273 for i, s := range parts { 274 if len(s) > 0 { 275 parts[i] = strings.ToUpper(s[:1]) + s[1:] 276 } 277 } 278 return strings.Join(parts, "") 279 }