github.com/gochain-io/gochain@v2.2.26+incompatible/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  	"container/list"
    22  	"context"
    23  	"encoding/json"
    24  	"errors"
    25  	"fmt"
    26  	"net"
    27  	"net/url"
    28  	"os"
    29  	"reflect"
    30  	"strconv"
    31  	"strings"
    32  	"sync"
    33  	"sync/atomic"
    34  	"time"
    35  
    36  	"github.com/gochain-io/gochain/log"
    37  )
    38  
    39  var (
    40  	ErrClientQuit                = errors.New("client is closed")
    41  	ErrNoResult                  = errors.New("no result in JSON-RPC response")
    42  	ErrSubscriptionQueueOverflow = errors.New("subscription queue overflow")
    43  )
    44  
    45  const (
    46  	// Timeouts
    47  	tcpKeepAliveInterval = 30 * time.Second
    48  	defaultDialTimeout   = 10 * time.Second // used when dialing if the context has no deadline
    49  	defaultWriteTimeout  = 10 * time.Second // used for calls if the context has no deadline
    50  	subscribeTimeout     = 5 * time.Second  // overall timeout eth_subscribe, rpc_modules calls
    51  )
    52  
    53  const (
    54  	// Subscriptions are removed when the subscriber cannot keep up.
    55  	//
    56  	// This can be worked around by supplying a channel with sufficiently sized buffer,
    57  	// but this can be inconvenient and hard to explain in the docs. Another issue with
    58  	// buffered channels is that the buffer is static even though it might not be needed
    59  	// most of the time.
    60  	//
    61  	// The approach taken here is to maintain a per-subscription linked list buffer
    62  	// shrinks on demand. If the buffer reaches the size below, the subscription is
    63  	// dropped.
    64  	maxClientSubscriptionBuffer = 20000
    65  )
    66  
    67  // BatchElem is an element in a batch request.
    68  type BatchElem struct {
    69  	Method string
    70  	Args   []interface{}
    71  	// The result is unmarshaled into this field. Result must be set to a
    72  	// non-nil pointer value of the desired type, otherwise the response will be
    73  	// discarded.
    74  	Result interface{}
    75  	// Error is set if the server returns an error for this request, or if
    76  	// unmarshaling into Result fails. It is not set for I/O errors.
    77  	Error error
    78  }
    79  
    80  // A value of this type can a JSON-RPC request, notification, successful response or
    81  // error response. Which one it is depends on the fields.
    82  type jsonrpcMessage struct {
    83  	Version string          `json:"jsonrpc"`
    84  	ID      json.RawMessage `json:"id,omitempty"`
    85  	Method  string          `json:"method,omitempty"`
    86  	Params  json.RawMessage `json:"params,omitempty"`
    87  	Error   *jsonError      `json:"error,omitempty"`
    88  	Result  json.RawMessage `json:"result,omitempty"`
    89  }
    90  
    91  func (msg *jsonrpcMessage) isNotification() bool {
    92  	return msg.ID == nil && msg.Method != ""
    93  }
    94  
    95  func (msg *jsonrpcMessage) isResponse() bool {
    96  	return msg.hasValidID() && msg.Method == "" && len(msg.Params) == 0
    97  }
    98  
    99  func (msg *jsonrpcMessage) hasValidID() bool {
   100  	return len(msg.ID) > 0 && msg.ID[0] != '{' && msg.ID[0] != '['
   101  }
   102  
   103  func (msg *jsonrpcMessage) String() string {
   104  	b, _ := json.Marshal(msg)
   105  	return string(b)
   106  }
   107  
   108  // Client represents a connection to an RPC server.
   109  type Client struct {
   110  	idCounter   uint32
   111  	connectFunc func(ctx context.Context) (net.Conn, error)
   112  	isHTTP      bool
   113  
   114  	// writeConn is only safe to access outside dispatch, with the
   115  	// write lock held. The write lock is taken by sending on
   116  	// requestOp and released by sending on sendDone.
   117  	writeConn net.Conn
   118  
   119  	// for dispatch
   120  	close       chan struct{}
   121  	didQuit     chan struct{}                  // closed when client quits
   122  	reconnected chan net.Conn                  // where write/reconnect sends the new connection
   123  	readErr     chan error                     // errors from read
   124  	readResp    chan []*jsonrpcMessage         // valid messages from read
   125  	requestOp   chan *requestOp                // for registering response IDs
   126  	sendDone    chan error                     // signals write completion, releases write lock
   127  	respWait    map[string]*requestOp          // active requests
   128  	subs        map[string]*ClientSubscription // active subscriptions
   129  }
   130  
   131  type requestOp struct {
   132  	ids  []json.RawMessage
   133  	err  error
   134  	resp chan *jsonrpcMessage // receives up to len(ids) responses
   135  	sub  *ClientSubscription  // only set for EthSubscribe requests
   136  }
   137  
   138  func (op *requestOp) wait(ctx context.Context) (*jsonrpcMessage, error) {
   139  	select {
   140  	case <-ctx.Done():
   141  		return nil, ctx.Err()
   142  	case resp := <-op.resp:
   143  		return resp, op.err
   144  	}
   145  }
   146  
   147  // Dial creates a new client for the given URL.
   148  //
   149  // The currently supported URL schemes are "http", "https", "ws" and "wss". If rawurl is a
   150  // file name with no URL scheme, a local socket connection is established using UNIX
   151  // domain sockets on supported platforms and named pipes on Windows. If you want to
   152  // configure transport options, use DialHTTP, DialWebsocket or DialIPC instead.
   153  //
   154  // For websocket connections, the origin is set to the local host name.
   155  //
   156  // The client reconnects automatically if the connection is lost.
   157  func Dial(rawurl string) (*Client, error) {
   158  	return DialContext(context.Background(), rawurl)
   159  }
   160  
   161  // DialContext creates a new RPC client, just like Dial.
   162  //
   163  // The context is used to cancel or time out the initial connection establishment. It does
   164  // not affect subsequent interactions with the client.
   165  func DialContext(ctx context.Context, rawurl string) (*Client, error) {
   166  	u, err := url.Parse(rawurl)
   167  	if err != nil {
   168  		return nil, err
   169  	}
   170  	switch u.Scheme {
   171  	case "http", "https":
   172  		return DialHTTP(rawurl)
   173  	case "ws", "wss":
   174  		return DialWebsocket(ctx, rawurl, "")
   175  	case "stdio":
   176  		return DialStdIO(ctx)
   177  	case "":
   178  		return DialIPC(ctx, rawurl)
   179  	default:
   180  		return nil, fmt.Errorf("no known transport for URL scheme %q", u.Scheme)
   181  	}
   182  }
   183  
   184  type StdIOConn struct{}
   185  
   186  func (io StdIOConn) Read(b []byte) (n int, err error) {
   187  	return os.Stdin.Read(b)
   188  }
   189  
   190  func (io StdIOConn) Write(b []byte) (n int, err error) {
   191  	return os.Stdout.Write(b)
   192  }
   193  
   194  func (io StdIOConn) Close() error {
   195  	return nil
   196  }
   197  
   198  func (io StdIOConn) LocalAddr() net.Addr {
   199  	return &net.UnixAddr{Name: "stdio", Net: "stdio"}
   200  }
   201  
   202  func (io StdIOConn) RemoteAddr() net.Addr {
   203  	return &net.UnixAddr{Name: "stdio", Net: "stdio"}
   204  }
   205  
   206  func (io StdIOConn) SetDeadline(t time.Time) error {
   207  	return &net.OpError{Op: "set", Net: "stdio", Source: nil, Addr: nil, Err: errors.New("deadline not supported")}
   208  }
   209  
   210  func (io StdIOConn) SetReadDeadline(t time.Time) error {
   211  	return &net.OpError{Op: "set", Net: "stdio", Source: nil, Addr: nil, Err: errors.New("deadline not supported")}
   212  }
   213  
   214  func (io StdIOConn) SetWriteDeadline(t time.Time) error {
   215  	return &net.OpError{Op: "set", Net: "stdio", Source: nil, Addr: nil, Err: errors.New("deadline not supported")}
   216  }
   217  func DialStdIO(ctx context.Context) (*Client, error) {
   218  	return newClient(ctx, func(_ context.Context) (net.Conn, error) {
   219  		return StdIOConn{}, nil
   220  	})
   221  }
   222  
   223  func newClient(initctx context.Context, connectFunc func(context.Context) (net.Conn, error)) (*Client, error) {
   224  	conn, err := connectFunc(initctx)
   225  	if err != nil {
   226  		return nil, err
   227  	}
   228  	_, isHTTP := conn.(*httpConn)
   229  
   230  	c := &Client{
   231  		writeConn:   conn,
   232  		isHTTP:      isHTTP,
   233  		connectFunc: connectFunc,
   234  		close:       make(chan struct{}),
   235  		didQuit:     make(chan struct{}),
   236  		reconnected: make(chan net.Conn),
   237  		readErr:     make(chan error),
   238  		readResp:    make(chan []*jsonrpcMessage),
   239  		requestOp:   make(chan *requestOp),
   240  		sendDone:    make(chan error, 1),
   241  		respWait:    make(map[string]*requestOp),
   242  		subs:        make(map[string]*ClientSubscription),
   243  	}
   244  	if !isHTTP {
   245  		go c.dispatch(conn)
   246  	}
   247  	return c, nil
   248  }
   249  
   250  func (c *Client) nextID() json.RawMessage {
   251  	id := atomic.AddUint32(&c.idCounter, 1)
   252  	return []byte(strconv.FormatUint(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.didQuit
   273  	case <-c.didQuit:
   274  	}
   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  	msg, err := c.newMessage(method, args...)
   294  	if err != nil {
   295  		return err
   296  	}
   297  	op := &requestOp{ids: []json.RawMessage{msg.ID}, resp: make(chan *jsonrpcMessage, 1)}
   298  
   299  	if c.isHTTP {
   300  		err = c.sendHTTP(ctx, op, msg)
   301  	} else {
   302  		err = c.send(ctx, op, msg)
   303  	}
   304  	if err != nil {
   305  		return err
   306  	}
   307  
   308  	// dispatch has accepted the request and will close the channel when it quits.
   309  	switch resp, err := op.wait(ctx); {
   310  	case err != nil:
   311  		return err
   312  	case resp.Error != nil:
   313  		return resp.Error
   314  	case len(resp.Result) == 0:
   315  		return ErrNoResult
   316  	default:
   317  		return json.Unmarshal(resp.Result, &result)
   318  	}
   319  }
   320  
   321  // BatchCall sends all given requests as a single batch and waits for the server
   322  // to return a response for all of them.
   323  //
   324  // In contrast to Call, BatchCall only returns I/O errors. Any error specific to
   325  // a request is reported through the 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) BatchCall(b []BatchElem) error {
   329  	ctx := context.Background()
   330  	return c.BatchCallContext(ctx, b)
   331  }
   332  
   333  // BatchCall sends all given requests as a single batch and waits for the server
   334  // to return a response for all of them. The wait duration is bounded by the
   335  // context's deadline.
   336  //
   337  // In contrast to CallContext, BatchCallContext only returns errors that have occurred
   338  // while sending the request. Any error specific to a request is reported through the
   339  // Error field of the corresponding BatchElem.
   340  //
   341  // Note that batch calls may not be executed atomically on the server side.
   342  func (c *Client) BatchCallContext(ctx context.Context, b []BatchElem) error {
   343  	msgs := make([]*jsonrpcMessage, len(b))
   344  	op := &requestOp{
   345  		ids:  make([]json.RawMessage, len(b)),
   346  		resp: make(chan *jsonrpcMessage, len(b)),
   347  	}
   348  	for i, elem := range b {
   349  		msg, err := c.newMessage(elem.Method, elem.Args...)
   350  		if err != nil {
   351  			return err
   352  		}
   353  		msgs[i] = msg
   354  		op.ids[i] = msg.ID
   355  	}
   356  
   357  	var err error
   358  	if c.isHTTP {
   359  		err = c.sendBatchHTTP(ctx, op, msgs)
   360  	} else {
   361  		err = c.send(ctx, op, msgs)
   362  	}
   363  
   364  	// Wait for all responses to come back.
   365  	for n := 0; n < len(b) && err == nil; n++ {
   366  		var resp *jsonrpcMessage
   367  		resp, err = op.wait(ctx)
   368  		if err != nil {
   369  			break
   370  		}
   371  		// Find the element corresponding to this response.
   372  		// The element is guaranteed to be present because dispatch
   373  		// only sends valid IDs to our channel.
   374  		var elem *BatchElem
   375  		for i := range msgs {
   376  			if bytes.Equal(msgs[i].ID, resp.ID) {
   377  				elem = &b[i]
   378  				break
   379  			}
   380  		}
   381  		if resp.Error != nil {
   382  			elem.Error = resp.Error
   383  			continue
   384  		}
   385  		if len(resp.Result) == 0 {
   386  			elem.Error = ErrNoResult
   387  			continue
   388  		}
   389  		elem.Error = json.Unmarshal(resp.Result, elem.Result)
   390  	}
   391  	return err
   392  }
   393  
   394  // EthSubscribe registers a subscripion under the "eth" namespace.
   395  func (c *Client) EthSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error) {
   396  	return c.Subscribe(ctx, "eth", channel, args...)
   397  }
   398  
   399  // ShhSubscribe registers a subscripion under the "shh" namespace.
   400  func (c *Client) ShhSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error) {
   401  	return c.Subscribe(ctx, "shh", channel, args...)
   402  }
   403  
   404  // Subscribe calls the "<namespace>_subscribe" method with the given arguments,
   405  // registering a subscription. Server notifications for the subscription are
   406  // sent to the given channel. The element type of the channel must match the
   407  // expected type of content returned by the subscription.
   408  //
   409  // The context argument cancels the RPC request that sets up the subscription but has no
   410  // effect on the subscription after Subscribe has returned.
   411  //
   412  // Slow subscribers will be dropped eventually. Client buffers up to 8000 notifications
   413  // before considering the subscriber dead. The subscription Err channel will receive
   414  // ErrSubscriptionQueueOverflow. Use a sufficiently large buffer on the channel or ensure
   415  // that the channel usually has at least one reader to prevent this issue.
   416  func (c *Client) Subscribe(ctx context.Context, namespace string, channel interface{}, args ...interface{}) (*ClientSubscription, error) {
   417  	// Check type of channel first.
   418  	chanVal := reflect.ValueOf(channel)
   419  	if chanVal.Kind() != reflect.Chan || chanVal.Type().ChanDir()&reflect.SendDir == 0 {
   420  		panic("first argument to Subscribe must be a writable channel")
   421  	}
   422  	if chanVal.IsNil() {
   423  		panic("channel given to Subscribe must not be nil")
   424  	}
   425  	if c.isHTTP {
   426  		return nil, ErrNotificationsUnsupported
   427  	}
   428  
   429  	msg, err := c.newMessage(namespace+subscribeMethodSuffix, args...)
   430  	if err != nil {
   431  		return nil, err
   432  	}
   433  	op := &requestOp{
   434  		ids:  []json.RawMessage{msg.ID},
   435  		resp: make(chan *jsonrpcMessage),
   436  		sub:  newClientSubscription(c, namespace, chanVal),
   437  	}
   438  
   439  	// Send the subscription request.
   440  	// The arrival and validity of the response is signaled on sub.quit.
   441  	if err := c.send(ctx, op, msg); err != nil {
   442  		return nil, err
   443  	}
   444  	if _, err := op.wait(ctx); err != nil {
   445  		return nil, err
   446  	}
   447  	return op.sub, nil
   448  }
   449  
   450  func (c *Client) newMessage(method string, paramsIn ...interface{}) (*jsonrpcMessage, error) {
   451  	params, err := json.Marshal(paramsIn)
   452  	if err != nil {
   453  		return nil, err
   454  	}
   455  	return &jsonrpcMessage{Version: "2.0", ID: c.nextID(), Method: method, Params: params}, nil
   456  }
   457  
   458  // send registers op with the dispatch loop, then sends msg on the connection.
   459  // if sending fails, op is deregistered.
   460  func (c *Client) send(ctx context.Context, op *requestOp, msg interface{}) error {
   461  	select {
   462  	case c.requestOp <- op:
   463  		if log.Tracing() {
   464  			log.Trace("", "msg", log.Lazy{Fn: func() string {
   465  				return fmt.Sprint("sending ", msg)
   466  			}})
   467  		}
   468  		err := c.write(ctx, msg)
   469  		c.sendDone <- 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.didQuit:
   476  		return ErrClientQuit
   477  	}
   478  }
   479  
   480  func (c *Client) write(ctx context.Context, msg interface{}) error {
   481  	deadline, ok := ctx.Deadline()
   482  	if !ok {
   483  		deadline = time.Now().Add(defaultWriteTimeout)
   484  	}
   485  	// The previous write failed. Try to establish a new connection.
   486  	if c.writeConn == nil {
   487  		if err := c.reconnect(ctx); err != nil {
   488  			return err
   489  		}
   490  	}
   491  	if err := c.writeConn.SetWriteDeadline(deadline); err != nil {
   492  		log.Error("Cannot set rpc client write deadline", "err", err)
   493  	}
   494  	err := json.NewEncoder(c.writeConn).Encode(msg)
   495  	c.writeConn.SetWriteDeadline(time.Time{})
   496  	if err != nil {
   497  		c.writeConn = nil
   498  	}
   499  	return err
   500  }
   501  
   502  func (c *Client) reconnect(ctx context.Context) error {
   503  	newconn, err := c.connectFunc(ctx)
   504  	if err != nil {
   505  		log.Trace(fmt.Sprintf("reconnect failed: %v", err))
   506  		return err
   507  	}
   508  	select {
   509  	case c.reconnected <- newconn:
   510  		c.writeConn = newconn
   511  		return nil
   512  	case <-c.didQuit:
   513  		if err := newconn.Close(); err != nil {
   514  			log.Error("Cannot close rpc client connection on reconnect", "err", err)
   515  		}
   516  		return ErrClientQuit
   517  	}
   518  }
   519  
   520  // dispatch is the main loop of the client.
   521  // It sends read messages to waiting calls to Call and BatchCall
   522  // and subscription notifications to registered subscriptions.
   523  func (c *Client) dispatch(conn net.Conn) {
   524  	// Spawn the initial read loop.
   525  	go func() {
   526  		if err := c.read(conn); err != nil {
   527  			log.Error("Cannot read dispatch from connection", "err", err)
   528  		}
   529  	}()
   530  
   531  	var (
   532  		lastOp        *requestOp    // tracks last send operation
   533  		requestOpLock = c.requestOp // nil while the send lock is held
   534  		reading       = true        // if true, a read loop is running
   535  	)
   536  	defer close(c.didQuit)
   537  	defer func() {
   538  		c.closeRequestOps(ErrClientQuit)
   539  		if err := conn.Close(); err != nil {
   540  			log.Error("Cannot close dispatch connection", "err", err)
   541  		}
   542  		if reading {
   543  			// Empty read channels until read is dead.
   544  			for {
   545  				select {
   546  				case <-c.readResp:
   547  				case <-c.readErr:
   548  					return
   549  				}
   550  			}
   551  		}
   552  	}()
   553  
   554  	for {
   555  		select {
   556  		case <-c.close:
   557  			return
   558  
   559  		// Read path.
   560  		case batch := <-c.readResp:
   561  			for _, msg := range batch {
   562  				switch {
   563  				case msg.isNotification():
   564  					if log.Tracing() {
   565  						log.Trace("", "msg", log.Lazy{Fn: func() string {
   566  							return fmt.Sprint("<-readResp: notification ", msg)
   567  						}})
   568  					}
   569  					c.handleNotification(msg)
   570  				case msg.isResponse():
   571  					if log.Tracing() {
   572  						log.Trace("", "msg", log.Lazy{Fn: func() string {
   573  							return fmt.Sprint("<-readResp: response ", msg)
   574  						}})
   575  					}
   576  					c.handleResponse(msg)
   577  				default:
   578  					log.Debug("", "msg", log.Lazy{Fn: func() string {
   579  						return fmt.Sprint("<-readResp: dropping weird message", msg)
   580  					}})
   581  					// TODO: maybe close
   582  				}
   583  			}
   584  
   585  		case err := <-c.readErr:
   586  			log.Debug(fmt.Sprintf("<-readErr: %v", err))
   587  			c.closeRequestOps(err)
   588  			if err := conn.Close(); err != nil {
   589  				log.Error("Cannot close connection on read error", "err", err)
   590  			}
   591  			reading = false
   592  
   593  		case newconn := <-c.reconnected:
   594  			log.Debug(fmt.Sprintf("<-reconnected: (reading=%t) %v", reading, conn.RemoteAddr()))
   595  			if reading {
   596  				// Wait for the previous read loop to exit. This is a rare case.
   597  				if err := conn.Close(); err != nil {
   598  					log.Error("Cannot close connection on reconnect", "err", err)
   599  				}
   600  				<-c.readErr
   601  			}
   602  			go func() {
   603  				if err := c.read(newconn); err != nil {
   604  					log.Error("Cannot read from reconnected connection", "err", err)
   605  				}
   606  			}()
   607  			reading = true
   608  			conn = newconn
   609  
   610  		// Send path.
   611  		case op := <-requestOpLock:
   612  			// Stop listening for further send ops until the current one is done.
   613  			requestOpLock = nil
   614  			lastOp = op
   615  			for _, id := range op.ids {
   616  				c.respWait[string(id)] = op
   617  			}
   618  
   619  		case err := <-c.sendDone:
   620  			if err != nil {
   621  				// Remove response handlers for the last send. We remove those here
   622  				// because the error is already handled in Call or BatchCall. When the
   623  				// read loop goes down, it will signal all other current operations.
   624  				for _, id := range lastOp.ids {
   625  					delete(c.respWait, string(id))
   626  				}
   627  			}
   628  			// Listen for send ops again.
   629  			requestOpLock = c.requestOp
   630  			lastOp = nil
   631  		}
   632  	}
   633  }
   634  
   635  // closeRequestOps unblocks pending send ops and active subscriptions.
   636  func (c *Client) closeRequestOps(err error) {
   637  	didClose := make(map[*requestOp]bool)
   638  
   639  	for id, op := range c.respWait {
   640  		// Remove the op so that later calls will not close op.resp again.
   641  		delete(c.respWait, id)
   642  
   643  		if !didClose[op] {
   644  			op.err = err
   645  			close(op.resp)
   646  			didClose[op] = true
   647  		}
   648  	}
   649  	for id, sub := range c.subs {
   650  		delete(c.subs, id)
   651  		sub.quitWithError(err, false)
   652  	}
   653  }
   654  
   655  func (c *Client) handleNotification(msg *jsonrpcMessage) {
   656  	if !strings.HasSuffix(msg.Method, notificationMethodSuffix) {
   657  		log.Debug("dropping non-subscription message", "msg", msg)
   658  		return
   659  	}
   660  	var subResult struct {
   661  		ID     string          `json:"subscription"`
   662  		Result json.RawMessage `json:"result"`
   663  	}
   664  	if err := json.Unmarshal(msg.Params, &subResult); err != nil {
   665  		log.Debug("dropping invalid subscription message", "msg", msg)
   666  		return
   667  	}
   668  	if c.subs[subResult.ID] != nil {
   669  		c.subs[subResult.ID].deliver(subResult.Result)
   670  	}
   671  }
   672  
   673  func (c *Client) handleResponse(msg *jsonrpcMessage) {
   674  	op := c.respWait[string(msg.ID)]
   675  	if op == nil {
   676  		log.Debug("unsolicited response", "msg", msg)
   677  		return
   678  	}
   679  	delete(c.respWait, string(msg.ID))
   680  	// For normal responses, just forward the reply to Call/BatchCall.
   681  	if op.sub == nil {
   682  		op.resp <- msg
   683  		return
   684  	}
   685  	// For subscription responses, start the subscription if the server
   686  	// indicates success. EthSubscribe gets unblocked in either case through
   687  	// the op.resp channel.
   688  	defer close(op.resp)
   689  	if msg.Error != nil {
   690  		op.err = msg.Error
   691  		return
   692  	}
   693  	if op.err = json.Unmarshal(msg.Result, &op.sub.subid); op.err == nil {
   694  		go op.sub.start()
   695  		c.subs[op.sub.subid] = op.sub
   696  	}
   697  }
   698  
   699  // Reading happens on a dedicated goroutine.
   700  func (c *Client) read(conn net.Conn) error {
   701  	var (
   702  		buf json.RawMessage
   703  		dec = json.NewDecoder(conn)
   704  	)
   705  	readMessage := func() (rs []*jsonrpcMessage, err error) {
   706  		buf = buf[:0]
   707  		if err = dec.Decode(&buf); err != nil {
   708  			return nil, err
   709  		}
   710  		if isBatch(buf) {
   711  			err = json.Unmarshal(buf, &rs)
   712  		} else {
   713  			rs = make([]*jsonrpcMessage, 1)
   714  			err = json.Unmarshal(buf, &rs[0])
   715  		}
   716  		return rs, err
   717  	}
   718  
   719  	for {
   720  		resp, err := readMessage()
   721  		if err != nil {
   722  			c.readErr <- err
   723  			return err
   724  		}
   725  		c.readResp <- resp
   726  	}
   727  }
   728  
   729  // Subscriptions.
   730  
   731  // A ClientSubscription represents a subscription established through EthSubscribe.
   732  type ClientSubscription struct {
   733  	client    *Client
   734  	etype     reflect.Type
   735  	channel   reflect.Value
   736  	namespace string
   737  	subid     string
   738  	in        chan json.RawMessage
   739  
   740  	quitOnce sync.Once     // ensures quit is closed once
   741  	quit     chan struct{} // quit is closed when the subscription exits
   742  	errOnce  sync.Once     // ensures err is closed once
   743  	err      chan error
   744  }
   745  
   746  func newClientSubscription(c *Client, namespace string, channel reflect.Value) *ClientSubscription {
   747  	sub := &ClientSubscription{
   748  		client:    c,
   749  		namespace: namespace,
   750  		etype:     channel.Type().Elem(),
   751  		channel:   channel,
   752  		quit:      make(chan struct{}),
   753  		err:       make(chan error, 1),
   754  		in:        make(chan json.RawMessage),
   755  	}
   756  	return sub
   757  }
   758  
   759  // Err returns the subscription error channel. The intended use of Err is to schedule
   760  // resubscription when the client connection is closed unexpectedly.
   761  //
   762  // The error channel receives a value when the subscription has ended due
   763  // to an error. The received error is nil if Close has been called
   764  // on the underlying client and no other error has occurred.
   765  //
   766  // The error channel is closed when Unsubscribe is called on the subscription.
   767  func (sub *ClientSubscription) Err() <-chan error {
   768  	return sub.err
   769  }
   770  
   771  // Unsubscribe unsubscribes the notification and closes the error channel.
   772  // It can safely be called more than once.
   773  func (sub *ClientSubscription) Unsubscribe() {
   774  	sub.quitWithError(nil, true)
   775  	sub.errOnce.Do(func() { close(sub.err) })
   776  }
   777  
   778  func (sub *ClientSubscription) quitWithError(err error, unsubscribeServer bool) {
   779  	sub.quitOnce.Do(func() {
   780  		// The dispatch loop won't be able to execute the unsubscribe call
   781  		// if it is blocked on deliver. Close sub.quit first because it
   782  		// unblocks deliver.
   783  		close(sub.quit)
   784  		if unsubscribeServer {
   785  			if err := sub.requestUnsubscribe(); err != nil {
   786  				log.Error("Cannot request unsubscribe", "err", err)
   787  			}
   788  		}
   789  		if err != nil {
   790  			if err == ErrClientQuit {
   791  				err = nil // Adhere to subscription semantics.
   792  			}
   793  			sub.err <- err
   794  		}
   795  	})
   796  }
   797  
   798  func (sub *ClientSubscription) deliver(result json.RawMessage) (ok bool) {
   799  	select {
   800  	case sub.in <- result:
   801  		return true
   802  	case <-sub.quit:
   803  		return false
   804  	}
   805  }
   806  
   807  func (sub *ClientSubscription) start() {
   808  	sub.quitWithError(sub.forward())
   809  }
   810  
   811  func (sub *ClientSubscription) forward() (err error, unsubscribeServer bool) {
   812  	cases := []reflect.SelectCase{
   813  		{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(sub.quit)},
   814  		{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(sub.in)},
   815  		{Dir: reflect.SelectSend, Chan: sub.channel},
   816  	}
   817  	buffer := list.New()
   818  	defer buffer.Init()
   819  	for {
   820  		var chosen int
   821  		var recv reflect.Value
   822  		if buffer.Len() == 0 {
   823  			// Idle, omit send case.
   824  			chosen, recv, _ = reflect.Select(cases[:2])
   825  		} else {
   826  			// Non-empty buffer, send the first queued item.
   827  			cases[2].Send = reflect.ValueOf(buffer.Front().Value)
   828  			chosen, recv, _ = reflect.Select(cases)
   829  		}
   830  
   831  		switch chosen {
   832  		case 0: // <-sub.quit
   833  			return nil, false
   834  		case 1: // <-sub.in
   835  			val, err := sub.unmarshal(recv.Interface().(json.RawMessage))
   836  			if err != nil {
   837  				return err, true
   838  			}
   839  			if buffer.Len() == maxClientSubscriptionBuffer {
   840  				return ErrSubscriptionQueueOverflow, true
   841  			}
   842  			buffer.PushBack(val)
   843  		case 2: // sub.channel<-
   844  			cases[2].Send = reflect.Value{} // Don't hold onto the value.
   845  			buffer.Remove(buffer.Front())
   846  		}
   847  	}
   848  }
   849  
   850  func (sub *ClientSubscription) unmarshal(result json.RawMessage) (interface{}, error) {
   851  	val := reflect.New(sub.etype)
   852  	err := json.Unmarshal(result, val.Interface())
   853  	return val.Elem().Interface(), err
   854  }
   855  
   856  func (sub *ClientSubscription) requestUnsubscribe() error {
   857  	var result interface{}
   858  	return sub.client.Call(&result, sub.namespace+unsubscribeMethodSuffix, sub.subid)
   859  }