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