abi.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. // Unpack output in v according to the abi specification
  75. func (abi ABI) Unpack(v interface{}, name string, data []byte) (err 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. if method, ok := abi.Methods[name]; ok {
  79. if len(data)%32 != 0 {
  80. return fmt.Errorf("abi: improperly formatted output: %s - Bytes: [%+v]", string(data), data)
  81. }
  82. return method.Outputs.Unpack(v, data)
  83. }
  84. if event, ok := abi.Events[name]; ok {
  85. return event.Inputs.Unpack(v, data)
  86. }
  87. return fmt.Errorf("abi: could not locate named method or event")
  88. }
  89. // UnpackIntoMap unpacks a log into the provided map[string]interface{}
  90. func (abi ABI) UnpackIntoMap(v map[string]interface{}, name string, data []byte) (err error) {
  91. // since there can't be naming collisions with contracts and events,
  92. // we need to decide whether we're calling a method or an event
  93. if method, ok := abi.Methods[name]; ok {
  94. if len(data)%32 != 0 {
  95. return fmt.Errorf("abi: improperly formatted output")
  96. }
  97. return method.Outputs.UnpackIntoMap(v, data)
  98. }
  99. if event, ok := abi.Events[name]; ok {
  100. return event.Inputs.UnpackIntoMap(v, data)
  101. }
  102. return fmt.Errorf("abi: could not locate named method or event")
  103. }
  104. // UnmarshalJSON implements json.Unmarshaler interface
  105. func (abi *ABI) UnmarshalJSON(data []byte) error {
  106. var fields []struct {
  107. Type string
  108. Name string
  109. Inputs []Argument
  110. Outputs []Argument
  111. // Status indicator which can be: "pure", "view",
  112. // "nonpayable" or "payable".
  113. StateMutability string
  114. // Deprecated Status indicators, but removed in v0.6.0.
  115. Constant bool // True if function is either pure or view
  116. Payable bool // True if function is payable
  117. // Event relevant indicator represents the event is
  118. // declared as anonymous.
  119. Anonymous bool
  120. }
  121. if err := json.Unmarshal(data, &fields); err != nil {
  122. return err
  123. }
  124. abi.Methods = make(map[string]Method)
  125. abi.Events = make(map[string]Event)
  126. for _, field := range fields {
  127. switch field.Type {
  128. case "constructor":
  129. abi.Constructor = NewMethod("", "", Constructor, field.StateMutability, field.Constant, field.Payable, field.Inputs, nil)
  130. case "function":
  131. name := abi.overloadedMethodName(field.Name)
  132. abi.Methods[name] = NewMethod(name, field.Name, Function, field.StateMutability, field.Constant, field.Payable, field.Inputs, field.Outputs)
  133. case "fallback":
  134. // New introduced function type in v0.6.0, check more detail
  135. // here https://solidity.readthedocs.io/en/v0.6.0/contracts.html#fallback-function
  136. if abi.HasFallback() {
  137. return errors.New("only single fallback is allowed")
  138. }
  139. abi.Fallback = NewMethod("", "", Fallback, field.StateMutability, field.Constant, field.Payable, nil, nil)
  140. case "receive":
  141. // New introduced function type in v0.6.0, check more detail
  142. // here https://solidity.readthedocs.io/en/v0.6.0/contracts.html#fallback-function
  143. if abi.HasReceive() {
  144. return errors.New("only single receive is allowed")
  145. }
  146. if field.StateMutability != "payable" {
  147. return errors.New("the statemutability of receive can only be payable")
  148. }
  149. abi.Receive = NewMethod("", "", Receive, field.StateMutability, field.Constant, field.Payable, nil, nil)
  150. case "event":
  151. name := abi.overloadedEventName(field.Name)
  152. abi.Events[name] = NewEvent(name, field.Name, field.Anonymous, field.Inputs)
  153. default:
  154. return fmt.Errorf("abi: could not recognize type %v of field %v", field.Type, field.Name)
  155. }
  156. }
  157. return nil
  158. }
  159. // overloadedMethodName returns the next available name for a given function.
  160. // Needed since solidity allows for function overload.
  161. //
  162. // e.g. if the abi contains Methods send, send1
  163. // overloadedMethodName would return send2 for input send.
  164. func (abi *ABI) overloadedMethodName(rawName string) string {
  165. name := rawName
  166. _, ok := abi.Methods[name]
  167. for idx := 0; ok; idx++ {
  168. name = fmt.Sprintf("%s%d", rawName, idx)
  169. _, ok = abi.Methods[name]
  170. }
  171. return name
  172. }
  173. // overloadedEventName returns the next available name for a given event.
  174. // Needed since solidity allows for event overload.
  175. //
  176. // e.g. if the abi contains events received, received1
  177. // overloadedEventName would return received2 for input received.
  178. func (abi *ABI) overloadedEventName(rawName string) string {
  179. name := rawName
  180. _, ok := abi.Events[name]
  181. for idx := 0; ok; idx++ {
  182. name = fmt.Sprintf("%s%d", rawName, idx)
  183. _, ok = abi.Events[name]
  184. }
  185. return name
  186. }
  187. // MethodById looks up a method by the 4-byte id
  188. // returns nil if none found
  189. func (abi *ABI) MethodById(sigdata []byte) (*Method, error) {
  190. if len(sigdata) < 4 {
  191. return nil, fmt.Errorf("data too short (%d bytes) for abi method lookup", len(sigdata))
  192. }
  193. for _, method := range abi.Methods {
  194. if bytes.Equal(method.ID, sigdata[:4]) {
  195. return &method, nil
  196. }
  197. }
  198. return nil, fmt.Errorf("no method with id: %#x", sigdata[:4])
  199. }
  200. // EventByID looks an event up by its topic hash in the
  201. // ABI and returns nil if none found.
  202. func (abi *ABI) EventByID(topic common.Hash) (*Event, error) {
  203. for _, event := range abi.Events {
  204. if bytes.Equal(event.ID.Bytes(), topic.Bytes()) {
  205. return &event, nil
  206. }
  207. }
  208. return nil, fmt.Errorf("no event with id: %#x", topic.Hex())
  209. }
  210. // HasFallback returns an indicator whether a fallback function is included.
  211. func (abi *ABI) HasFallback() bool {
  212. return abi.Fallback.Type == Fallback
  213. }
  214. // HasReceive returns an indicator whether a receive function is included.
  215. func (abi *ABI) HasReceive() bool {
  216. return abi.Receive.Type == Receive
  217. }
  218. // revertSelector is a special function selector for revert reason unpacking.
  219. var revertSelector = crypto.Keccak256([]byte("Error(string)"))[:4]
  220. // UnpackRevert resolves the abi-encoded revert reason. According to the solidity
  221. // spec https://solidity.readthedocs.io/en/latest/control-structures.html#revert,
  222. // the provided revert reason is abi-encoded as if it were a call to a function
  223. // `Error(string)`. So it's a special tool for it.
  224. func UnpackRevert(data []byte) (string, error) {
  225. if len(data) < 4 {
  226. return "", errors.New("invalid data for unpacking")
  227. }
  228. if !bytes.Equal(data[:4], revertSelector) {
  229. return "", errors.New("invalid data for unpacking")
  230. }
  231. var reason string
  232. typ, _ := NewType("string", "", nil)
  233. if err := (Arguments{{Type: typ}}).Unpack(&reason, data[4:]); err != nil {
  234. return "", err
  235. }
  236. return reason, nil
  237. }