json.go 9.95 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
	"context"
22
	"encoding/json"
23
	"errors"
24 25 26 27
	"fmt"
	"io"
	"reflect"
	"strings"
28
	"sync"
29
	"time"
30 31 32
)

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

	defaultWriteTimeout = 10 * time.Second // used if context has no deadline
40 41
)

42 43 44 45 46
var null = json.RawMessage("null")

type subscriptionResult struct {
	ID     string          `json:"subscription"`
	Result json.RawMessage `json:"result,omitempty"`
47 48
}

49 50 51 52 53 54 55 56 57
// A value of this type can a JSON-RPC request, notification, successful response or
// error response. Which one it is depends on the fields.
type jsonrpcMessage struct {
	Version string          `json:"jsonrpc,omitempty"`
	ID      json.RawMessage `json:"id,omitempty"`
	Method  string          `json:"method,omitempty"`
	Params  json.RawMessage `json:"params,omitempty"`
	Error   *jsonError      `json:"error,omitempty"`
	Result  json.RawMessage `json:"result,omitempty"`
58 59
}

60 61
func (msg *jsonrpcMessage) isNotification() bool {
	return msg.ID == nil && msg.Method != ""
62 63
}

64 65
func (msg *jsonrpcMessage) isCall() bool {
	return msg.hasValidID() && msg.Method != ""
66 67
}

68 69
func (msg *jsonrpcMessage) isResponse() bool {
	return msg.hasValidID() && msg.Method == "" && msg.Params == nil && (msg.Result != nil || msg.Error != nil)
70 71
}

72 73
func (msg *jsonrpcMessage) hasValidID() bool {
	return len(msg.ID) > 0 && msg.ID[0] != '{' && msg.ID[0] != '['
74 75
}

76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
func (msg *jsonrpcMessage) isSubscribe() bool {
	return strings.HasSuffix(msg.Method, subscribeMethodSuffix)
}

func (msg *jsonrpcMessage) isUnsubscribe() bool {
	return strings.HasSuffix(msg.Method, unsubscribeMethodSuffix)
}

func (msg *jsonrpcMessage) namespace() string {
	elem := strings.SplitN(msg.Method, serviceMethodSeparator, 2)
	return elem[0]
}

func (msg *jsonrpcMessage) String() string {
	b, _ := json.Marshal(msg)
	return string(b)
}

func (msg *jsonrpcMessage) errorResponse(err error) *jsonrpcMessage {
	resp := errorMessage(err)
	resp.ID = msg.ID
	return resp
}

func (msg *jsonrpcMessage) response(result interface{}) *jsonrpcMessage {
	enc, err := json.Marshal(result)
	if err != nil {
		// TODO: wrap with 'internal server error'
		return msg.errorResponse(err)
	}
	return &jsonrpcMessage{Version: vsn, ID: msg.ID, Result: enc}
}

func errorMessage(err error) *jsonrpcMessage {
	msg := &jsonrpcMessage{Version: vsn, ID: null, Error: &jsonError{
		Code:    defaultErrorCode,
		Message: err.Error(),
	}}
	ec, ok := err.(Error)
	if ok {
		msg.Error.Code = ec.ErrorCode()
	}
118 119 120 121
	de, ok := err.(DataError)
	if ok {
		msg.Error.Data = de.ErrorData()
	}
122 123 124 125 126 127 128
	return msg
}

type jsonError struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
129 130
}

131 132 133 134 135 136 137 138 139 140 141
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
}

142 143 144 145
func (err *jsonError) ErrorData() interface{} {
	return err.Data
}

146 147 148 149 150 151
// Conn is a subset of the methods of net.Conn which are sufficient for ServerCodec.
type Conn interface {
	io.ReadWriteCloser
	SetWriteDeadline(time.Time) error
}

152 153 154 155 156
type deadlineCloser interface {
	io.Closer
	SetWriteDeadline(time.Time) error
}

157 158 159 160 161 162 163 164 165 166
// ConnRemoteAddr wraps the RemoteAddr operation, which returns a description
// of the peer address of a connection. If a Conn also implements ConnRemoteAddr, this
// description is used in log messages.
type ConnRemoteAddr interface {
	RemoteAddr() string
}

// jsonCodec reads and writes JSON-RPC messages to the underlying connection. It also has
// support for parsing arguments and serializing (result) objects.
type jsonCodec struct {
167 168 169 170 171 172 173 174 175 176 177 178 179
	remote  string
	closer  sync.Once                 // close closed channel once
	closeCh chan interface{}          // closed on Close
	decode  func(v interface{}) error // decoder to allow multiple transports
	encMu   sync.Mutex                // guards the encoder
	encode  func(v interface{}) error // encoder to allow multiple transports
	conn    deadlineCloser
}

// NewFuncCodec creates a codec which uses the given functions to read and write. If conn
// implements ConnRemoteAddr, log messages will use it to include the remote address of
// the connection.
func NewFuncCodec(conn deadlineCloser, encode, decode func(v interface{}) error) ServerCodec {
180
	codec := &jsonCodec{
181 182 183 184
		closeCh: make(chan interface{}),
		encode:  encode,
		decode:  decode,
		conn:    conn,
185
	}
186
	if ra, ok := conn.(ConnRemoteAddr); ok {
187
		codec.remote = ra.RemoteAddr()
188 189
	}
	return codec
190 191
}

