diff options
Diffstat (limited to 'rpc')
-rw-r--r-- | rpc/api.go | 22 | ||||
-rw-r--r-- | rpc/http.go | 98 | ||||
-rw-r--r-- | rpc/responses.go | 36 | ||||
-rw-r--r-- | rpc/util.go | 47 |
4 files changed, 96 insertions, 107 deletions
diff --git a/rpc/api.go b/rpc/api.go index 3c46684d1..486eec008 100644 --- a/rpc/api.go +++ b/rpc/api.go @@ -251,7 +251,7 @@ func (p *EthereumApi) Transact(args *NewTxArgs, reply *interface{}) (err error) result, _ := account.Transact(common.FromHex(args.To), common.FromHex(args.Value), common.FromHex(args.Gas), common.FromHex(args.GasPrice), common.FromHex(args.Data)) if len(result) > 0 { - *reply = toHex(result) + *reply = common.ToHex(result) } } else if _, exists := p.register[args.From]; exists { p.register[ags.From] = append(p.register[args.From], args) @@ -291,7 +291,7 @@ func (p *EthereumApi) GetBalance(args *GetBalanceArgs, reply *interface{}) error return err } state := p.getStateWithNum(args.BlockNumber).SafeGet(args.Address) - *reply = toHex(state.Balance().Bytes()) + *reply = common.ToHex(state.Balance().Bytes()) return nil } @@ -389,7 +389,7 @@ func (p *EthereumApi) NewWhisperFilter(args *WhisperFilterArgs, reply *interface } id = p.xeth().Whisper().Watch(opts) p.messages[id] = &whisperFilter{timeout: time.Now()} - *reply = toHex(big.NewInt(int64(id)).Bytes()) + *reply = common.ToHex(big.NewInt(int64(id)).Bytes()) return nil } @@ -485,7 +485,7 @@ func (p *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) error if err := json.Unmarshal(req.Params, &args); err != nil { return err } - *reply = toHex(crypto.Sha3(common.FromHex(args.Data))) + *reply = common.ToHex(crypto.Sha3(common.FromHex(args.Data))) case "web3_clientVersion": *reply = p.xeth().Backend().Version() case "net_version": @@ -493,7 +493,7 @@ func (p *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) error case "net_listening": *reply = p.xeth().IsListening() case "net_peerCount": - *reply = toHex(big.NewInt(int64(p.xeth().PeerCount())).Bytes()) + *reply = common.ToHex(big.NewInt(int64(p.xeth().PeerCount())).Bytes()) case "eth_coinbase": // TODO handling of empty coinbase due to lack of accounts res := p.xeth().Coinbase() @@ -505,11 +505,11 @@ func (p *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) error case "eth_mining": *reply = p.xeth().IsMining() case "eth_gasPrice": - *reply = toHex(defaultGasPrice.Bytes()) + *reply = common.ToHex(defaultGasPrice.Bytes()) case "eth_accounts": *reply = p.xeth().Accounts() case "eth_blockNumber": - *reply = toHex(p.xeth().Backend().ChainManager().CurrentBlock().Number().Bytes()) + *reply = common.ToHex(p.xeth().Backend().ChainManager().CurrentBlock().Number().Bytes()) case "eth_getBalance": args := new(GetBalanceArgs) if err := json.Unmarshal(req.Params, &args); err != nil { @@ -544,7 +544,7 @@ func (p *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) error if err != nil { return err } - *reply = toHex(big.NewInt(v).Bytes()) + *reply = common.ToHex(big.NewInt(v).Bytes()) case "eth_getBlockTransactionCountByNumber": args := new(GetBlockByNumberArgs) if err := json.Unmarshal(req.Params, &args); err != nil { @@ -555,7 +555,7 @@ func (p *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) error if err != nil { return err } - *reply = toHex(big.NewInt(v).Bytes()) + *reply = common.ToHex(big.NewInt(v).Bytes()) case "eth_getUncleCountByBlockHash": args := new(GetBlockByHashArgs) if err := json.Unmarshal(req.Params, &args); err != nil { @@ -566,7 +566,7 @@ func (p *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) error if err != nil { return err } - *reply = toHex(big.NewInt(v).Bytes()) + *reply = common.ToHex(big.NewInt(v).Bytes()) case "eth_getUncleCountByBlockNumber": args := new(GetBlockByNumberArgs) if err := json.Unmarshal(req.Params, &args); err != nil { @@ -577,7 +577,7 @@ func (p *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) error if err != nil { return err } - *reply = toHex(big.NewInt(v).Bytes()) + *reply = common.ToHex(big.NewInt(v).Bytes()) case "eth_getData", "eth_getCode": args := new(GetDataArgs) if err := json.Unmarshal(req.Params, &args); err != nil { diff --git a/rpc/http.go b/rpc/http.go index b6edb7cd7..5f2445e6c 100644 --- a/rpc/http.go +++ b/rpc/http.go @@ -1,6 +1,9 @@ package rpc import ( + "encoding/json" + "io" + "io/ioutil" "net/http" "github.com/ethereum/go-ethereum/logger" @@ -16,54 +19,83 @@ const ( // 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) { + // TODO this needs to be configurable w.Header().Set("Access-Control-Allow-Origin", "*") - rpchttplogger.DebugDetailln("Handling request") - + // Limit request size to resist DoS if req.ContentLength > maxSizeReqLength { jsonerr := &RpcErrorObject{-32700, "Request too large"} - json.Send(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: nil, Error: jsonerr}) + 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 + // Read request body + defer req.Body.Close() + body, err := ioutil.ReadAll(req.Body) + if err != nil { + jsonerr := &RpcErrorObject{-32700, "Could not read request body"} + Send(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: nil, Error: jsonerr}) } - 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}) + // Try to parse the request as a single + var reqSingle RpcRequest + if err := json.Unmarshal(body, &reqSingle); err == nil { + response := RpcResponse(api, &reqSingle) + Send(w, &response) 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}) + } + + // 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 + } + Send(w, resBatch) return } - rpchttplogger.DebugDetailf("Generated response: %T %s", response, response) - json.Send(w, &RpcSuccessResponse{Jsonrpc: jsonrpcver, Id: reqParsed.Id, Result: response}) + // Not a batch or single request, error + jsonerr := &RpcErrorObject{-32600, "Could not decode request"} + 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: + response = &RpcSuccessResponse{Jsonrpc: jsonrpcver, Id: request.Id, Result: reply} + case *NotImplementedError: + jsonerr := &RpcErrorObject{-32601, reserr.Error()} + response = &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: request.Id, Error: jsonerr} + case *DecodeParamError, *InsufficientParamsError, *ValidationError: + jsonerr := &RpcErrorObject{-32602, reserr.Error()} + response = &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: request.Id, Error: jsonerr} + default: + jsonerr := &RpcErrorObject{-32603, reserr.Error()} + response = &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: request.Id, Error: jsonerr} + } + + rpchttplogger.DebugDetailf("Generated response: %T %s", response, response) + return &response +} + +func Send(writer io.Writer, v interface{}) (n int, err error) { + 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) +} diff --git a/rpc/responses.go b/rpc/responses.go index 5b2b9d488..5e197b729 100644 --- a/rpc/responses.go +++ b/rpc/responses.go @@ -57,23 +57,23 @@ func (b *BlockRes) MarshalJSON() ([]byte, error) { } // convert strict types to hexified strings - ext.BlockNumber = toHex(big.NewInt(b.BlockNumber).Bytes()) + ext.BlockNumber = common.ToHex(big.NewInt(b.BlockNumber).Bytes()) ext.BlockHash = b.BlockHash.Hex() ext.ParentHash = b.ParentHash.Hex() - ext.Nonce = toHex(b.Nonce[:]) + ext.Nonce = common.ToHex(b.Nonce[:]) ext.Sha3Uncles = b.Sha3Uncles.Hex() - ext.LogsBloom = toHex(b.LogsBloom[:]) + ext.LogsBloom = common.ToHex(b.LogsBloom[:]) ext.TransactionRoot = b.TransactionRoot.Hex() ext.StateRoot = b.StateRoot.Hex() ext.Miner = b.Miner.Hex() - ext.Difficulty = toHex(big.NewInt(b.Difficulty).Bytes()) - ext.TotalDifficulty = toHex(big.NewInt(b.TotalDifficulty).Bytes()) - ext.Size = toHex(big.NewInt(b.Size).Bytes()) - // ext.ExtraData = toHex(b.ExtraData) - ext.GasLimit = toHex(big.NewInt(b.GasLimit).Bytes()) - // ext.MinGasPrice = toHex(big.NewInt(b.MinGasPrice).Bytes()) - ext.GasUsed = toHex(big.NewInt(b.GasUsed).Bytes()) - ext.UnixTimestamp = toHex(big.NewInt(b.UnixTimestamp).Bytes()) + ext.Difficulty = common.ToHex(big.NewInt(b.Difficulty).Bytes()) + ext.TotalDifficulty = common.ToHex(big.NewInt(b.TotalDifficulty).Bytes()) + ext.Size = common.ToHex(big.NewInt(b.Size).Bytes()) + // ext.ExtraData = common.ToHex(b.ExtraData) + ext.GasLimit = common.ToHex(big.NewInt(b.GasLimit).Bytes()) + // ext.MinGasPrice = common.ToHex(big.NewInt(b.MinGasPrice).Bytes()) + ext.GasUsed = common.ToHex(big.NewInt(b.GasUsed).Bytes()) + ext.UnixTimestamp = common.ToHex(big.NewInt(b.UnixTimestamp).Bytes()) ext.Transactions = make([]interface{}, len(b.Transactions)) if b.fullTx { for i, tx := range b.Transactions { @@ -162,20 +162,20 @@ func (t *TransactionRes) MarshalJSON() ([]byte, error) { } ext.Hash = t.Hash.Hex() - ext.Nonce = toHex(big.NewInt(t.Nonce).Bytes()) + ext.Nonce = common.ToHex(big.NewInt(t.Nonce).Bytes()) ext.BlockHash = t.BlockHash.Hex() - ext.BlockNumber = toHex(big.NewInt(t.BlockNumber).Bytes()) - ext.TxIndex = toHex(big.NewInt(t.TxIndex).Bytes()) + ext.BlockNumber = common.ToHex(big.NewInt(t.BlockNumber).Bytes()) + ext.TxIndex = common.ToHex(big.NewInt(t.TxIndex).Bytes()) ext.From = t.From.Hex() if t.To == nil { ext.To = "0x00" } else { ext.To = t.To.Hex() } - ext.Value = toHex(big.NewInt(t.Value).Bytes()) - ext.Gas = toHex(big.NewInt(t.Gas).Bytes()) - ext.GasPrice = toHex(big.NewInt(t.GasPrice).Bytes()) - ext.Input = toHex(t.Input) + ext.Value = common.ToHex(big.NewInt(t.Value).Bytes()) + ext.Gas = common.ToHex(big.NewInt(t.Gas).Bytes()) + ext.GasPrice = common.ToHex(big.NewInt(t.GasPrice).Bytes()) + ext.Input = common.ToHex(t.Input) return json.Marshal(ext) } diff --git a/rpc/util.go b/rpc/util.go index b9b0fa442..b3d83409f 100644 --- a/rpc/util.go +++ b/rpc/util.go @@ -19,9 +19,7 @@ package rpc import ( "encoding/json" "fmt" - "io" "math/big" - "net/http" "reflect" "time" @@ -33,8 +31,6 @@ import ( var rpclogger = logger.NewLogger("RPC") -type JsonWrapper struct{} - // Unmarshal state is a helper method which has the ability to decode messsages // that use the `defaultBlock` (https://github.com/ethereum/wiki/wiki/JSON-RPC#the-default-block-parameter) // For example a `call`: [{to: "0x....", data:"0x..."}, "latest"]. The first argument is the transaction @@ -94,47 +90,8 @@ func UnmarshalRawMessages(b []byte, iface interface{}, number *int64) (err error return nil } -func (self JsonWrapper) Send(writer io.Writer, v interface{}) (n int, err error) { - 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) -} - -func (self JsonWrapper) ParseRequestBody(req *http.Request) (RpcRequest, error) { - var reqParsed RpcRequest - - // Convert JSON to native types - d := json.NewDecoder(req.Body) - defer req.Body.Close() - err := d.Decode(&reqParsed) - - if err != nil { - rpclogger.Errorln("Error decoding JSON: ", err) - return reqParsed, err - } - - rpclogger.DebugDetailf("Parsed request: %s", reqParsed) - - return reqParsed, nil -} - -func toHex(b []byte) string { - hex := common.Bytes2Hex(b) - // Prefer output of "0x0" instead of "0x" - if len(hex) == 0 { - hex = "0" - } - return "0x" + hex -} - func i2hex(n int) string { - return toHex(big.NewInt(int64(n)).Bytes()) + return common.ToHex(big.NewInt(int64(n)).Bytes()) } type RpcServer interface { @@ -156,7 +113,7 @@ func toLogs(logs state.Logs) (ls []Log) { var l Log l.Topic = make([]string, len(log.Topics())) l.Address = log.Address().Hex() - l.Data = toHex(log.Data()) + l.Data = common.ToHex(log.Data()) l.Number = log.Number() for j, topic := range log.Topics() { l.Topic[j] = topic.Hex() |