go-pulse/rpc/http.go

145 lines
4.1 KiB
Go
Raw Normal View History

package rpc
import (
"encoding/json"
"fmt"
2015-03-18 00:14:19 +00:00
"io"
"io/ioutil"
"net/http"
"github.com/ethereum/go-ethereum/logger"
2015-04-14 22:09:13 +00:00
"github.com/ethereum/go-ethereum/logger/glog"
"github.com/ethereum/go-ethereum/xeth"
"github.com/rs/cors"
)
2015-04-19 08:01:50 +00:00
var rpclistener *stoppableTCPListener
const (
jsonrpcver = "2.0"
maxSizeReqLength = 1024 * 1024 // 1MB
)
func Start(pipe *xeth.XEth, config RpcConfig) error {
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
}
2015-04-19 08:01:50 +00:00
l, err := newStoppableTCPListener(fmt.Sprintf("%s:%d", config.ListenAddress, config.ListenPort))
if err != nil {
2015-04-27 14:18:55 +00:00
glog.V(logger.Error).Infof("Can't listen on %s:%d: %v", config.ListenAddress, config.ListenPort, err)
return err
}
rpclistener = l
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)
2015-04-19 08:01:50 +00:00
handler = newStoppableHandler(c.Handler(JSONRPC(pipe)), l.stop)
} else {
2015-04-19 08:01:50 +00:00
handler = newStoppableHandler(JSONRPC(pipe), l.stop)
}
go http.Serve(l, handler)
return nil
}
func Stop() error {
if rpclistener != nil {
rpclistener.Stop()
rpclistener = nil
}
return nil
}
// JSONRPC returns a handler that implements the Ethereum JSON-RPC API.
2015-03-27 08:36:18 +00:00
func JSONRPC(pipe *xeth.XEth) http.Handler {
api := NewEthereumApi(pipe)
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
// Limit request size to resist DoS
if req.ContentLength > maxSizeReqLength {
jsonerr := &RpcErrorObject{-32700, "Request too large"}
2015-03-19 22:06:26 +00:00
send(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: nil, Error: jsonerr})
return
}
2015-03-18 00:14:19 +00:00
// Read request body
defer req.Body.Close()
body, err := ioutil.ReadAll(req.Body)
if err != nil {
jsonerr := &RpcErrorObject{-32700, "Could not read request body"}
2015-03-19 22:06:26 +00:00
send(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: nil, Error: jsonerr})
}
// Try to parse the request as a single
var reqSingle RpcRequest
if err := json.Unmarshal(body, &reqSingle); err == nil {
response := RpcResponse(api, &reqSingle)
2015-03-19 22:06:26 +00:00
send(w, &response)
return
}
// 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
}
2015-03-19 22:06:26 +00:00
send(w, resBatch)
return
}
// Not a batch or single request, error
jsonerr := &RpcErrorObject{-32600, "Could not decode request"}
2015-03-19 22:06:26 +00:00
send(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: nil, Error: jsonerr})
})
}
func RpcResponse(api *EthereumApi, request *RpcRequest) *interface{} {
var reply, response interface{}
reserr := api.GetRequestReply(request, &reply)
switch reserr.(type) {
case nil:
2015-03-17 21:46:22 +00:00
response = &RpcSuccessResponse{Jsonrpc: jsonrpcver, Id: request.Id, Result: reply}
case *NotImplementedError, *NotAvailableError:
jsonerr := &RpcErrorObject{-32601, reserr.Error()}
2015-03-17 21:46:22 +00:00
response = &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: request.Id, Error: jsonerr}
case *DecodeParamError, *InsufficientParamsError, *ValidationError, *InvalidTypeError:
jsonerr := &RpcErrorObject{-32602, reserr.Error()}
2015-03-17 21:46:22 +00:00
response = &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: request.Id, Error: jsonerr}
default:
jsonerr := &RpcErrorObject{-32603, reserr.Error()}
2015-03-17 21:46:22 +00:00
response = &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: request.Id, Error: jsonerr}
}
2015-04-14 22:09:13 +00:00
glog.V(logger.Detail).Infof("Generated response: %T %s", response, response)
return &response
}
2015-03-18 00:14:19 +00:00
2015-03-19 22:06:26 +00:00
func send(writer io.Writer, v interface{}) (n int, err error) {
2015-03-18 00:14:19 +00:00
var payload []byte
payload, err = json.MarshalIndent(v, "", "\t")
if err != nil {
2015-04-27 14:18:55 +00:00
glog.V(logger.Error).Infoln("Error marshalling JSON", err)
2015-03-18 00:14:19 +00:00
return 0, err
}
2015-04-14 22:09:13 +00:00
glog.V(logger.Detail).Infof("Sending payload: %s", payload)
2015-03-18 00:14:19 +00:00
return writer.Write(payload)
}