json.go 12.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

17
package rpc
18 19

import (
20
	"bytes"
21 22 23 24
	"encoding/json"
	"fmt"
	"io"
	"reflect"
25
	"strconv"
26
	"strings"
27
	"sync"
28

29
	"github.com/ethereum/go-ethereum/log"
30 31 32
)

const (
33 34 35 36 37
	jsonrpcVersion           = "2.0"
	serviceMethodSeparator   = "_"
	subscribeMethodSuffix    = "_subscribe"
	unsubscribeMethodSuffix  = "_unsubscribe"
	notificationMethodSuffix = "_subscription"
38 39
)

40
type jsonRequest struct {
41 42
	Method  string          `json:"method"`
	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 55 56 57 58
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

59
type jsonErrResponse struct {
60 61
	Version string      `json:"jsonrpc"`
	Id      interface{} `json:"id,omitempty"`
62
	Error   jsonError   `json:"error"`
63 64 65 66 67 68 69 70 71 72 73 74 75
}

type jsonSubscription struct {
	Subscription string      `json:"subscription"`
	Result       interface{} `json:"result,omitempty"`
}

type jsonNotification struct {
	Version string           `json:"jsonrpc"`
	Method  string           `json:"method"`
	Params  jsonSubscription `json:"params"`
}

76 77
// jsonCodec reads and writes JSON-RPC messages to the underlying connection. It
// also has support for parsing arguments and serializing (result) objects.
78
type jsonCodec struct {
79 80 81 82 83 84 85
	closer sync.Once          // close closed channel once
	closed chan interface{}   // closed on Close
	decMu  sync.Mutex         // guards d
	d      *json.Decoder      // decodes incoming requests
	encMu  sync.Mutex         // guards e
	e      *json.Encoder      // encodes responses
	rw     io.ReadWriteCloser // connection
86 87
}

88 89 90 91 92 93 94 95 96 97 98
func (err *jsonError) Error() string {
	if err.Message == "" {
		return fmt.Sprintf("json-rpc error %d", err.Code)
	}
	return err.Message
}

func (err *jsonError) ErrorCode() int {
	return err.Code
}

99 100 101 102
// NewJSONCodec creates a new RPC server codec with support for JSON-RPC 2.0
func NewJSONCodec(rwc io.ReadWriteCloser) ServerCodec {
	d := json.NewDecoder(rwc)
	d.UseNumber()
103
	return &jsonCodec{closed: make(chan interface{}), d: d, e: json.NewEncoder(rwc), rw: rwc}
104 105 106 107 108 109 110 111 112 113 114 115 116 117
}

// isBatch returns true when the first non-whitespace characters is '['
func isBatch(msg json.RawMessage) bool {
	for _, c := range msg {
		// skip insignificant whitespace (http://www.ietf.org/rfc/rfc4627.txt)
		if c == 0x20 || c == 0x09 || c == 0x0a || c == 0x0d {
			continue
		}
		return c == '['
	}
	return false
}

118 119 120
// ReadRequestHeaders will read new requests without parsing the arguments. It will
// return a collection of requests, an indication if these requests are in batch
// form or an error when the incoming message could not be read/parsed.
121
func (c *jsonCodec) ReadRequestHeaders() ([]rpcRequest, bool, Error) {
122 123 124
	c.decMu.Lock()
	defer c.decMu.Unlock()

125 126 127 128 129 130 131 132 133 134 135 136
	var incomingMsg json.RawMessage
	if err := c.d.Decode(&incomingMsg); err != nil {
		return nil, false, &invalidRequestError{err.Error()}
	}

	if isBatch(incomingMsg) {
		return parseBatchRequest(incomingMsg)
	}

	return parseRequest(incomingMsg)
}

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
// checkReqId returns an error when the given reqId isn't valid for RPC method calls.
// valid id's are strings, numbers or null
func checkReqId(reqId json.RawMessage) error {
	if len(reqId) == 0 {
		return fmt.Errorf("missing request id")
	}
	if _, err := strconv.ParseFloat(string(reqId), 64); err == nil {
		return nil
	}
	var str string
	if err := json.Unmarshal(reqId, &str); err == nil {
		return nil
	}
	return fmt.Errorf("invalid request id")
}

// parseRequest will parse a single request from the given RawMessage. It will return
// the parsed request, an indication if the request was a batch or an error when
// the request could not be parsed.
156 157
func parseRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) {
	var in jsonRequest
158 159 160 161
	if err := json.Unmarshal(incomingMsg, &in); err != nil {
		return nil, false, &invalidMessageError{err.Error()}
	}

162 163
	if err := checkReqId(in.Id); err != nil {
		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) {
Felix Lange's avatar
Felix Lange committed
168
		reqs := []rpcRequest{{id: &in.Id, isPubSub: true}}
169 170 171 172
		if len(in.Payload) > 0 {
			// first param must be subscription name
			var subscribeMethod [1]string
			if err := json.Unmarshal(in.Payload, &subscribeMethod); err != nil {
173
				log.Debug(fmt.Sprintf("Unable to parse subscription method: %v\n", err))
174 175 176
				return nil, false, &invalidRequestError{"Unable to parse subscription request"}
			}

177
			reqs[0].service, reqs[0].method = strings.TrimSuffix(in.Method, subscribeMethodSuffix), subscribeMethod[0]
178 179 180 181 182 183
			reqs[0].params = in.Payload
			return reqs, false, nil
		}
		return nil, false, &invalidRequestError{"Unable to parse subscription request"}
	}

184
	if strings.HasSuffix(in.Method, unsubscribeMethodSuffix) {
Felix Lange's avatar
Felix Lange committed
185
		return []rpcRequest{{id: &in.Id, isPubSub: true,
186
			method: in.Method, params: in.Payload}}, false, nil
187 188 189 190 191 192 193
	}

	elems := strings.Split(in.Method, serviceMethodSeparator)
	if len(elems) != 2 {
		return nil, false, &methodNotFoundError{in.Method, ""}
	}

194
	// regular RPC call
195
	if len(in.Payload) == 0 {
Felix Lange's avatar
Felix Lange committed
196
		return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id}}, false, nil
