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