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