aboutsummaryrefslogtreecommitdiffstats
path: root/rpc/http.go
blob: b6edb7cd75f1dfa27100aec7e6ccba13a4dd597f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package rpc

import (
    "net/http"

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

var rpchttplogger = logger.NewLogger("RPC-HTTP")

const (
    jsonrpcver       = "2.0"
    maxSizeReqLength = 1024 * 1024 // 1MB
)

// JSONRPC returns a handler that implements the Ethereum JSON-RPC API.
func JSONRPC(pipe *xeth.XEth, dataDir string) http.Handler {
    var json JsonWrapper
    api := NewEthereumApi(pipe, dataDir)

    return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
        w.Header().Set("Access-Control-Allow-Origin", "*")

        rpchttplogger.DebugDetailln("Handling request")

        if req.ContentLength > maxSizeReqLength {
            jsonerr := &RpcErrorObject{-32700, "Request too large"}
            json.Send(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: nil, Error: jsonerr})
            return
        }

        reqParsed, reqerr := json.ParseRequestBody(req)
        switch reqerr.(type) {
        case nil:
            break
        case *DecodeParamError, *InsufficientParamsError, *ValidationError:
            jsonerr := &RpcErrorObject{-32602, reqerr.Error()}
            json.Send(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: nil, Error: jsonerr})
            return
        default:
            jsonerr := &RpcErrorObject{-32700, "Could not parse request"}
            json.Send(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: nil, Error: jsonerr})
            return
        }

        var response interface{}
        reserr := api.GetRequestReply(&reqParsed, &response)
        switch reserr.(type) {
        case nil:
            break
        case *NotImplementedError:
            jsonerr := &RpcErrorObject{-32601, reserr.Error()}
            json.Send(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: reqParsed.Id, Error: jsonerr})
            return
        case *DecodeParamError, *InsufficientParamsError, *ValidationError:
            jsonerr := &RpcErrorObject{-32602, reserr.Error()}
            json.Send(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: reqParsed.Id, Error: jsonerr})
            return
        default:
            jsonerr := &RpcErrorObject{-32603, reserr.Error()}
            json.Send(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: reqParsed.Id, Error: jsonerr})
            return
        }

        rpchttplogger.DebugDetailf("Generated response: %T %s", response, response)
        json.Send(w, &RpcSuccessResponse{Jsonrpc: jsonrpcver, Id: reqParsed.Id, Result: response})
    })
}