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