unpack.go 9.8 KB

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