github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/rpc/client.go (about)

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