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