gitlab.com/flarenetwork/coreth@v0.1.1/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 "bytes" 31 "context" 32 "encoding/json" 33 "errors" 34 "fmt" 35 "net/url" 36 "reflect" 37 "strconv" 38 "sync/atomic" 39 "time" 40 41 "github.com/ethereum/go-ethereum/log" 42 ) 43 44 var ( 45 ErrClientQuit = errors.New("client is closed") 46 ErrNoResult = errors.New("no result in JSON-RPC response") 47 ErrSubscriptionQueueOverflow = errors.New("subscription queue overflow") 48 errClientReconnected = errors.New("client reconnected") 49 errDead = errors.New("connection lost") 50 ) 51 52 const ( 53 // Timeouts 54 defaultDialTimeout = 10 * time.Second // used if context has no deadline 55 subscribeTimeout = 5 * time.Second // overall timeout eth_subscribe, rpc_modules calls 56 ) 57 58 const ( 59 // Subscriptions are removed when the subscriber cannot keep up. 60 // 61 // This can be worked around by supplying a channel with sufficiently sized buffer, 62 // but this can be inconvenient and hard to explain in the docs. Another issue with 63 // buffered channels is that the buffer is static even though it might not be needed 64 // most of the time. 65 // 66 // The approach taken here is to maintain a per-subscription linked list buffer 67 // shrinks on demand. If the buffer reaches the size below, the subscription is 68 // dropped. 69 maxClientSubscriptionBuffer = 20000 70 ) 71 72 // BatchElem is an element in a batch request. 73 type BatchElem struct { 74 Method string 75 Args []interface{} 76 // The result is unmarshaled into this field. Result must be set to a 77 // non-nil pointer value of the desired type, otherwise the response will be 78 // discarded. 79 Result interface{} 80 // Error is set if the server returns an error for this request, or if 81 // unmarshaling into Result fails. It is not set for I/O errors. 82 Error error 83 } 84 85 // Client represents a connection to an RPC server. 86 type Client struct { 87 idgen func() ID // for subscriptions 88 isHTTP bool 89 services *serviceRegistry 90 91 idCounter uint32 92 93 // This function, if non-nil, is called when the connection is lost. 94 reconnectFunc reconnectFunc 95 96 // writeConn is used for writing to the connection on the caller's goroutine. It should 97 // only be accessed outside of dispatch, with the write lock held. The write lock is 98 // taken by sending on reqInit and released by sending on reqSent. 99 writeConn jsonWriter 100 101 // for dispatch 102 close chan struct{} 103 closing chan struct{} // closed when client is quitting 104 didClose chan struct{} // closed when client quits 105 reconnected chan ServerCodec // where write/reconnect sends the new connection 106 readOp chan readOp // read messages 107 readErr chan error // errors from read 108 reqInit chan *requestOp // register response IDs, takes write lock 109 reqSent chan error // signals write completion, releases write lock 110 reqTimeout chan *requestOp // removes response IDs when call timeout expires 111 } 112 113 type reconnectFunc func(ctx context.Context) (ServerCodec, error) 114 115 type clientContextKey struct{} 116 117 type clientConn struct { 118 codec ServerCodec 119 handler *handler 120 } 121 122 func (c *Client) newClientConn(conn ServerCodec, apiMaxDuration time.Duration) *clientConn { 123 ctx := context.WithValue(context.Background(), clientContextKey{}, c) 124 handler := newHandler(ctx, conn, c.idgen, c.services) 125 126 // When apiMaxDuration is 0 (as is the case for all client invocations of 127 // this function), deadlineContext is ignored. 128 handler.deadlineContext = apiMaxDuration 129 return &clientConn{conn, handler} 130 } 131 132 func (cc *clientConn) close(err error, inflightReq *requestOp) { 133 cc.handler.close(err, inflightReq) 134 cc.codec.close() 135 } 136 137 type readOp struct { 138 msgs []*jsonrpcMessage 139 batch bool 140 } 141 142 type requestOp struct { 143 ids []json.RawMessage 144 err error 145 resp chan *jsonrpcMessage // receives up to len(ids) responses 146 sub *ClientSubscription // only set for EthSubscribe requests 147 } 148 149 func (op *requestOp) wait(ctx context.Context, c *Client) (*jsonrpcMessage, error) { 150 select { 151 case <-ctx.Done(): 152 // Send the timeout to dispatch so it can remove the request IDs. 153 if !c.isHTTP { 154 select { 155 case c.reqTimeout <- op: 156 case <-c.closing: 157 } 158 } 159 return nil, ctx.Err() 160 case resp := <-op.resp: 161 return resp, op.err 162 } 163 } 164 165 // Dial creates a new client for the given URL. 166 // 167 // The currently supported URL schemes are "http", "https", "ws" and "wss". If rawurl is a 168 // file name with no URL scheme, a local socket connection is established using UNIX 169 // domain sockets on supported platforms and named pipes on Windows. If you want to 170 // configure transport options, use DialHTTP, DialWebsocket or DialIPC instead. 171 // 172 // For websocket connections, the origin is set to the local host name. 173 // 174 // The client reconnects automatically if the connection is lost. 175 func Dial(rawurl string) (*Client, error) { 176 return DialContext(context.Background(), rawurl) 177 } 178 179 // DialContext creates a new RPC client, just like Dial. 180 // 181 // The context is used to cancel or time out the initial connection establishment. It does 182 // not affect subsequent interactions with the client. 183 func DialContext(ctx context.Context, rawurl string) (*Client, error) { 184 u, err := url.Parse(rawurl) 185 if err != nil { 186 return nil, err 187 } 188 switch u.Scheme { 189 case "http", "https": 190 return DialHTTP(rawurl) 191 case "ws", "wss": 192 return DialWebsocket(ctx, rawurl, "") 193 //case "stdio": 194 // return DialStdIO(ctx) 195 //case "": 196 // return DialIPC(ctx, rawurl) 197 default: 198 return nil, fmt.Errorf("no known transport for URL scheme %q", u.Scheme) 199 } 200 } 201 202 // Client retrieves the client from the context, if any. This can be used to perform 203 // 'reverse calls' in a handler method. 204 func ClientFromContext(ctx context.Context) (*Client, bool) { 205 client, ok := ctx.Value(clientContextKey{}).(*Client) 206 return client, ok 207 } 208 209 func newClient(initctx context.Context, connect reconnectFunc) (*Client, error) { 210 conn, err := connect(initctx) 211 if err != nil { 212 return nil, err 213 } 214 c := initClient(conn, randomIDGenerator(), new(serviceRegistry), 0) 215 c.reconnectFunc = connect 216 return c, nil 217 } 218 219 func initClient(conn ServerCodec, idgen func() ID, services *serviceRegistry, apiMaxDuration time.Duration) *Client { 220 _, isHTTP := conn.(*httpConn) 221 c := &Client{ 222 idgen: idgen, 223 isHTTP: isHTTP, 224 services: services, 225 writeConn: conn, 226 close: make(chan struct{}), 227 closing: make(chan struct{}), 228 didClose: make(chan struct{}), 229 reconnected: make(chan ServerCodec), 230 readOp: make(chan readOp), 231 readErr: make(chan error), 232 reqInit: make(chan *requestOp), 233 reqSent: make(chan error, 1), 234 reqTimeout: make(chan *requestOp), 235 } 236 if !isHTTP { 237 go c.dispatch(conn, apiMaxDuration) 238 } 239 return c 240 } 241 242 // RegisterName creates a service for the given receiver type under the given name. When no 243 // methods on the given receiver match the criteria to be either a RPC method or a 244 // subscription an error is returned. Otherwise a new service is created and added to the 245 // service collection this client provides to the server. 246 func (c *Client) RegisterName(name string, receiver interface{}) error { 247 return c.services.registerName(name, receiver) 248 } 249 250 func (c *Client) nextID() json.RawMessage { 251 id := atomic.AddUint32(&c.idCounter, 1) 252 return strconv.AppendUint(nil, uint64(id), 10) 253 } 254 255 // SupportedModules calls the rpc_modules method, retrieving the list of 256 // APIs that are available on the server. 257 func (c *Client) SupportedModules() (map[string]string, error) { 258 var result map[string]string 259 ctx, cancel := context.WithTimeout(context.Background(), subscribeTimeout) 260 defer cancel() 261 err := c.CallContext(ctx, &result, "rpc_modules") 262 return result, err 263 } 264 265 // Close closes the client, aborting any in-flight requests. 266 func (c *Client) Close() { 267 if c.isHTTP { 268 return 269 } 270 select { 271 case c.close <- struct{}{}: 272 <-c.didClose 273 case <-c.didClose: 274 } 275 } 276 277 // SetHeader adds a custom HTTP header to the client's requests. 278 // This method only works for clients using HTTP, it doesn't have 279 // any effect for clients using another transport. 280 func (c *Client) SetHeader(key, value string) { 281 if !c.isHTTP { 282 return 283 } 284 conn := c.writeConn.(*httpConn) 285 conn.mu.Lock() 286 conn.headers.Set(key, value) 287 conn.mu.Unlock() 288 } 289 290 // Call performs a JSON-RPC call with the given arguments and unmarshals into 291 // result if no error occurred. 292 // 293 // The result must be a pointer so that package json can unmarshal into it. You 294 // can also pass nil, in which case the result is ignored. 295 func (c *Client) Call(result interface{}, method string, args ...interface{}) error { 296 ctx := context.Background() 297 return c.CallContext(ctx, result, method, args...) 298 } 299 300 // CallContext performs a JSON-RPC call with the given arguments. If the context is 301 // canceled before the call has successfully returned, CallContext returns immediately. 302 // 303 // The result must be a pointer so that package json can unmarshal into it. You 304 // can also pass nil, in which case the result is ignored. 305 func (c *Client) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error { 306 if result != nil && reflect.TypeOf(result).Kind() != reflect.Ptr { 307 return fmt.Errorf("call result parameter must be pointer or nil interface: %v", result) 308 } 309 msg, err := c.newMessage(method, args...) 310 if err != nil { 311 return err 312 } 313 op := &requestOp{ids: []json.RawMessage{msg.ID}, resp: make(chan *jsonrpcMessage, 1)} 314 315 if c.isHTTP { 316 err = c.sendHTTP(ctx, op, msg) 317 } else { 318 err = c.send(ctx, op, msg) 319 } 320 if err != nil { 321 return err 322 } 323 324 // dispatch has accepted the request and will close the channel when it quits. 325 switch resp, err := op.wait(ctx, c); { 326 case err != nil: 327 return err 328 case resp.Error != nil: 329 return resp.Error 330 case len(resp.Result) == 0: 331 return ErrNoResult 332 default: 333 return json.Unmarshal(resp.Result, &result) 334 } 335 } 336 337 // BatchCall sends all given requests as a single batch and waits for the server 338 // to return a response for all of them. 339 // 340 // In contrast to Call, BatchCall only returns I/O errors. Any error specific to 341 // a request is reported through the Error field of the corresponding BatchElem. 342 // 343 // Note that batch calls may not be executed atomically on the server side. 344 func (c *Client) BatchCall(b []BatchElem) error { 345 ctx := context.Background() 346 return c.BatchCallContext(ctx, b) 347 } 348 349 // BatchCall sends all given requests as a single batch and waits for the server 350 // to return a response for all of them. The wait duration is bounded by the 351 // context's deadline. 352 // 353 // In contrast to CallContext, BatchCallContext only returns errors that have occurred 354 // while sending the request. Any error specific to a request is reported through the 355 // Error field of the corresponding BatchElem. 356 // 357 // Note that batch calls may not be executed atomically on the server side. 358 func (c *Client) BatchCallContext(ctx context.Context, b []BatchElem) error { 359 msgs := make([]*jsonrpcMessage, len(b)) 360 op := &requestOp{ 361 ids: make([]json.RawMessage, len(b)), 362 resp: make(chan *jsonrpcMessage, len(b)), 363 } 364 for i, elem := range b { 365 msg, err := c.newMessage(elem.Method, elem.Args...) 366 if err != nil { 367 return err 368 } 369 msgs[i] = msg 370 op.ids[i] = msg.ID 371 } 372 373 var err error 374 if c.isHTTP { 375 err = c.sendBatchHTTP(ctx, op, msgs) 376 } else { 377 err = c.send(ctx, op, msgs) 378 } 379 380 // Wait for all responses to come back. 381 for n := 0; n < len(b) && err == nil; n++ { 382 var resp *jsonrpcMessage 383 resp, err = op.wait(ctx, c) 384 if err != nil { 385 break 386 } 387 // Find the element corresponding to this response. 388 // The element is guaranteed to be present because dispatch 389 // only sends valid IDs to our channel. 390 var elem *BatchElem 391 for i := range msgs { 392 if bytes.Equal(msgs[i].ID, resp.ID) { 393 elem = &b[i] 394 break 395 } 396 } 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 subscripion 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 subscripion 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("first argument to Subscribe must be a writable 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 // The previous write failed. Try to establish a new connection. 512 if c.writeConn == nil { 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 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) 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) 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 }