argument.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. "errors"
  20. "fmt"
  21. "reflect"
  22. "strings"
  23. )
  24. // Argument holds the name of the argument and the corresponding type.
  25. // Types are used when packing and testing arguments.
  26. type Argument struct {
  27. Name string
  28. Type Type
  29. Indexed bool // indexed is only used by events
  30. }
  31. type Arguments []Argument
  32. type ArgumentMarshaling struct {
  33. Name string
  34. Type string
  35. InternalType string
  36. Components []ArgumentMarshaling
  37. Indexed bool
  38. }
  39. // UnmarshalJSON implements json.Unmarshaler interface.
  40. func (argument *Argument) UnmarshalJSON(data []byte) error {
  41. var arg ArgumentMarshaling
  42. err := json.Unmarshal(data, &arg)
  43. if err != nil {
  44. return fmt.Errorf("argument json err: %v", err)
  45. }
  46. argument.Type, err = NewType(arg.Type, arg.InternalType, arg.Components)
  47. if err != nil {
  48. return err
  49. }
  50. argument.Name = arg.Name
  51. argument.Indexed = arg.Indexed
  52. return nil
  53. }
  54. // NonIndexed returns the arguments with indexed arguments filtered out.
  55. func (arguments Arguments) NonIndexed() Arguments {
  56. var ret []Argument
  57. for _, arg := range arguments {
  58. if !arg.Indexed {
  59. ret = append(ret, arg)
  60. }
  61. }
  62. return ret
  63. }
  64. // isTuple returns true for non-atomic constructs, like (uint,uint) or uint[].
  65. func (arguments Arguments) isTuple() bool {
  66. return len(arguments) > 1
  67. }
  68. // Unpack performs the operation hexdata -> Go format.
  69. func (arguments Arguments) Unpack(data []byte) ([]interface{}, error) {
  70. if len(data) == 0 {
  71. if len(arguments.NonIndexed()) != 0 {
  72. return nil, errors.New("abi: attempting to unmarshall an empty string while arguments are expected")
  73. }
  74. return make([]interface{}, 0), nil
  75. }
  76. return arguments.UnpackValues(data)
  77. }
  78. // UnpackIntoMap performs the operation hexdata -> mapping of argument name to argument value.
  79. func (arguments Arguments) UnpackIntoMap(v map[string]interface{}, data []byte) error {
  80. // Make sure map is not nil
  81. if v == nil {
  82. return errors.New("abi: cannot unpack into a nil map")
  83. }
  84. if len(data) == 0 {
  85. if len(arguments.NonIndexed()) != 0 {
  86. return errors.New("abi: attempting to unmarshall an empty string while arguments are expected")
  87. }
  88. return nil // Nothing to unmarshal, return
  89. }
  90. marshalledValues, err := arguments.UnpackValues(data)
  91. if err != nil {
  92. return err
  93. }
  94. for i, arg := range arguments.NonIndexed() {
  95. v[arg.Name] = marshalledValues[i]
  96. }
  97. return nil
  98. }
  99. // Copy performs the operation go format -> provided struct.
  100. func (arguments Arguments) Copy(v interface{}, values []interface{}) error {
  101. // make sure the passed value is arguments pointer
  102. if reflect.Ptr != reflect.ValueOf(v).Kind() {
  103. return fmt.Errorf("abi: Unpack(non-pointer %T)", v)
  104. }
  105. if len(values) == 0 {
  106. if len(arguments.NonIndexed()) != 0 {
  107. return errors.New("abi: attempting to copy no values while arguments are expected")
  108. }
  109. return nil // Nothing to copy, return
  110. }
  111. if arguments.isTuple() {
  112. return arguments.copyTuple(v, values)
  113. }
  114. return arguments.copyAtomic(v, values[0])
  115. }
  116. // unpackAtomic unpacks ( hexdata -> go ) a single value
  117. func (arguments Arguments) copyAtomic(v interface{}, marshalledValues interface{}) error {
  118. dst := reflect.ValueOf(v).Elem()
  119. src := reflect.ValueOf(marshalledValues)
  120. if dst.Kind() == reflect.Struct {
  121. return set(dst.Field(0), src)
  122. }
  123. return set(dst, src)
  124. }
  125. // copyTuple copies a batch of values from marshalledValues to v.
  126. func (arguments Arguments) copyTuple(v interface{}, marshalledValues []interface{}) error {
  127. value := reflect.ValueOf(v).Elem()
  128. nonIndexedArgs := arguments.NonIndexed()
  129. switch value.Kind() {
  130. case reflect.Struct:
  131. argNames := make([]string, len(nonIndexedArgs))
  132. for i, arg := range nonIndexedArgs {
  133. argNames[i] = arg.Name
  134. }
  135. var err error
  136. abi2struct, err := mapArgNamesToStructFields(argNames, value)
  137. if err != nil {
  138. return err
  139. }
  140. for i, arg := range nonIndexedArgs {
  141. field := value.FieldByName(abi2struct[arg.Name])
  142. if !field.IsValid() {
  143. return fmt.Errorf("abi: field %s can't be found in the given value", arg.Name)
  144. }
  145. if err := set(field, reflect.ValueOf(marshalledValues[i])); err != nil {
  146. return err
  147. }
  148. }
  149. case reflect.Slice, reflect.Array:
  150. if value.Len() < len(marshalledValues) {
  151. return fmt.Errorf("abi: insufficient number of arguments for unpack, want %d, got %d", len(arguments), value.Len())
  152. }
  153. for i := range nonIndexedArgs {
  154. if err := set(value.Index(i), reflect.ValueOf(marshalledValues[i])); err != nil {
  155. return err
  156. }
  157. }
  158. default:
  159. return fmt.Errorf("abi:[2] cannot unmarshal tuple in to %v", value.Type())
  160. }
  161. return nil
  162. }
  163. // UnpackValues can be used to unpack ABI-encoded hexdata according to the ABI-specification,
  164. // without supplying a struct to unpack into. Instead, this method returns a list containing the
  165. // values. An atomic argument will be a list with one element.
  166. func (arguments Arguments) UnpackValues(data []byte) ([]interface{}, error) {
  167. nonIndexedArgs := arguments.NonIndexed()
  168. retval := make([]interface{}, 0, len(nonIndexedArgs))
  169. virtualArgs := 0
  170. for index, arg := range nonIndexedArgs {
  171. marshalledValue, err := toGoType((index+virtualArgs)*32, arg.Type, data)
  172. if arg.Type.T == ArrayTy && !isDynamicType(arg.Type) {
  173. // If we have a static array, like [3]uint256, these are coded as
  174. // just like uint256,uint256,uint256.
  175. // This means that we need to add two 'virtual' arguments when
  176. // we count the index from now on.
  177. //
  178. // Array values nested multiple levels deep are also encoded inline:
  179. // [2][3]uint256: uint256,uint256,uint256,uint256,uint256,uint256
  180. //
  181. // Calculate the full array size to get the correct offset for the next argument.
  182. // Decrement it by 1, as the normal index increment is still applied.
  183. virtualArgs += getTypeSize(arg.Type)/32 - 1
  184. } else if arg.Type.T == TupleTy && !isDynamicType(arg.Type) {
  185. // If we have a static tuple, like (uint256, bool, uint256), these are
  186. // coded as just like uint256,bool,uint256
  187. virtualArgs += getTypeSize(arg.Type)/32 - 1
  188. }
  189. if err != nil {
  190. return nil, err
  191. }
  192. retval = append(retval, marshalledValue)
  193. }
  194. return retval, nil
  195. }
  196. // PackValues performs the operation Go format -> Hexdata.
  197. // It is the semantic opposite of UnpackValues.
  198. func (arguments Arguments) PackValues(args []interface{}) ([]byte, error) {
  199. return arguments.Pack(args...)
  200. }
  201. // Pack performs the operation Go format -> Hexdata.
  202. func (arguments Arguments) Pack(args ...interface{}) ([]byte, error) {
  203. // Make sure arguments match up and pack them
  204. abiArgs := arguments
  205. if len(args) != len(abiArgs) {
  206. return nil, fmt.Errorf("argument count mismatch: got %d for %d", len(args), len(abiArgs))
  207. }
  208. // variable input is the output appended at the end of packed
  209. // output. This is used for strings and bytes types input.
  210. var variableInput []byte
  211. // input offset is the bytes offset for packed output
  212. inputOffset := 0
  213. for _, abiArg := range abiArgs {
  214. inputOffset += getTypeSize(abiArg.Type)
  215. }
  216. var ret []byte
  217. for i, a := range args {
  218. input := abiArgs[i]
  219. // pack the input
  220. packed, err := input.Type.pack(reflect.ValueOf(a))
  221. if err != nil {
  222. return nil, err
  223. }
  224. // check for dynamic types
  225. if isDynamicType(input.Type) {
  226. // set the offset
  227. ret = append(ret, packNum(reflect.ValueOf(inputOffset))...)
  228. // calculate next offset
  229. inputOffset += len(packed)
  230. // append to variable input
  231. variableInput = append(variableInput, packed...)
  232. } else {
  233. // append the packed value to the input
  234. ret = append(ret, packed...)
  235. }
  236. }
  237. // append the variable input at the end of the packed input
  238. ret = append(ret, variableInput...)
  239. return ret, nil
  240. }
  241. // ToCamelCase converts an under-score string to a camel-case string
  242. func ToCamelCase(input string) string {
  243. parts := strings.Split(input, "_")
  244. for i, s := range parts {
  245. if len(s) > 0 {
  246. parts[i] = strings.ToUpper(s[:1]) + s[1:]
  247. }
  248. }
  249. return strings.Join(parts, "")
  250. }