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