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