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