argument.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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/json"
  19. "fmt"
  20. "reflect"
  21. "strings"
  22. )
  23. // Argument holds the name of the argument and the corresponding type.
  24. // Types are used when packing and testing arguments.
  25. type Argument struct {
  26. Name string
  27. Type Type
  28. Indexed bool // indexed is only used by events
  29. }
  30. type Arguments []Argument
  31. // UnmarshalJSON implements json.Unmarshaler interface
  32. func (argument *Argument) UnmarshalJSON(data []byte) error {
  33. var extarg struct {
  34. Name string
  35. Type string
  36. Indexed bool
  37. }
  38. err := json.Unmarshal(data, &extarg)
  39. if err != nil {
  40. return fmt.Errorf("argument json err: %v", err)
  41. }
  42. argument.Type, err = NewType(extarg.Type)
  43. if err != nil {
  44. return err
  45. }
  46. argument.Name = extarg.Name
  47. argument.Indexed = extarg.Indexed
  48. return nil
  49. }
  50. // LengthNonIndexed returns the number of arguments when not counting 'indexed' ones. Only events
  51. // can ever have 'indexed' arguments, it should always be false on arguments for method input/output
  52. func (arguments Arguments) LengthNonIndexed() int {
  53. out := 0
  54. for _, arg := range arguments {
  55. if !arg.Indexed {
  56. out++
  57. }
  58. }
  59. return out
  60. }
  61. // NonIndexed returns the arguments with indexed arguments filtered out
  62. func (arguments Arguments) NonIndexed() Arguments {
  63. var ret []Argument
  64. for _, arg := range arguments {
  65. if !arg.Indexed {
  66. ret = append(ret, arg)
  67. }
  68. }
  69. return ret
  70. }
  71. // isTuple returns true for non-atomic constructs, like (uint,uint) or uint[]
  72. func (arguments Arguments) isTuple() bool {
  73. return len(arguments) > 1
  74. }
  75. // Unpack performs the operation hexdata -> Go format
  76. func (arguments Arguments) Unpack(v interface{}, data []byte) error {
  77. // make sure the passed value is arguments pointer
  78. if reflect.Ptr != reflect.ValueOf(v).Kind() {
  79. return fmt.Errorf("abi: Unpack(non-pointer %T)", v)
  80. }
  81. marshalledValues, err := arguments.UnpackValues(data)
  82. if err != nil {
  83. return err
  84. }
  85. if arguments.isTuple() {
  86. return arguments.unpackTuple(v, marshalledValues)
  87. }
  88. return arguments.unpackAtomic(v, marshalledValues)
  89. }
  90. func (arguments Arguments) unpackTuple(v interface{}, marshalledValues []interface{}) error {
  91. var (
  92. value = reflect.ValueOf(v).Elem()
  93. typ = value.Type()
  94. kind = value.Kind()
  95. )
  96. if err := requireUnpackKind(value, typ, kind, arguments); err != nil {
  97. return err
  98. }
  99. // If the output interface is a struct, make sure names don't collide
  100. if kind == reflect.Struct {
  101. exists := make(map[string]bool)
  102. for _, arg := range arguments {
  103. field := capitalise(arg.Name)
  104. if field == "" {
  105. return fmt.Errorf("abi: purely underscored output cannot unpack to struct")
  106. }
  107. if exists[field] {
  108. return fmt.Errorf("abi: multiple outputs mapping to the same struct field '%s'", field)
  109. }
  110. exists[field] = true
  111. }
  112. }
  113. for i, arg := range arguments.NonIndexed() {
  114. reflectValue := reflect.ValueOf(marshalledValues[i])
  115. switch kind {
  116. case reflect.Struct:
  117. name := capitalise(arg.Name)
  118. for j := 0; j < typ.NumField(); j++ {
  119. // TODO read tags: `abi:"fieldName"`
  120. if typ.Field(j).Name == name {
  121. if err := set(value.Field(j), reflectValue, arg); err != nil {
  122. return err
  123. }
  124. }
  125. }
  126. case reflect.Slice, reflect.Array:
  127. if value.Len() < i {
  128. return fmt.Errorf("abi: insufficient number of arguments for unpack, want %d, got %d", len(arguments), value.Len())
  129. }
  130. v := value.Index(i)
  131. if err := requireAssignable(v, reflectValue); err != nil {
  132. return err
  133. }
  134. if err := set(v.Elem(), reflectValue, arg); err != nil {
  135. return err
  136. }
  137. default:
  138. return fmt.Errorf("abi:[2] cannot unmarshal tuple in to %v", typ)
  139. }
  140. }
  141. return nil
  142. }
  143. // unpackAtomic unpacks ( hexdata -> go ) a single value
  144. func (arguments Arguments) unpackAtomic(v interface{}, marshalledValues []interface{}) error {
  145. if len(marshalledValues) != 1 {
  146. return fmt.Errorf("abi: wrong length, expected single value, got %d", len(marshalledValues))
  147. }
  148. elem := reflect.ValueOf(v).Elem()
  149. reflectValue := reflect.ValueOf(marshalledValues[0])
  150. return set(elem, reflectValue, arguments.NonIndexed()[0])
  151. }
  152. // UnpackValues can be used to unpack ABI-encoded hexdata according to the ABI-specification,
  153. // without supplying a struct to unpack into. Instead, this method returns a list containing the
  154. // values. An atomic argument will be a list with one element.
  155. func (arguments Arguments) UnpackValues(data []byte) ([]interface{}, error) {
  156. retval := make([]interface{}, 0, arguments.LengthNonIndexed())
  157. virtualArgs := 0
  158. for index, arg := range arguments.NonIndexed() {
  159. marshalledValue, err := toGoType((index+virtualArgs)*32, arg.Type, data)
  160. if arg.Type.T == ArrayTy {
  161. // If we have a static array, like [3]uint256, these are coded as
  162. // just like uint256,uint256,uint256.
  163. // This means that we need to add two 'virtual' arguments when
  164. // we count the index from now on
  165. virtualArgs += arg.Type.Size - 1
  166. }
  167. if err != nil {
  168. return nil, err
  169. }
  170. retval = append(retval, marshalledValue)
  171. }
  172. return retval, nil
  173. }
  174. // PackValues performs the operation Go format -> Hexdata
  175. // It is the semantic opposite of UnpackValues
  176. func (arguments Arguments) PackValues(args []interface{}) ([]byte, error) {
  177. return arguments.Pack(args...)
  178. }
  179. // Pack performs the operation Go format -> Hexdata
  180. func (arguments Arguments) Pack(args ...interface{}) ([]byte, error) {
  181. // Make sure arguments match up and pack them
  182. abiArgs := arguments
  183. if len(args) != len(abiArgs) {
  184. return nil, fmt.Errorf("argument count mismatch: %d for %d", len(args), len(abiArgs))
  185. }
  186. // variable input is the output appended at the end of packed
  187. // output. This is used for strings and bytes types input.
  188. var variableInput []byte
  189. // input offset is the bytes offset for packed output
  190. inputOffset := 0
  191. for _, abiArg := range abiArgs {
  192. if abiArg.Type.T == ArrayTy {
  193. inputOffset += 32 * abiArg.Type.Size
  194. } else {
  195. inputOffset += 32
  196. }
  197. }
  198. var ret []byte
  199. for i, a := range args {
  200. input := abiArgs[i]
  201. // pack the input
  202. packed, err := input.Type.pack(reflect.ValueOf(a))
  203. if err != nil {
  204. return nil, err
  205. }
  206. // check for a slice type (string, bytes, slice)
  207. if input.Type.requiresLengthPrefix() {
  208. // calculate the offset
  209. offset := inputOffset + len(variableInput)
  210. // set the offset
  211. ret = append(ret, packNum(reflect.ValueOf(offset))...)
  212. // Append the packed output to the variable input. The variable input
  213. // will be appended at the end of the input.
  214. variableInput = append(variableInput, packed...)
  215. } else {
  216. // append the packed value to the input
  217. ret = append(ret, packed...)
  218. }
  219. }
  220. // append the variable input at the end of the packed input
  221. ret = append(ret, variableInput...)
  222. return ret, nil
  223. }
  224. // capitalise makes the first character of a string upper case, also removing any
  225. // prefixing underscores from the variable names.
  226. func capitalise(input string) string {
  227. for len(input) > 0 && input[0] == '_' {
  228. input = input[1:]
  229. }
  230. if len(input) == 0 {
  231. return ""
  232. }
  233. return strings.ToUpper(input[:1]) + input[1:]
  234. }