Enable RPC Server (#75)

- Introduces rpc command to cli (rest-server)
- Moves server/rpc to rpc/
- Enables module selection (eg. "web3" or "eth" or "web3,eth"), however there is no CLI flag to configure these (See #74)
- Adds CLI context to eth API
This commit is contained in:
David Ansermino
2019-07-15 10:13:59 -04:00
committed by GitHub
parent fbaa9466b0
commit 284c2a0333
9 changed files with 100 additions and 46 deletions
-46
View File
@@ -1,46 +0,0 @@
// Package rpc contains RPC handler methods and utilities to start
// Ethermint's Web3-compatibly JSON-RPC server.
package rpc
import (
"github.com/cosmos/ethermint/version"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/rpc"
)
// GetRPCAPIs returns the master list of public APIs for use with
// StartHTTPEndpoint.
func GetRPCAPIs() []rpc.API {
return []rpc.API{
{
Namespace: "web3",
Version: "1.0",
Service: NewPublicWeb3API(),
},
{
Namespace: "eth",
Version: "1.0",
Service: NewPublicEthAPI(),
},
}
}
// PublicWeb3API is the web3_ prefixed set of APIs in the Web3 JSON-RPC spec.
type PublicWeb3API struct {
}
// NewPublicWeb3API creates an instance of the Web3 API.
func NewPublicWeb3API() *PublicWeb3API {
return &PublicWeb3API{}
}
// ClientVersion returns the client version in the Web3 user agent format.
func (a *PublicWeb3API) ClientVersion() string {
return version.ClientVersion()
}
// Sha3 returns the keccak-256 hash of the passed-in input.
func (a *PublicWeb3API) Sha3(input hexutil.Bytes) hexutil.Bytes {
return crypto.Keccak256(input)
}
-76
View File
@@ -1,76 +0,0 @@
package rpc
import (
"context"
"testing"
"time"
"github.com/cosmos/ethermint/version"
"github.com/ethereum/go-ethereum/rpc"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
)
type apisTestSuite struct {
suite.Suite
Stop context.CancelFunc
Port int
}
func (s *apisTestSuite) SetupSuite() {
stop, port, err := startAPIServer()
require.Nil(s.T(), err, "unexpected error")
s.Stop = stop
s.Port = port
}
func (s *apisTestSuite) TearDownSuite() {
s.Stop()
}
func (s *apisTestSuite) TestPublicWeb3APIClientVersion() {
res, err := rpcCall(s.Port, "web3_clientVersion", []string{})
require.Nil(s.T(), err, "unexpected error")
require.Equal(s.T(), version.ClientVersion(), res)
}
func (s *apisTestSuite) TestPublicWeb3APISha3() {
res, err := rpcCall(s.Port, "web3_sha3", []string{"0x67656c6c6f20776f726c64"})
require.Nil(s.T(), err, "unexpected error")
require.Equal(s.T(), "0x1b84adea42d5b7d192fd8a61a85b25abe0757e9a65cab1da470258914053823f", res)
}
func (s *apisTestSuite) TestMiningAPIs() {
res, err := rpcCall(s.Port, "eth_mining", nil)
require.Nil(s.T(), err, "unexpected error")
require.Equal(s.T(), false, res)
res, err = rpcCall(s.Port, "eth_hashrate", nil)
require.Nil(s.T(), err, "unexpected error")
require.Equal(s.T(), "0x0", res)
}
func TestAPIsTestSuite(t *testing.T) {
suite.Run(t, new(apisTestSuite))
}
func startAPIServer() (context.CancelFunc, int, error) {
config := &Config{
RPCAddr: "127.0.0.1",
RPCPort: randomPort(),
}
timeouts := rpc.HTTPTimeouts{
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
IdleTimeout: 5 * time.Second,
}
ctx, cancel := context.WithCancel(context.Background())
_, err := StartHTTPEndpoint(ctx, config, GetRPCAPIs(), timeouts)
if err != nil {
return cancel, 0, err
}
return cancel, config.RPCPort, nil
}
-16
View File
@@ -1,16 +0,0 @@
package rpc
// Config contains configuration fields that determine the
// behavior of the RPC HTTP server.
type Config struct {
// EnableRPC defines whether or not to enable the RPC server
EnableRPC bool
// RPCAddr defines the IP address to listen on
RPCAddr string
// RPCPort defines the port to listen on
RPCPort int
// RPCCORSDomains defines list of domains to enable CORS headers for (used by browsers)
RPCCORSDomains []string
// RPCVhosts defines list of domains to listen on (useful if Tendermint is addressable via DNS)
RPCVHosts []string
}
-196
View File
@@ -1,196 +0,0 @@
package rpc
import (
"github.com/cosmos/ethermint/version"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/rpc"
"github.com/ethereum/go-ethereum/signer/core"
"math/big"
)
// PublicEthAPI is the eth_ prefixed set of APIs in the Web3 JSON-RPC spec.
type PublicEthAPI struct{}
// NewPublicEthAPI creates an instance of the public ETH Web3 API.
func NewPublicEthAPI() *PublicEthAPI {
return &PublicEthAPI{}
}
// ProtocolVersion returns the supported Ethereum protocol version.
func (e *PublicEthAPI) ProtocolVersion() string {
return version.ProtocolVersion
}
// Syncing returns whether or not the current node is syncing with other peers. Returns false if not, or a struct
// outlining the state of the sync if it is.
func (e *PublicEthAPI) Syncing() interface{} {
return false
}
// Coinbase returns this node's coinbase address. Not used in Ethermint.
func (e *PublicEthAPI) Coinbase() (addr common.Address) {
return
}
// Mining returns whether or not this node is currently mining. Always false.
func (e *PublicEthAPI) Mining() bool {
return false
}
// Hashrate returns the current node's hashrate. Always 0.
func (e *PublicEthAPI) Hashrate() hexutil.Uint64 {
return 0
}
// GasPrice returns the current gas price based on Ethermint's gas price oracle.
func (e *PublicEthAPI) GasPrice() *hexutil.Big {
out := big.NewInt(0)
return (*hexutil.Big)(out)
}
// Accounts returns the list of accounts available to this node.
func (e *PublicEthAPI) Accounts() []common.Address {
return nil
}
// BlockNumber returns the current block number.
func (e *PublicEthAPI) BlockNumber() *big.Int {
return big.NewInt(0)
}
// GetBalance returns the provided account's balance up to the provided block number.
func (e *PublicEthAPI) GetBalance(address common.Address, blockNum rpc.BlockNumber) *hexutil.Big {
out := big.NewInt(0)
return (*hexutil.Big)(out)
}
// GetStorageAt returns the contract storage at the given address, block number, and key.
func (e *PublicEthAPI) GetStorageAt(address common.Address, key string, blockNum rpc.BlockNumber) hexutil.Bytes {
return nil
}
// GetTransactionCount returns the number of transactions at the given address up to the given block number.
func (e *PublicEthAPI) GetTransactionCount(address common.Address, blockNum rpc.BlockNumber) hexutil.Uint64 {
return 0
}
// GetBlockTransactionCountByHash returns the number of transactions in the block identified by hash.
func (e *PublicEthAPI) GetBlockTransactionCountByHash(hash common.Hash) hexutil.Uint {
return 0
}
// GetBlockTransactionCountByNumber returns the number of transactions in the block identified by number.
func (e *PublicEthAPI) GetBlockTransactionCountByNumber(blockNum rpc.BlockNumber) hexutil.Uint {
return 0
}
// GetUncleCountByBlockHash returns the number of uncles in the block idenfied by hash. Always zero.
func (e *PublicEthAPI) GetUncleCountByBlockHash(hash common.Hash) hexutil.Uint {
return 0
}
// GetUncleCountByBlockNumber returns the number of uncles in the block idenfied by number. Always zero.
func (e *PublicEthAPI) GetUncleCountByBlockNumber(blockNum rpc.BlockNumber) hexutil.Uint {
return 0
}
// GetCode returns the contract code at the given address and block number.
func (e *PublicEthAPI) GetCode(address common.Address, blockNumber rpc.BlockNumber) hexutil.Bytes {
return nil
}
// Sign signs the provided data using the private key of address via Geth's signature standard.
func (e *PublicEthAPI) Sign(address common.Address, data hexutil.Bytes) hexutil.Bytes {
return nil
}
// SendTransaction sends an Ethereum transaction.
func (e *PublicEthAPI) SendTransaction(args core.SendTxArgs) common.Hash {
var h common.Hash
return h
}
// SendRawTransaction send a raw Ethereum transaction.
func (e *PublicEthAPI) SendRawTransaction(data hexutil.Bytes) common.Hash {
var h common.Hash
return h
}
// CallArgs represents arguments to a smart contract call as provided by RPC clients.
type CallArgs struct {
From common.Address `json:"from"`
To common.Address `json:"to"`
Gas hexutil.Uint64 `json:"gas"`
GasPrice hexutil.Big `json:"gasPrice"`
Value hexutil.Big `json:"value"`
Data hexutil.Bytes `json:"data"`
}
// Call performs a raw contract call.
func (e *PublicEthAPI) Call(args CallArgs, blockNum rpc.BlockNumber) hexutil.Bytes {
return nil
}
// EstimateGas estimates gas usage for the given smart contract call.
func (e *PublicEthAPI) EstimateGas(args CallArgs, blockNum rpc.BlockNumber) hexutil.Uint64 {
return 0
}
// GetBlockByHash returns the block identified by hash.
func (e *PublicEthAPI) GetBlockByHash(hash common.Hash, fullTx bool) map[string]interface{} {
return nil
}
// GetBlockByNumber returns the block identified by number.
func (e *PublicEthAPI) GetBlockByNumber(blockNum rpc.BlockNumber, fullTx bool) map[string]interface{} {
return nil
}
// Transaction represents a transaction returned to RPC clients.
type Transaction struct {
BlockHash common.Hash `json:"blockHash"`
BlockNumber *hexutil.Big `json:"blockNumber"`
From common.Address `json:"from"`
Gas hexutil.Uint64 `json:"gas"`
GasPrice *hexutil.Big `json:"gasPrice"`
Hash common.Hash `json:"hash"`
Input hexutil.Bytes `json:"input"`
Nonce hexutil.Uint64 `json:"nonce"`
To *common.Address `json:"to"`
TransactionIndex hexutil.Uint `json:"transactionIndex"`
Value *hexutil.Big `json:"value"`
V *hexutil.Big `json:"v"`
R *hexutil.Big `json:"r"`
S *hexutil.Big `json:"s"`
}
// GetTransactionByHash returns the transaction identified by hash.
func (e *PublicEthAPI) GetTransactionByHash(hash common.Hash) *Transaction {
return nil
}
// GetTransactionByBlockHashAndIndex returns the transaction identified by hash and index.
func (e *PublicEthAPI) GetTransactionByBlockHashAndIndex(hash common.Hash, idx hexutil.Uint) *Transaction {
return nil
}
// GetTransactionByBlockNumberAndIndex returns the transaction identified by number and index.
func (e *PublicEthAPI) GetTransactionByBlockNumberAndIndex(blockNumber rpc.BlockNumber, idx hexutil.Uint) *Transaction {
return nil
}
// GetTransactionReceipt returns the transaction receipt identified by hash.
func (e *PublicEthAPI) GetTransactionReceipt(hash common.Hash) map[string]interface{} {
return nil
}
// GetUncleByBlockHashAndIndex returns the uncle identified by hash and index. Always returns nil.
func (e *PublicEthAPI) GetUncleByBlockHashAndIndex(hash common.Hash, idx hexutil.Uint) map[string]interface{} {
return nil
}
// GetUncleByBlockNumberAndIndex returns the uncle identified by number and index. Always returns nil.
func (e *PublicEthAPI) GetUncleByBlockNumberAndIndex(number hexutil.Uint, idx hexutil.Uint) map[string]interface{} {
return nil
}
-38
View File
@@ -1,38 +0,0 @@
package rpc
import (
"context"
"fmt"
"github.com/ethereum/go-ethereum/rpc"
)
// StartHTTPEndpoint starts the Tendermint Web3-compatible RPC layer. Consumes
// a Context for cancellation, a config struct, and a list of rpc.API interfaces
// that will be automatically wired into a JSON-RPC webserver.
func StartHTTPEndpoint(ctx context.Context, config *Config, apis []rpc.API, timeouts rpc.HTTPTimeouts) (*rpc.Server, error) {
uniqModules := make(map[string]string)
for _, api := range apis {
uniqModules[api.Namespace] = api.Namespace
}
modules := make([]string, len(uniqModules))
i := 0
for k := range uniqModules {
modules[i] = k
i++
}
endpoint := fmt.Sprintf("%s:%d", config.RPCAddr, config.RPCPort)
_, server, err := rpc.StartHTTPEndpoint(
endpoint, apis, modules, config.RPCCORSDomains, config.RPCVHosts, timeouts,
)
go func() {
<-ctx.Done()
fmt.Println("Shutting down server.")
server.Stop()
}()
return server, err
}
-94
View File
@@ -1,94 +0,0 @@
package rpc
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"strings"
"testing"
"time"
"github.com/ethereum/go-ethereum/rpc"
"github.com/stretchr/testify/require"
)
type TestService struct{}
func (s *TestService) Foo(arg string) string {
return arg
}
func TestStartHTTPEndpointStartStop(t *testing.T) {
config := &Config{
RPCAddr: "127.0.0.1",
RPCPort: randomPort(),
}
ctx, cancel := context.WithCancel(context.Background())
_, err := StartHTTPEndpoint(
ctx, config, []rpc.API{
{
Namespace: "test",
Version: "1.0",
Service: &TestService{},
Public: true,
},
},
rpc.HTTPTimeouts{
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
IdleTimeout: 5 * time.Second,
},
)
require.Nil(t, err, "unexpected error")
res, err := rpcCall(config.RPCPort, "test_foo", []string{"baz"})
require.Nil(t, err, "unexpected error")
resStr := res.(string)
require.Equal(t, "baz", resStr)
cancel()
_, err = rpcCall(config.RPCPort, "test_foo", []string{"baz"})
require.NotNil(t, err)
}
func rpcCall(port int, method string, params []string) (interface{}, error) {
parsedParams, err := json.Marshal(params)
if err != nil {
return nil, err
}
fullBody := fmt.Sprintf(
`{ "id": 1, "jsonrpc": "2.0", "method": "%s", "params": %s }`,
method, string(parsedParams),
)
res, err := http.Post(fmt.Sprintf("http://127.0.0.1:%d", port), "application/json", strings.NewReader(fullBody))
if err != nil {
return nil, err
}
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var out map[string]interface{}
err = json.Unmarshal(data, &out)
if err != nil {
return nil, err
}
result := out["result"].(interface{})
return result, nil
}
func randomPort() int {
return rand.Intn(65535-1025) + 1025
}