github.com/cheng762/platon-go@v1.8.17-0.20190529111256-7deff2d7be26/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  	"encoding/json"
    22  	"fmt"
    23  	"io"
    24  	"reflect"
    25  	"strconv"
    26  	"strings"
    27  	"sync"
    28  
    29  	"github.com/PlatONnetwork/PlatON-Go/log"
    30  )
    31  
    32  const (
    33  	jsonrpcVersion           = "2.0"
    34  	serviceMethodSeparator   = "_"
    35  	subscribeMethodSuffix    = "_subscribe"
    36  	unsubscribeMethodSuffix  = "_unsubscribe"
    37  	notificationMethodSuffix = "_subscription"
    38  )
    39  
    40  type jsonRequest struct {
    41  	Method  string          `json:"method"`
    42  	Version string          `json:"jsonrpc"`
    43  	Id      json.RawMessage `json:"id,omitempty"`
    44  	Payload json.RawMessage `json:"params,omitempty"`
    45  }
    46  
    47  type jsonSuccessResponse struct {
    48  	Version string      `json:"jsonrpc"`
    49  	Id      interface{} `json:"id,omitempty"`
    50  	Result  interface{} `json:"result"`
    51  }
    52  
    53  type jsonError struct {
    54  	Code    int         `json:"code"`
    55  	Message string      `json:"message"`
    56  	Data    interface{} `json:"data,omitempty"`
    57  }
    58  
    59  type jsonErrResponse struct {
    60  	Version string      `json:"jsonrpc"`
    61  	Id      interface{} `json:"id,omitempty"`
    62  	Error   jsonError   `json:"error"`
    63  }
    64  
    65  type jsonSubscription struct {
    66  	Subscription string      `json:"subscription"`
    67  	Result       interface{} `json:"result,omitempty"`
    68  }
    69  
    70  type jsonNotification struct {
    71  	Version string           `json:"jsonrpc"`
    72  	Method  string           `json:"method"`
    73  	Params  jsonSubscription `json:"params"`
    74  }
    75  
    76  // jsonCodec reads and writes JSON-RPC messages to the underlying connection. It
    77  // also has support for parsing arguments and serializing (result) objects.
    78  type jsonCodec struct {
    79  	closer sync.Once                 // close closed channel once
    80  	closed chan interface{}          // closed on Close
    81  	decMu  sync.Mutex                // guards the decoder
    82  	decode func(v interface{}) error // decoder to allow multiple transports
    83  	encMu  sync.Mutex                // guards the encoder
    84  	encode func(v interface{}) error // encoder to allow multiple transports
    85  	rw     io.ReadWriteCloser        // connection
    86  }
    87  
    88  func (err *jsonError) Error() string {
    89  	if err.Message == "" {
    90  		return fmt.Sprintf("json-rpc error %d", err.Code)
    91  	}
    92  	return err.Message
    93  }
    94  
    95  func (err *jsonError) ErrorCode() int {
    96  	return err.Code
    97  }
    98  
    99  // NewCodec creates a new RPC server codec with support for JSON-RPC 2.0 based
   100  // on explicitly given encoding and decoding methods.
   101  func NewCodec(rwc io.ReadWriteCloser, encode, decode func(v interface{}) error) ServerCodec {
   102  	return &jsonCodec{
   103  		closed: make(chan interface{}),
   104  		encode: encode,
   105  		decode: decode,
   106  		rw:     rwc,
   107  	}
   108  }
   109  
   110  // NewJSONCodec creates a new RPC server codec with support for JSON-RPC 2.0.
   111  func NewJSONCodec(rwc io.ReadWriteCloser) ServerCodec {
   112  	enc := json.NewEncoder(rwc)
   113  	dec := json.NewDecoder(rwc)
   114  	dec.UseNumber()
   115  
   116  	return &jsonCodec{
   117  		closed: make(chan interface{}),
   118  		encode: enc.Encode,
   119  		decode: dec.Decode,
   120  		rw:     rwc,
   121  	}
   122  }
   123  
   124  // isBatch returns true when the first non-whitespace characters is '['
   125  func isBatch(msg json.RawMessage) bool {
   126  	for _, c := range msg {
   127  		// skip insignificant whitespace (http://www.ietf.org/rfc/rfc4627.txt)
   128  		if c == 0x20 || c == 0x09 || c == 0x0a || c == 0x0d {
   129  			continue
   130  		}
   131  		return c == '['
   132  	}
   133  	return false
   134  }
   135  
   136  // ReadRequestHeaders will read new requests without parsing the arguments. It will
   137  // return a collection of requests, an indication if these requests are in batch
   138  // form or an error when the incoming message could not be read/parsed.
   139  func (c *jsonCodec) ReadRequestHeaders() ([]rpcRequest, bool, Error) {
   140  	c.decMu.Lock()
   141  	defer c.decMu.Unlock()
   142  
   143  	var incomingMsg json.RawMessage
   144  	if err := c.decode(&incomingMsg); err != nil {
   145  		return nil, false, &invalidRequestError{err.Error()}
   146  	}
   147  	if isBatch(incomingMsg) {
   148  		return parseBatchRequest(incomingMsg)
   149  	}
   150  	return parseRequest(incomingMsg)
   151  }
   152  
   153  // checkReqId returns an error when the given reqId isn't valid for RPC method calls.
   154  // valid id's are strings, numbers or null
   155  func checkReqId(reqId json.RawMessage) error {
   156  	if len(reqId) == 0 {
   157  		return fmt.Errorf("missing request id")
   158  	}
   159  	if _, err := strconv.ParseFloat(string(reqId), 64); err == nil {
   160  		return nil
   161  	}
   162  	var str string
   163  
   164  	if err := json.Unmarshal(reqId, &str); err == nil {
   165  		return nil
   166  	}
   167  	return fmt.Errorf("invalid request id")
   168  }
   169  
   170  // parseRequest will parse a single request from the given RawMessage. It will return
   171  // the parsed request, an indication if the request was a batch or an error when
   172  // the request could not be parsed.
   173  func parseRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) {
   174  	var in jsonRequest
   175  	if err := json.Unmarshal(incomingMsg, &in); err != nil {
   176  		return nil, false, &invalidMessageError{err.Error()}
   177  	}
   178  
   179  	if err := checkReqId(in.Id); err != nil {
   180  		return nil, false, &invalidMessageError{err.Error()}
   181  	}
   182  
   183  	// subscribe are special, they will always use `subscribeMethod` as first param in the payload
   184  	if strings.HasSuffix(in.Method, subscribeMethodSuffix) {
   185  		reqs := []rpcRequest{{id: &in.Id, isPubSub: true}}
   186  		if len(in.Payload) > 0 {
   187  			// first param must be subscription name
   188  			var subscribeMethod [1]string
   189  			if err := json.Unmarshal(in.Payload, &subscribeMethod); err != nil {
   190  				log.Debug(fmt.Sprintf("Unable to parse subscription method: %v\n", err))
   191  				return nil, false, &invalidRequestError{"Unable to parse subscription request"}
   192  			}
   193  
   194  			reqs[0].service, reqs[0].method = strings.TrimSuffix(in.Method, subscribeMethodSuffix), subscribeMethod[0]
   195  			reqs[0].params = in.Payload
   196  			return reqs, false, nil
   197  		}
   198  		return nil, false, &invalidRequestError{"Unable to parse subscription request"}
   199  	}
   200  
   201  	if strings.HasSuffix(in.Method, unsubscribeMethodSuffix) {
   202  		return []rpcRequest{{id: &in.Id, isPubSub: true,
   203  			method: in.Method, params: in.Payload}}, false, nil
   204  	}
   205  
   206  	elems := strings.Split(in.Method, serviceMethodSeparator)
   207  	if len(elems) != 2 {
   208  		return nil, false, &methodNotFoundError{in.Method, ""}
   209  	}
   210  
   211  	// regular RPC call
   212  	if len(in.Payload) == 0 {
   213  		return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id}}, false, nil
   214  	}
   215  
   216  	return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id, params: in.Payload}}, false, nil
   217  }
   218  
   219  // parseBatchRequest will parse a batch request into a collection of requests from the given RawMessage, an indication
   220  // if the request was a batch or an error when the request could not be read.
   221  func parseBatchRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) {
   222  	var in []jsonRequest
   223  	if err := json.Unmarshal(incomingMsg, &in); err != nil {
   224  		return nil, false, &invalidMessageError{err.Error()}
   225  	}
   226  
   227  	requests := make([]rpcRequest, len(in))
   228  	for i, r := range in {
   229  		if err := checkReqId(r.Id); err != nil {
   230  			return nil, false, &invalidMessageError{err.Error()}
   231  		}
   232  
   233  		id := &in[i].Id
   234  
   235  		// subscribe are special, they will always use `subscriptionMethod` as first param in the payload
   236  		if strings.HasSuffix(r.Method, subscribeMethodSuffix) {
   237  			requests[i] = rpcRequest{id: id, isPubSub: true}
   238  			if len(r.Payload) > 0 {
   239  				// first param must be subscription name
   240  				var subscribeMethod [1]string
   241  				if err := json.Unmarshal(r.Payload, &subscribeMethod); err != nil {
   242  					log.Debug(fmt.Sprintf("Unable to parse subscription method: %v\n", err))
   243  					return nil, false, &invalidRequestError{"Unable to parse subscription request"}
   244  				}
   245  
   246  				requests[i].service, requests[i].method = strings.TrimSuffix(r.Method, subscribeMethodSuffix), subscribeMethod[0]
   247  				requests[i].params = r.Payload
   248  				continue
   249  			}
   250  
   251  			return nil, true, &invalidRequestError{"Unable to parse (un)subscribe request arguments"}
   252  		}
   253  
   254  		if strings.HasSuffix(r.Method, unsubscribeMethodSuffix) {
   255  			requests[i] = rpcRequest{id: id, isPubSub: true, method: r.Method, params: r.Payload}
   256  			continue
   257  		}
   258  
   259  		if len(r.Payload) == 0 {
   260  			requests[i] = rpcRequest{id: id, params: nil}
   261  		} else {
   262  			requests[i] = rpcRequest{id: id, params: r.Payload}
   263  		}
   264  		if elem := strings.Split(r.Method, serviceMethodSeparator); len(elem) == 2 {
   265  			requests[i].service, requests[i].method = elem[0], elem[1]
   266  		} else {
   267  			requests[i].err = &methodNotFoundError{r.Method, ""}
   268  		}
   269  	}
   270  
   271  	return requests, true, nil
   272  }
   273  
   274  // ParseRequestArguments tries to parse the given params (json.RawMessage) with the given
   275  // types. It returns the parsed values or an error when the parsing failed.
   276  func (c *jsonCodec) ParseRequestArguments(argTypes []reflect.Type, params interface{}) ([]reflect.Value, Error) {
   277  	if args, ok := params.(json.RawMessage); !ok {
   278  		return nil, &invalidParamsError{"Invalid params supplied"}
   279  	} else {
   280  		return parsePositionalArguments(args, argTypes)
   281  	}
   282  }
   283  
   284  // parsePositionalArguments tries to parse the given args to an array of values with the
   285  // given types. It returns the parsed values or an error when the args could not be
   286  // parsed. Missing optional arguments are returned as reflect.Zero values.
   287  func parsePositionalArguments(rawArgs json.RawMessage, types []reflect.Type) ([]reflect.Value, Error) {
   288  	// Read beginning of the args array.
   289  	dec := json.NewDecoder(bytes.NewReader(rawArgs))
   290  	if tok, _ := dec.Token(); tok != json.Delim('[') {
   291  		return nil, &invalidParamsError{"non-array args"}
   292  	}
   293  	// Read args.
   294  	args := make([]reflect.Value, 0, len(types))
   295  	for i := 0; dec.More(); i++ {
   296  		if i >= len(types) {
   297  			return nil, &invalidParamsError{fmt.Sprintf("too many arguments, want at most %d", len(types))}
   298  		}
   299  		argval := reflect.New(types[i])
   300  		if err := dec.Decode(argval.Interface()); err != nil {
   301  			return nil, &invalidParamsError{fmt.Sprintf("invalid argument %d: %v", i, err)}
   302  		}
   303  		if argval.IsNil() && types[i].Kind() != reflect.Ptr {
   304  			return nil, &invalidParamsError{fmt.Sprintf("missing value for required argument %d", i)}
   305  		}
   306  		args = append(args, argval.Elem())
   307  	}
   308  	// Read end of args array.
   309  	if _, err := dec.Token(); err != nil {
   310  		return nil, &invalidParamsError{err.Error()}
   311  	}
   312  	// Set any missing args to nil.
   313  	for i := len(args); i < len(types); i++ {
   314  		if types[i].Kind() != reflect.Ptr {
   315  			return nil, &invalidParamsError{fmt.Sprintf("missing value for required argument %d", i)}
   316  		}
   317  		args = append(args, reflect.Zero(types[i]))
   318  	}
   319  	return args, nil
   320  }
   321  
   322  // CreateResponse will create a JSON-RPC success response with the given id and reply as result.
   323  func (c *jsonCodec) CreateResponse(id interface{}, reply interface{}) interface{} {
   324  	return &jsonSuccessResponse{Version: jsonrpcVersion, Id: id, Result: reply}
   325  }
   326  
   327  // CreateErrorResponse will create a JSON-RPC error response with the given id and error.
   328  func (c *jsonCodec) CreateErrorResponse(id interface{}, err Error) interface{} {
   329  	return &jsonErrResponse{Version: jsonrpcVersion, Id: id, Error: jsonError{Code: err.ErrorCode(), Message: err.Error()}}
   330  }
   331  
   332  // CreateErrorResponseWithInfo will create a JSON-RPC error response with the given id and error.
   333  // info is optional and contains additional information about the error. When an empty string is passed it is ignored.
   334  func (c *jsonCodec) CreateErrorResponseWithInfo(id interface{}, err Error, info interface{}) interface{} {
   335  	return &jsonErrResponse{Version: jsonrpcVersion, Id: id,
   336  		Error: jsonError{Code: err.ErrorCode(), Message: err.Error(), Data: info}}
   337  }
   338  
   339  // CreateNotification will create a JSON-RPC notification with the given subscription id and event as params.
   340  func (c *jsonCodec) CreateNotification(subid, namespace string, event interface{}) interface{} {
   341  	return &jsonNotification{Version: jsonrpcVersion, Method: namespace + notificationMethodSuffix,
   342  		Params: jsonSubscription{Subscription: subid, Result: event}}
   343  }
   344  
   345  // Write message to client
   346  func (c *jsonCodec) Write(res interface{}) error {
   347  	c.encMu.Lock()
   348  	defer c.encMu.Unlock()
   349  
   350  	return c.encode(res)
   351  }
   352  
   353  // Close the underlying connection
   354  func (c *jsonCodec) Close() {
   355  	c.closer.Do(func() {
   356  		close(c.closed)
   357  		c.rw.Close()
   358  	})
   359  }
   360  
   361  // Closed returns a channel which will be closed when Close is called
   362  func (c *jsonCodec) Closed() <-chan interface{} {
   363  	return c.closed
   364  }