github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/accounts/abi/unpack.go (about) 1 // Copyright 2018 The go-ethereum Authors 2 // Copyright 2019 The go-aigar Authors 3 // This file is part of the go-aigar library. 4 // 5 // The go-aigar library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-aigar library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>. 17 18 package abi 19 20 import ( 21 "encoding/binary" 22 "fmt" 23 "math/big" 24 "reflect" 25 26 "github.com/AigarNetwork/aigar/common" 27 ) 28 29 var ( 30 maxUint256 = big.NewInt(0).Add( 31 big.NewInt(0).Exp(big.NewInt(2), big.NewInt(256), nil), 32 big.NewInt(-1)) 33 maxInt256 = big.NewInt(0).Add( 34 big.NewInt(0).Exp(big.NewInt(2), big.NewInt(255), nil), 35 big.NewInt(-1)) 36 ) 37 38 // reads the integer based on its kind 39 func readInteger(typ byte, kind reflect.Kind, b []byte) interface{} { 40 switch kind { 41 case reflect.Uint8: 42 return b[len(b)-1] 43 case reflect.Uint16: 44 return binary.BigEndian.Uint16(b[len(b)-2:]) 45 case reflect.Uint32: 46 return binary.BigEndian.Uint32(b[len(b)-4:]) 47 case reflect.Uint64: 48 return binary.BigEndian.Uint64(b[len(b)-8:]) 49 case reflect.Int8: 50 return int8(b[len(b)-1]) 51 case reflect.Int16: 52 return int16(binary.BigEndian.Uint16(b[len(b)-2:])) 53 case reflect.Int32: 54 return int32(binary.BigEndian.Uint32(b[len(b)-4:])) 55 case reflect.Int64: 56 return int64(binary.BigEndian.Uint64(b[len(b)-8:])) 57 default: 58 // the only case lefts for integer is int256/uint256. 59 // big.SetBytes can't tell if a number is negative, positive on itself. 60 // On EVM, if the returned number > max int256, it is negative. 61 ret := new(big.Int).SetBytes(b) 62 if typ == UintTy { 63 return ret 64 } 65 66 if ret.Cmp(maxInt256) > 0 { 67 ret.Add(maxUint256, big.NewInt(0).Neg(ret)) 68 ret.Add(ret, big.NewInt(1)) 69 ret.Neg(ret) 70 } 71 return ret 72 } 73 } 74 75 // reads a bool 76 func readBool(word []byte) (bool, error) { 77 for _, b := range word[:31] { 78 if b != 0 { 79 return false, errBadBool 80 } 81 } 82 switch word[31] { 83 case 0: 84 return false, nil 85 case 1: 86 return true, nil 87 default: 88 return false, errBadBool 89 } 90 } 91 92 // A function type is simply the address with the function selection signature at the end. 93 // This enforces that standard by always presenting it as a 24-array (address + sig = 24 bytes) 94 func readFunctionType(t Type, word []byte) (funcTy [24]byte, err error) { 95 if t.T != FunctionTy { 96 return [24]byte{}, fmt.Errorf("abi: invalid type in call to make function type byte array") 97 } 98 if garbage := binary.BigEndian.Uint64(word[24:32]); garbage != 0 { 99 err = fmt.Errorf("abi: got improperly encoded function type, got %v", word) 100 } else { 101 copy(funcTy[:], word[0:24]) 102 } 103 return 104 } 105 106 // through reflection, creates a fixed array to be read from 107 func readFixedBytes(t Type, word []byte) (interface{}, error) { 108 if t.T != FixedBytesTy { 109 return nil, fmt.Errorf("abi: invalid type in call to make fixed byte array") 110 } 111 // convert 112 array := reflect.New(t.Type).Elem() 113 114 reflect.Copy(array, reflect.ValueOf(word[0:t.Size])) 115 return array.Interface(), nil 116 117 } 118 119 // iteratively unpack elements 120 func forEachUnpack(t Type, output []byte, start, size int) (interface{}, error) { 121 if size < 0 { 122 return nil, fmt.Errorf("cannot marshal input to array, size is negative (%d)", size) 123 } 124 if start+32*size > len(output) { 125 return nil, fmt.Errorf("abi: cannot marshal in to go array: offset %d would go over slice boundary (len=%d)", len(output), start+32*size) 126 } 127 128 // this value will become our slice or our array, depending on the type 129 var refSlice reflect.Value 130 131 if t.T == SliceTy { 132 // declare our slice 133 refSlice = reflect.MakeSlice(t.Type, size, size) 134 } else if t.T == ArrayTy { 135 // declare our array 136 refSlice = reflect.New(t.Type).Elem() 137 } else { 138 return nil, fmt.Errorf("abi: invalid type in array/slice unpacking stage") 139 } 140 141 // Arrays have packed elements, resulting in longer unpack steps. 142 // Slices have just 32 bytes per element (pointing to the contents). 143 elemSize := getTypeSize(*t.Elem) 144 145 for i, j := start, 0; j < size; i, j = i+elemSize, j+1 { 146 inter, err := toGoType(i, *t.Elem, output) 147 if err != nil { 148 return nil, err 149 } 150 151 // append the item to our reflect slice 152 refSlice.Index(j).Set(reflect.ValueOf(inter)) 153 } 154 155 // return the interface 156 return refSlice.Interface(), nil 157 } 158 159 func forTupleUnpack(t Type, output []byte) (interface{}, error) { 160 retval := reflect.New(t.Type).Elem() 161 virtualArgs := 0 162 for index, elem := range t.TupleElems { 163 marshalledValue, err := toGoType((index+virtualArgs)*32, *elem, output) 164 if elem.T == ArrayTy && !isDynamicType(*elem) { 165 // If we have a static array, like [3]uint256, these are coded as 166 // just like uint256,uint256,uint256. 167 // This means that we need to add two 'virtual' arguments when 168 // we count the index from now on. 169 // 170 // Array values nested multiple levels deep are also encoded inline: 171 // [2][3]uint256: uint256,uint256,uint256,uint256,uint256,uint256 172 // 173 // Calculate the full array size to get the correct offset for the next argument. 174 // Decrement it by 1, as the normal index increment is still applied. 175 virtualArgs += getTypeSize(*elem)/32 - 1 176 } else if elem.T == TupleTy && !isDynamicType(*elem) { 177 // If we have a static tuple, like (uint256, bool, uint256), these are 178 // coded as just like uint256,bool,uint256 179 virtualArgs += getTypeSize(*elem)/32 - 1 180 } 181 if err != nil { 182 return nil, err 183 } 184 retval.Field(index).Set(reflect.ValueOf(marshalledValue)) 185 } 186 return retval.Interface(), nil 187 } 188 189 // toGoType parses the output bytes and recursively assigns the value of these bytes 190 // into a go type with accordance with the ABI spec. 191 func toGoType(index int, t Type, output []byte) (interface{}, error) { 192 if index+32 > len(output) { 193 return nil, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %d require %d", len(output), index+32) 194 } 195 196 var ( 197 returnOutput []byte 198 begin, length int 199 err error 200 ) 201 202 // if we require a length prefix, find the beginning word and size returned. 203 if t.requiresLengthPrefix() { 204 begin, length, err = lengthPrefixPointsTo(index, output) 205 if err != nil { 206 return nil, err 207 } 208 } else { 209 returnOutput = output[index : index+32] 210 } 211 212 switch t.T { 213 case TupleTy: 214 if isDynamicType(t) { 215 begin, err := tuplePointsTo(index, output) 216 if err != nil { 217 return nil, err 218 } 219 return forTupleUnpack(t, output[begin:]) 220 } else { 221 return forTupleUnpack(t, output[index:]) 222 } 223 case SliceTy: 224 return forEachUnpack(t, output[begin:], 0, length) 225 case ArrayTy: 226 if isDynamicType(*t.Elem) { 227 offset := int64(binary.BigEndian.Uint64(returnOutput[len(returnOutput)-8:])) 228 return forEachUnpack(t, output[offset:], 0, t.Size) 229 } 230 return forEachUnpack(t, output[index:], 0, t.Size) 231 case StringTy: // variable arrays are written at the end of the return bytes 232 return string(output[begin : begin+length]), nil 233 case IntTy, UintTy: 234 return readInteger(t.T, t.Kind, returnOutput), nil 235 case BoolTy: 236 return readBool(returnOutput) 237 case AddressTy: 238 return common.BytesToAddress(returnOutput), nil 239 case HashTy: 240 return common.BytesToHash(returnOutput), nil 241 case BytesTy: 242 return output[begin : begin+length], nil 243 case FixedBytesTy: 244 return readFixedBytes(t, returnOutput) 245 case FunctionTy: 246 return readFunctionType(t, returnOutput) 247 default: 248 return nil, fmt.Errorf("abi: unknown type %v", t.T) 249 } 250 } 251 252 // interprets a 32 byte slice as an offset and then determines which indice to look to decode the type. 253 func lengthPrefixPointsTo(index int, output []byte) (start int, length int, err error) { 254 bigOffsetEnd := big.NewInt(0).SetBytes(output[index : index+32]) 255 bigOffsetEnd.Add(bigOffsetEnd, common.Big32) 256 outputLength := big.NewInt(int64(len(output))) 257 258 if bigOffsetEnd.Cmp(outputLength) > 0 { 259 return 0, 0, fmt.Errorf("abi: cannot marshal in to go slice: offset %v would go over slice boundary (len=%v)", bigOffsetEnd, outputLength) 260 } 261 262 if bigOffsetEnd.BitLen() > 63 { 263 return 0, 0, fmt.Errorf("abi offset larger than int64: %v", bigOffsetEnd) 264 } 265 266 offsetEnd := int(bigOffsetEnd.Uint64()) 267 lengthBig := big.NewInt(0).SetBytes(output[offsetEnd-32 : offsetEnd]) 268 269 totalSize := big.NewInt(0) 270 totalSize.Add(totalSize, bigOffsetEnd) 271 totalSize.Add(totalSize, lengthBig) 272 if totalSize.BitLen() > 63 { 273 return 0, 0, fmt.Errorf("abi: length larger than int64: %v", totalSize) 274 } 275 276 if totalSize.Cmp(outputLength) > 0 { 277 return 0, 0, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %v require %v", outputLength, totalSize) 278 } 279 start = int(bigOffsetEnd.Uint64()) 280 length = int(lengthBig.Uint64()) 281 return 282 } 283 284 // tuplePointsTo resolves the location reference for dynamic tuple. 285 func tuplePointsTo(index int, output []byte) (start int, err error) { 286 offset := big.NewInt(0).SetBytes(output[index : index+32]) 287 outputLen := big.NewInt(int64(len(output))) 288 289 if offset.Cmp(big.NewInt(int64(len(output)))) > 0 { 290 return 0, fmt.Errorf("abi: cannot marshal in to go slice: offset %v would go over slice boundary (len=%v)", offset, outputLen) 291 } 292 if offset.BitLen() > 63 { 293 return 0, fmt.Errorf("abi offset larger than int64: %v", offset) 294 } 295 return int(offset.Uint64()), nil 296 }