utils.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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 rpc
  17. import (
  18. "crypto/rand"
  19. "encoding/hex"
  20. "errors"
  21. "fmt"
  22. "math/big"
  23. "reflect"
  24. "unicode"
  25. "unicode/utf8"
  26. "golang.org/x/net/context"
  27. )
  28. // Is this an exported - upper case - name?
  29. func isExported(name string) bool {
  30. rune, _ := utf8.DecodeRuneInString(name)
  31. return unicode.IsUpper(rune)
  32. }
  33. // Is this type exported or a builtin?
  34. func isExportedOrBuiltinType(t reflect.Type) bool {
  35. for t.Kind() == reflect.Ptr {
  36. t = t.Elem()
  37. }
  38. // PkgPath will be non-empty even for an exported type,
  39. // so we need to check the type name as well.
  40. return isExported(t.Name()) || t.PkgPath() == ""
  41. }
  42. var errorType = reflect.TypeOf((*error)(nil)).Elem()
  43. // Implements this type the error interface
  44. func isErrorType(t reflect.Type) bool {
  45. for t.Kind() == reflect.Ptr {
  46. t = t.Elem()
  47. }
  48. return t.Implements(errorType)
  49. }
  50. var subscriptionType = reflect.TypeOf((*Subscription)(nil)).Elem()
  51. func isSubscriptionType(t reflect.Type) bool {
  52. for t.Kind() == reflect.Ptr {
  53. t = t.Elem()
  54. }
  55. return t == subscriptionType
  56. }
  57. // isPubSub tests whether the given method return the pair (v2.Subscription, error)
  58. func isPubSub(methodType reflect.Type) bool {
  59. if methodType.NumOut() != 2 {
  60. return false
  61. }
  62. return isSubscriptionType(methodType.Out(0)) && isErrorType(methodType.Out(1))
  63. }
  64. // formatName will convert to first character to lower case
  65. func formatName(name string) string {
  66. ret := []rune(name)
  67. if len(ret) > 0 {
  68. ret[0] = unicode.ToLower(ret[0])
  69. }
  70. return string(ret)
  71. }
  72. var bigIntType = reflect.TypeOf((*big.Int)(nil)).Elem()
  73. // Indication if this type should be serialized in hex
  74. func isHexNum(t reflect.Type) bool {
  75. if t == nil {
  76. return false
  77. }
  78. for t.Kind() == reflect.Ptr {
  79. t = t.Elem()
  80. }
  81. return t == bigIntType
  82. }
  83. var blockNumberType = reflect.TypeOf((*BlockNumber)(nil)).Elem()
  84. // Indication if the given block is a BlockNumber
  85. func isBlockNumber(t reflect.Type) bool {
  86. if t == nil {
  87. return false
  88. }
  89. for t.Kind() == reflect.Ptr {
  90. t = t.Elem()
  91. }
  92. return t == blockNumberType
  93. }
  94. var contextType = reflect.TypeOf(new(context.Context)).Elem()
  95. // suitableCallbacks iterates over the methods of the given type. It will determine if a method satisfies the criteria
  96. // for a RPC callback or a subscription callback and adds it to the collection of callbacks or subscriptions. See server
  97. // documentation for a summary of these criteria.
  98. func suitableCallbacks(rcvr reflect.Value, typ reflect.Type) (callbacks, subscriptions) {
  99. callbacks := make(callbacks)
  100. subscriptions := make(subscriptions)
  101. METHODS:
  102. for m := 0; m < typ.NumMethod(); m++ {
  103. method := typ.Method(m)
  104. mtype := method.Type
  105. mname := formatName(method.Name)
  106. if method.PkgPath != "" { // method must be exported
  107. continue
  108. }
  109. var h callback
  110. h.isSubscribe = isPubSub(mtype)
  111. h.rcvr = rcvr
  112. h.method = method
  113. h.errPos = -1
  114. firstArg := 1
  115. numIn := mtype.NumIn()
  116. if numIn >= 2 && mtype.In(1) == contextType {
  117. h.hasCtx = true
  118. firstArg = 2
  119. }
  120. if h.isSubscribe {
  121. h.argTypes = make([]reflect.Type, numIn-firstArg) // skip rcvr type
  122. for i := firstArg; i < numIn; i++ {
  123. argType := mtype.In(i)
  124. if isExportedOrBuiltinType(argType) {
  125. h.argTypes[i-firstArg] = argType
  126. } else {
  127. continue METHODS
  128. }
  129. }
  130. subscriptions[mname] = &h
  131. continue METHODS
  132. }
  133. // determine method arguments, ignore first arg since it's the receiver type
  134. // Arguments must be exported or builtin types
  135. h.argTypes = make([]reflect.Type, numIn-firstArg)
  136. for i := firstArg; i < numIn; i++ {
  137. argType := mtype.In(i)
  138. if !isExportedOrBuiltinType(argType) {
  139. continue METHODS
  140. }
  141. h.argTypes[i-firstArg] = argType
  142. }
  143. // check that all returned values are exported or builtin types
  144. for i := 0; i < mtype.NumOut(); i++ {
  145. if !isExportedOrBuiltinType(mtype.Out(i)) {
  146. continue METHODS
  147. }
  148. }
  149. // when a method returns an error it must be the last returned value
  150. h.errPos = -1
  151. for i := 0; i < mtype.NumOut(); i++ {
  152. if isErrorType(mtype.Out(i)) {
  153. h.errPos = i
  154. break
  155. }
  156. }
  157. if h.errPos >= 0 && h.errPos != mtype.NumOut()-1 {
  158. continue METHODS
  159. }
  160. switch mtype.NumOut() {
  161. case 0, 1:
  162. break
  163. case 2:
  164. if h.errPos == -1 { // method must one return value and 1 error
  165. continue METHODS
  166. }
  167. break
  168. default:
  169. continue METHODS
  170. }
  171. callbacks[mname] = &h
  172. }
  173. return callbacks, subscriptions
  174. }
  175. func newSubscriptionId() (string, error) {
  176. var subid [16]byte
  177. n, _ := rand.Read(subid[:])
  178. if n != 16 {
  179. return "", errors.New("Unable to generate subscription id")
  180. }
  181. return "0x" + hex.EncodeToString(subid[:]), nil
  182. }
  183. // SupportedModules returns the collection of API's that the RPC server offers
  184. // on which the given client connects.
  185. func SupportedModules(client Client) (map[string]string, error) {
  186. req := JSONRequest{
  187. Id: new(int64),
  188. Version: "2.0",
  189. Method: "rpc_modules",
  190. }
  191. if err := client.Send(req); err != nil {
  192. return nil, err
  193. }
  194. var response JSONSuccessResponse
  195. if err := client.Recv(&response); err != nil {
  196. return nil, err
  197. }
  198. if response.Result != nil {
  199. mods := make(map[string]string)
  200. if modules, ok := response.Result.(map[string]interface{}); ok {
  201. for m, v := range modules {
  202. mods[m] = fmt.Sprintf("%s", v)
  203. }
  204. return mods, nil
  205. }
  206. }
  207. return nil, fmt.Errorf("unable to retrieve modules")
  208. }