abi.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. "io"
  21. "math"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/logger"
  24. "github.com/ethereum/go-ethereum/logger/glog"
  25. )
  26. // Executer is an executer method for performing state executions. It takes one
  27. // argument which is the input data and expects output data to be returned as
  28. // multiple 32 byte word length concatenated slice
  29. type Executer func(datain []byte) []byte
  30. // The ABI holds information about a contract's context and available
  31. // invokable methods. It will allow you to type check function calls and
  32. // packs data accordingly.
  33. type ABI struct {
  34. Methods map[string]Method
  35. Events map[string]Event
  36. }
  37. // JSON returns a parsed ABI interface and error if it failed.
  38. func JSON(reader io.Reader) (ABI, error) {
  39. dec := json.NewDecoder(reader)
  40. var abi ABI
  41. if err := dec.Decode(&abi); err != nil {
  42. return ABI{}, err
  43. }
  44. return abi, nil
  45. }
  46. // tests, tests whether the given input would result in a successful
  47. // call. Checks argument list count and matches input to `input`.
  48. func (abi ABI) pack(name string, args ...interface{}) ([]byte, error) {
  49. method := abi.Methods[name]
  50. var ret []byte
  51. for i, a := range args {
  52. input := method.Inputs[i]
  53. packed, err := input.Type.pack(a)
  54. if err != nil {
  55. return nil, fmt.Errorf("`%s` %v", name, err)
  56. }
  57. ret = append(ret, packed...)
  58. }
  59. return ret, nil
  60. }
  61. // Pack the given method name to conform the ABI. Method call's data
  62. // will consist of method_id, args0, arg1, ... argN. Method id consists
  63. // of 4 bytes and arguments are all 32 bytes.
  64. // Method ids are created from the first 4 bytes of the hash of the
  65. // methods string signature. (signature = baz(uint32,string32))
  66. func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) {
  67. method, exist := abi.Methods[name]
  68. if !exist {
  69. return nil, fmt.Errorf("method '%s' not found", name)
  70. }
  71. // start with argument count match
  72. if len(args) != len(method.Inputs) {
  73. return nil, fmt.Errorf("argument count mismatch: %d for %d", len(args), len(method.Inputs))
  74. }
  75. arguments, err := abi.pack(name, args...)
  76. if err != nil {
  77. return nil, err
  78. }
  79. // Set function id
  80. packed := abi.Methods[name].Id()
  81. packed = append(packed, arguments...)
  82. return packed, nil
  83. }
  84. // toGoType parses the input and casts it to the proper type defined by the ABI
  85. // argument in t.
  86. func toGoType(t Argument, input []byte) interface{} {
  87. switch t.Type.T {
  88. case IntTy:
  89. return common.BytesToBig(input)
  90. case UintTy:
  91. return common.BytesToBig(input)
  92. case BoolTy:
  93. return common.BytesToBig(input).Uint64() > 0
  94. case AddressTy:
  95. return common.BytesToAddress(input)
  96. case HashTy:
  97. return common.BytesToHash(input)
  98. }
  99. return nil
  100. }
  101. // Call executes a call and attemps to parse the return values and returns it as
  102. // an interface. It uses the executer method to perform the actual call since
  103. // the abi knows nothing of the lower level calling mechanism.
  104. //
  105. // Call supports all abi types and includes multiple return values. When only
  106. // one item is returned a single interface{} will be returned, if a contract
  107. // method returns multiple values an []interface{} slice is returned.
  108. func (abi ABI) Call(executer Executer, name string, args ...interface{}) interface{} {
  109. callData, err := abi.Pack(name, args...)
  110. if err != nil {
  111. glog.V(logger.Debug).Infoln("pack error:", err)
  112. return nil
  113. }
  114. output := executer(callData)
  115. method := abi.Methods[name]
  116. ret := make([]interface{}, int(math.Max(float64(len(method.Outputs)), float64(len(output)/32))))
  117. for i := 0; i < len(ret); i += 32 {
  118. index := i / 32
  119. ret[index] = toGoType(method.Outputs[index], output[i:i+32])
  120. }
  121. // return single interface
  122. if len(ret) == 1 {
  123. return ret[0]
  124. }
  125. return ret
  126. }
  127. func (abi *ABI) UnmarshalJSON(data []byte) error {
  128. var fields []struct {
  129. Type string
  130. Name string
  131. Const bool
  132. Indexed bool
  133. Inputs []Argument
  134. Outputs []Argument
  135. }
  136. if err := json.Unmarshal(data, &fields); err != nil {
  137. return err
  138. }
  139. abi.Methods = make(map[string]Method)
  140. abi.Events = make(map[string]Event)
  141. for _, field := range fields {
  142. switch field.Type {
  143. // empty defaults to function according to the abi spec
  144. case "function", "":
  145. abi.Methods[field.Name] = Method{
  146. Name: field.Name,
  147. Const: field.Const,
  148. Inputs: field.Inputs,
  149. Outputs: field.Outputs,
  150. }
  151. case "event":
  152. abi.Events[field.Name] = Event{
  153. Name: field.Name,
  154. Inputs: field.Inputs,
  155. }
  156. }
  157. }
  158. return nil
  159. }