argument.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. type ArgumentMarshaling struct {
  32. Name string
  33. Type string
  34. InternalType string
  35. Components []ArgumentMarshaling
  36. Indexed bool
  37. }
  38. // UnmarshalJSON implements json.Unmarshaler interface
  39. func (argument *Argument) UnmarshalJSON(data []byte) error {
  40. var arg ArgumentMarshaling
  41. err := json.Unmarshal(data, &arg)
  42. if err != nil {
  43. return fmt.Errorf("argument json err: %v", err)
  44. }
  45. argument.Type, err = NewType(arg.Type, arg.InternalType, arg.Components)
  46. if err != nil {
  47. return err
  48. }
  49. argument.Name = arg.Name
  50. argument.Indexed = arg.Indexed
  51. return nil
  52. }
  53. // NonIndexed returns the arguments with indexed arguments filtered out
  54. func (arguments Arguments) NonIndexed() Arguments {
  55. var ret []Argument
  56. for _, arg := range arguments {
  57. if !arg.Indexed {
  58. ret = append(ret, arg)
  59. }
  60. }
  61. return ret
  62. }
  63. // isTuple returns true for non-atomic constructs, like (uint,uint) or uint[]
  64. func (arguments Arguments) isTuple() bool {
  65. return len(arguments) > 1
  66. }
  67. // Unpack performs the operation hexdata -> Go format
  68. func (arguments Arguments) Unpack(v interface{}, data []byte) error {
  69. if len(data) == 0 {
  70. if len(arguments) != 0 {
  71. return fmt.Errorf("abi: attempting to unmarshall an empty string while arguments are expected")
  72. }
  73. return nil // Nothing to unmarshal, return
  74. }
  75. // make sure the passed value is arguments pointer
  76. if reflect.Ptr != reflect.ValueOf(v).Kind() {
  77. return fmt.Errorf("abi: Unpack(non-pointer %T)", v)
  78. }
  79. marshalledValues, err := arguments.UnpackValues(data)
  80. if err != nil {
  81. return err
  82. }
  83. if len(marshalledValues) == 0 {
  84. return fmt.Errorf("abi: Unpack(no-values unmarshalled %T)", v)
  85. }
  86. if arguments.isTuple() {
  87. return arguments.unpackTuple(v, marshalledValues)
  88. }
  89. return arguments.unpackAtomic(v, marshalledValues[0])
  90. }
  91. // UnpackIntoMap performs the operation hexdata -> mapping of argument name to argument value
  92. func (arguments Arguments) UnpackIntoMap(v map[string]interface{}, data []byte) error {
  93. // Make sure map is not nil
  94. if v == nil {
  95. return fmt.Errorf("abi: cannot unpack into a nil map")
  96. }
  97. if len(data) == 0 {
  98. if len(arguments) != 0 {
  99. return fmt.Errorf("abi: attempting to unmarshall an empty string while arguments are expected")
  100. }
  101. return nil // Nothing to unmarshal, return
  102. }
  103. marshalledValues, err := arguments.UnpackValues(data)
  104. if err != nil {
  105. return err
  106. }
  107. for i, arg := range arguments.NonIndexed() {
  108. v[arg.Name] = marshalledValues[i]
  109. }
  110. return nil
  111. }
  112. // unpack sets the unmarshalled value to go format.
  113. // Note the dst here must be settable.
  114. func unpack(t *Type, dst interface{}, src interface{}) error {
  115. var (
  116. dstVal = reflect.ValueOf(dst).Elem()
  117. srcVal = reflect.ValueOf(src)
  118. )
  119. tuple, typ := false, t
  120. for {
  121. if typ.T == SliceTy || typ.T == ArrayTy {
  122. typ = typ.Elem
  123. continue
  124. }
  125. tuple = typ.T == TupleTy
  126. break
  127. }
  128. if !tuple {
  129. return set(dstVal, srcVal)
  130. }
  131. // Dereferences interface or pointer wrapper
  132. dstVal = indirectInterfaceOrPtr(dstVal)
  133. switch t.T {
  134. case TupleTy:
  135. if dstVal.Kind() != reflect.Struct {
  136. return fmt.Errorf("abi: invalid dst value for unpack, want struct, got %s", dstVal.Kind())
  137. }
  138. fieldmap, err := mapArgNamesToStructFields(t.TupleRawNames, dstVal)
  139. if err != nil {
  140. return err
  141. }
  142. for i, elem := range t.TupleElems {
  143. fname := fieldmap[t.TupleRawNames[i]]
  144. field := dstVal.FieldByName(fname)
  145. if !field.IsValid() {
  146. return fmt.Errorf("abi: field %s can't found in the given value", t.TupleRawNames[i])
  147. }
  148. if err := unpack(elem, field.Addr().Interface(), srcVal.Field(i).Interface()); err != nil {
  149. return err
  150. }
  151. }
  152. return nil
  153. case SliceTy:
  154. if dstVal.Kind() != reflect.Slice {
  155. return fmt.Errorf("abi: invalid dst value for unpack, want slice, got %s", dstVal.Kind())
  156. }
  157. slice := reflect.MakeSlice(dstVal.Type(), srcVal.Len(), srcVal.Len())
  158. for i := 0; i < slice.Len(); i++ {
  159. if err := unpack(t.Elem, slice.Index(i).Addr().Interface(), srcVal.Index(i).Interface()); err != nil {
  160. return err
  161. }
  162. }
  163. dstVal.Set(slice)
  164. case ArrayTy:
  165. if dstVal.Kind() != reflect.Array {
  166. return fmt.Errorf("abi: invalid dst value for unpack, want array, got %s", dstVal.Kind())
  167. }
  168. array := reflect.New(dstVal.Type()).Elem()
  169. for i := 0; i < array.Len(); i++ {
  170. if err := unpack(t.Elem, array.Index(i).Addr().Interface(), srcVal.Index(i).Interface()); err != nil {
  171. return err
  172. }
  173. }
  174. dstVal.Set(array)
  175. }
  176. return nil
  177. }
  178. // unpackAtomic unpacks ( hexdata -> go ) a single value
  179. func (arguments Arguments) unpackAtomic(v interface{}, marshalledValues interface{}) error {
  180. nonIndexedArgs := arguments.NonIndexed()
  181. if len(nonIndexedArgs) == 0 {
  182. return nil
  183. }
  184. argument := nonIndexedArgs[0]
  185. elem := reflect.ValueOf(v).Elem()
  186. if elem.Kind() == reflect.Struct && argument.Type.T != TupleTy {
  187. fieldmap, err := mapArgNamesToStructFields([]string{argument.Name}, elem)
  188. if err != nil {
  189. return err
  190. }
  191. field := elem.FieldByName(fieldmap[argument.Name])
  192. if !field.IsValid() {
  193. return fmt.Errorf("abi: field %s can't be found in the given value", argument.Name)
  194. }
  195. return unpack(&argument.Type, field.Addr().Interface(), marshalledValues)
  196. }
  197. return unpack(&argument.Type, elem.Addr().Interface(), marshalledValues)
  198. }
  199. // unpackTuple unpacks ( hexdata -> go ) a batch of values.
  200. func (arguments Arguments) unpackTuple(v interface{}, marshalledValues []interface{}) error {
  201. var (
  202. value = reflect.ValueOf(v).Elem()
  203. typ = value.Type()
  204. kind = value.Kind()
  205. nonIndexedArgs = arguments.NonIndexed()
  206. )
  207. if err := requireUnpackKind(value, len(nonIndexedArgs), arguments); err != nil {
  208. return err
  209. }
  210. // If the interface is a struct, get of abi->struct_field mapping
  211. var abi2struct map[string]string
  212. if kind == reflect.Struct {
  213. argNames := make([]string, len(nonIndexedArgs))
  214. for i, arg := range nonIndexedArgs {
  215. argNames[i] = arg.Name
  216. }
  217. var err error
  218. if abi2struct, err = mapArgNamesToStructFields(argNames, value); err != nil {
  219. return err
  220. }
  221. }
  222. for i, arg := range nonIndexedArgs {
  223. switch kind {
  224. case reflect.Struct:
  225. field := value.FieldByName(abi2struct[arg.Name])
  226. if !field.IsValid() {
  227. return fmt.Errorf("abi: field %s can't be found in the given value", arg.Name)
  228. }
  229. if err := unpack(&arg.Type, field.Addr().Interface(), marshalledValues[i]); err != nil {
  230. return err
  231. }
  232. case reflect.Slice, reflect.Array:
  233. if value.Len() < i {
  234. return fmt.Errorf("abi: insufficient number of arguments for unpack, want %d, got %d", len(arguments), value.Len())
  235. }
  236. v := value.Index(i)
  237. if err := requireAssignable(v, reflect.ValueOf(marshalledValues[i])); err != nil {
  238. return err
  239. }
  240. if err := unpack(&arg.Type, v.Addr().Interface(), marshalledValues[i]); err != nil {
  241. return err
  242. }
  243. default:
  244. return fmt.Errorf("abi:[2] cannot unmarshal tuple in to %v", typ)
  245. }
  246. }
  247. return nil
  248. }
  249. // UnpackValues can be used to unpack ABI-encoded hexdata according to the ABI-specification,
  250. // without supplying a struct to unpack into. Instead, this method returns a list containing the
  251. // values. An atomic argument will be a list with one element.
  252. func (arguments Arguments) UnpackValues(data []byte) ([]interface{}, error) {
  253. nonIndexedArgs := arguments.NonIndexed()
  254. retval := make([]interface{}, 0, len(nonIndexedArgs))
  255. virtualArgs := 0
  256. for index, arg := range nonIndexedArgs {
  257. marshalledValue, err := toGoType((index+virtualArgs)*32, arg.Type, data)
  258. if arg.Type.T == ArrayTy && !isDynamicType(arg.Type) {
  259. // If we have a static array, like [3]uint256, these are coded as
  260. // just like uint256,uint256,uint256.
  261. // This means that we need to add two 'virtual' arguments when
  262. // we count the index from now on.
  263. //
  264. // Array values nested multiple levels deep are also encoded inline:
  265. // [2][3]uint256: uint256,uint256,uint256,uint256,uint256,uint256
  266. //
  267. // Calculate the full array size to get the correct offset for the next argument.
  268. // Decrement it by 1, as the normal index increment is still applied.
  269. virtualArgs += getTypeSize(arg.Type)/32 - 1
  270. } else if arg.Type.T == TupleTy && !isDynamicType(arg.Type) {
  271. // If we have a static tuple, like (uint256, bool, uint256), these are
  272. // coded as just like uint256,bool,uint256
  273. virtualArgs += getTypeSize(arg.Type)/32 - 1
  274. }
  275. if err != nil {
  276. return nil, err
  277. }
  278. retval = append(retval, marshalledValue)
  279. }
  280. return retval, nil
  281. }
  282. // PackValues performs the operation Go format -> Hexdata
  283. // It is the semantic opposite of UnpackValues
  284. func (arguments Arguments) PackValues(args []interface{}) ([]byte, error) {
  285. return arguments.Pack(args...)
  286. }
  287. // Pack performs the operation Go format -> Hexdata
  288. func (arguments Arguments) Pack(args ...interface{}) ([]byte, error) {
  289. // Make sure arguments match up and pack them
  290. abiArgs := arguments
  291. if len(args) != len(abiArgs) {
  292. return nil, fmt.Errorf("argument count mismatch: got %d for %d", len(args), len(abiArgs))
  293. }
  294. // variable input is the output appended at the end of packed
  295. // output. This is used for strings and bytes types input.
  296. var variableInput []byte
  297. // input offset is the bytes offset for packed output
  298. inputOffset := 0
  299. for _, abiArg := range abiArgs {
  300. inputOffset += getTypeSize(abiArg.Type)
  301. }
  302. var ret []byte
  303. for i, a := range args {
  304. input := abiArgs[i]
  305. // pack the input
  306. packed, err := input.Type.pack(reflect.ValueOf(a))
  307. if err != nil {
  308. return nil, err
  309. }
  310. // check for dynamic types
  311. if isDynamicType(input.Type) {
  312. // set the offset
  313. ret = append(ret, packNum(reflect.ValueOf(inputOffset))...)
  314. // calculate next offset
  315. inputOffset += len(packed)
  316. // append to variable input
  317. variableInput = append(variableInput, packed...)
  318. } else {
  319. // append the packed value to the input
  320. ret = append(ret, packed...)
  321. }
  322. }
  323. // append the variable input at the end of the packed input
  324. ret = append(ret, variableInput...)
  325. return ret, nil
  326. }
  327. // ToCamelCase converts an under-score string to a camel-case string
  328. func ToCamelCase(input string) string {
  329. parts := strings.Split(input, "_")
  330. for i, s := range parts {
  331. if len(s) > 0 {
  332. parts[i] = strings.ToUpper(s[:1]) + s[1:]
  333. }
  334. }
  335. return strings.Join(parts, "")
  336. }