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