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