gitee.com/liu-zhao234568/cntest@v1.0.0/rpc/json.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package rpc
    18  
    19  import (
    20  	"bytes"
    21  	"context"
    22  	"encoding/json"
    23  	"errors"
    24  	"fmt"
    25  	"io"
    26  	"reflect"
    27  	"strings"
    28  	"sync"
    29  	"time"
    30  )
    31  
    32  const (
    33  	vsn                      = "2.0"
    34  	serviceMethodSeparator   = "_"
    35  	subscribeMethodSuffix    = "_subscribe"
    36  	unsubscribeMethodSuffix  = "_unsubscribe"
    37  	notificationMethodSuffix = "_subscription"
    38  
    39  	defaultWriteTimeout = 10 * time.Second // used if context has no deadline
    40  )
    41  
    42  var null = json.RawMessage("null")
    43  
    44  type subscriptionResult struct {
    45  	ID     string          `json:"subscription"`
    46  	Result json.RawMessage `json:"result,omitempty"`
    47  }
    48  
    49  // A value of this type can a JSON-RPC request, notification, successful response or
    50  // error response. Which one it is depends on the fields.
    51  type jsonrpcMessage struct {
    52  	Version string          `json:"jsonrpc,omitempty"`
    53  	ID      json.RawMessage `json:"id,omitempty"`
    54  	Method  string          `json:"method,omitempty"`
    55  	Params  json.RawMessage `json:"params,omitempty"`
    56  	Error   *jsonError      `json:"error,omitempty"`
    57  	Result  json.RawMessage `json:"result,omitempty"`
    58  }
    59  
    60  func (msg *jsonrpcMessage) isNotification() bool {
    61  	return msg.ID == nil && msg.Method != ""
    62  }
    63  
    64  func (msg *jsonrpcMessage) isCall() bool {
    65  	return msg.hasValidID() && msg.Method != ""
    66  }
    67  
    68  func (msg *jsonrpcMessage) isResponse() bool {
    69  	return msg.hasValidID() && msg.Method == "" && msg.Params == nil && (msg.Result != nil || msg.Error != nil)
    70  }
    71  
    72  func (msg *jsonrpcMessage) hasValidID() bool {
    73  	return len(msg.ID) > 0 && msg.ID[0] != '{' && msg.ID[0] != '['
    74  }
    75  
    76  func (msg *jsonrpcMessage) isSubscribe() bool {
    77  	return strings.HasSuffix(msg.Method, subscribeMethodSuffix)
    78  }
    79  
    80  func (msg *jsonrpcMessage) isUnsubscribe() bool {
    81  	return strings.HasSuffix(msg.Method, unsubscribeMethodSuffix)
    82  }
    83  
    84  func (msg *jsonrpcMessage) namespace() string {
    85  	elem := strings.SplitN(msg.Method, serviceMethodSeparator, 2)
    86  	return elem[0]
    87  }
    88  
    89  func (msg *jsonrpcMessage) String() string {
    90  	b, _ := json.Marshal(msg)
    91  	return string(b)
    92  }
    93  
    94  func (msg *jsonrpcMessage) errorResponse(err error) *jsonrpcMessage {
    95  	resp := errorMessage(err)
    96  	resp.ID = msg.ID
    97  	return resp
    98  }
    99  
   100  func (msg *jsonrpcMessage) response(result interface{}) *jsonrpcMessage {
   101  	enc, err := json.Marshal(result)
   102  	if err != nil {
   103  		// TODO: wrap with 'internal server error'
   104  		return msg.errorResponse(err)
   105  	}
   106  	return &jsonrpcMessage{Version: vsn, ID: msg.ID, Result: enc}
   107  }
   108  
   109  func errorMessage(err error) *jsonrpcMessage {
   110  	msg := &jsonrpcMessage{Version: vsn, ID: null, Error: &jsonError{
   111  		Code:    defaultErrorCode,
   112  		Message: err.Error(),
   113  	}}
   114  	ec, ok := err.(Error)
   115  	if ok {
   116  		msg.Error.Code = ec.ErrorCode()
   117  	}
   118  	de, ok := err.(DataError)
   119  	if ok {
   120  		msg.Error.Data = de.ErrorData()
   121  	}
   122  	return msg
   123  }
   124  
   125  type jsonError struct {
   126  	Code    int         `json:"code"`
   127  	Message string      `json:"message"`
   128  	Data    interface{} `json:"data,omitempty"`
   129  }
   130  
   131  func (err *jsonError) Error() string {
   132  	if err.Message == "" {
   133  		return fmt.Sprintf("json-rpc error %d", err.Code)
   134  	}
   135  	return err.Message
   136  }
   137  
   138  func (err *jsonError) ErrorCode() int {
   139  	return err.Code
   140  }
   141  
   142  func (err *jsonError) ErrorData() interface{} {
   143  	return err.Data
   144  }
   145  
   146  // Conn is a subset of the methods of net.Conn which are sufficient for ServerCodec.
   147  type Conn interface {
   148  	io.ReadWriteCloser
   149  	SetWriteDeadline(time.Time) error
   150  }
   151  
   152  type deadlineCloser interface {
   153  	io.Closer
   154  	SetWriteDeadline(time.Time) error
   155  }
   156  
   157  // ConnRemoteAddr wraps the RemoteAddr operation, which returns a description
   158  // of the peer address of a connection. If a Conn also implements ConnRemoteAddr, this
   159  // description is used in log messages.
   160  type ConnRemoteAddr interface {
   161  	RemoteAddr() string
   162  }
   163  
   164  // jsonCodec reads and writes JSON-RPC messages to the underlying connection. It also has
   165  // support for parsing arguments and serializing (result) objects.
   166  type jsonCodec struct {
   167  	remote  string
   168  	closer  sync.Once                 // close closed channel once
   169  	closeCh chan interface{}          // closed on Close
   170  	decode  func(v interface{}) error // decoder to allow multiple transports
   171  	encMu   sync.Mutex                // guards the encoder
   172  	encode  func(v interface{}) error // encoder to allow multiple transports
   173  	conn    deadlineCloser
   174  }
   175  
   176  // NewFuncCodec creates a codec which uses the given functions to read and write. If conn
   177  // implements ConnRemoteAddr, log messages will use it to include the remote address of
   178  // the connection.
   179  func NewFuncCodec(conn deadlineCloser, encode, decode func(v interface{}) error) ServerCodec {
   180  	codec := &jsonCodec{
   181  		closeCh: make(chan interface{}),
   182  		encode:  encode,
   183  		decode:  decode,
   184  		conn:    conn,
   185  	}
   186  	if ra, ok := conn.(ConnRemoteAddr); ok {
   187  		codec.remote = ra.RemoteAddr()
   188  	}
   189  	return codec
   190  }
   191  
   192  // NewCodec creates a codec on the given connection. If conn implements ConnRemoteAddr, log
   193  // messages will use it to include the remote address of the connection.
   194  func NewCodec(conn Conn) ServerCodec {
   195  	enc := json.NewEncoder(conn)
   196  	dec := json.NewDecoder(conn)
   197  	dec.UseNumber()
   198  	return NewFuncCodec(conn, enc.Encode, dec.Decode)
   199  }
   200  
   201  func (c *jsonCodec) remoteAddr() string {
   202  	return c.remote
   203  }
   204  
   205  func (c *jsonCodec) readBatch() (messages []*jsonrpcMessage, batch bool, err error) {
   206  	// Decode the next JSON object in the input stream.
   207  	// This verifies basic syntax, etc.
   208  	var rawmsg json.RawMessage
   209  	if err := c.decode(&rawmsg); err != nil {
   210  		return nil, false, err
   211  	}
   212  	messages, batch = parseMessage(rawmsg)
   213  	for i, msg := range messages {
   214  		if msg == nil {
   215  			// Message is JSON 'null'. Replace with zero value so it
   216  			// will be treated like any other invalid message.
   217  			messages[i] = new(jsonrpcMessage)
   218  		}
   219  	}
   220  	return messages, batch, nil
   221  }
   222  
   223  func (c *jsonCodec) writeJSON(ctx context.Context, v interface{}) error {
   224  	c.encMu.Lock()
   225  	defer c.encMu.Unlock()
   226  
   227  	deadline, ok := ctx.Deadline()
   228  	if !ok {
   229  		deadline = time.Now().Add(defaultWriteTimeout)
   230  	}
   231  	c.conn.SetWriteDeadline(deadline)
   232  	return c.encode(v)
   233  }
   234  
   235  func (c *jsonCodec) close() {
   236  	c.closer.Do(func() {
   237  		close(c.closeCh)
   238  		c.conn.Close()
   239  	})
   240  }
   241  
   242  // Closed returns a channel which will be closed when Close is called
   243  func (c *jsonCodec) closed() <-chan interface{} {
   244  	return c.closeCh
   245  }
   246  
   247  // parseMessage parses raw bytes as a (batch of) JSON-RPC message(s). There are no error
   248  // checks in this function because the raw message has already been syntax-checked when it
   249  // is called. Any non-JSON-RPC messages in the input return the zero value of
   250  // jsonrpcMessage.
   251  func parseMessage(raw json.RawMessage) ([]*jsonrpcMessage, bool) {
   252  	if !isBatch(raw) {
   253  		msgs := []*jsonrpcMessage{{}}
   254  		json.Unmarshal(raw, &msgs[0])
   255  		return msgs, false
   256  	}
   257  	dec := json.NewDecoder(bytes.NewReader(raw))
   258  	dec.Token() // skip '['
   259  	var msgs []*jsonrpcMessage
   260  	for dec.More() {
   261  		msgs = append(msgs, new(jsonrpcMessage))
   262  		dec.Decode(&msgs[len(msgs)-1])
   263  	}
   264  	return msgs, true
   265  }
   266  
   267  // isBatch returns true when the first non-whitespace characters is '['
   268  func isBatch(raw json.RawMessage) bool {
   269  	for _, c := range raw {
   270  		// skip insignificant whitespace (http://www.ietf.org/rfc/rfc4627.txt)
   271  		if c == 0x20 || c == 0x09 || c == 0x0a || c == 0x0d {
   272  			continue
   273  		}
   274  		return c == '['
   275  	}
   276  	return false
   277  }
   278  
   279  // parsePositionalArguments tries to parse the given args to an array of values with the
   280  // given types. It returns the parsed values or an error when the args could not be
   281  // parsed. Missing optional arguments are returned as reflect.Zero values.
   282  func parsePositionalArguments(rawArgs json.RawMessage, types []reflect.Type) ([]reflect.Value, error) {
   283  	dec := json.NewDecoder(bytes.NewReader(rawArgs))
   284  	var args []reflect.Value
   285  	tok, err := dec.Token()
   286  	switch {
   287  	case err == io.EOF || tok == nil && err == nil:
   288  		// "params" is optional and may be empty. Also allow "params":null even though it's
   289  		// not in the spec because our own client used to send it.
   290  	case err != nil:
   291  		return nil, err
   292  	case tok == json.Delim('['):
   293  		// Read argument array.
   294  		if args, err = parseArgumentArray(dec, types); err != nil {
   295  			return nil, err
   296  		}
   297  	default:
   298  		return nil, errors.New("non-array args")
   299  	}
   300  	// Set any missing args to nil.
   301  	for i := len(args); i < len(types); i++ {
   302  		if types[i].Kind() != reflect.Ptr {
   303  			return nil, fmt.Errorf("missing value for required argument %d", i)
   304  		}
   305  		args = append(args, reflect.Zero(types[i]))
   306  	}
   307  	return args, nil
   308  }
   309  
   310  func parseArgumentArray(dec *json.Decoder, types []reflect.Type) ([]reflect.Value, error) {
   311  	args := make([]reflect.Value, 0, len(types))
   312  	for i := 0; dec.More(); i++ {
   313  		if i >= len(types) {
   314  			return args, fmt.Errorf("too many arguments, want at most %d", len(types))
   315  		}
   316  		argval := reflect.New(types[i])
   317  		if err := dec.Decode(argval.Interface()); err != nil {
   318  			return args, fmt.Errorf("invalid argument %d: %v", i, err)
   319  		}
   320  		if argval.IsNil() && types[i].Kind() != reflect.Ptr {
   321  			return args, fmt.Errorf("missing value for required argument %d", i)
   322  		}
   323  		args = append(args, argval.Elem())
   324  	}
   325  	// Read end of args array.
   326  	_, err := dec.Token()
   327  	return args, err
   328  }
   329  
   330  // parseSubscriptionName extracts the subscription name from an encoded argument array.
   331  func parseSubscriptionName(rawArgs json.RawMessage) (string, error) {
   332  	dec := json.NewDecoder(bytes.NewReader(rawArgs))
   333  	if tok, _ := dec.Token(); tok != json.Delim('[') {
   334  		return "", errors.New("non-array args")
   335  	}
   336  	v, _ := dec.Token()
   337  	method, ok := v.(string)
   338  	if !ok {
   339  		return "", errors.New("expected subscription name as first argument")
   340  	}
   341  	return method, nil
   342  }