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