github.com/4000d/go-ethereum@v1.8.2-0.20180223170251-423c8bb1d821/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/ethereum/go-ethereum/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 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 return parsePositionalArguments(args, argTypes) 264 } 265 } 266 267 // parsePositionalArguments tries to parse the given args to an array of values with the 268 // given types. It returns the parsed values or an error when the args could not be 269 // parsed. Missing optional arguments are returned as reflect.Zero values. 270 func parsePositionalArguments(rawArgs json.RawMessage, types []reflect.Type) ([]reflect.Value, Error) { 271 // Read beginning of the args array. 272 dec := json.NewDecoder(bytes.NewReader(rawArgs)) 273 if tok, _ := dec.Token(); tok != json.Delim('[') { 274 return nil, &invalidParamsError{"non-array args"} 275 } 276 // Read args. 277 args := make([]reflect.Value, 0, len(types)) 278 for i := 0; dec.More(); i++ { 279 if i >= len(types) { 280 return nil, &invalidParamsError{fmt.Sprintf("too many arguments, want at most %d", len(types))} 281 } 282 argval := reflect.New(types[i]) 283 if err := dec.Decode(argval.Interface()); err != nil { 284 return nil, &invalidParamsError{fmt.Sprintf("invalid argument %d: %v", i, err)} 285 } 286 if argval.IsNil() && types[i].Kind() != reflect.Ptr { 287 return nil, &invalidParamsError{fmt.Sprintf("missing value for required argument %d", i)} 288 } 289 args = append(args, argval.Elem()) 290 } 291 // Read end of args array. 292 if _, err := dec.Token(); err != nil { 293 return nil, &invalidParamsError{err.Error()} 294 } 295 // Set any missing args to nil. 296 for i := len(args); i < len(types); i++ { 297 if types[i].Kind() != reflect.Ptr { 298 return nil, &invalidParamsError{fmt.Sprintf("missing value for required argument %d", i)} 299 } 300 args = append(args, reflect.Zero(types[i])) 301 } 302 return args, nil 303 } 304 305 // CreateResponse will create a JSON-RPC success response with the given id and reply as result. 306 func (c *jsonCodec) CreateResponse(id interface{}, reply interface{}) interface{} { 307 if isHexNum(reflect.TypeOf(reply)) { 308 return &jsonSuccessResponse{Version: jsonrpcVersion, Id: id, Result: fmt.Sprintf(`%#x`, reply)} 309 } 310 return &jsonSuccessResponse{Version: jsonrpcVersion, Id: id, Result: reply} 311 } 312 313 // CreateErrorResponse will create a JSON-RPC error response with the given id and error. 314 func (c *jsonCodec) CreateErrorResponse(id interface{}, err Error) interface{} { 315 return &jsonErrResponse{Version: jsonrpcVersion, Id: id, Error: jsonError{Code: err.ErrorCode(), Message: err.Error()}} 316 } 317 318 // CreateErrorResponseWithInfo will create a JSON-RPC error response with the given id and error. 319 // info is optional and contains additional information about the error. When an empty string is passed it is ignored. 320 func (c *jsonCodec) CreateErrorResponseWithInfo(id interface{}, err Error, info interface{}) interface{} { 321 return &jsonErrResponse{Version: jsonrpcVersion, Id: id, 322 Error: jsonError{Code: err.ErrorCode(), Message: err.Error(), Data: info}} 323 } 324 325 // CreateNotification will create a JSON-RPC notification with the given subscription id and event as params. 326 func (c *jsonCodec) CreateNotification(subid, namespace string, event interface{}) interface{} { 327 if isHexNum(reflect.TypeOf(event)) { 328 return &jsonNotification{Version: jsonrpcVersion, Method: namespace + notificationMethodSuffix, 329 Params: jsonSubscription{Subscription: subid, Result: fmt.Sprintf(`%#x`, event)}} 330 } 331 332 return &jsonNotification{Version: jsonrpcVersion, Method: namespace + notificationMethodSuffix, 333 Params: jsonSubscription{Subscription: subid, Result: event}} 334 } 335 336 // Write message to client 337 func (c *jsonCodec) Write(res interface{}) error { 338 c.encMu.Lock() 339 defer c.encMu.Unlock() 340 341 return c.e.Encode(res) 342 } 343 344 // Close the underlying connection 345 func (c *jsonCodec) Close() { 346 c.closer.Do(func() { 347 close(c.closed) 348 c.rw.Close() 349 }) 350 } 351 352 // Closed returns a channel which will be closed when Close is called 353 func (c *jsonCodec) Closed() <-chan interface{} { 354 return c.closed 355 }