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

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