argument.go 7.6 KB

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