abi.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. "fmt"
  21. "io"
  22. "github.com/ethereum/go-ethereum/common"
  23. )
  24. // The ABI holds information about a contract's context and available
  25. // invokable methods. It will allow you to type check function calls and
  26. // packs data accordingly.
  27. type ABI struct {
  28. Constructor Method
  29. Methods map[string]Method
  30. Events map[string]Event
  31. }
  32. // JSON returns a parsed ABI interface and error if it failed.
  33. func JSON(reader io.Reader) (ABI, error) {
  34. dec := json.NewDecoder(reader)
  35. var abi ABI
  36. if err := dec.Decode(&abi); err != nil {
  37. return ABI{}, err
  38. }
  39. return abi, nil
  40. }
  41. // Pack the given method name to conform the ABI. Method call's data
  42. // will consist of method_id, args0, arg1, ... argN. Method id consists
  43. // of 4 bytes and arguments are all 32 bytes.
  44. // Method ids are created from the first 4 bytes of the hash of the
  45. // methods string signature. (signature = baz(uint32,string32))
  46. func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) {
  47. // Fetch the ABI of the requested method
  48. if name == "" {
  49. // constructor
  50. arguments, err := abi.Constructor.Inputs.Pack(args...)
  51. if err != nil {
  52. return nil, err
  53. }
  54. return arguments, nil
  55. }
  56. method, exist := abi.Methods[name]
  57. if !exist {
  58. return nil, fmt.Errorf("method '%s' not found", name)
  59. }
  60. arguments, err := method.Inputs.Pack(args...)
  61. if err != nil {
  62. return nil, err
  63. }
  64. // Pack up the method ID too if not a constructor and return
  65. return append(method.ID(), arguments...), nil
  66. }
  67. // Unpack output in v according to the abi specification
  68. func (abi ABI) Unpack(v interface{}, name string, data []byte) (err error) {
  69. if len(data) == 0 {
  70. return fmt.Errorf("abi: unmarshalling empty output")
  71. }
  72. // since there can't be naming collisions with contracts and events,
  73. // we need to decide whether we're calling a method or an event
  74. if method, ok := abi.Methods[name]; ok {
  75. if len(data)%32 != 0 {
  76. return fmt.Errorf("abi: improperly formatted output: %s - Bytes: [%+v]", string(data), data)
  77. }
  78. return method.Outputs.Unpack(v, data)
  79. }
  80. if event, ok := abi.Events[name]; ok {
  81. return event.Inputs.Unpack(v, data)
  82. }
  83. return fmt.Errorf("abi: could not locate named method or event")
  84. }
  85. // UnpackIntoMap unpacks a log into the provided map[string]interface{}
  86. func (abi ABI) UnpackIntoMap(v map[string]interface{}, name string, data []byte) (err error) {
  87. if len(data) == 0 {
  88. return fmt.Errorf("abi: unmarshalling empty output")
  89. }
  90. // since there can't be naming collisions with contracts and events,
  91. // we need to decide whether we're calling a method or an event
  92. if method, ok := abi.Methods[name]; ok {
  93. if len(data)%32 != 0 {
  94. return fmt.Errorf("abi: improperly formatted output")
  95. }
  96. return method.Outputs.UnpackIntoMap(v, data)
  97. }
  98. if event, ok := abi.Events[name]; ok {
  99. return event.Inputs.UnpackIntoMap(v, data)
  100. }
  101. return fmt.Errorf("abi: could not locate named method or event")
  102. }
  103. // UnmarshalJSON implements json.Unmarshaler interface
  104. func (abi *ABI) UnmarshalJSON(data []byte) error {
  105. var fields []struct {
  106. Type string
  107. Name string
  108. Constant bool
  109. Anonymous bool
  110. Inputs []Argument
  111. Outputs []Argument
  112. }
  113. if err := json.Unmarshal(data, &fields); err != nil {
  114. return err
  115. }
  116. abi.Methods = make(map[string]Method)
  117. abi.Events = make(map[string]Event)
  118. for _, field := range fields {
  119. switch field.Type {
  120. case "constructor":
  121. abi.Constructor = Method{
  122. Inputs: field.Inputs,
  123. }
  124. // empty defaults to function according to the abi spec
  125. case "function", "":
  126. name := field.Name
  127. _, ok := abi.Methods[name]
  128. for idx := 0; ok; idx++ {
  129. name = fmt.Sprintf("%s%d", field.Name, idx)
  130. _, ok = abi.Methods[name]
  131. }
  132. abi.Methods[name] = Method{
  133. Name: name,
  134. RawName: field.Name,
  135. Const: field.Constant,
  136. Inputs: field.Inputs,
  137. Outputs: field.Outputs,
  138. }
  139. case "event":
  140. name := field.Name
  141. _, ok := abi.Events[name]
  142. for idx := 0; ok; idx++ {
  143. name = fmt.Sprintf("%s%d", field.Name, idx)
  144. _, ok = abi.Events[name]
  145. }
  146. abi.Events[name] = Event{
  147. Name: name,
  148. RawName: field.Name,
  149. Anonymous: field.Anonymous,
  150. Inputs: field.Inputs,
  151. }
  152. }
  153. }
  154. return nil
  155. }
  156. // MethodById looks up a method by the 4-byte id
  157. // returns nil if none found
  158. func (abi *ABI) MethodById(sigdata []byte) (*Method, error) {
  159. if len(sigdata) < 4 {
  160. return nil, fmt.Errorf("data too short (%d bytes) for abi method lookup", len(sigdata))
  161. }
  162. for _, method := range abi.Methods {
  163. if bytes.Equal(method.ID(), sigdata[:4]) {
  164. return &method, nil
  165. }
  166. }
  167. return nil, fmt.Errorf("no method with id: %#x", sigdata[:4])
  168. }
  169. // EventByID looks an event up by its topic hash in the
  170. // ABI and returns nil if none found.
  171. func (abi *ABI) EventByID(topic common.Hash) (*Event, error) {
  172. for _, event := range abi.Events {
  173. if bytes.Equal(event.ID().Bytes(), topic.Bytes()) {
  174. return &event, nil
  175. }
  176. }
  177. return nil, fmt.Errorf("no event with id: %#x", topic.Hex())
  178. }