unpack.go 9.5 KB

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