github.com/devfans/go-ethereum@v1.5.10-0.20170326212234-7419d0c38291/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/ethereum/go-ethereum/log"
    30  )
    31  
    32  const (
    33  	jsonrpcVersion         = "2.0"
    34  	serviceMethodSeparator = "_"
    35  	subscribeMethod        = "eth_subscribe"
    36  	unsubscribeMethod      = "eth_unsubscribe"
    37  	notificationMethod     = "eth_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  	d      *json.Decoder      // decodes incoming requests
    83  	encMu  sync.Mutex         // guards e
    84  	e      *json.Encoder      // 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  // NewJSONCodec creates a new RPC server codec with support for JSON-RPC 2.0
   100  func NewJSONCodec(rwc io.ReadWriteCloser) ServerCodec {
   101  	d := json.NewDecoder(rwc)
   102  	d.UseNumber()
   103  	return &jsonCodec{closed: make(chan interface{}), d: d, e: json.NewEncoder(rwc), rw: rwc}
   104  }
   105  
   106  // isBatch returns true when the first non-whitespace characters is '['
   107  func isBatch(msg json.RawMessage) bool {
   108  	for _, c := range msg {
   109  		// skip insignificant whitespace (http://www.ietf.org/rfc/rfc4627.txt)
   110  		if c == 0x20 || c == 0x09 || c == 0x0a || c == 0x0d {
   111  			continue
   112  		}
   113  		return c == '['
   114  	}
   115  	return false
   116  }
   117  
   118  // ReadRequestHeaders will read new requests without parsing the arguments. It will
   119  // return a collection of requests, an indication if these requests are in batch
   120  // form or an error when the incoming message could not be read/parsed.
   121  func (c *jsonCodec) ReadRequestHeaders() ([]rpcRequest, bool, Error) {
   122  	c.decMu.Lock()
   123  	defer c.decMu.Unlock()
   124  
   125  	var incomingMsg json.RawMessage
   126  	if err := c.d.Decode(&incomingMsg); err != nil {
   127  		return nil, false, &invalidRequestError{err.Error()}
   128  	}
   129  
   130  	if isBatch(incomingMsg) {
   131  		return parseBatchRequest(incomingMsg)
   132  	}
   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 in.Method == subscribeMethod {
   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  			// all subscriptions are made on the eth service
   178  			reqs[0].service, reqs[0].method = "eth", subscribeMethod[0]
   179  			reqs[0].params = in.Payload
   180  			return reqs, false, nil
   181  		}
   182  		return nil, false, &invalidRequestError{"Unable to parse subscription request"}
   183  	}
   184  
   185  	if in.Method == unsubscribeMethod {
   186  		return []rpcRequest{{id: &in.Id, isPubSub: true,
   187  			method: unsubscribeMethod, params: in.Payload}}, false, nil
   188  	}
   189  
   190  	elems := strings.Split(in.Method, serviceMethodSeparator)
   191  	if len(elems) != 2 {
   192  		return nil, false, &methodNotFoundError{in.Method, ""}
   193  	}
   194  
   195  	// regular RPC call
   196  	if len(in.Payload) == 0 {
   197  		return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id}}, false, nil
   198  	}
   199  
   200  	return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id, params: in.Payload}}, false, nil
   201  }
   202  
   203  // parseBatchRequest will parse a batch request into a collection of requests from the given RawMessage, an indication
   204  // if the request was a batch or an error when the request could not be read.
   205  func parseBatchRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) {
   206  	var in []jsonRequest
   207  	if err := json.Unmarshal(incomingMsg, &in); err != nil {
   208  		return nil, false, &invalidMessageError{err.Error()}
   209  	}
   210  
   211  	requests := make([]rpcRequest, len(in))
   212  	for i, r := range in {
   213  		if err := checkReqId(r.Id); err != nil {
   214  			return nil, false, &invalidMessageError{err.Error()}
   215  		}
   216  
   217  		id := &in[i].Id
   218  
   219  		// subscribe are special, they will always use `subscribeMethod` as first param in the payload
   220  		if r.Method == subscribeMethod {
   221  			requests[i] = rpcRequest{id: id, isPubSub: true}
   222  			if len(r.Payload) > 0 {
   223  				// first param must be subscription name
   224  				var subscribeMethod [1]string
   225  				if err := json.Unmarshal(r.Payload, &subscribeMethod); err != nil {
   226  					log.Debug(fmt.Sprintf("Unable to parse subscription method: %v\n", err))
   227  					return nil, false, &invalidRequestError{"Unable to parse subscription request"}
   228  				}
   229  
   230  				// all subscriptions are made on the eth service
   231  				requests[i].service, requests[i].method = "eth", subscribeMethod[0]
   232  				requests[i].params = r.Payload
   233  				continue
   234  			}
   235  
   236  			return nil, true, &invalidRequestError{"Unable to parse (un)subscribe request arguments"}
   237  		}
   238  
   239  		if r.Method == unsubscribeMethod {
   240  			requests[i] = rpcRequest{id: id, isPubSub: true, method: unsubscribeMethod, params: r.Payload}
   241  			continue
   242  		}
   243  
   244  		if len(r.Payload) == 0 {
   245  			requests[i] = rpcRequest{id: id, params: nil}
   246  		} else {
   247  			requests[i] = rpcRequest{id: id, params: r.Payload}
   248  		}
   249  		if elem := strings.Split(r.Method, serviceMethodSeparator); len(elem) == 2 {
   250  			requests[i].service, requests[i].method = elem[0], elem[1]
   251  		} else {
   252  			requests[i].err = &methodNotFoundError{r.Method, ""}
   253  		}
   254  	}
   255  
   256  	return requests, true, nil
   257  }
   258  
   259  // ParseRequestArguments tries to parse the given params (json.RawMessage) with the given
   260  // types. It returns the parsed values or an error when the parsing failed.
   261  func (c *jsonCodec) ParseRequestArguments(argTypes []reflect.Type, params interface{}) ([]reflect.Value, Error) {
   262  	if args, ok := params.(json.RawMessage); !ok {
   263  		return nil, &invalidParamsError{"Invalid params supplied"}
   264  	} else {
   265  		return parsePositionalArguments(args, argTypes)
   266  	}
   267  }
   268  
   269  // parsePositionalArguments tries to parse the given args to an array of values with the
   270  // given types. It returns the parsed values or an error when the args could not be
   271  // parsed. Missing optional arguments are returned as reflect.Zero values.
   272  func parsePositionalArguments(rawArgs json.RawMessage, types []reflect.Type) ([]reflect.Value, Error) {
   273  	// Read beginning of the args array.
   274  	dec := json.NewDecoder(bytes.NewReader(rawArgs))
   275  	if tok, _ := dec.Token(); tok != json.Delim('[') {
   276  		return nil, &invalidParamsError{"non-array args"}
   277  	}
   278  	// Read args.
   279  	args := make([]reflect.Value, 0, len(types))
   280  	for i := 0; dec.More(); i++ {
   281  		if i >= len(types) {
   282  			return nil, &invalidParamsError{fmt.Sprintf("too many arguments, want at most %d", len(types))}
   283  		}
   284  		argval := reflect.New(types[i])
   285  		if err := dec.Decode(argval.Interface()); err != nil {
   286  			return nil, &invalidParamsError{fmt.Sprintf("invalid argument %d: %v", i, err)}
   287  		}
   288  		if argval.IsNil() && types[i].Kind() != reflect.Ptr {
   289  			return nil, &invalidParamsError{fmt.Sprintf("missing value for required argument %d", i)}
   290  		}
   291  		args = append(args, argval.Elem())
   292  	}
   293  	// Read end of args array.
   294  	if _, err := dec.Token(); err != nil {
   295  		return nil, &invalidParamsError{err.Error()}
   296  	}
   297  	// Set any missing args to nil.
   298  	for i := len(args); i < len(types); i++ {
   299  		if types[i].Kind() != reflect.Ptr {
   300  			return nil, &invalidParamsError{fmt.Sprintf("missing value for required argument %d", i)}
   301  		}
   302  		args = append(args, reflect.Zero(types[i]))
   303  	}
   304  	return args, nil
   305  }
   306  
   307  // CreateResponse will create a JSON-RPC success response with the given id and reply as result.
   308  func (c *jsonCodec) CreateResponse(id interface{}, reply interface{}) interface{} {
   309  	if isHexNum(reflect.TypeOf(reply)) {
   310  		return &jsonSuccessResponse{Version: jsonrpcVersion, Id: id, Result: fmt.Sprintf(`%#x`, reply)}
   311  	}
   312  	return &jsonSuccessResponse{Version: jsonrpcVersion, Id: id, Result: reply}
   313  }
   314  
   315  // CreateErrorResponse will create a JSON-RPC error response with the given id and error.
   316  func (c *jsonCodec) CreateErrorResponse(id interface{}, err Error) interface{} {
   317  	return &jsonErrResponse{Version: jsonrpcVersion, Id: id, Error: jsonError{Code: err.ErrorCode(), Message: err.Error()}}
   318  }
   319  
   320  // CreateErrorResponseWithInfo will create a JSON-RPC error response with the given id and error.
   321  // info is optional and contains additional information about the error. When an empty string is passed it is ignored.
   322  func (c *jsonCodec) CreateErrorResponseWithInfo(id interface{}, err Error, info interface{}) interface{} {
   323  	return &jsonErrResponse{Version: jsonrpcVersion, Id: id,
   324  		Error: jsonError{Code: err.ErrorCode(), Message: err.Error(), Data: info}}
   325  }
   326  
   327  // CreateNotification will create a JSON-RPC notification with the given subscription id and event as params.
   328  func (c *jsonCodec) CreateNotification(subid string, event interface{}) interface{} {
   329  	if isHexNum(reflect.TypeOf(event)) {
   330  		return &jsonNotification{Version: jsonrpcVersion, Method: notificationMethod,
   331  			Params: jsonSubscription{Subscription: subid, Result: fmt.Sprintf(`%#x`, event)}}
   332  	}
   333  
   334  	return &jsonNotification{Version: jsonrpcVersion, Method: notificationMethod,
   335  		Params: jsonSubscription{Subscription: subid, Result: event}}
   336  }
   337  
   338  // Write message to client
   339  func (c *jsonCodec) Write(res interface{}) error {
   340  	c.encMu.Lock()
   341  	defer c.encMu.Unlock()
   342  
   343  	return c.e.Encode(res)
   344  }
   345  
   346  // Close the underlying connection
   347  func (c *jsonCodec) Close() {
   348  	c.closer.Do(func() {
   349  		close(c.closed)
   350  		c.rw.Close()
   351  	})
   352  }
   353  
   354  // Closed returns a channel which will be closed when Close is called
   355  func (c *jsonCodec) Closed() <-chan interface{} {
   356  	return c.closed
   357  }