json.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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 v2
  17. import (
  18. "encoding/json"
  19. "fmt"
  20. "io"
  21. "reflect"
  22. "strings"
  23. "sync/atomic"
  24. "github.com/ethereum/go-ethereum/logger"
  25. "github.com/ethereum/go-ethereum/logger/glog"
  26. )
  27. const (
  28. jsonRPCVersion = "2.0"
  29. serviceMethodSeparator = "_"
  30. subscribeMethod = "eth_subscribe"
  31. unsubscribeMethod = "eth_unsubscribe"
  32. notificationMethod = "eth_subscription"
  33. )
  34. // JSON-RPC request
  35. type jsonRequest struct {
  36. Method string `json:"method"`
  37. Version string `json:"jsonrpc"`
  38. Id *int64 `json:"id,omitempty"`
  39. Payload json.RawMessage `json:"params"`
  40. }
  41. // JSON-RPC response
  42. type jsonSuccessResponse struct {
  43. Version string `json:"jsonrpc"`
  44. Id int64 `json:"id"`
  45. Result interface{} `json:"result,omitempty"`
  46. }
  47. // JSON-RPC error object
  48. type jsonError struct {
  49. Code int `json:"code"`
  50. Message string `json:"message"`
  51. Data interface{} `json:"data,omitempty"`
  52. }
  53. // JSON-RPC error response
  54. type jsonErrResponse struct {
  55. Version string `json:"jsonrpc"`
  56. Id *int64 `json:"id,omitempty"`
  57. Error jsonError `json:"error"`
  58. }
  59. // JSON-RPC notification payload
  60. type jsonSubscription struct {
  61. Subscription string `json:"subscription"`
  62. Result interface{} `json:"result,omitempty"`
  63. }
  64. // JSON-RPC notification
  65. type jsonNotification struct {
  66. Version string `json:"jsonrpc"`
  67. Method string `json:"method"`
  68. Params jsonSubscription `json:"params"`
  69. }
  70. // jsonCodec reads and writes JSON-RPC messages to the underlying connection. It also has support for parsing arguments
  71. // and serializing (result) objects.
  72. type jsonCodec struct {
  73. closed chan interface{}
  74. isClosed int32
  75. d *json.Decoder
  76. e *json.Encoder
  77. req jsonRequest
  78. rw io.ReadWriteCloser
  79. }
  80. // NewJSONCodec creates a new RPC server codec with support for JSON-RPC 2.0
  81. func NewJSONCodec(rwc io.ReadWriteCloser) ServerCodec {
  82. d := json.NewDecoder(rwc)
  83. d.UseNumber()
  84. return &jsonCodec{closed: make(chan interface{}), d: d, e: json.NewEncoder(rwc), rw: rwc, isClosed: 0}
  85. }
  86. // isBatch returns true when the first non-whitespace characters is '['
  87. func isBatch(msg json.RawMessage) bool {
  88. for _, c := range msg {
  89. // skip insignificant whitespace (http://www.ietf.org/rfc/rfc4627.txt)
  90. if c == 0x20 || c == 0x09 || c == 0x0a || c == 0x0d {
  91. continue
  92. }
  93. return c == '['
  94. }
  95. return false
  96. }
  97. // ReadRequestHeaders will read new requests without parsing the arguments. It will return a collection of requests, an
  98. // indication if these requests are in batch form or an error when the incoming message could not be read/parsed.
  99. func (c *jsonCodec) ReadRequestHeaders() ([]rpcRequest, bool, RPCError) {
  100. var incomingMsg json.RawMessage
  101. if err := c.d.Decode(&incomingMsg); err != nil {
  102. return nil, false, &invalidRequestError{err.Error()}
  103. }
  104. if isBatch(incomingMsg) {
  105. return parseBatchRequest(incomingMsg)
  106. }
  107. return parseRequest(incomingMsg)
  108. }
  109. // parseRequest will parse a single request from the given RawMessage. It will return the parsed request, an indication
  110. // if the request was a batch or an error when the request could not be parsed.
  111. func parseRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, RPCError) {
  112. var in jsonRequest
  113. if err := json.Unmarshal(incomingMsg, &in); err != nil {
  114. return nil, false, &invalidMessageError{err.Error()}
  115. }
  116. if in.Id == nil {
  117. return nil, false, &invalidMessageError{"Server cannot handle notifications"}
  118. }
  119. // subscribe are special, they will always use `subscribeMethod` as service method
  120. if in.Method == subscribeMethod {
  121. reqs := []rpcRequest{rpcRequest{id: *in.Id, isPubSub: true}}
  122. if len(in.Payload) > 0 {
  123. // first param must be subscription name
  124. var subscribeMethod [1]string
  125. if err := json.Unmarshal(in.Payload, &subscribeMethod); err != nil {
  126. glog.V(logger.Debug).Infof("Unable to parse subscription method: %v\n", err)
  127. return nil, false, &invalidRequestError{"Unable to parse subscription request"}
  128. }
  129. // all subscriptions are made on the eth service
  130. reqs[0].service, reqs[0].method = "eth", subscribeMethod[0]
  131. reqs[0].params = in.Payload
  132. return reqs, false, nil
  133. }
  134. return nil, false, &invalidRequestError{"Unable to parse subscription request"}
  135. }
  136. if in.Method == unsubscribeMethod {
  137. return []rpcRequest{rpcRequest{id: *in.Id, isPubSub: true,
  138. method: unsubscribeMethod, params: in.Payload}}, false, nil
  139. }
  140. // regular RPC call
  141. elems := strings.Split(in.Method, serviceMethodSeparator)
  142. if len(elems) != 2 {
  143. return nil, false, &methodNotFoundError{in.Method, ""}
  144. }
  145. if len(in.Payload) == 0 {
  146. return []rpcRequest{rpcRequest{service: elems[0], method: elems[1], id: *in.Id}}, false, nil
  147. }
  148. return []rpcRequest{rpcRequest{service: elems[0], method: elems[1], id: *in.Id, params: in.Payload}}, false, nil
  149. }
  150. // parseBatchRequest will parse a batch request into a collection of requests from the given RawMessage, an indication
  151. // if the request was a batch or an error when the request could not be read.
  152. func parseBatchRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, RPCError) {
  153. var in []jsonRequest
  154. if err := json.Unmarshal(incomingMsg, &in); err != nil {
  155. return nil, false, &invalidMessageError{err.Error()}
  156. }
  157. requests := make([]rpcRequest, len(in))
  158. for i, r := range in {
  159. if r.Id == nil {
  160. return nil, true, &invalidMessageError{"Server cannot handle notifications"}
  161. }
  162. // (un)subscribe are special, they will always use the same service.method
  163. if r.Method == subscribeMethod {
  164. requests[i] = rpcRequest{id: *r.Id, isPubSub: true}
  165. if len(r.Payload) > 0 {
  166. var subscribeMethod [1]string
  167. if err := json.Unmarshal(r.Payload, &subscribeMethod); err != nil {
  168. glog.V(logger.Debug).Infof("Unable to parse subscription method: %v\n", err)
  169. return nil, false, &invalidRequestError{"Unable to parse subscription request"}
  170. }
  171. // all subscriptions are made on the eth service
  172. requests[i].service, requests[i].method = "eth", subscribeMethod[0]
  173. requests[i].params = r.Payload
  174. continue
  175. }
  176. return nil, true, &invalidRequestError{"Unable to parse (un)subscribe request arguments"}
  177. }
  178. if r.Method == unsubscribeMethod {
  179. requests[i] = rpcRequest{id: *r.Id, isPubSub: true, method: unsubscribeMethod, params: r.Payload}
  180. continue
  181. }
  182. elems := strings.Split(r.Method, serviceMethodSeparator)
  183. if len(elems) != 2 {
  184. return nil, true, &methodNotFoundError{r.Method, ""}
  185. }
  186. if len(r.Payload) == 0 {
  187. requests[i] = rpcRequest{service: elems[0], method: elems[1], id: *r.Id, params: nil}
  188. } else {
  189. requests[i] = rpcRequest{service: elems[0], method: elems[1], id: *r.Id, params: r.Payload}
  190. }
  191. }
  192. return requests, true, nil
  193. }
  194. // ParseRequestArguments tries to parse the given params (json.RawMessage) with the given types. It returns the parsed
  195. // values or an error when the parsing failed.
  196. func (c *jsonCodec) ParseRequestArguments(argTypes []reflect.Type, params interface{}) ([]reflect.Value, RPCError) {
  197. if args, ok := params.(json.RawMessage); !ok {
  198. return nil, &invalidParamsError{"Invalid params supplied"}
  199. } else {
  200. return parsePositionalArguments(args, argTypes)
  201. }
  202. }
  203. func countArguments(args json.RawMessage) (int, error) {
  204. var cnt []interface{}
  205. if err := json.Unmarshal(args, &cnt); err != nil {
  206. return -1, nil
  207. }
  208. return len(cnt), nil
  209. }
  210. // parsePositionalArguments tries to parse the given args to an array of values with the given types. It returns the
  211. // parsed values or an error when the args could not be parsed.
  212. func parsePositionalArguments(args json.RawMessage, argTypes []reflect.Type) ([]reflect.Value, RPCError) {
  213. argValues := make([]reflect.Value, len(argTypes))
  214. params := make([]interface{}, len(argTypes))
  215. n, err := countArguments(args)
  216. if err != nil {
  217. return nil, &invalidParamsError{err.Error()}
  218. }
  219. if n != len(argTypes) {
  220. return nil, &invalidParamsError{fmt.Sprintf("insufficient params, want %d have %d", len(argTypes), n)}
  221. }
  222. for i, t := range argTypes {
  223. if t.Kind() == reflect.Ptr {
  224. // values must be pointers for the Unmarshal method, reflect.
  225. // Dereference otherwise reflect.New would create **SomeType
  226. argValues[i] = reflect.New(t.Elem())
  227. params[i] = argValues[i].Interface()
  228. // when not specified blockNumbers are by default latest (-1)
  229. if blockNumber, ok := params[i].(*BlockNumber); ok {
  230. *blockNumber = BlockNumber(-1)
  231. }
  232. } else {
  233. argValues[i] = reflect.New(t)
  234. params[i] = argValues[i].Interface()
  235. // when not specified blockNumbers are by default latest (-1)
  236. if blockNumber, ok := params[i].(*BlockNumber); ok {
  237. *blockNumber = BlockNumber(-1)
  238. }
  239. }
  240. }
  241. if err := json.Unmarshal(args, &params); err != nil {
  242. return nil, &invalidParamsError{err.Error()}
  243. }
  244. // Convert pointers back to values where necessary
  245. for i, a := range argValues {
  246. if a.Kind() != argTypes[i].Kind() {
  247. argValues[i] = reflect.Indirect(argValues[i])
  248. }
  249. }
  250. return argValues, nil
  251. }
  252. // CreateResponse will create a JSON-RPC success response with the given id and reply as result.
  253. func (c *jsonCodec) CreateResponse(id int64, reply interface{}) interface{} {
  254. if isHexNum(reflect.TypeOf(reply)) {
  255. return &jsonSuccessResponse{Version: jsonRPCVersion, Id: id, Result: fmt.Sprintf(`%#x`, reply)}
  256. }
  257. return &jsonSuccessResponse{Version: jsonRPCVersion, Id: id, Result: reply}
  258. }
  259. // CreateErrorResponse will create a JSON-RPC error response with the given id and error.
  260. func (c *jsonCodec) CreateErrorResponse(id *int64, err RPCError) interface{} {
  261. return &jsonErrResponse{Version: jsonRPCVersion, Id: id, Error: jsonError{Code: err.Code(), Message: err.Error()}}
  262. }
  263. // CreateErrorResponseWithInfo will create a JSON-RPC error response with the given id and error.
  264. // info is optional and contains additional information about the error. When an empty string is passed it is ignored.
  265. func (c *jsonCodec) CreateErrorResponseWithInfo(id *int64, err RPCError, info interface{}) interface{} {
  266. return &jsonErrResponse{Version: jsonRPCVersion, Id: id,
  267. Error: jsonError{Code: err.Code(), Message: err.Error(), Data: info}}
  268. }
  269. // CreateNotification will create a JSON-RPC notification with the given subscription id and event as params.
  270. func (c *jsonCodec) CreateNotification(subid string, event interface{}) interface{} {
  271. if isHexNum(reflect.TypeOf(event)) {
  272. return &jsonNotification{Version: jsonRPCVersion, Method: notificationMethod,
  273. Params: jsonSubscription{Subscription: subid, Result: fmt.Sprintf(`%#x`, event)}}
  274. }
  275. return &jsonNotification{Version: jsonRPCVersion, Method: notificationMethod,
  276. Params: jsonSubscription{Subscription: subid, Result: event}}
  277. }
  278. // Write message to client
  279. func (c *jsonCodec) Write(res interface{}) error {
  280. return c.e.Encode(res)
  281. }
  282. // Close the underlying connection
  283. func (c *jsonCodec) Close() {
  284. if atomic.CompareAndSwapInt32(&c.isClosed, 0, 1) {
  285. close(c.closed)
  286. c.rw.Close()
  287. }
  288. }
  289. // Closed returns a channel which will be closed when Close is called
  290. func (c *jsonCodec) Closed() <-chan interface{} {
  291. return c.closed
  292. }