abi.go 9.2 KB

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