192 193 194
// NewCodec creates a codec on the given connection. If conn implements ConnRemoteAddr, log
// messages will use it to include the remote address of the connection.
func NewCodec(conn Conn) ServerCodec {
195 196
	enc := json.NewEncoder(conn)
	dec := json.NewDecoder(conn)
197
	dec.UseNumber()
198
	return NewFuncCodec(conn, enc.Encode, dec.Decode)
199
}
200

201 202
func (c *jsonCodec) remoteAddr() string {
	return c.remote
203 204
}

205
func (c *jsonCodec) readBatch() (messages []*jsonrpcMessage, batch bool, err error) {
206 207 208 209 210
	// Decode the next JSON object in the input stream.
	// This verifies basic syntax, etc.
	var rawmsg json.RawMessage
	if err := c.decode(&rawmsg); err != nil {
		return nil, false, err
211
	}
212 213 214 215 216 217 218 219 220
	messages, batch = parseMessage(rawmsg)
	for i, msg := range messages {
		if msg == nil {
			// Message is JSON 'null'. Replace with zero value so it
			// will be treated like any other invalid message.
			messages[i] = new(jsonrpcMessage)
		}
	}
	return messages, batch, nil
221 222
}

223
func (c *jsonCodec) writeJSON(ctx context.Context, v interface{}) error {
224 225
	c.encMu.Lock()
	defer c.encMu.Unlock()
226

227 228 229
	deadline, ok := ctx.Deadline()
	if !ok {
		deadline = time.Now().Add(defaultWriteTimeout)
230
	}
231 232
	c.conn.SetWriteDeadline(deadline)
	return c.encode(v)
233 234
}

235
func (c *jsonCodec) close() {
236
	c.closer.Do(func() {
237
		close(c.closeCh)
238 239
		c.conn.Close()
	})
240 241
}

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

247 248 249 250 251 252 253 254 255
// parseMessage parses raw bytes as a (batch of) JSON-RPC message(s). There are no error
// checks in this function because the raw message has already been syntax-checked when it
// is called. Any non-JSON-RPC messages in the input return the zero value of
// jsonrpcMessage.
func parseMessage(raw json.RawMessage) ([]*jsonrpcMessage, bool) {
	if !isBatch(raw) {
		msgs := []*jsonrpcMessage{{}}
		json.Unmarshal(raw, &msgs[0])
		return msgs, false
256
	}
257 258 259 260 261 262
	dec := json.NewDecoder(bytes.NewReader(raw))
	dec.Token() // skip '['
	var msgs []*jsonrpcMessage
	for dec.More() {
		msgs = append(msgs, new(jsonrpcMessage))
		dec.Decode(&msgs[len(msgs)-1])
263
	}
264
	return msgs, true
265 266
}

267 268 269 270 271
// isBatch returns true when the first non-whitespace characters is '['
func isBatch(raw json.RawMessage) bool {
	for _, c := range raw {
		// skip insignificant whitespace (http://www.ietf.org/rfc/rfc4627.txt)
		if c == 0x20 || c == 0x09 || c == 0x0a || c == 0x0d {
272 273
			continue
		}
274
		return c == '['
275
	}
276
	return false
277 278
}

279 280 281
// 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.
282
func parsePositionalArguments(rawArgs json.RawMessage, types []reflect.Type) ([]reflect.Value, error) {
283
	dec := json.NewDecoder(bytes.NewReader(rawArgs))
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
	var args []reflect.Value
	tok, err := dec.Token()
	switch {
	case err == io.EOF || tok == nil && err == nil:
		// "params" is optional and may be empty. Also allow "params":null even though it's
		// not in the spec because our own client used to send it.
	case err != nil:
		return nil, err
	case tok == json.Delim('['):
		// Read argument array.
		if args, err = parseArgumentArray(dec, types); err != nil {
			return nil, err
		}
	default:
		return nil, errors.New("non-array args")
299
	}
300 301 302 303 304 305 306 307 308 309 310
	// Set any missing args to nil.
	for i := len(args); i < len(types); i++ {
		if types[i].Kind() != reflect.Ptr {
			return nil, fmt.Errorf("missing value for required argument %d", i)
		}
		args = append(args, reflect.Zero(types[i]))
	}
	return args, nil
}

func parseArgumentArray(dec *json.Decoder, types []reflect.Type) ([]reflect.Value, error) {
311 312 313
	args := make([]reflect.Value, 0, len(types))
	for i := 0; dec.More(); i++ {
		if i >= len(types) {
314
			return args, fmt.Errorf("too many arguments, want at most %d", len(types))
315 316 317
		}
		argval := reflect.New(types[i])
		if err := dec.Decode(argval.Interface()); err != nil {
318
			return args, fmt.Errorf("invalid argument %d: %v", i, err)
319 320
		}
		if argval.IsNil() && types[i].Kind() != reflect.Ptr {
321
			return args, fmt.Errorf("missing value for required argument %d", i)
322 323
		}
		args = append(args, argval.Elem())
324
	}
325
	// Read end of args array.
326 327
	_, err := dec.Token()
	return args, err
328 329
}

330 331 332 333 334 335 336 337 338 339 340 341
// parseSubscriptionName extracts the subscription name from an encoded argument array.
func parseSubscriptionName(rawArgs json.RawMessage) (string, error) {
	dec := json.NewDecoder(bytes.NewReader(rawArgs))
	if tok, _ := dec.Token(); tok != json.Delim('[') {
		return "", errors.New("non-array args")
	}
	v, _ := dec.Token()
	method, ok := v.(string)
	if !ok {
		return "", errors.New("expected subscription name as first argument")
	}
	return method, nil
342
}