abi.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. "reflect"
  22. "strings"
  23. "github.com/ethereum/go-ethereum/common"
  24. )
  25. // The ABI holds information about a contract's context and available
  26. // invokable methods. It will allow you to type check function calls and
  27. // packs data accordingly.
  28. type ABI struct {
  29. Constructor Method
  30. Methods map[string]Method
  31. Events map[string]Event
  32. }
  33. // JSON returns a parsed ABI interface and error if it failed.
  34. func JSON(reader io.Reader) (ABI, error) {
  35. dec := json.NewDecoder(reader)
  36. var abi ABI
  37. if err := dec.Decode(&abi); err != nil {
  38. return ABI{}, err
  39. }
  40. return abi, nil
  41. }
  42. // Pack the given method name to conform the ABI. Method call's data
  43. // will consist of method_id, args0, arg1, ... argN. Method id consists
  44. // of 4 bytes and arguments are all 32 bytes.
  45. // Method ids are created from the first 4 bytes of the hash of the
  46. // methods string signature. (signature = baz(uint32,string32))
  47. func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) {
  48. // Fetch the ABI of the requested method
  49. var method Method
  50. if name == "" {
  51. method = abi.Constructor
  52. } else {
  53. m, exist := abi.Methods[name]
  54. if !exist {
  55. return nil, fmt.Errorf("method '%s' not found", name)
  56. }
  57. method = m
  58. }
  59. arguments, err := method.pack(args...)
  60. if err != nil {
  61. return nil, err
  62. }
  63. // Pack up the method ID too if not a constructor and return
  64. if name == "" {
  65. return arguments, nil
  66. }
  67. return append(method.Id(), arguments...), nil
  68. }
  69. // these variable are used to determine certain types during type assertion for
  70. // assignment.
  71. var (
  72. r_interSlice = reflect.TypeOf([]interface{}{})
  73. r_hash = reflect.TypeOf(common.Hash{})
  74. r_bytes = reflect.TypeOf([]byte{})
  75. r_byte = reflect.TypeOf(byte(0))
  76. )
  77. // Unpack output in v according to the abi specification
  78. func (abi ABI) Unpack(v interface{}, name string, output []byte) error {
  79. var method = abi.Methods[name]
  80. if len(output) == 0 {
  81. return fmt.Errorf("abi: unmarshalling empty output")
  82. }
  83. // make sure the passed value is a pointer
  84. valueOf := reflect.ValueOf(v)
  85. if reflect.Ptr != valueOf.Kind() {
  86. return fmt.Errorf("abi: Unpack(non-pointer %T)", v)
  87. }
  88. var (
  89. value = valueOf.Elem()
  90. typ = value.Type()
  91. )
  92. if len(method.Outputs) > 1 {
  93. switch value.Kind() {
  94. // struct will match named return values to the struct's field
  95. // names
  96. case reflect.Struct:
  97. for i := 0; i < len(method.Outputs); i++ {
  98. marshalledValue, err := toGoType(i, method.Outputs[i], output)
  99. if err != nil {
  100. return err
  101. }
  102. reflectValue := reflect.ValueOf(marshalledValue)
  103. for j := 0; j < typ.NumField(); j++ {
  104. field := typ.Field(j)
  105. // TODO read tags: `abi:"fieldName"`
  106. if field.Name == strings.ToUpper(method.Outputs[i].Name[:1])+method.Outputs[i].Name[1:] {
  107. if err := set(value.Field(j), reflectValue, method.Outputs[i]); err != nil {
  108. return err
  109. }
  110. }
  111. }
  112. }
  113. case reflect.Slice:
  114. if !value.Type().AssignableTo(r_interSlice) {
  115. return fmt.Errorf("abi: cannot marshal tuple in to slice %T (only []interface{} is supported)", v)
  116. }
  117. // if the slice already contains values, set those instead of the interface slice itself.
  118. if value.Len() > 0 {
  119. if len(method.Outputs) > value.Len() {
  120. return fmt.Errorf("abi: cannot marshal in to slices of unequal size (require: %v, got: %v)", len(method.Outputs), value.Len())
  121. }
  122. for i := 0; i < len(method.Outputs); i++ {
  123. marshalledValue, err := toGoType(i, method.Outputs[i], output)
  124. if err != nil {
  125. return err
  126. }
  127. reflectValue := reflect.ValueOf(marshalledValue)
  128. if err := set(value.Index(i).Elem(), reflectValue, method.Outputs[i]); err != nil {
  129. return err
  130. }
  131. }
  132. return nil
  133. }
  134. // create a new slice and start appending the unmarshalled
  135. // values to the new interface slice.
  136. z := reflect.MakeSlice(typ, 0, len(method.Outputs))
  137. for i := 0; i < len(method.Outputs); i++ {
  138. marshalledValue, err := toGoType(i, method.Outputs[i], output)
  139. if err != nil {
  140. return err
  141. }
  142. z = reflect.Append(z, reflect.ValueOf(marshalledValue))
  143. }
  144. value.Set(z)
  145. default:
  146. return fmt.Errorf("abi: cannot unmarshal tuple in to %v", typ)
  147. }
  148. } else {
  149. marshalledValue, err := toGoType(0, method.Outputs[0], output)
  150. if err != nil {
  151. return err
  152. }
  153. if err := set(value, reflect.ValueOf(marshalledValue), method.Outputs[0]); err != nil {
  154. return err
  155. }
  156. }
  157. return nil
  158. }
  159. func (abi *ABI) UnmarshalJSON(data []byte) error {
  160. var fields []struct {
  161. Type string
  162. Name string
  163. Constant bool
  164. Indexed bool
  165. Anonymous bool
  166. Inputs []Argument
  167. Outputs []Argument
  168. }
  169. if err := json.Unmarshal(data, &fields); err != nil {
  170. return err
  171. }
  172. abi.Methods = make(map[string]Method)
  173. abi.Events = make(map[string]Event)
  174. for _, field := range fields {
  175. switch field.Type {
  176. case "constructor":
  177. abi.Constructor = Method{
  178. Inputs: field.Inputs,
  179. }
  180. // empty defaults to function according to the abi spec
  181. case "function", "":
  182. abi.Methods[field.Name] = Method{
  183. Name: field.Name,
  184. Const: field.Constant,
  185. Inputs: field.Inputs,
  186. Outputs: field.Outputs,
  187. }
  188. case "event":
  189. abi.Events[field.Name] = Event{
  190. Name: field.Name,
  191. Anonymous: field.Anonymous,
  192. Inputs: field.Inputs,
  193. }
  194. }
  195. }
  196. return nil
  197. }