197 198
	}

Felix Lange's avatar
Felix Lange committed
199
	return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id, params: in.Payload}}, false, nil
200 201 202 203
}

// parseBatchRequest will parse a batch request into a collection of requests from the given RawMessage, an indication
// if the request was a batch or an error when the request could not be read.
204 205
func parseBatchRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) {
	var in []jsonRequest
206 207 208 209 210 211
	if err := json.Unmarshal(incomingMsg, &in); err != nil {
		return nil, false, &invalidMessageError{err.Error()}
	}

	requests := make([]rpcRequest, len(in))
	for i, r := range in {
212 213
		if err := checkReqId(r.Id); err != nil {
			return nil, false, &invalidMessageError{err.Error()}
214 215
		}

216 217
		id := &in[i].Id

218 219
		// subscribe are special, they will always use `subscriptionMethod` as first param in the payload
		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 224
				var subscribeMethod [1]string
				if err := json.Unmarshal(r.Payload, &subscribeMethod); err != nil {
225
					log.Debug(fmt.Sprintf("Unable to parse subscription method: %v\n", err))
226 227 228
					return nil, false, &invalidRequestError{"Unable to parse subscription request"}
				}

229
				requests[i].service, requests[i].method = strings.TrimSuffix(r.Method, subscribeMethodSuffix), subscribeMethod[0]
230 231 232 233 234 235 236
				requests[i].params = r.Payload
				continue
			}

			return nil, true, &invalidRequestError{"Unable to parse (un)subscribe request arguments"}
		}

