github.com/calmw/ethereum@v0.1.1/accounts/abi/unpack.go (about) 1 // Copyright 2017 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 "encoding/binary" 21 "fmt" 22 "math" 23 "math/big" 24 "reflect" 25 26 "github.com/calmw/ethereum/common" 27 ) 28 29 var ( 30 // MaxUint256 is the maximum value that can be represented by a uint256. 31 MaxUint256 = new(big.Int).Sub(new(big.Int).Lsh(common.Big1, 256), common.Big1) 32 // MaxInt256 is the maximum value that can be represented by a int256. 33 MaxInt256 = new(big.Int).Sub(new(big.Int).Lsh(common.Big1, 255), common.Big1) 34 ) 35 36 // ReadInteger reads the integer based on its kind and returns the appropriate value. 37 func ReadInteger(typ Type, b []byte) (interface{}, error) { 38 ret := new(big.Int).SetBytes(b) 39 40 if typ.T == UintTy { 41 u64, isu64 := ret.Uint64(), ret.IsUint64() 42 switch typ.Size { 43 case 8: 44 if !isu64 || u64 > math.MaxUint8 { 45 return nil, errBadUint8 46 } 47 return byte(u64), nil 48 case 16: 49 if !isu64 || u64 > math.MaxUint16 { 50 return nil, errBadUint16 51 } 52 return uint16(u64), nil 53 case 32: 54 if !isu64 || u64 > math.MaxUint32 { 55 return nil, errBadUint32 56 } 57 return uint32(u64), nil 58 case 64: 59 if !isu64 { 60 return nil, errBadUint64 61 } 62 return u64, nil 63 default: 64 // the only case left for unsigned integer is uint256. 65 return ret, nil 66 } 67 } 68 69 // big.SetBytes can't tell if a number is negative or positive in itself. 70 // On EVM, if the returned number > max int256, it is negative. 71 // A number is > max int256 if the bit at position 255 is set. 72 if ret.Bit(255) == 1 { 73 ret.Add(MaxUint256, new(big.Int).Neg(ret)) 74 ret.Add(ret, common.Big1) 75 ret.Neg(ret) 76 } 77 i64, isi64 := ret.Int64(), ret.IsInt64() 78 switch typ.Size { 79 case 8: 80 if !isi64 || i64 < math.MinInt8 || i64 > math.MaxInt8 { 81 return nil, errBadInt8 82 } 83 return int8(i64), nil 84 case 16: 85 if !isi64 || i64 < math.MinInt16 || i64 > math.MaxInt16 { 86 return nil, errBadInt16 87 } 88 return int16(i64), nil 89 case 32: 90 if !isi64 || i64 < math.MinInt32 || i64 > math.MaxInt32 { 91 return nil, errBadInt32 92 } 93 return int32(i64), nil 94 case 64: 95 if !isi64 { 96 return nil, errBadInt64 97 } 98 return i64, nil 99 default: 100 // the only case left for integer is int256 101 102 return ret, nil 103 } 104 } 105 106 // readBool reads a bool. 107 func readBool(word []byte) (bool, error) { 108 for _, b := range word[:31] { 109 if b != 0 { 110 return false, errBadBool 111 } 112 } 113 switch word[31] { 114 case 0: 115 return false, nil 116 case 1: 117 return true, nil 118 default: 119 return false, errBadBool 120 } 121 } 122 123 // A function type is simply the address with the function selection signature at the end. 124 // 125 // readFunctionType enforces that standard by always presenting it as a 24-array (address + sig = 24 bytes) 126 func readFunctionType(t Type, word []byte) (funcTy [24]byte, err error) { 127 if t.T != FunctionTy { 128 return [24]byte{}, fmt.Errorf("abi: invalid type in call to make function type byte array") 129 } 130 if garbage := binary.BigEndian.Uint64(word[24:32]); garbage != 0 { 131 err = fmt.Errorf("abi: got improperly encoded function type, got %v", word) 132 } else { 133 copy(funcTy[:], word[0:24]) 134 } 135 return 136 } 137 138 // ReadFixedBytes uses reflection to create a fixed array to be read from. 139 func ReadFixedBytes(t Type, word []byte) (interface{}, error) { 140 if t.T != FixedBytesTy { 141 return nil, fmt.Errorf("abi: invalid type in call to make fixed byte array") 142 } 143 // convert 144 array := reflect.New(t.GetType()).Elem() 145 146 reflect.Copy(array, reflect.ValueOf(word[0:t.Size])) 147 return array.Interface(), nil 148 } 149 150 // forEachUnpack iteratively unpack elements. 151 func forEachUnpack(t Type, output []byte, start, size int) (interface{}, error) { 152 if size < 0 { 153 return nil, fmt.Errorf("cannot marshal input to array, size is negative (%d)", size) 154 } 155 if start+32*size > len(output) { 156 return nil, fmt.Errorf("abi: cannot marshal into go array: offset %d would go over slice boundary (len=%d)", len(output), start+32*size) 157 } 158 159 // this value will become our slice or our array, depending on the type 160 var refSlice reflect.Value 161 162 if t.T == SliceTy { 163 // declare our slice 164 refSlice = reflect.MakeSlice(t.GetType(), size, size) 165 } else if t.T == ArrayTy { 166 // declare our array 167 refSlice = reflect.New(t.GetType()).Elem() 168 } else { 169 return nil, fmt.Errorf("abi: invalid type in array/slice unpacking stage") 170 } 171 172 // Arrays have packed elements, resulting in longer unpack steps. 173 // Slices have just 32 bytes per element (pointing to the contents). 174 elemSize := getTypeSize(*t.Elem) 175 176 for i, j := start, 0; j < size; i, j = i+elemSize, j+1 { 177 inter, err := toGoType(i, *t.Elem, output) 178 if err != nil { 179 return nil, err 180 } 181 182 // append the item to our reflect slice 183 refSlice.Index(j).Set(reflect.ValueOf(inter)) 184 } 185 186 // return the interface 187 return refSlice.Interface(), nil 188 } 189 190 func forTupleUnpack(t Type, output []byte) (interface{}, error) { 191 retval := reflect.New(t.GetType()).Elem() 192 virtualArgs := 0 193 for index, elem := range t.TupleElems { 194 marshalledValue, err := toGoType((index+virtualArgs)*32, *elem, output) 195 if err != nil { 196 return nil, err 197 } 198 if elem.T == ArrayTy && !isDynamicType(*elem) { 199 // If we have a static array, like [3]uint256, these are coded as 200 // just like uint256,uint256,uint256. 201 // This means that we need to add two 'virtual' arguments when 202 // we count the index from now on. 203 // 204 // Array values nested multiple levels deep are also encoded inline: 205 // [2][3]uint256: uint256,uint256,uint256,uint256,uint256,uint256 206 // 207 // Calculate the full array size to get the correct offset for the next argument. 208 // Decrement it by 1, as the normal index increment is still applied. 209 virtualArgs += getTypeSize(*elem)/32 - 1 210 } else if elem.T == TupleTy && !isDynamicType(*elem) { 211 // If we have a static tuple, like (uint256, bool, uint256), these are 212 // coded as just like uint256,bool,uint256 213 virtualArgs += getTypeSize(*elem)/32 - 1 214 } 215 retval.Field(index).Set(reflect.ValueOf(marshalledValue)) 216 } 217 return retval.Interface(), nil 218 } 219 220 // toGoType parses the output bytes and recursively assigns the value of these bytes 221 // into a go type with accordance with the ABI spec. 222 func toGoType(index int, t Type, output []byte) (interface{}, error) { 223 if index+32 > len(output) { 224 return nil, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %d require %d", len(output), index+32) 225 } 226 227 var ( 228 returnOutput []byte 229 begin, length int 230 err error 231 ) 232 233 // if we require a length prefix, find the beginning word and size returned. 234 if t.requiresLengthPrefix() { 235 begin, length, err = lengthPrefixPointsTo(index, output) 236 if err != nil { 237 return nil, err 238 } 239 } else { 240 returnOutput = output[index : index+32] 241 } 242 243 switch t.T { 244 case TupleTy: 245 if isDynamicType(t) { 246 begin, err := tuplePointsTo(index, output) 247 if err != nil { 248 return nil, err 249 } 250 return forTupleUnpack(t, output[begin:]) 251 } 252 return forTupleUnpack(t, output[index:]) 253 case SliceTy: 254 return forEachUnpack(t, output[begin:], 0, length) 255 case ArrayTy: 256 if isDynamicType(*t.Elem) { 257 offset := binary.BigEndian.Uint64(returnOutput[len(returnOutput)-8:]) 258 if offset > uint64(len(output)) { 259 return nil, fmt.Errorf("abi: toGoType offset greater than output length: offset: %d, len(output): %d", offset, len(output)) 260 } 261 return forEachUnpack(t, output[offset:], 0, t.Size) 262 } 263 return forEachUnpack(t, output[index:], 0, t.Size) 264 case StringTy: // variable arrays are written at the end of the return bytes 265 return string(output[begin : begin+length]), nil 266 case IntTy, UintTy: 267 return ReadInteger(t, returnOutput) 268 case BoolTy: 269 return readBool(returnOutput) 270 case AddressTy: 271 return common.BytesToAddress(returnOutput), nil 272 case HashTy: 273 return common.BytesToHash(returnOutput), nil 274 case BytesTy: 275 return output[begin : begin+length], nil 276 case FixedBytesTy: 277 return ReadFixedBytes(t, returnOutput) 278 case FunctionTy: 279 return readFunctionType(t, returnOutput) 280 default: 281 return nil, fmt.Errorf("abi: unknown type %v", t.T) 282 } 283 } 284 285 // lengthPrefixPointsTo interprets a 32 byte slice as an offset and then determines which indices to look to decode the type. 286 func lengthPrefixPointsTo(index int, output []byte) (start int, length int, err error) { 287 bigOffsetEnd := new(big.Int).SetBytes(output[index : index+32]) 288 bigOffsetEnd.Add(bigOffsetEnd, common.Big32) 289 outputLength := big.NewInt(int64(len(output))) 290 291 if bigOffsetEnd.Cmp(outputLength) > 0 { 292 return 0, 0, fmt.Errorf("abi: cannot marshal in to go slice: offset %v would go over slice boundary (len=%v)", bigOffsetEnd, outputLength) 293 } 294 295 if bigOffsetEnd.BitLen() > 63 { 296 return 0, 0, fmt.Errorf("abi offset larger than int64: %v", bigOffsetEnd) 297 } 298 299 offsetEnd := int(bigOffsetEnd.Uint64()) 300 lengthBig := new(big.Int).SetBytes(output[offsetEnd-32 : offsetEnd]) 301 302 totalSize := new(big.Int).Add(bigOffsetEnd, lengthBig) 303 if totalSize.BitLen() > 63 { 304 return 0, 0, fmt.Errorf("abi: length larger than int64: %v", totalSize) 305 } 306 307 if totalSize.Cmp(outputLength) > 0 { 308 return 0, 0, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %v require %v", outputLength, totalSize) 309 } 310 start = int(bigOffsetEnd.Uint64()) 311 length = int(lengthBig.Uint64()) 312 return 313 } 314 315 // tuplePointsTo resolves the location reference for dynamic tuple. 316 func tuplePointsTo(index int, output []byte) (start int, err error) { 317 offset := new(big.Int).SetBytes(output[index : index+32]) 318 outputLen := big.NewInt(int64(len(output))) 319 320 if offset.Cmp(outputLen) > 0 { 321 return 0, fmt.Errorf("abi: cannot marshal in to go slice: offset %v would go over slice boundary (len=%v)", offset, outputLen) 322 } 323 if offset.BitLen() > 63 { 324 return 0, fmt.Errorf("abi offset larger than int64: %v", offset) 325 } 326 return int(offset.Uint64()), nil 327 }