json.go 12 KB

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