json.go 12 KB

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