http.go 4.1 KB
Newer Older
1 2 3
package rpc

import (
T
Taylor Gerring 已提交
4
	"encoding/json"
T
Taylor Gerring 已提交
5
	"fmt"
T
Taylor Gerring 已提交
6
	"io"
T
Taylor Gerring 已提交
7
	"io/ioutil"
8 9 10
	"net/http"

	"github.com/ethereum/go-ethereum/logger"
O
obscuren 已提交
11
	"github.com/ethereum/go-ethereum/logger/glog"
12
	"github.com/ethereum/go-ethereum/xeth"
13
	"github.com/rs/cors"
14 15
)

T
Taylor Gerring 已提交
16
var rpclogger = logger.NewLogger("RPC")
17
var rpclistener *StoppableTCPListener
18

19 20 21 22 23
const (
	jsonrpcver       = "2.0"
	maxSizeReqLength = 1024 * 1024 // 1MB
)

T
Taylor Gerring 已提交
24
func Start(pipe *xeth.XEth, config RpcConfig) error {
25 26 27 28 29
	if rpclistener != nil {
		if fmt.Sprintf("%s:%d", config.ListenAddress, config.ListenPort) != rpclistener.Addr().String() {
			return fmt.Errorf("RPC service already running on %s ", rpclistener.Addr().String())
		}
		return nil // RPC service already running on given host/port
30 31
	}

32
	l, err := NewStoppableTCPListener(fmt.Sprintf("%s:%d", config.ListenAddress, config.ListenPort))
T
Taylor Gerring 已提交
33 34 35 36
	if err != nil {
		rpclogger.Errorf("Can't listen on %s:%d: %v", config.ListenAddress, config.ListenPort, err)
		return err
	}
37
	rpclistener = l
38 39 40 41 42 43 44 45

	var handler http.Handler
	if len(config.CorsDomain) > 0 {
		var opts cors.Options
		opts.AllowedMethods = []string{"POST"}
		opts.AllowedOrigins = []string{config.CorsDomain}

		c := cors.New(opts)
46
		handler = NewStoppableHandler(c.Handler(JSONRPC(pipe)), l.stop)
47
	} else {
48
		handler = NewStoppableHandler(JSONRPC(pipe), l.stop)
49 50 51 52
	}

	go http.Serve(l, handler)

T
Taylor Gerring 已提交
53 54 55
	return nil
}

56
func Stop() error {
57 58 59
	if rpclistener != nil {
		rpclistener.Stop()
		rpclistener = nil
60 61 62 63 64
	}

	return nil
}

65
// JSONRPC returns a handler that implements the Ethereum JSON-RPC API.
66 67
func JSONRPC(pipe *xeth.XEth) http.Handler {
	api := NewEthereumApi(pipe)
68 69

	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
70
		w.Header().Set("Content-Type", "application/json")
71

T
Taylor Gerring 已提交
72
		// Limit request size to resist DoS
73
		if req.ContentLength > maxSizeReqLength {
T
Taylor Gerring 已提交
74
			jsonerr := &RpcErrorObject{-32700, "Request too large"}
T
Taylor Gerring 已提交
75
			send(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: nil, Error: jsonerr})
76 77 78
			return
		}

T
Taylor Gerring 已提交
79
		// Read request body
T
Taylor Gerring 已提交
80 81 82 83
		defer req.Body.Close()
		body, err := ioutil.ReadAll(req.Body)
		if err != nil {
			jsonerr := &RpcErrorObject{-32700, "Could not read request body"}
T
Taylor Gerring 已提交
84
			send(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: nil, Error: jsonerr})
85 86
		}

T
Taylor Gerring 已提交
87 88 89 90
		// Try to parse the request as a single
		var reqSingle RpcRequest
		if err := json.Unmarshal(body, &reqSingle); err == nil {
			response := RpcResponse(api, &reqSingle)
T
Taylor Gerring 已提交
91
			send(w, &response)
T
Taylor Gerring 已提交
92
			return
T
Taylor Gerring 已提交
93 94 95 96 97 98 99 100 101 102 103
		}

		// Try to parse the request to batch
		var reqBatch []RpcRequest
		if err := json.Unmarshal(body, &reqBatch); err == nil {
			// Build response batch
			resBatch := make([]*interface{}, len(reqBatch))
			for i, request := range reqBatch {
				response := RpcResponse(api, &request)
				resBatch[i] = response
			}
T
Taylor Gerring 已提交
104
			send(w, resBatch)
105 106 107
			return
		}

T
Taylor Gerring 已提交
108 109
		// Not a batch or single request, error
		jsonerr := &RpcErrorObject{-32600, "Could not decode request"}
T
Taylor Gerring 已提交
110
		send(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: nil, Error: jsonerr})
111 112
	})
}
T
Taylor Gerring 已提交
113 114 115 116 117 118

func RpcResponse(api *EthereumApi, request *RpcRequest) *interface{} {
	var reply, response interface{}
	reserr := api.GetRequestReply(request, &reply)
	switch reserr.(type) {
	case nil:
T
Taylor Gerring 已提交
119
		response = &RpcSuccessResponse{Jsonrpc: jsonrpcver, Id: request.Id, Result: reply}
T
Taylor Gerring 已提交
120 121
	case *NotImplementedError:
		jsonerr := &RpcErrorObject{-32601, reserr.Error()}
T
Taylor Gerring 已提交
122
		response = &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: request.Id, Error: jsonerr}
123
	case *DecodeParamError, *InsufficientParamsError, *ValidationError, *InvalidTypeError:
T
Taylor Gerring 已提交
124
		jsonerr := &RpcErrorObject{-32602, reserr.Error()}
T
Taylor Gerring 已提交
125
		response = &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: request.Id, Error: jsonerr}
T
Taylor Gerring 已提交
126 127
	default:
		jsonerr := &RpcErrorObject{-32603, reserr.Error()}
T
Taylor Gerring 已提交
128
		response = &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: request.Id, Error: jsonerr}
T
Taylor Gerring 已提交
129 130
	}

O
obscuren 已提交
131
	glog.V(logger.Detail).Infof("Generated response: %T %s", response, response)
T
Taylor Gerring 已提交
132 133
	return &response
}
T
Taylor Gerring 已提交
134

T
Taylor Gerring 已提交
135
func send(writer io.Writer, v interface{}) (n int, err error) {
T
Taylor Gerring 已提交
136 137 138 139 140 141
	var payload []byte
	payload, err = json.MarshalIndent(v, "", "\t")
	if err != nil {
		rpclogger.Fatalln("Error marshalling JSON", err)
		return 0, err
	}
O
obscuren 已提交
142
	glog.V(logger.Detail).Infof("Sending payload: %s", payload)
T
Taylor Gerring 已提交
143 144 145

	return writer.Write(payload)
}