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