github.com/aerth/aquachain@v1.4.1/rpc/json.go (about)

     1  // Copyright 2015 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  	"github.com/aquanetwork/aquachain/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 d
    82  	decode func(v interface{}) error // decodes incoming requests
    83  	encMu  sync.Mutex                // guards e
    84  	encode func(v interface{}) error // encodes responses
    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  
   148  	if isBatch(incomingMsg) {
   149  		return parseBatchRequest(incomingMsg)
   150  	}
   151  
   152  	return parseRequest(incomingMsg)
   153  }
   154  
   155  // checkReqId returns an error when the given reqId isn't valid for RPC method calls.
   156  // valid id's are strings, numbers or null
   157  func checkReqId(reqId json.RawMessage) error {
   158  	if len(reqId) == 0 {
   159  		return fmt.Errorf("missing request id")
   160  	}
   161  	if _, err := strconv.ParseFloat(string(reqId), 64); err == nil {
   162  		return nil
   163  	}
   164  	var str string
   165  	if err := json.Unmarshal(reqId, &str); err == nil {
   166  		return nil
   167  	}
   168  	return fmt.Errorf("invalid request id")
   169  }
   170  
   171  // parseRequest will parse a single request from the given RawMessage. It will return
   172  // the parsed request, an indication if the request was a batch or an error when
   173  // the request could not be parsed.
   174  func parseRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) {
   175  	var in jsonRequest
   176  	if err := json.Unmarshal(incomingMsg, &in); err != nil {
   177  		return nil, false, &invalidMessageError{err.Error()}
   178  	}
   179  
   180  	if err := checkReqId(in.Id); err != nil {
   181  		return nil, false, &invalidMessageError{err.Error()}
   182  	}
   183  
   184  	// subscribe are special, they will always use `subscribeMethod` as first param in the payload
   185  	if strings.HasSuffix(in.Method, subscribeMethodSuffix) {
   186  		reqs := []rpcRequest{{id: &in.Id, isPubSub: true}}
   187  		if len(in.Payload) > 0 {
   188  			// first param must be subscription name
   189  			var subscribeMethod [1]string
   190  			if err := json.Unmarshal(in.Payload, &subscribeMethod); err != nil {
   191  				log.Debug(fmt.Sprintf("Unable to parse subscription method: %v\n", err))
   192  				return nil, false, &invalidRequestError{"Unable to parse subscription request"}
   193  			}
   194  
   195  			reqs[0].service, reqs[0].method = strings.TrimSuffix(in.Method, subscribeMethodSuffix), subscribeMethod[0]
   196  			reqs[0].params = in.Payload
   197  			return reqs, false, nil
   198  		}
   199  		return nil, false, &invalidRequestError{"Unable to parse subscription request"}
   200  	}
   201  
   202  	if strings.HasPrefix(in.Method, "eth_") {
   203  		in.Method = "aqua_" + strings.TrimPrefix(in.Method, "eth_")
   204  	}
   205  
   206  	if strings.HasSuffix(in.Method, unsubscribeMethodSuffix) {
   207  		return []rpcRequest{{id: &in.Id, isPubSub: true,
   208  			method: in.Method, params: in.Payload}}, false, nil
   209  	}
   210  
   211  	elems := strings.Split(in.Method, serviceMethodSeparator)
   212  	if len(elems) != 2 {
   213  		return nil, false, &methodNotFoundError{in.Method, ""}
   214  	}
   215  
   216  	// regular RPC call
   217  	if len(in.Payload) == 0 {
   218  		return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id}}, false, nil
   219  	}
   220  
   221  	return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id, params: in.Payload}}, false, nil
   222  }
   223  
   224  // parseBatchRequest will parse a batch request into a collection of requests from the given RawMessage, an indication
   225  // if the request was a batch or an error when the request could not be read.
   226  func parseBatchRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) {
   227  	var in []jsonRequest
   228  	if err := json.Unmarshal(incomingMsg, &in); err != nil {
   229  		return nil, false, &invalidMessageError{err.Error()}
   230  	}
   231  
   232  	requests := make([]rpcRequest, len(in))
   233  	for i, r := range in {
   234  		if err := checkReqId(r.Id); err != nil {
   235  			return nil, false, &invalidMessageError{err.Error()}
   236  		}
   237  
   238  		id := &in[i].Id
   239  
   240  		// subscribe are special, they will always use `subscriptionMethod` as first param in the payload
   241  		if strings.HasSuffix(r.Method, subscribeMethodSuffix) {
   242  			requests[i] = rpcRequest{id: id, isPubSub: true}
   243  			if len(r.Payload) > 0 {
   244  				// first param must be subscription name
   245  				var subscribeMethod [1]string
   246  				if err := json.Unmarshal(r.Payload, &subscribeMethod); err != nil {
   247  					log.Debug(fmt.Sprintf("Unable to parse subscription method: %v\n", err))
   248  					return nil, false, &invalidRequestError{"Unable to parse subscription request"}
   249  				}
   250  
   251  				requests[i].service, requests[i].method = strings.TrimSuffix(r.Method, subscribeMethodSuffix), subscribeMethod[0]
   252  				requests[i].params = r.Payload
   253  				continue
   254  			}
   255  
   256  			return nil, true, &invalidRequestError{"Unable to parse (un)subscribe request arguments"}
   257  		}
   258  
   259  		if strings.HasSuffix(r.Method, unsubscribeMethodSuffix) {
   260  			requests[i] = rpcRequest{id: id, isPubSub: true, method: r.Method, params: r.Payload}
   261  			continue
   262  		}
   263  
   264  		if len(r.Payload) == 0 {
   265  			requests[i] = rpcRequest{id: id, params: nil}
   266  		} else {
   267  			requests[i] = rpcRequest{id: id, params: r.Payload}
   268  		}
   269  		if elem := strings.Split(r.Method, serviceMethodSeparator); len(elem) == 2 {
   270  			requests[i].service, requests[i].method = elem[0], elem[1]
   271  		} else {
   272  			requests[i].err = &methodNotFoundError{r.Method, ""}
   273  		}
   274  	}
   275  
   276  	return requests, true, nil
   277  }
   278  
   279  // ParseRequestArguments tries to parse the given params (json.RawMessage) with the given
   280  // types. It returns the parsed values or an error when the parsing failed.
   281  func (c *jsonCodec) ParseRequestArguments(argTypes []reflect.Type, params interface{}) ([]reflect.Value, Error) {
   282  	if args, ok := params.(json.RawMessage); !ok {
   283  		return nil, &invalidParamsError{"Invalid params supplied"}
   284  	} else {
   285  		return parsePositionalArguments(args, argTypes)
   286  	}
   287  }
   288  
   289  // parsePositionalArguments tries to parse the given args to an array of values with the
   290  // given types. It returns the parsed values or an error when the args could not be
   291  // parsed. Missing optional arguments are returned as reflect.Zero values.
   292  func parsePositionalArguments(rawArgs json.RawMessage, types []reflect.Type) ([]reflect.Value, Error) {
   293  	// Read beginning of the args array.
   294  	dec := json.NewDecoder(bytes.NewReader(rawArgs))
   295  	if tok, _ := dec.Token(); tok != json.Delim('[') {
   296  		return nil, &invalidParamsError{"non-array args"}
   297  	}
   298  	// Read args.
   299  	args := make([]reflect.Value, 0, len(types))
   300  	for i := 0; dec.More(); i++ {
   301  		if i >= len(types) {
   302  			return nil, &invalidParamsError{fmt.Sprintf("too many arguments, want at most %d", len(types))}
   303  		}
   304  		argval := reflect.New(types[i])
   305  		if err := dec.Decode(argval.Interface()); err != nil {
   306  			return nil, &invalidParamsError{fmt.Sprintf("invalid argument %d: %v", i, err)}
   307  		}
   308  		if argval.IsNil() && types[i].Kind() != reflect.Ptr {
   309  			return nil, &invalidParamsError{fmt.Sprintf("missing value for required argument %d", i)}
   310  		}
   311  		args = append(args, argval.Elem())
   312  	}
   313  	// Read end of args array.
   314  	if _, err := dec.Token(); err != nil {
   315  		return nil, &invalidParamsError{err.Error()}
   316  	}
   317  	// Set any missing args to nil.
   318  	for i := len(args); i < len(types); i++ {
   319  		if types[i].Kind() != reflect.Ptr {
   320  			return nil, &invalidParamsError{fmt.Sprintf("missing value for required argument %d", i)}
   321  		}
   322  		args = append(args, reflect.Zero(types[i]))
   323  	}
   324  	return args, nil
   325  }
   326  
   327  // CreateResponse will create a JSON-RPC success response with the given id and reply as result.
   328  func (c *jsonCodec) CreateResponse(id interface{}, reply interface{}) interface{} {
   329  	if isHexNum(reflect.TypeOf(reply)) {
   330  		return &jsonSuccessResponse{Version: jsonrpcVersion, Id: id, Result: fmt.Sprintf(`%#x`, reply)}
   331  	}
   332  	return &jsonSuccessResponse{Version: jsonrpcVersion, Id: id, Result: reply}
   333  }
   334  
   335  // CreateErrorResponse will create a JSON-RPC error response with the given id and error.
   336  func (c *jsonCodec) CreateErrorResponse(id interface{}, err Error) interface{} {
   337  	return &jsonErrResponse{Version: jsonrpcVersion, Id: id, Error: jsonError{Code: err.ErrorCode(), Message: err.Error()}}
   338  }
   339  
   340  // CreateErrorResponseWithInfo will create a JSON-RPC error response with the given id and error.
   341  // info is optional and contains additional information about the error. When an empty string is passed it is ignored.
   342  func (c *jsonCodec) CreateErrorResponseWithInfo(id interface{}, err Error, info interface{}) interface{} {
   343  	return &jsonErrResponse{Version: jsonrpcVersion, Id: id,
   344  		Error: jsonError{Code: err.ErrorCode(), Message: err.Error(), Data: info}}
   345  }
   346  
   347  // CreateNotification will create a JSON-RPC notification with the given subscription id and event as params.
   348  func (c *jsonCodec) CreateNotification(subid, namespace string, event interface{}) interface{} {
   349  	if isHexNum(reflect.TypeOf(event)) {
   350  		return &jsonNotification{Version: jsonrpcVersion, Method: namespace + notificationMethodSuffix,
   351  			Params: jsonSubscription{Subscription: subid, Result: fmt.Sprintf(`%#x`, event)}}
   352  	}
   353  
   354  	return &jsonNotification{Version: jsonrpcVersion, Method: namespace + notificationMethodSuffix,
   355  		Params: jsonSubscription{Subscription: subid, Result: event}}
   356  }
   357  
   358  // Write message to client
   359  func (c *jsonCodec) Write(res interface{}) error {
   360  	c.encMu.Lock()
   361  	defer c.encMu.Unlock()
   362  
   363  	return c.encode(res)
   364  }
   365  
   366  // Close the underlying connection
   367  func (c *jsonCodec) Close() {
   368  	c.closer.Do(func() {
   369  		close(c.closed)
   370  		c.rw.Close()
   371  	})
   372  }
   373  
   374  // Closed returns a channel which will be closed when Close is called
   375  func (c *jsonCodec) Closed() <-chan interface{} {
   376  	return c.closed
   377  }