json.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. "bytes"
  19. "encoding/json"
  20. "fmt"
  21. "io"
  22. "reflect"
  23. "strconv"
  24. "strings"
  25. "sync"
  26. "github.com/ethereum/go-ethereum/log"
  27. )
  28. const (
  29. jsonrpcVersion = "2.0"
  30. serviceMethodSeparator = "_"
  31. subscribeMethodSuffix = "_subscribe"
  32. unsubscribeMethodSuffix = "_unsubscribe"
  33. notificationMethodSuffix = "_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 the decoder
  71. decode func(v interface{}) error // decoder to allow multiple transports
  72. encMu sync.Mutex // guards the encoder
  73. encode func(v interface{}) error // encoder to allow multiple transports
  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. // NewCodec creates a new RPC server codec with support for JSON-RPC 2.0 based
  86. // on explicitly given encoding and decoding methods.
  87. func NewCodec(rwc io.ReadWriteCloser, encode, decode func(v interface{}) error) ServerCodec {
  88. return &jsonCodec{
  89. closed: make(chan interface{}),
  90. encode: encode,
  91. decode: decode,
  92. rw: rwc,
  93. }
  94. }
  95. // NewJSONCodec creates a new RPC server codec with support for JSON-RPC 2.0.
  96. func NewJSONCodec(rwc io.ReadWriteCloser) ServerCodec {
  97. enc := json.NewEncoder(rwc)
  98. dec := json.NewDecoder(rwc)
  99. dec.UseNumber()
  100. return &jsonCodec{
  101. closed: make(chan interface{}),
  102. encode: enc.Encode,
  103. decode: dec.Decode,
  104. rw: rwc,
  105. }
  106. }
  107. // isBatch returns true when the first non-whitespace characters is '['
  108. func isBatch(msg json.RawMessage) bool {
  109. for _, c := range msg {
  110. // skip insignificant whitespace (http://www.ietf.org/rfc/rfc4627.txt)
  111. if c == 0x20 || c == 0x09 || c == 0x0a || c == 0x0d {
  112. continue
  113. }
  114. return c == '['
  115. }
  116. return false
  117. }
  118. // ReadRequestHeaders will read new requests without parsing the arguments. It will
  119. // return a collection of requests, an indication if these requests are in batch
  120. // form or an error when the incoming message could not be read/parsed.
  121. func (c *jsonCodec) ReadRequestHeaders() ([]rpcRequest, bool, Error) {
  122. c.decMu.Lock()
  123. defer c.decMu.Unlock()
  124. var incomingMsg json.RawMessage
  125. if err := c.decode(&incomingMsg); err != nil {
  126. return nil, false, &invalidRequestError{err.Error()}
  127. }
  128. if isBatch(incomingMsg) {
  129. return parseBatchRequest(incomingMsg)
  130. }
  131. return parseRequest(incomingMsg)
  132. }
  133. // checkReqId returns an error when the given reqId isn't valid for RPC method calls.
  134. // valid id's are strings, numbers or null
  135. func checkReqId(reqId json.RawMessage) error {
  136. if len(reqId) == 0 {
  137. return fmt.Errorf("missing request id")
  138. }
  139. if _, err := strconv.ParseFloat(string(reqId), 64); err == nil {
  140. return nil
  141. }
  142. var str string
  143. if err := json.Unmarshal(reqId, &str); err == nil {
  144. return nil
  145. }
  146. return fmt.Errorf("invalid request id")
  147. }
  148. // parseRequest will parse a single request from the given RawMessage. It will return
  149. // the parsed request, an indication if the request was a batch or an error when
  150. // the request could not be parsed.
  151. func parseRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) {
  152. var in jsonRequest
  153. if err := json.Unmarshal(incomingMsg, &in); err != nil {
  154. return nil, false, &invalidMessageError{err.Error()}
  155. }
  156. if err := checkReqId(in.Id); err != nil {
  157. return nil, false, &invalidMessageError{err.Error()}
  158. }
  159. // subscribe are special, they will always use `subscribeMethod` as first param in the payload
  160. if strings.HasSuffix(in.Method, subscribeMethodSuffix) {
  161. reqs := []rpcRequest{{id: &in.Id, isPubSub: true}}
  162. if len(in.Payload) > 0 {
  163. // first param must be subscription name
  164. var subscribeMethod [1]string
  165. if err := json.Unmarshal(in.Payload, &subscribeMethod); err != nil {
  166. log.Debug(fmt.Sprintf("Unable to parse subscription method: %v\n", err))
  167. return nil, false, &invalidRequestError{"Unable to parse subscription request"}
  168. }
  169. reqs[0].service, reqs[0].method = strings.TrimSuffix(in.Method, subscribeMethodSuffix), subscribeMethod[0]
  170. reqs[0].params = in.Payload
  171. return reqs, false, nil
  172. }
  173. return nil, false, &invalidRequestError{"Unable to parse subscription request"}
  174. }
  175. if strings.HasSuffix(in.Method, unsubscribeMethodSuffix) {
  176. return []rpcRequest{{id: &in.Id, isPubSub: true,
  177. method: in.Method, params: in.Payload}}, false, nil
  178. }
  179. elems := strings.Split(in.Method, serviceMethodSeparator)
  180. if len(elems) != 2 {
  181. return nil, false, &methodNotFoundError{in.Method, ""}
  182. }
  183. // regular RPC call
  184. if len(in.Payload) == 0 {
  185. return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id}}, false, nil
  186. }
  187. return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id, params: in.Payload}}, false, nil
  188. }
  189. // parseBatchRequest will parse a batch request into a collection of requests from the given RawMessage, an indication
  190. // if the request was a batch or an error when the request could not be read.
  191. func parseBatchRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) {
  192. var in []jsonRequest
  193. if err := json.Unmarshal(incomingMsg, &in); err != nil {
  194. return nil, false, &invalidMessageError{err.Error()}
  195. }
  196. requests := make([]rpcRequest, len(in))
  197. for i, r := range in {
  198. if err := checkReqId(r.Id); err != nil {
  199. return nil, false, &invalidMessageError{err.Error()}
  200. }
  201. id := &in[i].Id
  202. // subscribe are special, they will always use `subscriptionMethod` as first param in the payload
  203. if strings.HasSuffix(r.Method, subscribeMethodSuffix) {
  204. requests[i] = rpcRequest{id: id, isPubSub: true}
  205. if len(r.Payload) > 0 {
  206. // first param must be subscription name
  207. var subscribeMethod [1]string
  208. if err := json.Unmarshal(r.Payload, &subscribeMethod); err != nil {
  209. log.Debug(fmt.Sprintf("Unable to parse subscription method: %v\n", err))
  210. return nil, false, &invalidRequestError{"Unable to parse subscription request"}
  211. }
  212. requests[i].service, requests[i].method = strings.TrimSuffix(r.Method, subscribeMethodSuffix), subscribeMethod[0]
  213. requests[i].params = r.Payload
  214. continue
  215. }
  216. return nil, true, &invalidRequestError{"Unable to parse (un)subscribe request arguments"}
  217. }
  218. if strings.HasSuffix(r.Method, unsubscribeMethodSuffix) {
  219. requests[i] = rpcRequest{id: id, isPubSub: true, method: r.Method, params: r.Payload}
  220. continue
  221. }
  222. if len(r.Payload) == 0 {
  223. requests[i] = rpcRequest{id: id, params: nil}
  224. } else {
  225. requests[i] = rpcRequest{id: id, params: r.Payload}
  226. }
  227. if elem := strings.Split(r.Method, serviceMethodSeparator); len(elem) == 2 {
  228. requests[i].service, requests[i].method = elem[0], elem[1]
  229. } else {
  230. requests[i].err = &methodNotFoundError{r.Method, ""}
  231. }
  232. }
  233. return requests, true, nil
  234. }
  235. // ParseRequestArguments tries to parse the given params (json.RawMessage) with the given
  236. // types. It returns the parsed values or an error when the parsing failed.
  237. func (c *jsonCodec) ParseRequestArguments(argTypes []reflect.Type, params interface{}) ([]reflect.Value, Error) {
  238. if args, ok := params.(json.RawMessage); !ok {
  239. return nil, &invalidParamsError{"Invalid params supplied"}
  240. } else {
  241. return parsePositionalArguments(args, argTypes)
  242. }
  243. }
  244. // parsePositionalArguments tries to parse the given args to an array of values with the
  245. // given types. It returns the parsed values or an error when the args could not be
  246. // parsed. Missing optional arguments are returned as reflect.Zero values.
  247. func parsePositionalArguments(rawArgs json.RawMessage, types []reflect.Type) ([]reflect.Value, Error) {
  248. // Read beginning of the args array.
  249. dec := json.NewDecoder(bytes.NewReader(rawArgs))
  250. if tok, _ := dec.Token(); tok != json.Delim('[') {
  251. return nil, &invalidParamsError{"non-array args"}
  252. }
  253. // Read args.
  254. args := make([]reflect.Value, 0, len(types))
  255. for i := 0; dec.More(); i++ {
  256. if i >= len(types) {
  257. return nil, &invalidParamsError{fmt.Sprintf("too many arguments, want at most %d", len(types))}
  258. }
  259. argval := reflect.New(types[i])
  260. if err := dec.Decode(argval.Interface()); err != nil {
  261. return nil, &invalidParamsError{fmt.Sprintf("invalid argument %d: %v", i, err)}
  262. }
  263. if argval.IsNil() && types[i].Kind() != reflect.Ptr {
  264. return nil, &invalidParamsError{fmt.Sprintf("missing value for required argument %d", i)}
  265. }
  266. args = append(args, argval.Elem())
  267. }
  268. // Read end of args array.
  269. if _, err := dec.Token(); err != nil {
  270. return nil, &invalidParamsError{err.Error()}
  271. }
  272. // Set any missing args to nil.
  273. for i := len(args); i < len(types); i++ {
  274. if types[i].Kind() != reflect.Ptr {
  275. return nil, &invalidParamsError{fmt.Sprintf("missing value for required argument %d", i)}
  276. }
  277. args = append(args, reflect.Zero(types[i]))
  278. }
  279. return args, nil
  280. }
  281. // CreateResponse will create a JSON-RPC success response with the given id and reply as result.
  282. func (c *jsonCodec) CreateResponse(id interface{}, reply interface{}) interface{} {
  283. if isHexNum(reflect.TypeOf(reply)) {
  284. return &jsonSuccessResponse{Version: jsonrpcVersion, Id: id, Result: fmt.Sprintf(`%#x`, reply)}
  285. }
  286. return &jsonSuccessResponse{Version: jsonrpcVersion, Id: id, Result: reply}
  287. }
  288. // CreateErrorResponse will create a JSON-RPC error response with the given id and error.
  289. func (c *jsonCodec) CreateErrorResponse(id interface{}, err Error) interface{} {
  290. return &jsonErrResponse{Version: jsonrpcVersion, Id: id, Error: jsonError{Code: err.ErrorCode(), Message: err.Error()}}
  291. }
  292. // CreateErrorResponseWithInfo will create a JSON-RPC error response with the given id and error.
  293. // info is optional and contains additional information about the error. When an empty string is passed it is ignored.
  294. func (c *jsonCodec) CreateErrorResponseWithInfo(id interface{}, err Error, info interface{}) interface{} {
  295. return &jsonErrResponse{Version: jsonrpcVersion, Id: id,
  296. Error: jsonError{Code: err.ErrorCode(), Message: err.Error(), Data: info}}
  297. }
  298. // CreateNotification will create a JSON-RPC notification with the given subscription id and event as params.
  299. func (c *jsonCodec) CreateNotification(subid, namespace string, event interface{}) interface{} {
  300. if isHexNum(reflect.TypeOf(event)) {
  301. return &jsonNotification{Version: jsonrpcVersion, Method: namespace + notificationMethodSuffix,
  302. Params: jsonSubscription{Subscription: subid, Result: fmt.Sprintf(`%#x`, event)}}
  303. }
  304. return &jsonNotification{Version: jsonrpcVersion, Method: namespace + notificationMethodSuffix,
  305. Params: jsonSubscription{Subscription: subid, Result: event}}
  306. }
  307. // Write message to client
  308. func (c *jsonCodec) Write(res interface{}) error {
  309. c.encMu.Lock()
  310. defer c.encMu.Unlock()
  311. return c.encode(res)
  312. }
  313. // Close the underlying connection
  314. func (c *jsonCodec) Close() {
  315. c.closer.Do(func() {
  316. close(c.closed)
  317. c.rw.Close()
  318. })
  319. }
  320. // Closed returns a channel which will be closed when Close is called
  321. func (c *jsonCodec) Closed() <-chan interface{} {
  322. return c.closed
  323. }