http.go 3.3 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"
T
Taylor Gerring 已提交
8
	"net"
9 10 11 12 13 14
	"net/http"

	"github.com/ethereum/go-ethereum/logger"
	"github.com/ethereum/go-ethereum/xeth"
)

T
Taylor Gerring 已提交
15
var rpclogger = logger.NewLogger("RPC")
16

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

T
Taylor Gerring 已提交
22 23 24 25 26 27 28 29 30 31
func Start(pipe *xeth.XEth, config RpcConfig) error {
	l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", config.ListenAddress, config.ListenPort))
	if err != nil {
		rpclogger.Errorf("Can't listen on %s:%d: %v", config.ListenAddress, config.ListenPort, err)
		return err
	}
	go http.Serve(l, JSONRPC(pipe))
	return nil
}

32
// JSONRPC returns a handler that implements the Ethereum JSON-RPC API.
33 34
func JSONRPC(pipe *xeth.XEth) http.Handler {
	api := NewEthereumApi(pipe)
35 36

	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
T
Taylor Gerring 已提交
37
		// TODO this needs to be configurable
38 39
		w.Header().Set("Access-Control-Allow-Origin", "*")

T
Taylor Gerring 已提交
40
		// Limit request size to resist DoS
41
		if req.ContentLength > maxSizeReqLength {
T
Taylor Gerring 已提交
42
			jsonerr := &RpcErrorObject{-32700, "Request too large"}
T
Taylor Gerring 已提交
43
			send(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: nil, Error: jsonerr})
44 45 46
			return
		}

T
Taylor Gerring 已提交
47
		// Read request body
T
Taylor Gerring 已提交
48 49 50 51
		defer req.Body.Close()
		body, err := ioutil.ReadAll(req.Body)
		if err != nil {
			jsonerr := &RpcErrorObject{-32700, "Could not read request body"}
T
Taylor Gerring 已提交
52
			send(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: nil, Error: jsonerr})
53 54
		}

T
Taylor Gerring 已提交
55 56 57 58
		// 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 已提交
59
			send(w, &response)
T
Taylor Gerring 已提交
60
			return
T
Taylor Gerring 已提交
61 62 63 64 65 66 67 68 69 70 71
		}

		// 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 已提交
72
			send(w, resBatch)
73 74 75
			return
		}

T
Taylor Gerring 已提交
76 77
		// Not a batch or single request, error
		jsonerr := &RpcErrorObject{-32600, "Could not decode request"}
T
Taylor Gerring 已提交
78
		send(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: nil, Error: jsonerr})
79 80
	})
}
T
Taylor Gerring 已提交
81 82 83 84 85 86

func RpcResponse(api *EthereumApi, request *RpcRequest) *interface{} {
	var reply, response interface{}
	reserr := api.GetRequestReply(request, &reply)
	switch reserr.(type) {
	case nil:
T
Taylor Gerring 已提交
87
		response = &RpcSuccessResponse{Jsonrpc: jsonrpcver, Id: request.Id, Result: reply}
T
Taylor Gerring 已提交
88 89
	case *NotImplementedError:
		jsonerr := &RpcErrorObject{-32601, reserr.Error()}
T
Taylor Gerring 已提交
90
		response = &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: request.Id, Error: jsonerr}
91
	case *DecodeParamError, *InsufficientParamsError, *ValidationError, *InvalidTypeError:
T
Taylor Gerring 已提交
92
		jsonerr := &RpcErrorObject{-32602, reserr.Error()}
T
Taylor Gerring 已提交
93
		response = &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: request.Id, Error: jsonerr}
T
Taylor Gerring 已提交
94 95
	default:
		jsonerr := &RpcErrorObject{-32603, reserr.Error()}
T
Taylor Gerring 已提交
96
		response = &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: request.Id, Error: jsonerr}
T
Taylor Gerring 已提交
97 98
	}

T
Taylor Gerring 已提交
99
	rpclogger.DebugDetailf("Generated response: %T %s", response, response)
T
Taylor Gerring 已提交
100 101
	return &response
}
T
Taylor Gerring 已提交
102

T
Taylor Gerring 已提交
103
func send(writer io.Writer, v interface{}) (n int, err error) {
T
Taylor Gerring 已提交
104 105 106 107 108 109 110 111 112 113
	var payload []byte
	payload, err = json.MarshalIndent(v, "", "\t")
	if err != nil {
		rpclogger.Fatalln("Error marshalling JSON", err)
		return 0, err
	}
	rpclogger.DebugDetailf("Sending payload: %s", payload)

	return writer.Write(payload)
}