http.go 4.5 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
)

B
Bas van Kervel 已提交
16
var rpclistener *stoppableTCPListener
17

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

T
Taylor Gerring 已提交
23
func Start(pipe *xeth.XEth, config RpcConfig) error {
24 25 26 27 28
	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
29 30
	}

B
Bas van Kervel 已提交
31
	l, err := newStoppableTCPListener(fmt.Sprintf("%s:%d", config.ListenAddress, config.ListenPort))
T
Taylor Gerring 已提交
32
	if err != nil {
T
Taylor Gerring 已提交
33
		glog.V(logger.Error).Infof("Can't listen on %s:%d: %v", config.ListenAddress, config.ListenPort, err)
T
Taylor Gerring 已提交
34 35
		return err
	}
36
	rpclistener = l
37 38 39 40 41 42 43 44

	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)
B
Bas van Kervel 已提交
45
		handler = newStoppableHandler(c.Handler(JSONRPC(pipe)), l.stop)
46
	} else {
B
Bas van Kervel 已提交
47
		handler = newStoppableHandler(JSONRPC(pipe), l.stop)
48 49 50 51
	}

	go http.Serve(l, handler)

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

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

	return nil
}

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

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

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

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

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

		// 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))
101 102
			resCount := 0

T
Taylor Gerring 已提交
103 104
			for i, request := range reqBatch {
				response := RpcResponse(api, &request)
105 106 107 108 109
				// this leaves nil entries in the response batch for later removal
				if request.Id != nil {
					resBatch[i] = response
					resCount = resCount + 1
				}
T
Taylor Gerring 已提交
110
			}
111 112 113 114 115 116 117 118 119 120 121 122

			// make response omitting nil entries
			respBatchComp := make([]*interface{}, resCount)
			resCount = resCount - 1
			for _, v := range resBatch {
				if v != nil {
					respBatchComp[resCount] = v
					resCount = resCount - 1
				}
			}

			send(w, respBatchComp)
123 124 125
			return
		}

T
Taylor Gerring 已提交
126 127
		// Not a batch or single request, error
		jsonerr := &RpcErrorObject{-32600, "Could not decode request"}
T
Taylor Gerring 已提交
128
		send(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: nil, Error: jsonerr})
129 130
	})
}
T
Taylor Gerring 已提交
131 132 133 134 135 136

func RpcResponse(api *EthereumApi, request *RpcRequest) *interface{} {
	var reply, response interface{}
	reserr := api.GetRequestReply(request, &reply)
	switch reserr.(type) {
	case nil:
T
Taylor Gerring 已提交
137
		response = &RpcSuccessResponse{Jsonrpc: jsonrpcver, Id: request.Id, Result: reply}
138
	case *NotImplementedError, *NotAvailableError:
T
Taylor Gerring 已提交
139
		jsonerr := &RpcErrorObject{-32601, reserr.Error()}
T
Taylor Gerring 已提交
140
		response = &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: request.Id, Error: jsonerr}
141
	case *DecodeParamError, *InsufficientParamsError, *ValidationError, *InvalidTypeError:
T
Taylor Gerring 已提交
142
		jsonerr := &RpcErrorObject{-32602, reserr.Error()}
T
Taylor Gerring 已提交
143
		response = &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: request.Id, Error: jsonerr}
T
Taylor Gerring 已提交
144 145
	default:
		jsonerr := &RpcErrorObject{-32603, reserr.Error()}
T
Taylor Gerring 已提交
146
		response = &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: request.Id, Error: jsonerr}
T
Taylor Gerring 已提交
147 148
	}

O
obscuren 已提交
149
	glog.V(logger.Detail).Infof("Generated response: %T %s", response, response)
T
Taylor Gerring 已提交
150 151
	return &response
}
T
Taylor Gerring 已提交
152

T
Taylor Gerring 已提交
153
func send(writer io.Writer, v interface{}) (n int, err error) {
T
Taylor Gerring 已提交
154 155 156
	var payload []byte
	payload, err = json.MarshalIndent(v, "", "\t")
	if err != nil {
T
Taylor Gerring 已提交
157
		glog.V(logger.Error).Infoln("Error marshalling JSON", err)
T
Taylor Gerring 已提交
158 159
		return 0, err
	}
O
obscuren 已提交
160
	glog.V(logger.Detail).Infof("Sending payload: %s", payload)
T
Taylor Gerring 已提交
161 162 163

	return writer.Write(payload)
}