gitlab.com/aquachain/aquachain@v1.17.16-rc3.0.20221018032414-e3ddf1e1c055/rpc/json.go (about)

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