github.com/Emus88/go-ethereum@v1.9.7/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 "context" 22 "encoding/json" 23 "errors" 24 "fmt" 25 "io" 26 "reflect" 27 "strings" 28 "sync" 29 "time" 30 ) 31 32 const ( 33 vsn = "2.0" 34 serviceMethodSeparator = "_" 35 subscribeMethodSuffix = "_subscribe" 36 unsubscribeMethodSuffix = "_unsubscribe" 37 notificationMethodSuffix = "_subscription" 38 39 defaultWriteTimeout = 10 * time.Second // used if context has no deadline 40 ) 41 42 var null = json.RawMessage("null") 43 44 type subscriptionResult struct { 45 ID string `json:"subscription"` 46 Result json.RawMessage `json:"result,omitempty"` 47 } 48 49 // A value of this type can a JSON-RPC request, notification, successful response or 50 // error response. Which one it is depends on the fields. 51 type jsonrpcMessage struct { 52 Version string `json:"jsonrpc,omitempty"` 53 ID json.RawMessage `json:"id,omitempty"` 54 Method string `json:"method,omitempty"` 55 Params json.RawMessage `json:"params,omitempty"` 56 Error *jsonError `json:"error,omitempty"` 57 Result json.RawMessage `json:"result,omitempty"` 58 } 59 60 func (msg *jsonrpcMessage) isNotification() bool { 61 return msg.ID == nil && msg.Method != "" 62 } 63 64 func (msg *jsonrpcMessage) isCall() bool { 65 return msg.hasValidID() && msg.Method != "" 66 } 67 68 func (msg *jsonrpcMessage) isResponse() bool { 69 return msg.hasValidID() && msg.Method == "" && msg.Params == nil && (msg.Result != nil || msg.Error != nil) 70 } 71 72 func (msg *jsonrpcMessage) hasValidID() bool { 73 return len(msg.ID) > 0 && msg.ID[0] != '{' && msg.ID[0] != '[' 74 } 75 76 func (msg *jsonrpcMessage) isSubscribe() bool { 77 return strings.HasSuffix(msg.Method, subscribeMethodSuffix) 78 } 79 80 func (msg *jsonrpcMessage) isUnsubscribe() bool { 81 return strings.HasSuffix(msg.Method, unsubscribeMethodSuffix) 82 } 83 84 func (msg *jsonrpcMessage) namespace() string { 85 elem := strings.SplitN(msg.Method, serviceMethodSeparator, 2) 86 return elem[0] 87 } 88 89 func (msg *jsonrpcMessage) String() string { 90 b, _ := json.Marshal(msg) 91 return string(b) 92 } 93 94 func (msg *jsonrpcMessage) errorResponse(err error) *jsonrpcMessage { 95 resp := errorMessage(err) 96 resp.ID = msg.ID 97 return resp 98 } 99 100 func (msg *jsonrpcMessage) response(result interface{}) *jsonrpcMessage { 101 enc, err := json.Marshal(result) 102 if err != nil { 103 // TODO: wrap with 'internal server error' 104 return msg.errorResponse(err) 105 } 106 return &jsonrpcMessage{Version: vsn, ID: msg.ID, Result: enc} 107 } 108 109 func errorMessage(err error) *jsonrpcMessage { 110 msg := &jsonrpcMessage{Version: vsn, ID: null, Error: &jsonError{ 111 Code: defaultErrorCode, 112 Message: err.Error(), 113 }} 114 ec, ok := err.(Error) 115 if ok { 116 msg.Error.Code = ec.ErrorCode() 117 } 118 return msg 119 } 120 121 type jsonError struct { 122 Code int `json:"code"` 123 Message string `json:"message"` 124 Data interface{} `json:"data,omitempty"` 125 } 126 127 func (err *jsonError) Error() string { 128 if err.Message == "" { 129 return fmt.Sprintf("json-rpc error %d", err.Code) 130 } 131 return err.Message 132 } 133 134 func (err *jsonError) ErrorCode() int { 135 return err.Code 136 } 137 138 // Conn is a subset of the methods of net.Conn which are sufficient for ServerCodec. 139 type Conn interface { 140 io.ReadWriteCloser 141 SetWriteDeadline(time.Time) error 142 } 143 144 type deadlineCloser interface { 145 io.Closer 146 SetWriteDeadline(time.Time) error 147 } 148 149 // ConnRemoteAddr wraps the RemoteAddr operation, which returns a description 150 // of the peer address of a connection. If a Conn also implements ConnRemoteAddr, this 151 // description is used in log messages. 152 type ConnRemoteAddr interface { 153 RemoteAddr() string 154 } 155 156 // connWithRemoteAddr overrides the remote address of a connection. 157 type connWithRemoteAddr struct { 158 Conn 159 addr string 160 } 161 162 func (c connWithRemoteAddr) RemoteAddr() string { return c.addr } 163 164 // jsonCodec reads and writes JSON-RPC messages to the underlying connection. It also has 165 // support for parsing arguments and serializing (result) objects. 166 type jsonCodec struct { 167 remoteAddr string 168 closer sync.Once // close closed channel once 169 closed chan interface{} // closed on Close 170 decode func(v interface{}) error // decoder to allow multiple transports 171 encMu sync.Mutex // guards the encoder 172 encode func(v interface{}) error // encoder to allow multiple transports 173 conn deadlineCloser 174 } 175 176 func newCodec(conn deadlineCloser, encode, decode func(v interface{}) error) ServerCodec { 177 codec := &jsonCodec{ 178 closed: make(chan interface{}), 179 encode: encode, 180 decode: decode, 181 conn: conn, 182 } 183 if ra, ok := conn.(ConnRemoteAddr); ok { 184 codec.remoteAddr = ra.RemoteAddr() 185 } 186 return codec 187 } 188 189 // NewJSONCodec creates a codec that reads from the given connection. If conn implements 190 // ConnRemoteAddr, log messages will use it to include the remote address of the 191 // connection. 192 func NewJSONCodec(conn Conn) ServerCodec { 193 enc := json.NewEncoder(conn) 194 dec := json.NewDecoder(conn) 195 dec.UseNumber() 196 return newCodec(conn, enc.Encode, dec.Decode) 197 } 198 199 func (c *jsonCodec) RemoteAddr() string { 200 return c.remoteAddr 201 } 202 203 func (c *jsonCodec) Read() (msg []*jsonrpcMessage, batch bool, err error) { 204 // Decode the next JSON object in the input stream. 205 // This verifies basic syntax, etc. 206 var rawmsg json.RawMessage 207 if err := c.decode(&rawmsg); err != nil { 208 return nil, false, err 209 } 210 msg, batch = parseMessage(rawmsg) 211 return msg, batch, nil 212 } 213 214 // Write sends a message to client. 215 func (c *jsonCodec) Write(ctx context.Context, v interface{}) error { 216 c.encMu.Lock() 217 defer c.encMu.Unlock() 218 219 deadline, ok := ctx.Deadline() 220 if !ok { 221 deadline = time.Now().Add(defaultWriteTimeout) 222 } 223 c.conn.SetWriteDeadline(deadline) 224 return c.encode(v) 225 } 226 227 // Close the underlying connection 228 func (c *jsonCodec) Close() { 229 c.closer.Do(func() { 230 close(c.closed) 231 c.conn.Close() 232 }) 233 } 234 235 // Closed returns a channel which will be closed when Close is called 236 func (c *jsonCodec) Closed() <-chan interface{} { 237 return c.closed 238 } 239 240 // parseMessage parses raw bytes as a (batch of) JSON-RPC message(s). There are no error 241 // checks in this function because the raw message has already been syntax-checked when it 242 // is called. Any non-JSON-RPC messages in the input return the zero value of 243 // jsonrpcMessage. 244 func parseMessage(raw json.RawMessage) ([]*jsonrpcMessage, bool) { 245 if !isBatch(raw) { 246 msgs := []*jsonrpcMessage{{}} 247 json.Unmarshal(raw, &msgs[0]) 248 return msgs, false 249 } 250 dec := json.NewDecoder(bytes.NewReader(raw)) 251 dec.Token() // skip '[' 252 var msgs []*jsonrpcMessage 253 for dec.More() { 254 msgs = append(msgs, new(jsonrpcMessage)) 255 dec.Decode(&msgs[len(msgs)-1]) 256 } 257 return msgs, true 258 } 259 260 // isBatch returns true when the first non-whitespace characters is '[' 261 func isBatch(raw json.RawMessage) bool { 262 for _, c := range raw { 263 // skip insignificant whitespace (http://www.ietf.org/rfc/rfc4627.txt) 264 if c == 0x20 || c == 0x09 || c == 0x0a || c == 0x0d { 265 continue 266 } 267 return c == '[' 268 } 269 return false 270 } 271 272 // parsePositionalArguments tries to parse the given args to an array of values with the 273 // given types. It returns the parsed values or an error when the args could not be 274 // parsed. Missing optional arguments are returned as reflect.Zero values. 275 func parsePositionalArguments(rawArgs json.RawMessage, types []reflect.Type) ([]reflect.Value, error) { 276 dec := json.NewDecoder(bytes.NewReader(rawArgs)) 277 var args []reflect.Value 278 tok, err := dec.Token() 279 switch { 280 case err == io.EOF || tok == nil && err == nil: 281 // "params" is optional and may be empty. Also allow "params":null even though it's 282 // not in the spec because our own client used to send it. 283 case err != nil: 284 return nil, err 285 case tok == json.Delim('['): 286 // Read argument array. 287 if args, err = parseArgumentArray(dec, types); err != nil { 288 return nil, err 289 } 290 default: 291 return nil, errors.New("non-array args") 292 } 293 // Set any missing args to nil. 294 for i := len(args); i < len(types); i++ { 295 if types[i].Kind() != reflect.Ptr { 296 return nil, fmt.Errorf("missing value for required argument %d", i) 297 } 298 args = append(args, reflect.Zero(types[i])) 299 } 300 return args, nil 301 } 302 303 func parseArgumentArray(dec *json.Decoder, types []reflect.Type) ([]reflect.Value, error) { 304 args := make([]reflect.Value, 0, len(types)) 305 for i := 0; dec.More(); i++ { 306 if i >= len(types) { 307 return args, fmt.Errorf("too many arguments, want at most %d", len(types)) 308 } 309 argval := reflect.New(types[i]) 310 if err := dec.Decode(argval.Interface()); err != nil { 311 return args, fmt.Errorf("invalid argument %d: %v", i, err) 312 } 313 if argval.IsNil() && types[i].Kind() != reflect.Ptr { 314 return args, fmt.Errorf("missing value for required argument %d", i) 315 } 316 args = append(args, argval.Elem()) 317 } 318 // Read end of args array. 319 _, err := dec.Token() 320 return args, err 321 } 322 323 // parseSubscriptionName extracts the subscription name from an encoded argument array. 324 func parseSubscriptionName(rawArgs json.RawMessage) (string, error) { 325 dec := json.NewDecoder(bytes.NewReader(rawArgs)) 326 if tok, _ := dec.Token(); tok != json.Delim('[') { 327 return "", errors.New("non-array args") 328 } 329 v, _ := dec.Token() 330 method, ok := v.(string) 331 if !ok { 332 return "", errors.New("expected subscription name as first argument") 333 } 334 return method, nil 335 }