github.com/ethereum/go-ethereum@v1.16.1/accounts/abi/type.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 "errors" 21 "fmt" 22 "reflect" 23 "regexp" 24 "strconv" 25 "strings" 26 "unicode" 27 "unicode/utf8" 28 29 "github.com/ethereum/go-ethereum/common" 30 ) 31 32 // Type enumerator 33 const ( 34 IntTy byte = iota 35 UintTy 36 BoolTy 37 StringTy 38 SliceTy 39 ArrayTy 40 TupleTy 41 AddressTy 42 FixedBytesTy 43 BytesTy 44 HashTy 45 FixedPointTy 46 FunctionTy 47 ) 48 49 // Type is the reflection of the supported argument type. 50 type Type struct { 51 Elem *Type 52 Size int 53 T byte // Our own type checking 54 55 stringKind string // holds the unparsed string for deriving signatures 56 57 // Tuple relative fields 58 TupleRawName string // Raw struct name defined in source code, may be empty. 59 TupleElems []*Type // Type information of all tuple fields 60 TupleRawNames []string // Raw field name of all tuple fields 61 TupleType reflect.Type // Underlying struct of the tuple 62 } 63 64 var ( 65 // typeRegex parses the abi sub types 66 typeRegex = regexp.MustCompile("([a-zA-Z]+)(([0-9]+)(x([0-9]+))?)?") 67 68 // sliceSizeRegex grab the slice size 69 sliceSizeRegex = regexp.MustCompile("[0-9]+") 70 ) 71 72 // NewType creates a new reflection type of abi type given in t. 73 func NewType(t string, internalType string, components []ArgumentMarshaling) (typ Type, err error) { 74 // check that array brackets are equal if they exist 75 if strings.Count(t, "[") != strings.Count(t, "]") { 76 return Type{}, errors.New("invalid arg type in abi") 77 } 78 typ.stringKind = t 79 80 // if there are brackets, get ready to go into slice/array mode and 81 // recursively create the type 82 if strings.Count(t, "[") != 0 { 83 // Note internalType can be empty here. 84 subInternal := internalType 85 if i := strings.LastIndex(internalType, "["); i != -1 { 86 subInternal = subInternal[:i] 87 } 88 // recursively embed the type 89 i := strings.LastIndex(t, "[") 90 embeddedType, err := NewType(t[:i], subInternal, components) 91 if err != nil { 92 return Type{}, err 93 } 94 // grab the last cell and create a type from there 95 sliced := t[i:] 96 // grab the slice size with regexp 97 intz := sliceSizeRegex.FindAllString(sliced, -1) 98 99 if len(intz) == 0 { 100 // is a slice 101 typ.T = SliceTy 102 typ.Elem = &embeddedType 103 typ.stringKind = embeddedType.stringKind + sliced 104 } else if len(intz) == 1 { 105 // is an array 106 typ.T = ArrayTy 107 typ.Elem = &embeddedType 108 typ.Size, err = strconv.Atoi(intz[0]) 109 if err != nil { 110 return Type{}, fmt.Errorf("abi: error parsing variable size: %v", err) 111 } 112 typ.stringKind = embeddedType.stringKind + sliced 113 } else { 114 return Type{}, errors.New("invalid formatting of array type") 115 } 116 return typ, err 117 } 118 // parse the type and size of the abi-type. 119 matches := typeRegex.FindAllStringSubmatch(t, -1) 120 if len(matches) == 0 { 121 return Type{}, fmt.Errorf("invalid type '%v'", t) 122 } 123 parsedType := matches[0] 124 125 // varSize is the size of the variable 126 var varSize int 127 if len(parsedType[3]) > 0 { 128 var err error 129 varSize, err = strconv.Atoi(parsedType[2]) 130 if err != nil { 131 return Type{}, fmt.Errorf("abi: error parsing variable size: %v", err) 132 } 133 } else { 134 if parsedType[0] == "uint" || parsedType[0] == "int" { 135 // this should fail because it means that there's something wrong with 136 // the abi type (the compiler should always format it to the size...always) 137 return Type{}, fmt.Errorf("unsupported arg type: %s", t) 138 } 139 } 140 // varType is the parsed abi type 141 switch varType := parsedType[1]; varType { 142 case "int": 143 typ.Size = varSize 144 typ.T = IntTy 145 case "uint": 146 typ.Size = varSize 147 typ.T = UintTy 148 case "bool": 149 typ.T = BoolTy 150 case "address": 151 typ.Size = 20 152 typ.T = AddressTy 153 case "string": 154 typ.T = StringTy 155 case "bytes": 156 if varSize == 0 { 157 typ.T = BytesTy 158 } else { 159 if varSize > 32 { 160 return Type{}, fmt.Errorf("unsupported arg type: %s", t) 161 } 162 typ.T = FixedBytesTy 163 typ.Size = varSize 164 } 165 case "tuple": 166 var ( 167 fields []reflect.StructField 168 elems []*Type 169 names []string 170 expression string // canonical parameter expression 171 used = make(map[string]bool) 172 ) 173 expression += "(" 174 for idx, c := range components { 175 cType, err := NewType(c.Type, c.InternalType, c.Components) 176 if err != nil { 177 return Type{}, err 178 } 179 name := ToCamelCase(c.Name) 180 if name == "" { 181 return Type{}, errors.New("abi: purely anonymous or underscored field is not supported") 182 } 183 fieldName := ResolveNameConflict(name, func(s string) bool { return used[s] }) 184 used[fieldName] = true 185 if !isValidFieldName(fieldName) { 186 return Type{}, fmt.Errorf("field %d has invalid name", idx) 187 } 188 fields = append(fields, reflect.StructField{ 189 Name: fieldName, // reflect.StructOf will panic for any exported field. 190 Type: cType.GetType(), 191 Tag: reflect.StructTag("json:\"" + c.Name + "\""), 192 }) 193 elems = append(elems, &cType) 194 names = append(names, c.Name) 195 expression += cType.stringKind 196 if idx != len(components)-1 { 197 expression += "," 198 } 199 } 200 expression += ")" 201 202 typ.TupleType = reflect.StructOf(fields) 203 typ.TupleElems = elems 204 typ.TupleRawNames = names 205 typ.T = TupleTy 206 typ.stringKind = expression 207 208 const structPrefix = "struct " 209 // After solidity 0.5.10, a new field of abi "internalType" 210 // is introduced. From that we can obtain the struct name 211 // user defined in the source code. 212 if internalType != "" && strings.HasPrefix(internalType, structPrefix) { 213 // Foo.Bar type definition is not allowed in golang, 214 // convert the format to FooBar 215 typ.TupleRawName = strings.ReplaceAll(internalType[len(structPrefix):], ".", "") 216 } 217 218 case "function": 219 typ.T = FunctionTy 220 typ.Size = 24 221 default: 222 if strings.HasPrefix(internalType, "contract ") { 223 typ.Size = 20 224 typ.T = AddressTy 225 } else { 226 return Type{}, fmt.Errorf("unsupported arg type: %s", t) 227 } 228 } 229 230 return 231 } 232 233 // GetType returns the reflection type of the ABI type. 234 func (t Type) GetType() reflect.Type { 235 switch t.T { 236 case IntTy: 237 return reflectIntType(false, t.Size) 238 case UintTy: 239 return reflectIntType(true, t.Size) 240 case BoolTy: 241 return reflect.TypeOf(false) 242 case StringTy: 243 return reflect.TypeOf("") 244 case SliceTy: 245 return reflect.SliceOf(t.Elem.GetType()) 246 case ArrayTy: 247 return reflect.ArrayOf(t.Size, t.Elem.GetType()) 248 case TupleTy: 249 return t.TupleType 250 case AddressTy: 251 return reflect.TypeOf(common.Address{}) 252 case FixedBytesTy: 253 return reflect.ArrayOf(t.Size, reflect.TypeOf(byte(0))) 254 case BytesTy: 255 return reflect.SliceOf(reflect.TypeOf(byte(0))) 256 case HashTy: 257 // hashtype currently not used 258 return reflect.ArrayOf(32, reflect.TypeOf(byte(0))) 259 case FixedPointTy: 260 // fixedpoint type currently not used 261 return reflect.ArrayOf(32, reflect.TypeOf(byte(0))) 262 case FunctionTy: 263 return reflect.ArrayOf(24, reflect.TypeOf(byte(0))) 264 default: 265 panic("Invalid type") 266 } 267 } 268 269 // String implements Stringer. 270 func (t Type) String() (out string) { 271 return t.stringKind 272 } 273 274 func (t Type) pack(v reflect.Value) ([]byte, error) { 275 // dereference pointer first if it's a pointer 276 v = indirect(v) 277 if err := typeCheck(t, v); err != nil { 278 return nil, err 279 } 280 281 switch t.T { 282 case SliceTy, ArrayTy: 283 var ret []byte 284 285 if t.requiresLengthPrefix() { 286 // append length 287 ret = append(ret, packNum(reflect.ValueOf(v.Len()))...) 288 } 289 290 // calculate offset if any 291 offset := 0 292 offsetReq := isDynamicType(*t.Elem) 293 if offsetReq { 294 offset = getTypeSize(*t.Elem) * v.Len() 295 } 296 var tail []byte 297 for i := 0; i < v.Len(); i++ { 298 val, err := t.Elem.pack(v.Index(i)) 299 if err != nil { 300 return nil, err 301 } 302 if !offsetReq { 303 ret = append(ret, val...) 304 continue 305 } 306 ret = append(ret, packNum(reflect.ValueOf(offset))...) 307 offset += len(val) 308 tail = append(tail, val...) 309 } 310 return append(ret, tail...), nil 311 case TupleTy: 312 // (T1,...,Tk) for k >= 0 and any types T1, …, Tk 313 // enc(X) = head(X(1)) ... head(X(k)) tail(X(1)) ... tail(X(k)) 314 // where X = (X(1), ..., X(k)) and head and tail are defined for Ti being a static 315 // type as 316 // head(X(i)) = enc(X(i)) and tail(X(i)) = "" (the empty string) 317 // and as 318 // head(X(i)) = enc(len(head(X(1)) ... head(X(k)) tail(X(1)) ... tail(X(i-1)))) 319 // tail(X(i)) = enc(X(i)) 320 // otherwise, i.e. if Ti is a dynamic type. 321 fieldmap, err := mapArgNamesToStructFields(t.TupleRawNames, v) 322 if err != nil { 323 return nil, err 324 } 325 // Calculate prefix occupied size. 326 offset := 0 327 for _, elem := range t.TupleElems { 328 offset += getTypeSize(*elem) 329 } 330 var ret, tail []byte 331 for i, elem := range t.TupleElems { 332 field := v.FieldByName(fieldmap[t.TupleRawNames[i]]) 333 if !field.IsValid() { 334 return nil, fmt.Errorf("field %s for tuple not found in the given struct", t.TupleRawNames[i]) 335 } 336 val, err := elem.pack(field) 337 if err != nil { 338 return nil, err 339 } 340 if isDynamicType(*elem) { 341 ret = append(ret, packNum(reflect.ValueOf(offset))...) 342 tail = append(tail, val...) 343 offset += len(val) 344 } else { 345 ret = append(ret, val...) 346 } 347 } 348 return append(ret, tail...), nil 349 350 default: 351 return packElement(t, v) 352 } 353 } 354 355 // requiresLengthPrefix returns whether the type requires any sort of length 356 // prefixing. 357 func (t Type) requiresLengthPrefix() bool { 358 return t.T == StringTy || t.T == BytesTy || t.T == SliceTy 359 } 360 361 // isDynamicType returns true if the type is dynamic. 362 // The following types are called “dynamic”: 363 // * bytes 364 // * string 365 // * T[] for any T 366 // * T[k] for any dynamic T and any k >= 0 367 // * (T1,...,Tk) if Ti is dynamic for some 1 <= i <= k 368 func isDynamicType(t Type) bool { 369 if t.T == TupleTy { 370 for _, elem := range t.TupleElems { 371 if isDynamicType(*elem) { 372 return true 373 } 374 } 375 return false 376 } 377 return t.T == StringTy || t.T == BytesTy || t.T == SliceTy || (t.T == ArrayTy && isDynamicType(*t.Elem)) 378 } 379 380 // getTypeSize returns the size that this type needs to occupy. 381 // We distinguish static and dynamic types. Static types are encoded in-place 382 // and dynamic types are encoded at a separately allocated location after the 383 // current block. 384 // So for a static variable, the size returned represents the size that the 385 // variable actually occupies. 386 // For a dynamic variable, the returned size is fixed 32 bytes, which is used 387 // to store the location reference for actual value storage. 388 func getTypeSize(t Type) int { 389 if t.T == ArrayTy && !isDynamicType(*t.Elem) { 390 // Recursively calculate type size if it is a nested array 391 if t.Elem.T == ArrayTy || t.Elem.T == TupleTy { 392 return t.Size * getTypeSize(*t.Elem) 393 } 394 return t.Size * 32 395 } else if t.T == TupleTy && !isDynamicType(t) { 396 total := 0 397 for _, elem := range t.TupleElems { 398 total += getTypeSize(*elem) 399 } 400 return total 401 } 402 return 32 403 } 404 405 // isLetter reports whether a given 'rune' is classified as a Letter. 406 // This method is copied from reflect/type.go 407 func isLetter(ch rune) bool { 408 return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= utf8.RuneSelf && unicode.IsLetter(ch) 409 } 410 411 // isValidFieldName checks if a string is a valid (struct) field name or not. 412 // 413 // According to the language spec, a field name should be an identifier. 414 // 415 // identifier = letter { letter | unicode_digit } . 416 // letter = unicode_letter | "_" . 417 // This method is copied from reflect/type.go 418 func isValidFieldName(fieldName string) bool { 419 for i, c := range fieldName { 420 if i == 0 && !isLetter(c) { 421 return false 422 } 423 424 if !(isLetter(c) || unicode.IsDigit(c)) { 425 return false 426 } 427 } 428 429 return len(fieldName) > 0 430 }