github.com/dim4egster/coreth@v0.10.2/rpc/client.go (about) 1 // (c) 2019-2020, Ava Labs, Inc. 2 // 3 // This file is a derived work, based on the go-ethereum library whose original 4 // notices appear below. 5 // 6 // It is distributed under a license compatible with the licensing terms of the 7 // original code from which it is derived. 8 // 9 // Much love to the original authors for their work. 10 // ********** 11 // Copyright 2016 The go-ethereum Authors 12 // This file is part of the go-ethereum library. 13 // 14 // The go-ethereum library is free software: you can redistribute it and/or modify 15 // it under the terms of the GNU Lesser General Public License as published by 16 // the Free Software Foundation, either version 3 of the License, or 17 // (at your option) any later version. 18 // 19 // The go-ethereum library is distributed in the hope that it will be useful, 20 // but WITHOUT ANY WARRANTY; without even the implied warranty of 21 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 // GNU Lesser General Public License for more details. 23 // 24 // You should have received a copy of the GNU Lesser General Public License 25 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 26 27 package rpc 28 29 import ( 30 "context" 31 "encoding/json" 32 "errors" 33 "fmt" 34 "net/url" 35 "reflect" 36 "strconv" 37 "sync/atomic" 38 "time" 39 40 "github.com/ethereum/go-ethereum/log" 41 ) 42 43 var ( 44 ErrClientQuit = errors.New("client is closed") 45 ErrNoResult = errors.New("no result in JSON-RPC response") 46 ErrSubscriptionQueueOverflow = errors.New("subscription queue overflow") 47 errClientReconnected = errors.New("client reconnected") 48 errDead = errors.New("connection lost") 49 ) 50 51 const ( 52 // Timeouts 53 defaultDialTimeout = 10 * time.Second // used if context has no deadline 54 subscribeTimeout = 5 * time.Second // overall timeout eth_subscribe, rpc_modules calls 55 ) 56 57 const ( 58 // Subscriptions are removed when the subscriber cannot keep up. 59 // 60 // This can be worked around by supplying a channel with sufficiently sized buffer, 61 // but this can be inconvenient and hard to explain in the docs. Another issue with 62 // buffered channels is that the buffer is static even though it might not be needed 63 // most of the time. 64 // 65 // The approach taken here is to maintain a per-subscription linked list buffer 66 // shrinks on demand. If the buffer reaches the size below, the subscription is 67 // dropped. 68 maxClientSubscriptionBuffer = 20000 69 ) 70 71 // BatchElem is an element in a batch request. 72 type BatchElem struct { 73 Method string 74 Args []interface{} 75 // The result is unmarshaled into this field. Result must be set to a 76 // non-nil pointer value of the desired type, otherwise the response will be 77 // discarded. 78 Result interface{} 79 // Error is set if the server returns an error for this request, or if 80 // unmarshaling into Result fails. It is not set for I/O errors. 81 Error error 82 } 83 84 // Client represents a connection to an RPC server. 85 type Client struct { 86 idgen func() ID // for subscriptions 87 isHTTP bool // isHTTP specifies if the client uses an HTTP connection 88 services *serviceRegistry 89 90 idCounter uint32 91 92 // This function, if non-nil, is called when the connection is lost. 93 reconnectFunc reconnectFunc 94 95 // writeConn is used for writing to the connection on the caller's goroutine. It should 96 // only be accessed outside of dispatch, with the write lock held. The write lock is 97 // taken by sending on reqInit and released by sending on reqSent. 98 writeConn jsonWriter 99 100 // for dispatch 101 close chan struct{} 102 closing chan struct{} // closed when client is quitting 103 didClose chan struct{} // closed when client quits 104 reconnected chan ServerCodec // where write/reconnect sends the new connection 105 readOp chan readOp // read messages 106 readErr chan error // errors from read 107 reqInit chan *requestOp // register response IDs, takes write lock 108 reqSent chan error // signals write completion, releases write lock 109 reqTimeout chan *requestOp // removes response IDs when call timeout expires 110 } 111 112 type reconnectFunc func(ctx context.Context) (ServerCodec, error) 113 114 type clientContextKey struct{} 115 116 type clientConn struct { 117 codec ServerCodec 118 handler *handler 119 } 120 121 func (c *Client) newClientConn(conn ServerCodec, apiMaxDuration, refillRate, maxStored time.Duration) *clientConn { 122 ctx := context.Background() 123 ctx = context.WithValue(ctx, clientContextKey{}, c) 124 ctx = context.WithValue(ctx, peerInfoContextKey{}, conn.peerInfo()) 125 handler := newHandler(ctx, conn, c.idgen, c.services) 126 127 // When [apiMaxDuration] or [refillRate]/[maxStored] is 0 (as is the case for 128 // all client invocations of this function), it is ignored. 129 handler.deadlineContext = apiMaxDuration 130 handler.addLimiter(refillRate, maxStored) 131 return &clientConn{conn, handler} 132 } 133 134 func (cc *clientConn) close(err error, inflightReq *requestOp) { 135 cc.handler.close(err, inflightReq) 136 cc.codec.close() 137 } 138 139 type readOp struct { 140 msgs []*jsonrpcMessage 141 batch bool 142 } 143 144 type requestOp struct { 145 ids []json.RawMessage 146 err error 147 resp chan *jsonrpcMessage // receives up to len(ids) responses 148 sub *ClientSubscription // only set for EthSubscribe requests 149 } 150 151 func (op *requestOp) wait(ctx context.Context, c *Client) (*jsonrpcMessage, error) { 152 select { 153 case <-ctx.Done(): 154 // Send the timeout to dispatch so it can remove the request IDs. 155 if !c.isHTTP { 156 select { 157 case c.reqTimeout <- op: 158 case <-c.closing: 159 } 160 } 161 return nil, ctx.Err() 162 case resp := <-op.resp: 163 return resp, op.err 164 } 165 } 166 167 // Dial creates a new client for the given URL. 168 // 169 // The currently supported URL schemes are "http", "https", "ws" and "wss". If rawurl is a 170 // file name with no URL scheme, a local socket connection is established using UNIX 171 // domain sockets on supported platforms and named pipes on Windows. If you want to 172 // configure transport options, use DialHTTP, DialWebsocket or DialIPC instead. 173 // 174 // For websocket connections, the origin is set to the local host name. 175 // 176 // The client reconnects automatically if the connection is lost. 177 func Dial(rawurl string) (*Client, error) { 178 return DialContext(context.Background(), rawurl) 179 } 180 181 // DialContext creates a new RPC client, just like Dial. 182 // 183 // The context is used to cancel or time out the initial connection establishment. It does 184 // not affect subsequent interactions with the client. 185 func DialContext(ctx context.Context, rawurl string) (*Client, error) { 186 u, err := url.Parse(rawurl) 187 if err != nil { 188 return nil, err 189 } 190 switch u.Scheme { 191 case "http", "https": 192 return DialHTTP(rawurl) 193 case "ws", "wss": 194 return DialWebsocket(ctx, rawurl, "") 195 //case "stdio": 196 // return DialStdIO(ctx) 197 //case "": 198 // return DialIPC(ctx, rawurl) 199 default: 200 return nil, fmt.Errorf("no known transport for URL scheme %q", u.Scheme) 201 } 202 } 203 204 // ClientFromContext retrieves the client from the context, if any. This can be used to perform 205 // 'reverse calls' in a handler method. 206 func ClientFromContext(ctx context.Context) (*Client, bool) { 207 client, ok := ctx.Value(clientContextKey{}).(*Client) 208 return client, ok 209 } 210 211 func newClient(initctx context.Context, connect reconnectFunc) (*Client, error) { 212 conn, err := connect(initctx) 213 if err != nil { 214 return nil, err 215 } 216 c := initClient(conn, randomIDGenerator(), new(serviceRegistry), 0, 0, 0) 217 c.reconnectFunc = connect 218 return c, nil 219 } 220 221 func initClient(conn ServerCodec, idgen func() ID, services *serviceRegistry, apiMaxDuration, refillRate, maxStored time.Duration) *Client { 222 _, isHTTP := conn.(*httpConn) 223 c := &Client{ 224 idgen: idgen, 225 isHTTP: isHTTP, 226 services: services, 227 writeConn: conn, 228 close: make(chan struct{}), 229 closing: make(chan struct{}), 230 didClose: make(chan struct{}), 231 reconnected: make(chan ServerCodec), 232 readOp: make(chan readOp), 233 readErr: make(chan error), 234 reqInit: make(chan *requestOp), 235 reqSent: make(chan error, 1), 236 reqTimeout: make(chan *requestOp), 237 } 238 if !c.isHTTP { 239 go c.dispatch(conn, apiMaxDuration, refillRate, maxStored) 240 } 241 return c 242 } 243 244 // RegisterName creates a service for the given receiver type under the given name. When no 245 // methods on the given receiver match the criteria to be either a RPC method or a 246 // subscription an error is returned. Otherwise a new service is created and added to the 247 // service collection this client provides to the server. 248 func (c *Client) RegisterName(name string, receiver interface{}) error { 249 return c.services.registerName(name, receiver) 250 } 251 252 func (c *Client) nextID() json.RawMessage { 253 id := atomic.AddUint32(&c.idCounter, 1) 254 return strconv.AppendUint(nil, uint64(id), 10) 255 } 256 257 // SupportedModules calls the rpc_modules method, retrieving the list of 258 // APIs that are available on the server. 259 func (c *Client) SupportedModules() (map[string]string, error) { 260 var result map[string]string 261 ctx, cancel := context.WithTimeout(context.Background(), subscribeTimeout) 262 defer cancel() 263 err := c.CallContext(ctx, &result, "rpc_modules") 264 return result, err 265 } 266 267 // Close closes the client, aborting any in-flight requests. 268 func (c *Client) Close() { 269 if c.isHTTP { 270 return 271 } 272 select { 273 case c.close <- struct{}{}: 274 <-c.didClose 275 case <-c.didClose: 276 } 277 } 278 279 // SetHeader adds a custom HTTP header to the client's requests. 280 // This method only works for clients using HTTP, it doesn't have 281 // any effect for clients using another transport. 282 func (c *Client) SetHeader(key, value string) { 283 if !c.isHTTP { 284 return 285 } 286 conn := c.writeConn.(*httpConn) 287 conn.mu.Lock() 288 conn.headers.Set(key, value) 289 conn.mu.Unlock() 290 } 291 292 // Call performs a JSON-RPC call with the given arguments and unmarshals into 293 // result if no error occurred. 294 // 295 // The result must be a pointer so that package json can unmarshal into it. You 296 // can also pass nil, in which case the result is ignored. 297 func (c *Client) Call(result interface{}, method string, args ...interface{}) error { 298 ctx := context.Background() 299 return c.CallContext(ctx, result, method, args...) 300 } 301 302 // CallContext performs a JSON-RPC call with the given arguments. If the context is 303 // canceled before the call has successfully returned, CallContext returns immediately. 304 // 305 // The result must be a pointer so that package json can unmarshal into it. You 306 // can also pass nil, in which case the result is ignored. 307 func (c *Client) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error { 308 if result != nil && reflect.TypeOf(result).Kind() != reflect.Ptr { 309 return fmt.Errorf("call result parameter must be pointer or nil interface: %v", result) 310 } 311 msg, err := c.newMessage(method, args...) 312 if err != nil { 313 return err 314 } 315 op := &requestOp{ids: []json.RawMessage{msg.ID}, resp: make(chan *jsonrpcMessage, 1)} 316 317 if c.isHTTP { 318 err = c.sendHTTP(ctx, op, msg) 319 } else { 320 err = c.send(ctx, op, msg) 321 } 322 if err != nil { 323 return err 324 } 325 326 // dispatch has accepted the request and will close the channel when it quits. 327 switch resp, err := op.wait(ctx, c); { 328 case err != nil: 329 return err 330 case resp.Error != nil: 331 return resp.Error 332 case len(resp.Result) == 0: 333 return ErrNoResult 334 default: 335 return json.Unmarshal(resp.Result, &result) 336 } 337 } 338 339 // BatchCall sends all given requests as a single batch and waits for the server 340 // to return a response for all of them. 341 // 342 // In contrast to Call, BatchCall only returns I/O errors. Any error specific to 343 // a request is reported through the Error field of the corresponding BatchElem. 344 // 345 // Note that batch calls may not be executed atomically on the server side. 346 func (c *Client) BatchCall(b []BatchElem) error { 347 ctx := context.Background() 348 return c.BatchCallContext(ctx, b) 349 } 350 351 // BatchCallContext sends all given requests as a single batch and waits for the server 352 // to return a response for all of them. The wait duration is bounded by the 353 // context's deadline. 354 // 355 // In contrast to CallContext, BatchCallContext only returns errors that have occurred 356 // while sending the request. Any error specific to a request is reported through the 357 // Error field of the corresponding BatchElem. 358 // 359 // Note that batch calls may not be executed atomically on the server side. 360 func (c *Client) BatchCallContext(ctx context.Context, b []BatchElem) error { 361 var ( 362 msgs = make([]*jsonrpcMessage, len(b)) 363 byID = make(map[string]int, len(b)) 364 ) 365 op := &requestOp{ 366 ids: make([]json.RawMessage, len(b)), 367 resp: make(chan *jsonrpcMessage, len(b)), 368 } 369 for i, elem := range b { 370 msg, err := c.newMessage(elem.Method, elem.Args...) 371 if err != nil { 372 return err 373 } 374 msgs[i] = msg 375 op.ids[i] = msg.ID 376 byID[string(msg.ID)] = i 377 } 378 379 var err error 380 if c.isHTTP { 381 err = c.sendBatchHTTP(ctx, op, msgs) 382 } else { 383 err = c.send(ctx, op, msgs) 384 } 385 386 // Wait for all responses to come back. 387 for n := 0; n < len(b) && err == nil; n++ { 388 var resp *jsonrpcMessage 389 resp, err = op.wait(ctx, c) 390 if err != nil { 391 break 392 } 393 // Find the element corresponding to this response. 394 // The element is guaranteed to be present because dispatch 395 // only sends valid IDs to our channel. 396 elem := &b[byID[string(resp.ID)]] 397 if resp.Error != nil { 398 elem.Error = resp.Error 399 continue 400 } 401 if len(resp.Result) == 0 { 402 elem.Error = ErrNoResult 403 continue 404 } 405 elem.Error = json.Unmarshal(resp.Result, elem.Result) 406 } 407 return err 408 } 409 410 // Notify sends a notification, i.e. a method call that doesn't expect a response. 411 func (c *Client) Notify(ctx context.Context, method string, args ...interface{}) error { 412 op := new(requestOp) 413 msg, err := c.newMessage(method, args...) 414 if err != nil { 415 return err 416 } 417 msg.ID = nil 418 419 if c.isHTTP { 420 return c.sendHTTP(ctx, op, msg) 421 } 422 return c.send(ctx, op, msg) 423 } 424 425 // EthSubscribe registers a subscription under the "eth" namespace. 426 func (c *Client) EthSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error) { 427 return c.Subscribe(ctx, "eth", channel, args...) 428 } 429 430 // ShhSubscribe registers a subscription under the "shh" namespace. 431 // Deprecated: use Subscribe(ctx, "shh", ...). 432 func (c *Client) ShhSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error) { 433 return c.Subscribe(ctx, "shh", channel, args...) 434 } 435 436 // Subscribe calls the "<namespace>_subscribe" method with the given arguments, 437 // registering a subscription. Server notifications for the subscription are 438 // sent to the given channel. The element type of the channel must match the 439 // expected type of content returned by the subscription. 440 // 441 // The context argument cancels the RPC request that sets up the subscription but has no 442 // effect on the subscription after Subscribe has returned. 443 // 444 // Slow subscribers will be dropped eventually. Client buffers up to 20000 notifications 445 // before considering the subscriber dead. The subscription Err channel will receive 446 // ErrSubscriptionQueueOverflow. Use a sufficiently large buffer on the channel or ensure 447 // that the channel usually has at least one reader to prevent this issue. 448 func (c *Client) Subscribe(ctx context.Context, namespace string, channel interface{}, args ...interface{}) (*ClientSubscription, error) { 449 // Check type of channel first. 450 chanVal := reflect.ValueOf(channel) 451 if chanVal.Kind() != reflect.Chan || chanVal.Type().ChanDir()&reflect.SendDir == 0 { 452 panic(fmt.Sprintf("channel argument of Subscribe has type %T, need writable channel", channel)) 453 } 454 if chanVal.IsNil() { 455 panic("channel given to Subscribe must not be nil") 456 } 457 if c.isHTTP { 458 return nil, ErrNotificationsUnsupported 459 } 460 461 msg, err := c.newMessage(namespace+subscribeMethodSuffix, args...) 462 if err != nil { 463 return nil, err 464 } 465 op := &requestOp{ 466 ids: []json.RawMessage{msg.ID}, 467 resp: make(chan *jsonrpcMessage), 468 sub: newClientSubscription(c, namespace, chanVal), 469 } 470 471 // Send the subscription request. 472 // The arrival and validity of the response is signaled on sub.quit. 473 if err := c.send(ctx, op, msg); err != nil { 474 return nil, err 475 } 476 if _, err := op.wait(ctx, c); err != nil { 477 return nil, err 478 } 479 return op.sub, nil 480 } 481 482 func (c *Client) newMessage(method string, paramsIn ...interface{}) (*jsonrpcMessage, error) { 483 msg := &jsonrpcMessage{Version: vsn, ID: c.nextID(), Method: method} 484 if paramsIn != nil { // prevent sending "params":null 485 var err error 486 if msg.Params, err = json.Marshal(paramsIn); err != nil { 487 return nil, err 488 } 489 } 490 return msg, nil 491 } 492 493 // send registers op with the dispatch loop, then sends msg on the connection. 494 // if sending fails, op is deregistered. 495 func (c *Client) send(ctx context.Context, op *requestOp, msg interface{}) error { 496 select { 497 case c.reqInit <- op: 498 err := c.write(ctx, msg, false) 499 c.reqSent <- err 500 return err 501 case <-ctx.Done(): 502 // This can happen if the client is overloaded or unable to keep up with 503 // subscription notifications. 504 return ctx.Err() 505 case <-c.closing: 506 return ErrClientQuit 507 } 508 } 509 510 func (c *Client) write(ctx context.Context, msg interface{}, retry bool) error { 511 if c.writeConn == nil { 512 // The previous write failed. Try to establish a new connection. 513 if err := c.reconnect(ctx); err != nil { 514 return err 515 } 516 } 517 err := c.writeConn.writeJSON(ctx, msg) 518 if err != nil { 519 c.writeConn = nil 520 if !retry { 521 return c.write(ctx, msg, true) 522 } 523 } 524 return err 525 } 526 527 func (c *Client) reconnect(ctx context.Context) error { 528 if c.reconnectFunc == nil { 529 return errDead 530 } 531 532 if _, ok := ctx.Deadline(); !ok { 533 var cancel func() 534 ctx, cancel = context.WithTimeout(ctx, defaultDialTimeout) 535 defer cancel() 536 } 537 newconn, err := c.reconnectFunc(ctx) 538 if err != nil { 539 log.Trace("RPC client reconnect failed", "err", err) 540 return err 541 } 542 select { 543 case c.reconnected <- newconn: 544 c.writeConn = newconn 545 return nil 546 case <-c.didClose: 547 newconn.close() 548 return ErrClientQuit 549 } 550 } 551 552 // dispatch is the main loop of the client. 553 // It sends read messages to waiting calls to Call and BatchCall 554 // and subscription notifications to registered subscriptions. 555 func (c *Client) dispatch(codec ServerCodec, apiMaxDuration, refillRate, maxStored time.Duration) { 556 var ( 557 lastOp *requestOp // tracks last send operation 558 reqInitLock = c.reqInit // nil while the send lock is held 559 conn = c.newClientConn(codec, apiMaxDuration, refillRate, maxStored) 560 reading = true 561 ) 562 defer func() { 563 close(c.closing) 564 if reading { 565 conn.close(ErrClientQuit, nil) 566 c.drainRead() 567 } 568 close(c.didClose) 569 }() 570 571 // Spawn the initial read loop. 572 go c.read(codec) 573 574 for { 575 select { 576 case <-c.close: 577 return 578 579 // Read path: 580 case op := <-c.readOp: 581 if op.batch { 582 conn.handler.handleBatch(op.msgs) 583 } else { 584 conn.handler.handleMsg(op.msgs[0]) 585 } 586 587 case err := <-c.readErr: 588 conn.handler.log.Debug("RPC connection read error", "err", err) 589 conn.close(err, lastOp) 590 reading = false 591 592 // Reconnect: 593 case newcodec := <-c.reconnected: 594 log.Debug("RPC client reconnected", "reading", reading, "conn", newcodec.remoteAddr()) 595 if reading { 596 // Wait for the previous read loop to exit. This is a rare case which 597 // happens if this loop isn't notified in time after the connection breaks. 598 // In those cases the caller will notice first and reconnect. Closing the 599 // handler terminates all waiting requests (closing op.resp) except for 600 // lastOp, which will be transferred to the new handler. 601 conn.close(errClientReconnected, lastOp) 602 c.drainRead() 603 } 604 go c.read(newcodec) 605 reading = true 606 conn = c.newClientConn(newcodec, apiMaxDuration, refillRate, maxStored) 607 // Re-register the in-flight request on the new handler 608 // because that's where it will be sent. 609 conn.handler.addRequestOp(lastOp) 610 611 // Send path: 612 case op := <-reqInitLock: 613 // Stop listening for further requests until the current one has been sent. 614 reqInitLock = nil 615 lastOp = op 616 conn.handler.addRequestOp(op) 617 618 case err := <-c.reqSent: 619 if err != nil { 620 // Remove response handlers for the last send. When the read loop 621 // goes down, it will signal all other current operations. 622 conn.handler.removeRequestOp(lastOp) 623 } 624 // Let the next request in. 625 reqInitLock = c.reqInit 626 lastOp = nil 627 628 case op := <-c.reqTimeout: 629 conn.handler.removeRequestOp(op) 630 } 631 } 632 } 633 634 // drainRead drops read messages until an error occurs. 635 func (c *Client) drainRead() { 636 for { 637 select { 638 case <-c.readOp: 639 case <-c.readErr: 640 return 641 } 642 } 643 } 644 645 // read decodes RPC messages from a codec, feeding them into dispatch. 646 func (c *Client) read(codec ServerCodec) { 647 for { 648 msgs, batch, err := codec.readBatch() 649 if _, ok := err.(*json.SyntaxError); ok { 650 codec.writeJSON(context.Background(), errorMessage(&parseError{err.Error()})) 651 } 652 if err != nil { 653 c.readErr <- err 654 return 655 } 656 c.readOp <- readOp{msgs, batch} 657 } 658 }