argument.go 8.7 KB

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