237 238
		if strings.HasSuffix(r.Method, unsubscribeMethodSuffix) {
			requests[i] = rpcRequest{id: id, isPubSub: true, method: r.Method, params: r.Payload}
239 240 241 242
			continue
		}

		if len(r.Payload) == 0 {
243 244 245 246 247 248
			requests[i] = rpcRequest{id: id, params: nil}
		} else {
			requests[i] = rpcRequest{id: id, params: r.Payload}
		}
		if elem := strings.Split(r.Method, serviceMethodSeparator); len(elem) == 2 {
			requests[i].service, requests[i].method = elem[0], elem[1]
249
		} else {
250
			requests[i].err = &methodNotFoundError{r.Method, ""}
251 252 253 254 255 256
		}
	}

	return requests, true, nil
}

257 258
// ParseRequestArguments tries to parse the given params (json.RawMessage) with the given
// 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 261 262 263 264 265 266
	if args, ok := params.(json.RawMessage); !ok {
		return nil, &invalidParamsError{"Invalid params supplied"}
	} else {
		return parsePositionalArguments(args, argTypes)
	}
}

267 268 269 270 271 272 273 274
// parsePositionalArguments tries to parse the given args to an array of values with the
// given types. It returns the parsed values or an error when the args could not be
// parsed. Missing optional arguments are returned as reflect.Zero values.
func parsePositionalArguments(rawArgs json.RawMessage, types []reflect.Type) ([]reflect.Value, Error) {
	// Read beginning of the args array.
	dec := json.NewDecoder(bytes.NewReader(rawArgs))
	if tok, _ := dec.Token(); tok != json.Delim('[') {
		return nil, &invalidParamsError{"non-array args"}
275
	}
276 277 278 279 280 281 282 283 284 285 286 287 288 289
	// Read args.
	args := make([]reflect.Value, 0, len(types))
	for i := 0; dec.More(); i++ {
		if i >= len(types) {
			return nil, &invalidParamsError{fmt.Sprintf("too many arguments, want at most %d", len(types))}
		}
		argval := reflect.New(types[i])
		if err := dec.Decode(argval.Interface()); err != nil {
			return nil, &invalidParamsError{fmt.Sprintf("invalid argument %d: %v", i, err)}
		}
		if argval.IsNil() && types[i].Kind() != reflect.Ptr {
			return nil, &invalidParamsError{fmt.Sprintf("missing value for required argument %d", i)}
		}
		args = append(args, argval.Elem())
290
	}
291 292 293
	// Read end of args array.
	if _, err := dec.Token(); err != nil {
		return nil, &invalidParamsError{err.Error()}
294
	}
295 296 297 298
	// Set any missing args to nil.
	for i := len(args); i < len(types); i++ {
		if types[i].Kind() != reflect.Ptr {
			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 315
func (c *jsonCodec) CreateErrorResponse(id interface{}, err Error) interface{} {
	return &jsonErrResponse{Version: jsonrpcVersion, Id: id, Error: jsonError{Code: err.ErrorCode(), Message: err.Error()}}
316 317 318 319
}

// CreateErrorResponseWithInfo will create a JSON-RPC error response with the given id and error.
// info is optional and contains additional information about the error. When an empty string is passed it is ignored.
320 321 322
func (c *jsonCodec) CreateErrorResponseWithInfo(id interface{}, err Error, info interface{}) interface{} {
	return &jsonErrResponse{Version: jsonrpcVersion, Id: id,
		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 330 331
			Params: jsonSubscription{Subscription: subid, Result: fmt.Sprintf(`%#x`, event)}}
	}

332
	return &jsonNotification{Version: jsonrpcVersion, Method: namespace + notificationMethodSuffix,
333 334 335 336 337
		Params: jsonSubscription{Subscription: subid, Result: event}}
}

// Write message to client
func (c *jsonCodec) Write(res interface{}) error {
338 339
	c.encMu.Lock()
	defer c.encMu.Unlock()
340

341 342 343 344 345
	return c.e.Encode(res)
}

// Close the underlying connection
func (c *jsonCodec) Close() {
346
	c.closer.Do(func() {
347 348
		close(c.closed)
		c.rw.Close()
349
	})
350 351 352 353 354 355
}

// Closed returns a channel which will be closed when Close is called
func (c *jsonCodec) Closed() <-chan interface{} {
	return c.closed
}