utils.go 6.4 KB

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