unpack.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. // reads the integer based on its kind
  25. func readInteger(kind reflect.Kind, b []byte) interface{} {
  26. switch kind {
  27. case reflect.Uint8:
  28. return b[len(b)-1]
  29. case reflect.Uint16:
  30. return binary.BigEndian.Uint16(b[len(b)-2:])
  31. case reflect.Uint32:
  32. return binary.BigEndian.Uint32(b[len(b)-4:])
  33. case reflect.Uint64:
  34. return binary.BigEndian.Uint64(b[len(b)-8:])
  35. case reflect.Int8:
  36. return int8(b[len(b)-1])
  37. case reflect.Int16:
  38. return int16(binary.BigEndian.Uint16(b[len(b)-2:]))
  39. case reflect.Int32:
  40. return int32(binary.BigEndian.Uint32(b[len(b)-4:]))
  41. case reflect.Int64:
  42. return int64(binary.BigEndian.Uint64(b[len(b)-8:]))
  43. default:
  44. return new(big.Int).SetBytes(b)
  45. }
  46. }
  47. // reads a bool
  48. func readBool(word []byte) (bool, error) {
  49. for _, b := range word[:31] {
  50. if b != 0 {
  51. return false, errBadBool
  52. }
  53. }
  54. switch word[31] {
  55. case 0:
  56. return false, nil
  57. case 1:
  58. return true, nil
  59. default:
  60. return false, errBadBool
  61. }
  62. }
  63. // A function type is simply the address with the function selection signature at the end.
  64. // This enforces that standard by always presenting it as a 24-array (address + sig = 24 bytes)
  65. func readFunctionType(t Type, word []byte) (funcTy [24]byte, err error) {
  66. if t.T != FunctionTy {
  67. return [24]byte{}, fmt.Errorf("abi: invalid type in call to make function type byte array")
  68. }
  69. if garbage := binary.BigEndian.Uint64(word[24:32]); garbage != 0 {
  70. err = fmt.Errorf("abi: got improperly encoded function type, got %v", word)
  71. } else {
  72. copy(funcTy[:], word[0:24])
  73. }
  74. return
  75. }
  76. // through reflection, creates a fixed array to be read from
  77. func readFixedBytes(t Type, word []byte) (interface{}, error) {
  78. if t.T != FixedBytesTy {
  79. return nil, fmt.Errorf("abi: invalid type in call to make fixed byte array")
  80. }
  81. // convert
  82. array := reflect.New(t.Type).Elem()
  83. reflect.Copy(array, reflect.ValueOf(word[0:t.Size]))
  84. return array.Interface(), nil
  85. }
  86. func getFullElemSize(elem *Type) int {
  87. //all other should be counted as 32 (slices have pointers to respective elements)
  88. size := 32
  89. //arrays wrap it, each element being the same size
  90. for elem.T == ArrayTy {
  91. size *= elem.Size
  92. elem = elem.Elem
  93. }
  94. return size
  95. }
  96. // iteratively unpack elements
  97. func forEachUnpack(t Type, output []byte, start, size int) (interface{}, error) {
  98. if size < 0 {
  99. return nil, fmt.Errorf("cannot marshal input to array, size is negative (%d)", size)
  100. }
  101. if start+32*size > len(output) {
  102. 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)
  103. }
  104. // this value will become our slice or our array, depending on the type
  105. var refSlice reflect.Value
  106. if t.T == SliceTy {
  107. // declare our slice
  108. refSlice = reflect.MakeSlice(t.Type, size, size)
  109. } else if t.T == ArrayTy {
  110. // declare our array
  111. refSlice = reflect.New(t.Type).Elem()
  112. } else {
  113. return nil, fmt.Errorf("abi: invalid type in array/slice unpacking stage")
  114. }
  115. // Arrays have packed elements, resulting in longer unpack steps.
  116. // Slices have just 32 bytes per element (pointing to the contents).
  117. elemSize := 32
  118. if t.T == ArrayTy {
  119. elemSize = getFullElemSize(t.Elem)
  120. }
  121. for i, j := start, 0; j < size; i, j = i+elemSize, j+1 {
  122. inter, err := toGoType(i, *t.Elem, output)
  123. if err != nil {
  124. return nil, err
  125. }
  126. // append the item to our reflect slice
  127. refSlice.Index(j).Set(reflect.ValueOf(inter))
  128. }
  129. // return the interface
  130. return refSlice.Interface(), nil
  131. }
  132. // toGoType parses the output bytes and recursively assigns the value of these bytes
  133. // into a go type with accordance with the ABI spec.
  134. func toGoType(index int, t Type, output []byte) (interface{}, error) {
  135. if index+32 > len(output) {
  136. return nil, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %d require %d", len(output), index+32)
  137. }
  138. var (
  139. returnOutput []byte
  140. begin, end int
  141. err error
  142. )
  143. // if we require a length prefix, find the beginning word and size returned.
  144. if t.requiresLengthPrefix() {
  145. begin, end, err = lengthPrefixPointsTo(index, output)
  146. if err != nil {
  147. return nil, err
  148. }
  149. } else {
  150. returnOutput = output[index : index+32]
  151. }
  152. switch t.T {
  153. case SliceTy:
  154. return forEachUnpack(t, output, begin, end)
  155. case ArrayTy:
  156. return forEachUnpack(t, output, index, t.Size)
  157. case StringTy: // variable arrays are written at the end of the return bytes
  158. return string(output[begin : begin+end]), nil
  159. case IntTy, UintTy:
  160. return readInteger(t.Kind, returnOutput), nil
  161. case BoolTy:
  162. return readBool(returnOutput)
  163. case AddressTy:
  164. return common.BytesToAddress(returnOutput), nil
  165. case HashTy:
  166. return common.BytesToHash(returnOutput), nil
  167. case BytesTy:
  168. return output[begin : begin+end], nil
  169. case FixedBytesTy:
  170. return readFixedBytes(t, returnOutput)
  171. case FunctionTy:
  172. return readFunctionType(t, returnOutput)
  173. default:
  174. return nil, fmt.Errorf("abi: unknown type %v", t.T)
  175. }
  176. }
  177. // interprets a 32 byte slice as an offset and then determines which indice to look to decode the type.
  178. func lengthPrefixPointsTo(index int, output []byte) (start int, length int, err error) {
  179. bigOffsetEnd := big.NewInt(0).SetBytes(output[index : index+32])
  180. bigOffsetEnd.Add(bigOffsetEnd, common.Big32)
  181. outputLength := big.NewInt(int64(len(output)))
  182. if bigOffsetEnd.Cmp(outputLength) > 0 {
  183. return 0, 0, fmt.Errorf("abi: cannot marshal in to go slice: offset %v would go over slice boundary (len=%v)", bigOffsetEnd, outputLength)
  184. }
  185. if bigOffsetEnd.BitLen() > 63 {
  186. return 0, 0, fmt.Errorf("abi offset larger than int64: %v", bigOffsetEnd)
  187. }
  188. offsetEnd := int(bigOffsetEnd.Uint64())
  189. lengthBig := big.NewInt(0).SetBytes(output[offsetEnd-32 : offsetEnd])
  190. totalSize := big.NewInt(0)
  191. totalSize.Add(totalSize, bigOffsetEnd)
  192. totalSize.Add(totalSize, lengthBig)
  193. if totalSize.BitLen() > 63 {
  194. return 0, 0, fmt.Errorf("abi length larger than int64: %v", totalSize)
  195. }
  196. if totalSize.Cmp(outputLength) > 0 {
  197. return 0, 0, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %v require %v", outputLength, totalSize)
  198. }
  199. start = int(bigOffsetEnd.Uint64())
  200. length = int(lengthBig.Uint64())
  201. return
  202. }