json.go 12 KB

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