argument.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 interface is a struct, get of abi->struct_field mapping
  100. var abi2struct map[string]string
  101. if kind == reflect.Struct {
  102. var err error
  103. abi2struct, err = mapAbiToStructFields(arguments, value)
  104. if err != nil {
  105. return err
  106. }
  107. }
  108. for i, arg := range arguments.NonIndexed() {
  109. reflectValue := reflect.ValueOf(marshalledValues[i])
  110. switch kind {
  111. case reflect.Struct:
  112. if structField, ok := abi2struct[arg.Name]; ok {
  113. if err := set(value.FieldByName(structField), reflectValue, arg); err != nil {
  114. return err
  115. }
  116. }
  117. case reflect.Slice, reflect.Array:
  118. if value.Len() < i {
  119. return fmt.Errorf("abi: insufficient number of arguments for unpack, want %d, got %d", len(arguments), value.Len())
  120. }
  121. v := value.Index(i)
  122. if err := requireAssignable(v, reflectValue); err != nil {
  123. return err
  124. }
  125. if err := set(v.Elem(), reflectValue, arg); err != nil {
  126. return err
  127. }
  128. default:
  129. return fmt.Errorf("abi:[2] cannot unmarshal tuple in to %v", typ)
  130. }
  131. }
  132. return nil
  133. }
  134. // unpackAtomic unpacks ( hexdata -> go ) a single value
  135. func (arguments Arguments) unpackAtomic(v interface{}, marshalledValues []interface{}) error {
  136. if len(marshalledValues) != 1 {
  137. return fmt.Errorf("abi: wrong length, expected single value, got %d", len(marshalledValues))
  138. }
  139. elem := reflect.ValueOf(v).Elem()
  140. kind := elem.Kind()
  141. reflectValue := reflect.ValueOf(marshalledValues[0])
  142. var abi2struct map[string]string
  143. if kind == reflect.Struct {
  144. var err error
  145. if abi2struct, err = mapAbiToStructFields(arguments, elem); err != nil {
  146. return err
  147. }
  148. arg := arguments.NonIndexed()[0]
  149. if structField, ok := abi2struct[arg.Name]; ok {
  150. return set(elem.FieldByName(structField), reflectValue, arg)
  151. }
  152. return nil
  153. }
  154. return set(elem, reflectValue, arguments.NonIndexed()[0])
  155. }
  156. // Computes the full size of an array;
  157. // i.e. counting nested arrays, which count towards size for unpacking.
  158. func getArraySize(arr *Type) int {
  159. size := arr.Size
  160. // Arrays can be nested, with each element being the same size
  161. arr = arr.Elem
  162. for arr.T == ArrayTy {
  163. // Keep multiplying by elem.Size while the elem is an array.
  164. size *= arr.Size
  165. arr = arr.Elem
  166. }
  167. // Now we have the full array size, including its children.
  168. return size
  169. }
  170. // UnpackValues can be used to unpack ABI-encoded hexdata according to the ABI-specification,
  171. // without supplying a struct to unpack into. Instead, this method returns a list containing the
  172. // values. An atomic argument will be a list with one element.
  173. func (arguments Arguments) UnpackValues(data []byte) ([]interface{}, error) {
  174. retval := make([]interface{}, 0, arguments.LengthNonIndexed())
  175. virtualArgs := 0
  176. for index, arg := range arguments.NonIndexed() {
  177. marshalledValue, err := toGoType((index+virtualArgs)*32, arg.Type, data)
  178. if arg.Type.T == ArrayTy && (*arg.Type.Elem).T != StringTy {
  179. // If we have a static array, like [3]uint256, these are coded as
  180. // just like uint256,uint256,uint256.
  181. // This means that we need to add two 'virtual' arguments when
  182. // we count the index from now on.
  183. //
  184. // Array values nested multiple levels deep are also encoded inline:
  185. // [2][3]uint256: uint256,uint256,uint256,uint256,uint256,uint256
  186. //
  187. // Calculate the full array size to get the correct offset for the next argument.
  188. // Decrement it by 1, as the normal index increment is still applied.
  189. virtualArgs += getArraySize(&arg.Type) - 1
  190. }
  191. if err != nil {
  192. return nil, err
  193. }
  194. retval = append(retval, marshalledValue)
  195. }
  196. return retval, nil
  197. }
  198. // PackValues performs the operation Go format -> Hexdata
  199. // It is the semantic opposite of UnpackValues
  200. func (arguments Arguments) PackValues(args []interface{}) ([]byte, error) {
  201. return arguments.Pack(args...)
  202. }
  203. // Pack performs the operation Go format -> Hexdata
  204. func (arguments Arguments) Pack(args ...interface{}) ([]byte, error) {
  205. // Make sure arguments match up and pack them
  206. abiArgs := arguments
  207. if len(args) != len(abiArgs) {
  208. return nil, fmt.Errorf("argument count mismatch: %d for %d", len(args), len(abiArgs))
  209. }
  210. // variable input is the output appended at the end of packed
  211. // output. This is used for strings and bytes types input.
  212. var variableInput []byte
  213. // input offset is the bytes offset for packed output
  214. inputOffset := 0
  215. for _, abiArg := range abiArgs {
  216. inputOffset += getDynamicTypeOffset(abiArg.Type)
  217. }
  218. var ret []byte
  219. for i, a := range args {
  220. input := abiArgs[i]
  221. // pack the input
  222. packed, err := input.Type.pack(reflect.ValueOf(a))
  223. if err != nil {
  224. return nil, err
  225. }
  226. // check for dynamic types
  227. if isDynamicType(input.Type) {
  228. // set the offset
  229. ret = append(ret, packNum(reflect.ValueOf(inputOffset))...)
  230. // calculate next offset
  231. inputOffset += len(packed)
  232. // append to variable input
  233. variableInput = append(variableInput, packed...)
  234. } else {
  235. // append the packed value to the input
  236. ret = append(ret, packed...)
  237. }
  238. }
  239. // append the variable input at the end of the packed input
  240. ret = append(ret, variableInput...)
  241. return ret, nil
  242. }
  243. // ToCamelCase converts an under-score string to a camel-case string
  244. func ToCamelCase(input string) string {
  245. parts := strings.Split(input, "_")
  246. for i, s := range parts {
  247. if len(s) > 0 {
  248. parts[i] = strings.ToUpper(s[:1]) + s[1:]
  249. }
  250. }
  251. return strings.Join(parts, "")
  252. }