github.com/daeglee/go-ethereum@v0.0.0-20190504220456-cad3e8d18e9b/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 28 // Type enumerator 29 const ( 30 IntTy byte = iota 31 UintTy 32 BoolTy 33 StringTy 34 SliceTy 35 ArrayTy 36 TupleTy 37 AddressTy 38 FixedBytesTy 39 BytesTy 40 HashTy 41 FixedPointTy 42 FunctionTy 43 ) 44 45 // Type is the reflection of the supported argument type 46 type Type struct { 47 Elem *Type 48 Kind reflect.Kind 49 Type reflect.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 TupleElems []*Type // Type information of all tuple fields 57 TupleRawNames []string // Raw field name of all tuple fields 58 } 59 60 var ( 61 // typeRegex parses the abi sub types 62 typeRegex = regexp.MustCompile("([a-zA-Z]+)(([0-9]+)(x([0-9]+))?)?") 63 ) 64 65 // NewType creates a new reflection type of abi type given in t. 66 func NewType(t 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 72 typ.stringKind = t 73 74 // if there are brackets, get ready to go into slice/array mode and 75 // recursively create the type 76 if strings.Count(t, "[") != 0 { 77 i := strings.LastIndex(t, "[") 78 // recursively embed the type 79 embeddedType, err := NewType(t[:i], components) 80 if err != nil { 81 return Type{}, err 82 } 83 // grab the last cell and create a type from there 84 sliced := t[i:] 85 // grab the slice size with regexp 86 re := regexp.MustCompile("[0-9]+") 87 intz := re.FindAllString(sliced, -1) 88 89 if len(intz) == 0 { 90 // is a slice 91 typ.T = SliceTy 92 typ.Kind = reflect.Slice 93 typ.Elem = &embeddedType 94 typ.Type = reflect.SliceOf(embeddedType.Type) 95 if embeddedType.T == TupleTy { 96 typ.stringKind = embeddedType.stringKind + sliced 97 } 98 } else if len(intz) == 1 { 99 // is a array 100 typ.T = ArrayTy 101 typ.Kind = reflect.Array 102 typ.Elem = &embeddedType 103 typ.Size, err = strconv.Atoi(intz[0]) 104 if err != nil { 105 return Type{}, fmt.Errorf("abi: error parsing variable size: %v", err) 106 } 107 typ.Type = reflect.ArrayOf(typ.Size, embeddedType.Type) 108 if embeddedType.T == TupleTy { 109 typ.stringKind = embeddedType.stringKind + sliced 110 } 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.Kind, typ.Type = reflectIntKindAndType(false, varSize) 142 typ.Size = varSize 143 typ.T = IntTy 144 case "uint": 145 typ.Kind, typ.Type = reflectIntKindAndType(true, varSize) 146 typ.Size = varSize 147 typ.T = UintTy 148 case "bool": 149 typ.Kind = reflect.Bool 150 typ.T = BoolTy 151 typ.Type = reflect.TypeOf(bool(false)) 152 case "address": 153 typ.Kind = reflect.Array 154 typ.Type = addressT 155 typ.Size = 20 156 typ.T = AddressTy 157 case "string": 158 typ.Kind = reflect.String 159 typ.Type = reflect.TypeOf("") 160 typ.T = StringTy 161 case "bytes": 162 if varSize == 0 { 163 typ.T = BytesTy 164 typ.Kind = reflect.Slice 165 typ.Type = reflect.SliceOf(reflect.TypeOf(byte(0))) 166 } else { 167 typ.T = FixedBytesTy 168 typ.Kind = reflect.Array 169 typ.Size = varSize 170 typ.Type = reflect.ArrayOf(varSize, reflect.TypeOf(byte(0))) 171 } 172 case "tuple": 173 var ( 174 fields []reflect.StructField 175 elems []*Type 176 names []string 177 expression string // canonical parameter expression 178 ) 179 expression += "(" 180 for idx, c := range components { 181 cType, err := NewType(c.Type, c.Components) 182 if err != nil { 183 return Type{}, err 184 } 185 if ToCamelCase(c.Name) == "" { 186 return Type{}, errors.New("abi: purely anonymous or underscored field is not supported") 187 } 188 fields = append(fields, reflect.StructField{ 189 Name: ToCamelCase(c.Name), // reflect.StructOf will panic for any exported field. 190 Type: cType.Type, 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 typ.Kind = reflect.Struct 202 typ.Type = reflect.StructOf(fields) 203 typ.TupleElems = elems 204 typ.TupleRawNames = names 205 typ.T = TupleTy 206 typ.stringKind = expression 207 case "function": 208 typ.Kind = reflect.Array 209 typ.T = FunctionTy 210 typ.Size = 24 211 typ.Type = reflect.ArrayOf(24, reflect.TypeOf(byte(0))) 212 default: 213 return Type{}, fmt.Errorf("unsupported arg type: %s", t) 214 } 215 216 return 217 } 218 219 // String implements Stringer 220 func (t Type) String() (out string) { 221 return t.stringKind 222 } 223 224 func (t Type) pack(v reflect.Value) ([]byte, error) { 225 // dereference pointer first if it's a pointer 226 v = indirect(v) 227 if err := typeCheck(t, v); err != nil { 228 return nil, err 229 } 230 231 switch t.T { 232 case SliceTy, ArrayTy: 233 var ret []byte 234 235 if t.requiresLengthPrefix() { 236 // append length 237 ret = append(ret, packNum(reflect.ValueOf(v.Len()))...) 238 } 239 240 // calculate offset if any 241 offset := 0 242 offsetReq := isDynamicType(*t.Elem) 243 if offsetReq { 244 offset = getTypeSize(*t.Elem) * v.Len() 245 } 246 var tail []byte 247 for i := 0; i < v.Len(); i++ { 248 val, err := t.Elem.pack(v.Index(i)) 249 if err != nil { 250 return nil, err 251 } 252 if !offsetReq { 253 ret = append(ret, val...) 254 continue 255 } 256 ret = append(ret, packNum(reflect.ValueOf(offset))...) 257 offset += len(val) 258 tail = append(tail, val...) 259 } 260 return append(ret, tail...), nil 261 case TupleTy: 262 // (T1,...,Tk) for k >= 0 and any types T1, …, Tk 263 // enc(X) = head(X(1)) ... head(X(k)) tail(X(1)) ... tail(X(k)) 264 // where X = (X(1), ..., X(k)) and head and tail are defined for Ti being a static 265 // type as 266 // head(X(i)) = enc(X(i)) and tail(X(i)) = "" (the empty string) 267 // and as 268 // head(X(i)) = enc(len(head(X(1)) ... head(X(k)) tail(X(1)) ... tail(X(i-1)))) 269 // tail(X(i)) = enc(X(i)) 270 // otherwise, i.e. if Ti is a dynamic type. 271 fieldmap, err := mapArgNamesToStructFields(t.TupleRawNames, v) 272 if err != nil { 273 return nil, err 274 } 275 // Calculate prefix occupied size. 276 offset := 0 277 for _, elem := range t.TupleElems { 278 offset += getTypeSize(*elem) 279 } 280 var ret, tail []byte 281 for i, elem := range t.TupleElems { 282 field := v.FieldByName(fieldmap[t.TupleRawNames[i]]) 283 if !field.IsValid() { 284 return nil, fmt.Errorf("field %s for tuple not found in the given struct", t.TupleRawNames[i]) 285 } 286 val, err := elem.pack(field) 287 if err != nil { 288 return nil, err 289 } 290 if isDynamicType(*elem) { 291 ret = append(ret, packNum(reflect.ValueOf(offset))...) 292 tail = append(tail, val...) 293 offset += len(val) 294 } else { 295 ret = append(ret, val...) 296 } 297 } 298 return append(ret, tail...), nil 299 300 default: 301 return packElement(t, v), nil 302 } 303 } 304 305 // requireLengthPrefix returns whether the type requires any sort of length 306 // prefixing. 307 func (t Type) requiresLengthPrefix() bool { 308 return t.T == StringTy || t.T == BytesTy || t.T == SliceTy 309 } 310 311 // isDynamicType returns true if the type is dynamic. 312 // The following types are called “dynamic”: 313 // * bytes 314 // * string 315 // * T[] for any T 316 // * T[k] for any dynamic T and any k >= 0 317 // * (T1,...,Tk) if Ti is dynamic for some 1 <= i <= k 318 func isDynamicType(t Type) bool { 319 if t.T == TupleTy { 320 for _, elem := range t.TupleElems { 321 if isDynamicType(*elem) { 322 return true 323 } 324 } 325 return false 326 } 327 return t.T == StringTy || t.T == BytesTy || t.T == SliceTy || (t.T == ArrayTy && isDynamicType(*t.Elem)) 328 } 329 330 // getTypeSize returns the size that this type needs to occupy. 331 // We distinguish static and dynamic types. Static types are encoded in-place 332 // and dynamic types are encoded at a separately allocated location after the 333 // current block. 334 // So for a static variable, the size returned represents the size that the 335 // variable actually occupies. 336 // For a dynamic variable, the returned size is fixed 32 bytes, which is used 337 // to store the location reference for actual value storage. 338 func getTypeSize(t Type) int { 339 if t.T == ArrayTy && !isDynamicType(*t.Elem) { 340 // Recursively calculate type size if it is a nested array 341 if t.Elem.T == ArrayTy { 342 return t.Size * getTypeSize(*t.Elem) 343 } 344 return t.Size * 32 345 } else if t.T == TupleTy && !isDynamicType(t) { 346 total := 0 347 for _, elem := range t.TupleElems { 348 total += getTypeSize(*elem) 349 } 350 return total 351 } 352 return 32 353 }