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