json.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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 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 strings.HasSuffix(in.Method, subscribeMethodSuffix) {
  145. reqs := []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. log.Debug(fmt.Sprintf("Unable to parse subscription method: %v\n", err))
  151. return nil, false, &invalidRequestError{"Unable to parse subscription request"}
  152. }
  153. reqs[0].service, reqs[0].method = strings.TrimSuffix(in.Method, subscribeMethodSuffix), subscribeMethod[0]
  154. reqs[0].params = in.Payload
  155. return reqs, false, nil
  156. }
  157. return nil, false, &invalidRequestError{"Unable to parse subscription request"}
  158. }
  159. if strings.HasSuffix(in.Method, unsubscribeMethodSuffix) {
  160. return []rpcRequest{{id: &in.Id, isPubSub: true,
  161. method: in.Method, params: in.Payload}}, false, nil
  162. }
  163. elems := strings.Split(in.Method, serviceMethodSeparator)
  164. if len(elems) != 2 {
  165. return nil, false, &methodNotFoundError{in.Method, ""}
  166. }
  167. // regular RPC call
  168. if len(in.Payload) == 0 {
  169. return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id}}, false, nil
  170. }
  171. return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id, params: in.Payload}}, false, nil
  172. }
  173. // parseBatchRequest will parse a batch request into a collection of requests from the given RawMessage, an indication
  174. // if the request was a batch or an error when the request could not be read.
  175. func parseBatchRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) {
  176. var in []jsonRequest
  177. if err := json.Unmarshal(incomingMsg, &in); err != nil {
  178. return nil, false, &invalidMessageError{err.Error()}
  179. }
  180. requests := make([]rpcRequest, len(in))
  181. for i, r := range in {
  182. if err := checkReqId(r.Id); err != nil {
  183. return nil, false, &invalidMessageError{err.Error()}
  184. }
  185. id := &in[i].Id
  186. // subscribe are special, they will always use `subscriptionMethod` as first param in the payload
  187. if strings.HasSuffix(r.Method, subscribeMethodSuffix) {
  188. requests[i] = rpcRequest{id: id, isPubSub: true}
  189. if len(r.Payload) > 0 {
  190. // first param must be subscription name
  191. var subscribeMethod [1]string
  192. if err := json.Unmarshal(r.Payload, &subscribeMethod); err != nil {
  193. log.Debug(fmt.Sprintf("Unable to parse subscription method: %v\n", err))
  194. return nil, false, &invalidRequestError{"Unable to parse subscription request"}
  195. }
  196. requests[i].service, requests[i].method = strings.TrimSuffix(r.Method, subscribeMethodSuffix), subscribeMethod[0]
  197. requests[i].params = r.Payload
  198. continue
  199. }
  200. return nil, true, &invalidRequestError{"Unable to parse (un)subscribe request arguments"}
  201. }
  202. if strings.HasSuffix(r.Method, unsubscribeMethodSuffix) {
  203. requests[i] = rpcRequest{id: id, isPubSub: true, method: r.Method, params: r.Payload}
  204. continue
  205. }
  206. if len(r.Payload) == 0 {
  207. requests[i] = rpcRequest{id: id, params: nil}
  208. } else {
  209. requests[i] = rpcRequest{id: id, params: r.Payload}
  210. }
  211. if elem := strings.Split(r.Method, serviceMethodSeparator); len(elem) == 2 {
  212. requests[i].service, requests[i].method = elem[0], elem[1]
  213. } else {
  214. requests[i].err = &methodNotFoundError{r.Method, ""}
  215. }
  216. }
  217. return requests, true, nil
  218. }
  219. // ParseRequestArguments tries to parse the given params (json.RawMessage) with the given
  220. // types. It returns the parsed values or an error when the parsing failed.
  221. func (c *jsonCodec) ParseRequestArguments(argTypes []reflect.Type, params interface{}) ([]reflect.Value, Error) {
  222. if args, ok := params.(json.RawMessage); !ok {
  223. return nil, &invalidParamsError{"Invalid params supplied"}
  224. } else {
  225. return parsePositionalArguments(args, argTypes)
  226. }
  227. }
  228. // parsePositionalArguments tries to parse the given args to an array of values with the
  229. // given types. It returns the parsed values or an error when the args could not be
  230. // parsed. Missing optional arguments are returned as reflect.Zero values.
  231. func parsePositionalArguments(rawArgs json.RawMessage, types []reflect.Type) ([]reflect.Value, Error) {
  232. // Read beginning of the args array.
  233. dec := json.NewDecoder(bytes.NewReader(rawArgs))
  234. if tok, _ := dec.Token(); tok != json.Delim('[') {
  235. return nil, &invalidParamsError{"non-array args"}
  236. }
  237. // Read args.
  238. args := make([]reflect.Value, 0, len(types))
  239. for i := 0; dec.More(); i++ {
  240. if i >= len(types) {
  241. return nil, &invalidParamsError{fmt.Sprintf("too many arguments, want at most %d", len(types))}
  242. }
  243. argval := reflect.New(types[i])
  244. if err := dec.Decode(argval.Interface()); err != nil {
  245. return nil, &invalidParamsError{fmt.Sprintf("invalid argument %d: %v", i, err)}
  246. }
  247. if argval.IsNil() && types[i].Kind() != reflect.Ptr {
  248. return nil, &invalidParamsError{fmt.Sprintf("missing value for required argument %d", i)}
  249. }
  250. args = append(args, argval.Elem())
  251. }
  252. // Read end of args array.
  253. if _, err := dec.Token(); err != nil {
  254. return nil, &invalidParamsError{err.Error()}
  255. }
  256. // Set any missing args to nil.
  257. for i := len(args); i < len(types); i++ {
  258. if types[i].Kind() != reflect.Ptr {
  259. return nil, &invalidParamsError{fmt.Sprintf("missing value for required argument %d", i)}
  260. }
  261. args = append(args, reflect.Zero(types[i]))
  262. }
  263. return args, nil
  264. }
  265. // CreateResponse will create a JSON-RPC success response with the given id and reply as result.
  266. func (c *jsonCodec) CreateResponse(id interface{}, reply interface{}) interface{} {
  267. if isHexNum(reflect.TypeOf(reply)) {
  268. return &jsonSuccessResponse{Version: jsonrpcVersion, Id: id, Result: fmt.Sprintf(`%#x`, reply)}
  269. }
  270. return &jsonSuccessResponse{Version: jsonrpcVersion, Id: id, Result: reply}
  271. }
  272. // CreateErrorResponse will create a JSON-RPC error response with the given id and error.
  273. func (c *jsonCodec) CreateErrorResponse(id interface{}, err Error) interface{} {
  274. return &jsonErrResponse{Version: jsonrpcVersion, Id: id, Error: jsonError{Code: err.ErrorCode(), Message: err.Error()}}
  275. }
  276. // CreateErrorResponseWithInfo will create a JSON-RPC error response with the given id and error.
  277. // info is optional and contains additional information about the error. When an empty string is passed it is ignored.
  278. func (c *jsonCodec) CreateErrorResponseWithInfo(id interface{}, err Error, info interface{}) interface{} {
  279. return &jsonErrResponse{Version: jsonrpcVersion, Id: id,
  280. Error: jsonError{Code: err.ErrorCode(), Message: err.Error(), Data: info}}
  281. }
  282. // CreateNotification will create a JSON-RPC notification with the given subscription id and event as params.
  283. func (c *jsonCodec) CreateNotification(subid, namespace string, event interface{}) interface{} {
  284. if isHexNum(reflect.TypeOf(event)) {
  285. return &jsonNotification{Version: jsonrpcVersion, Method: namespace + notificationMethodSuffix,
  286. Params: jsonSubscription{Subscription: subid, Result: fmt.Sprintf(`%#x`, event)}}
  287. }
  288. return &jsonNotification{Version: jsonrpcVersion, Method: namespace + notificationMethodSuffix,
  289. Params: jsonSubscription{Subscription: subid, Result: event}}
  290. }
  291. // Write message to client
  292. func (c *jsonCodec) Write(res interface{}) error {
  293. c.encMu.Lock()
  294. defer c.encMu.Unlock()
  295. return c.e.Encode(res)
  296. }
  297. // Close the underlying connection
  298. func (c *jsonCodec) Close() {
  299. c.closer.Do(func() {
  300. close(c.closed)
  301. c.rw.Close()
  302. })
  303. }
  304. // Closed returns a channel which will be closed when Close is called
  305. func (c *jsonCodec) Closed() <-chan interface{} {
  306. return c.closed
  307. }