unpack.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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. // iteratively unpack elements
  87. func forEachUnpack(t Type, output []byte, start, size int) (interface{}, error) {
  88. if size < 0 {
  89. return nil, fmt.Errorf("cannot marshal input to array, size is negative (%d)", size)
  90. }
  91. if start+32*size > len(output) {
  92. 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)
  93. }
  94. // this value will become our slice or our array, depending on the type
  95. var refSlice reflect.Value
  96. slice := output[start : start+size*32]
  97. if t.T == SliceTy {
  98. // declare our slice
  99. refSlice = reflect.MakeSlice(t.Type, size, size)
  100. } else if t.T == ArrayTy {
  101. // declare our array
  102. refSlice = reflect.New(t.Type).Elem()
  103. } else {
  104. return nil, fmt.Errorf("abi: invalid type in array/slice unpacking stage")
  105. }
  106. for i, j := start, 0; j*32 < len(slice); i, j = i+32, j+1 {
  107. // this corrects the arrangement so that we get all the underlying array values
  108. if t.Elem.T == ArrayTy && j != 0 {
  109. i = start + t.Elem.Size*32*j
  110. }
  111. inter, err := toGoType(i, *t.Elem, output)
  112. if err != nil {
  113. return nil, err
  114. }
  115. // append the item to our reflect slice
  116. refSlice.Index(j).Set(reflect.ValueOf(inter))
  117. }
  118. // return the interface
  119. return refSlice.Interface(), nil
  120. }
  121. // toGoType parses the output bytes and recursively assigns the value of these bytes
  122. // into a go type with accordance with the ABI spec.
  123. func toGoType(index int, t Type, output []byte) (interface{}, error) {
  124. if index+32 > len(output) {
  125. return nil, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %d require %d", len(output), index+32)
  126. }
  127. var (
  128. returnOutput []byte
  129. begin, end int
  130. err error
  131. )
  132. // if we require a length prefix, find the beginning word and size returned.
  133. if t.requiresLengthPrefix() {
  134. begin, end, err = lengthPrefixPointsTo(index, output)
  135. if err != nil {
  136. return nil, err
  137. }
  138. } else {
  139. returnOutput = output[index : index+32]
  140. }
  141. switch t.T {
  142. case SliceTy:
  143. return forEachUnpack(t, output, begin, end)
  144. case ArrayTy:
  145. return forEachUnpack(t, output, index, t.Size)
  146. case StringTy: // variable arrays are written at the end of the return bytes
  147. return string(output[begin : begin+end]), nil
  148. case IntTy, UintTy:
  149. return readInteger(t.Kind, returnOutput), nil
  150. case BoolTy:
  151. return readBool(returnOutput)
  152. case AddressTy:
  153. return common.BytesToAddress(returnOutput), nil
  154. case HashTy:
  155. return common.BytesToHash(returnOutput), nil
  156. case BytesTy:
  157. return output[begin : begin+end], nil
  158. case FixedBytesTy:
  159. return readFixedBytes(t, returnOutput)
  160. case FunctionTy:
  161. return readFunctionType(t, returnOutput)
  162. default:
  163. return nil, fmt.Errorf("abi: unknown type %v", t.T)
  164. }
  165. }
  166. // interprets a 32 byte slice as an offset and then determines which indice to look to decode the type.
  167. func lengthPrefixPointsTo(index int, output []byte) (start int, length int, err error) {
  168. offsetBig := big.NewInt(0).SetBytes(output[index : index+32])
  169. if !offsetBig.IsInt64() {
  170. return 0, 0, fmt.Errorf("abi offset larger than int64: %v", offsetBig)
  171. }
  172. offset := int(offsetBig.Int64())
  173. if offset+32 > len(output) {
  174. 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)
  175. }
  176. lengthBig := big.NewInt(0).SetBytes(output[offset : offset+32])
  177. if !lengthBig.IsInt64() {
  178. return 0, 0, fmt.Errorf("abi length larger than int64: %v", lengthBig)
  179. }
  180. length = int(lengthBig.Int64())
  181. if offset+32+length > len(output) {
  182. return 0, 0, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %d require %d", len(output), offset+32+length)
  183. }
  184. start = offset + 32
  185. return
  186. }