abi.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. "bytes"
  19. "encoding/json"
  20. "errors"
  21. "fmt"
  22. "io"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/crypto"
  25. )
  26. // The ABI holds information about a contract's context and available
  27. // invokable methods. It will allow you to type check function calls and
  28. // packs data accordingly.
  29. type ABI struct {
  30. Constructor Method
  31. Methods map[string]Method
  32. Events map[string]Event
  33. Errors map[string]Error
  34. // Additional "special" functions introduced in solidity v0.6.0.
  35. // It's separated from the original default fallback. Each contract
  36. // can only define one fallback and receive function.
  37. Fallback Method // Note it's also used to represent legacy fallback before v0.6.0
  38. Receive Method
  39. }
  40. // JSON returns a parsed ABI interface and error if it failed.
  41. func JSON(reader io.Reader) (ABI, error) {
  42. dec := json.NewDecoder(reader)
  43. var abi ABI
  44. if err := dec.Decode(&abi); err != nil {
  45. return ABI{}, err
  46. }
  47. return abi, nil
  48. }
  49. // Pack the given method name to conform the ABI. Method call's data
  50. // will consist of method_id, args0, arg1, ... argN. Method id consists
  51. // of 4 bytes and arguments are all 32 bytes.
  52. // Method ids are created from the first 4 bytes of the hash of the
  53. // methods string signature. (signature = baz(uint32,string32))
  54. func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) {
  55. // Fetch the ABI of the requested method
  56. if name == "" {
  57. // constructor
  58. arguments, err := abi.Constructor.Inputs.Pack(args...)
  59. if err != nil {
  60. return nil, err
  61. }
  62. return arguments, nil
  63. }
  64. method, exist := abi.Methods[name]
  65. if !exist {
  66. return nil, fmt.Errorf("method '%s' not found", name)
  67. }
  68. arguments, err := method.Inputs.Pack(args...)
  69. if err != nil {
  70. return nil, err
  71. }
  72. // Pack up the method ID too if not a constructor and return
  73. return append(method.ID, arguments...), nil
  74. }
  75. func (abi ABI) getArguments(name string, data []byte) (Arguments, error) {
  76. // since there can't be naming collisions with contracts and events,
  77. // we need to decide whether we're calling a method or an event
  78. var args Arguments
  79. if method, ok := abi.Methods[name]; ok {
  80. if len(data)%32 != 0 {
  81. return nil, fmt.Errorf("abi: improperly formatted output: %s - Bytes: [%+v]", string(data), data)
  82. }
  83. args = method.Outputs
  84. }
  85. if event, ok := abi.Events[name]; ok {
  86. args = event.Inputs
  87. }
  88. if args == nil {
  89. return nil, fmt.Errorf("abi: could not locate named method or event: %s", name)
  90. }
  91. return args, nil
  92. }
  93. // Unpack unpacks the output according to the abi specification.
  94. func (abi ABI) Unpack(name string, data []byte) ([]interface{}, error) {
  95. args, err := abi.getArguments(name, data)
  96. if err != nil {
  97. return nil, err
  98. }
  99. return args.Unpack(data)
  100. }
  101. // UnpackIntoInterface unpacks the output in v according to the abi specification.
  102. // It performs an additional copy. Please only use, if you want to unpack into a
  103. // structure that does not strictly conform to the abi structure (e.g. has additional arguments)
  104. func (abi ABI) UnpackIntoInterface(v interface{}, name string, data []byte) error {
  105. args, err := abi.getArguments(name, data)
  106. if err != nil {
  107. return err
  108. }
  109. unpacked, err := args.Unpack(data)
  110. if err != nil {
  111. return err
  112. }
  113. return args.Copy(v, unpacked)
  114. }
  115. // UnpackIntoMap unpacks a log into the provided map[string]interface{}.
  116. func (abi ABI) UnpackIntoMap(v map[string]interface{}, name string, data []byte) (err error) {
  117. args, err := abi.getArguments(name, data)
  118. if err != nil {
  119. return err
  120. }
  121. return args.UnpackIntoMap(v, data)
  122. }
  123. // UnmarshalJSON implements json.Unmarshaler interface.
  124. func (abi *ABI) UnmarshalJSON(data []byte) error {
  125. var fields []struct {
  126. Type string
  127. Name string
  128. Inputs []Argument
  129. Outputs []Argument
  130. // Status indicator which can be: "pure", "view",
  131. // "nonpayable" or "payable".
  132. StateMutability string
  133. // Deprecated Status indicators, but removed in v0.6.0.
  134. Constant bool // True if function is either pure or view
  135. Payable bool // True if function is payable
  136. // Event relevant indicator represents the event is
  137. // declared as anonymous.
  138. Anonymous bool
  139. }
  140. if err := json.Unmarshal(data, &fields); err != nil {
  141. return err
  142. }
  143. abi.Methods = make(map[string]Method)
  144. abi.Events = make(map[string]Event)
  145. abi.Errors = make(map[string]Error)
  146. for _, field := range fields {
  147. switch field.Type {
  148. case "constructor":
  149. abi.Constructor = NewMethod("", "", Constructor, field.StateMutability, field.Constant, field.Payable, field.Inputs, nil)
  150. case "function":
  151. name := ResolveNameConflict(field.Name, func(s string) bool { _, ok := abi.Methods[s]; return ok })
  152. abi.Methods[name] = NewMethod(name, field.Name, Function, field.StateMutability, field.Constant, field.Payable, field.Inputs, field.Outputs)
  153. case "fallback":
  154. // New introduced function type in v0.6.0, check more detail
  155. // here https://solidity.readthedocs.io/en/v0.6.0/contracts.html#fallback-function
  156. if abi.HasFallback() {
  157. return errors.New("only single fallback is allowed")
  158. }
  159. abi.Fallback = NewMethod("", "", Fallback, field.StateMutability, field.Constant, field.Payable, nil, nil)
  160. case "receive":
  161. // New introduced function type in v0.6.0, check more detail
  162. // here https://solidity.readthedocs.io/en/v0.6.0/contracts.html#fallback-function
  163. if abi.HasReceive() {
  164. return errors.New("only single receive is allowed")
  165. }
  166. if field.StateMutability != "payable" {
  167. return errors.New("the statemutability of receive can only be payable")
  168. }
  169. abi.Receive = NewMethod("", "", Receive, field.StateMutability, field.Constant, field.Payable, nil, nil)
  170. case "event":
  171. name := ResolveNameConflict(field.Name, func(s string) bool { _, ok := abi.Events[s]; return ok })
  172. abi.Events[name] = NewEvent(name, field.Name, field.Anonymous, field.Inputs)
  173. case "error":
  174. // Errors cannot be overloaded or overridden but are inherited,
  175. // no need to resolve the name conflict here.
  176. abi.Errors[field.Name] = NewError(field.Name, field.Inputs)
  177. default:
  178. return fmt.Errorf("abi: could not recognize type %v of field %v", field.Type, field.Name)
  179. }
  180. }
  181. return nil
  182. }
  183. // MethodById looks up a method by the 4-byte id,
  184. // returns nil if none found.
  185. func (abi *ABI) MethodById(sigdata []byte) (*Method, error) {
  186. if len(sigdata) < 4 {
  187. return nil, fmt.Errorf("data too short (%d bytes) for abi method lookup", len(sigdata))
  188. }
  189. for _, method := range abi.Methods {
  190. if bytes.Equal(method.ID, sigdata[:4]) {
  191. return &method, nil
  192. }
  193. }
  194. return nil, fmt.Errorf("no method with id: %#x", sigdata[:4])
  195. }
  196. // EventByID looks an event up by its topic hash in the
  197. // ABI and returns nil if none found.
  198. func (abi *ABI) EventByID(topic common.Hash) (*Event, error) {
  199. for _, event := range abi.Events {
  200. if bytes.Equal(event.ID.Bytes(), topic.Bytes()) {
  201. return &event, nil
  202. }
  203. }
  204. return nil, fmt.Errorf("no event with id: %#x", topic.Hex())
  205. }
  206. // HasFallback returns an indicator whether a fallback function is included.
  207. func (abi *ABI) HasFallback() bool {
  208. return abi.Fallback.Type == Fallback
  209. }
  210. // HasReceive returns an indicator whether a receive function is included.
  211. func (abi *ABI) HasReceive() bool {
  212. return abi.Receive.Type == Receive
  213. }
  214. // revertSelector is a special function selector for revert reason unpacking.
  215. var revertSelector = crypto.Keccak256([]byte("Error(string)"))[:4]
  216. // UnpackRevert resolves the abi-encoded revert reason. According to the solidity
  217. // spec https://solidity.readthedocs.io/en/latest/control-structures.html#revert,
  218. // the provided revert reason is abi-encoded as if it were a call to a function
  219. // `Error(string)`. So it's a special tool for it.
  220. func UnpackRevert(data []byte) (string, error) {
  221. if len(data) < 4 {
  222. return "", errors.New("invalid data for unpacking")
  223. }
  224. if !bytes.Equal(data[:4], revertSelector) {
  225. return "", errors.New("invalid data for unpacking")
  226. }
  227. typ, _ := NewType("string", "", nil)
  228. unpacked, err := (Arguments{{Type: typ}}).Unpack(data[4:])
  229. if err != nil {
  230. return "", err
  231. }
  232. return unpacked[0].(string), nil
  233. }