unpack.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. // 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. // This enforces that standard by always presenting it as a 24-array (address + sig = 24 bytes)
  88. func readFunctionType(t Type, word []byte) (funcTy [24]byte, err error) {
  89. if t.T != FunctionTy {
  90. return [24]byte{}, fmt.Errorf("abi: invalid type in call to make function type byte array")
  91. }
  92. if garbage := binary.BigEndian.Uint64(word[24:32]); garbage != 0 {
  93. err = fmt.Errorf("abi: got improperly encoded function type, got %v", word)
  94. } else {
  95. copy(funcTy[:], word[0:24])
  96. }
  97. return
  98. }
  99. // ReadFixedBytes uses reflection to create a fixed array to be read from
  100. func ReadFixedBytes(t Type, word []byte) (interface{}, error) {
  101. if t.T != FixedBytesTy {
  102. return nil, fmt.Errorf("abi: invalid type in call to make fixed byte array")
  103. }
  104. // convert
  105. array := reflect.New(t.GetType()).Elem()
  106. reflect.Copy(array, reflect.ValueOf(word[0:t.Size]))
  107. return array.Interface(), nil
  108. }
  109. // iteratively unpack elements
  110. func forEachUnpack(t Type, output []byte, start, size int) (interface{}, error) {
  111. if size < 0 {
  112. return nil, fmt.Errorf("cannot marshal input to array, size is negative (%d)", size)
  113. }
  114. if start+32*size > len(output) {
  115. 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)
  116. }
  117. // this value will become our slice or our array, depending on the type
  118. var refSlice reflect.Value
  119. if t.T == SliceTy {
  120. // declare our slice
  121. refSlice = reflect.MakeSlice(t.GetType(), size, size)
  122. } else if t.T == ArrayTy {
  123. // declare our array
  124. refSlice = reflect.New(t.GetType()).Elem()
  125. } else {
  126. return nil, fmt.Errorf("abi: invalid type in array/slice unpacking stage")
  127. }
  128. // Arrays have packed elements, resulting in longer unpack steps.
  129. // Slices have just 32 bytes per element (pointing to the contents).
  130. elemSize := getTypeSize(*t.Elem)
  131. for i, j := start, 0; j < size; i, j = i+elemSize, j+1 {
  132. inter, err := toGoType(i, *t.Elem, output)
  133. if err != nil {
  134. return nil, err
  135. }
  136. // append the item to our reflect slice
  137. refSlice.Index(j).Set(reflect.ValueOf(inter))
  138. }
  139. // return the interface
  140. return refSlice.Interface(), nil
  141. }
  142. func forTupleUnpack(t Type, output []byte) (interface{}, error) {
  143. retval := reflect.New(t.GetType()).Elem()
  144. virtualArgs := 0
  145. for index, elem := range t.TupleElems {
  146. marshalledValue, err := toGoType((index+virtualArgs)*32, *elem, output)
  147. if elem.T == ArrayTy && !isDynamicType(*elem) {
  148. // If we have a static array, like [3]uint256, these are coded as
  149. // just like uint256,uint256,uint256.
  150. // This means that we need to add two 'virtual' arguments when
  151. // we count the index from now on.
  152. //
  153. // Array values nested multiple levels deep are also encoded inline:
  154. // [2][3]uint256: uint256,uint256,uint256,uint256,uint256,uint256
  155. //
  156. // Calculate the full array size to get the correct offset for the next argument.
  157. // Decrement it by 1, as the normal index increment is still applied.
  158. virtualArgs += getTypeSize(*elem)/32 - 1
  159. } else if elem.T == TupleTy && !isDynamicType(*elem) {
  160. // If we have a static tuple, like (uint256, bool, uint256), these are
  161. // coded as just like uint256,bool,uint256
  162. virtualArgs += getTypeSize(*elem)/32 - 1
  163. }
  164. if err != nil {
  165. return nil, err
  166. }
  167. retval.Field(index).Set(reflect.ValueOf(marshalledValue))
  168. }
  169. return retval.Interface(), nil
  170. }
  171. // toGoType parses the output bytes and recursively assigns the value of these bytes
  172. // into a go type with accordance with the ABI spec.
  173. func toGoType(index int, t Type, output []byte) (interface{}, error) {
  174. if index+32 > len(output) {
  175. return nil, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %d require %d", len(output), index+32)
  176. }
  177. var (
  178. returnOutput []byte
  179. begin, length int
  180. err error
  181. )
  182. // if we require a length prefix, find the beginning word and size returned.
  183. if t.requiresLengthPrefix() {
  184. begin, length, err = lengthPrefixPointsTo(index, output)
  185. if err != nil {
  186. return nil, err
  187. }
  188. } else {
  189. returnOutput = output[index : index+32]
  190. }
  191. switch t.T {
  192. case TupleTy:
  193. if isDynamicType(t) {
  194. begin, err := tuplePointsTo(index, output)
  195. if err != nil {
  196. return nil, err
  197. }
  198. return forTupleUnpack(t, output[begin:])
  199. }
  200. return forTupleUnpack(t, output[index:])
  201. case SliceTy:
  202. return forEachUnpack(t, output[begin:], 0, length)
  203. case ArrayTy:
  204. if isDynamicType(*t.Elem) {
  205. offset := int64(binary.BigEndian.Uint64(returnOutput[len(returnOutput)-8:]))
  206. return forEachUnpack(t, output[offset:], 0, t.Size)
  207. }
  208. return forEachUnpack(t, output[index:], 0, t.Size)
  209. case StringTy: // variable arrays are written at the end of the return bytes
  210. return string(output[begin : begin+length]), nil
  211. case IntTy, UintTy:
  212. return ReadInteger(t, returnOutput), nil
  213. case BoolTy:
  214. return readBool(returnOutput)
  215. case AddressTy:
  216. return common.BytesToAddress(returnOutput), nil
  217. case HashTy:
  218. return common.BytesToHash(returnOutput), nil
  219. case BytesTy:
  220. return output[begin : begin+length], nil
  221. case FixedBytesTy:
  222. return ReadFixedBytes(t, returnOutput)
  223. case FunctionTy:
  224. return readFunctionType(t, returnOutput)
  225. default:
  226. return nil, fmt.Errorf("abi: unknown type %v", t.T)
  227. }
  228. }
  229. // interprets a 32 byte slice as an offset and then determines which indice to look to decode the type.
  230. func lengthPrefixPointsTo(index int, output []byte) (start int, length int, err error) {
  231. bigOffsetEnd := big.NewInt(0).SetBytes(output[index : index+32])
  232. bigOffsetEnd.Add(bigOffsetEnd, common.Big32)
  233. outputLength := big.NewInt(int64(len(output)))
  234. if bigOffsetEnd.Cmp(outputLength) > 0 {
  235. return 0, 0, fmt.Errorf("abi: cannot marshal in to go slice: offset %v would go over slice boundary (len=%v)", bigOffsetEnd, outputLength)
  236. }
  237. if bigOffsetEnd.BitLen() > 63 {
  238. return 0, 0, fmt.Errorf("abi offset larger than int64: %v", bigOffsetEnd)
  239. }
  240. offsetEnd := int(bigOffsetEnd.Uint64())
  241. lengthBig := big.NewInt(0).SetBytes(output[offsetEnd-32 : offsetEnd])
  242. totalSize := big.NewInt(0)
  243. totalSize.Add(totalSize, bigOffsetEnd)
  244. totalSize.Add(totalSize, lengthBig)
  245. if totalSize.BitLen() > 63 {
  246. return 0, 0, fmt.Errorf("abi: length larger than int64: %v", totalSize)
  247. }
  248. if totalSize.Cmp(outputLength) > 0 {
  249. return 0, 0, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %v require %v", outputLength, totalSize)
  250. }
  251. start = int(bigOffsetEnd.Uint64())
  252. length = int(lengthBig.Uint64())
  253. return
  254. }
  255. // tuplePointsTo resolves the location reference for dynamic tuple.
  256. func tuplePointsTo(index int, output []byte) (start int, err error) {
  257. offset := big.NewInt(0).SetBytes(output[index : index+32])
  258. outputLen := big.NewInt(int64(len(output)))
  259. if offset.Cmp(big.NewInt(int64(len(output)))) > 0 {
  260. return 0, fmt.Errorf("abi: cannot marshal in to go slice: offset %v would go over slice boundary (len=%v)", offset, outputLen)
  261. }
  262. if offset.BitLen() > 63 {
  263. return 0, fmt.Errorf("abi offset larger than int64: %v", offset)
  264. }
  265. return int(offset.Uint64()), nil
  266. }