unpack.go 6.4 KB

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