forked from cerc-io/laconicd-deprecated
Basic RPC and CLI Queries (#77)
- Adds ethermint query command (`emintcli query ethermint <query>`)
- Supports block number, storage, code, balance lookups
- Implements RPC API methods `eth_blockNumber`, `eth_getStorageAt`, `eth_getBalance`, and `eth_getCode`
- Adds tester utility for RPC calls
- Adheres to go test format, but should not be run with regular suite
- Requires daemon and RPC server to be running
- Excluded from `make test`, available with `make test-rpc`
- Implemented AppModule interface and added EVM module to app
- Required for routing
- Implements `InitGenesis` (`x/evm/genesis.go`) and stubs `ExportGenesis`
- Modifies GenesisAccount to match expected format
This commit is contained in:
@@ -1,77 +0,0 @@
|
||||
package rpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
sdkcontext"github.com/cosmos/cosmos-sdk/client/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(sdkcontext.NewCLIContext()), timeouts)
|
||||
if err != nil {
|
||||
return cancel, 0, err
|
||||
}
|
||||
|
||||
return cancel, config.RPCPort, nil
|
||||
}
|
||||
+39
-6
@@ -1,8 +1,10 @@
|
||||
package rpc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/cosmos/cosmos-sdk/client/context"
|
||||
"github.com/cosmos/ethermint/version"
|
||||
"github.com/cosmos/ethermint/x/evm/types"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/common/hexutil"
|
||||
"github.com/ethereum/go-ethereum/rpc"
|
||||
@@ -11,7 +13,7 @@ import (
|
||||
)
|
||||
|
||||
// PublicEthAPI is the eth_ prefixed set of APIs in the Web3 JSON-RPC spec.
|
||||
type PublicEthAPI struct{
|
||||
type PublicEthAPI struct {
|
||||
cliCtx context.CLIContext
|
||||
}
|
||||
|
||||
@@ -61,18 +63,41 @@ func (e *PublicEthAPI) Accounts() []common.Address {
|
||||
|
||||
// BlockNumber returns the current block number.
|
||||
func (e *PublicEthAPI) BlockNumber() *big.Int {
|
||||
return big.NewInt(0)
|
||||
res, _, err := e.cliCtx.QueryWithData(fmt.Sprintf("custom/%s/blockNumber", types.ModuleName), nil)
|
||||
if err != nil {
|
||||
fmt.Printf("could not resolve: %s\n", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
var out types.QueryResBlockNumber
|
||||
e.cliCtx.Codec.MustUnmarshalJSON(res, &out)
|
||||
return out.Number
|
||||
}
|
||||
|
||||
// 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)
|
||||
res, _, err := e.cliCtx.QueryWithData(fmt.Sprintf("custom/%s/balance/%s", types.ModuleName, address), nil)
|
||||
if err != nil {
|
||||
fmt.Printf("could not resolve: %s\n", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
var out types.QueryResBalance
|
||||
e.cliCtx.Codec.MustUnmarshalJSON(res, &out)
|
||||
return (*hexutil.Big)(out.Balance)
|
||||
}
|
||||
|
||||
// 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
|
||||
res, _, err := e.cliCtx.QueryWithData(fmt.Sprintf("custom/%s/storage/%s/%s", types.ModuleName, address, key), nil)
|
||||
if err != nil {
|
||||
fmt.Printf("could not resolve: %s\n", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
var out types.QueryResStorage
|
||||
e.cliCtx.Codec.MustUnmarshalJSON(res, &out)
|
||||
return out.Value[:]
|
||||
}
|
||||
|
||||
// GetTransactionCount returns the number of transactions at the given address up to the given block number.
|
||||
@@ -102,7 +127,15 @@ func (e *PublicEthAPI) GetUncleCountByBlockNumber(blockNum rpc.BlockNumber) hexu
|
||||
|
||||
// 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
|
||||
res, _, err := e.cliCtx.QueryWithData(fmt.Sprintf("custom/%s/code/%s", types.ModuleName, address), nil)
|
||||
if err != nil {
|
||||
fmt.Printf("could not resolve: %s\n", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
var out types.QueryResCode
|
||||
e.cliCtx.Codec.MustUnmarshalJSON(res, &out)
|
||||
return out.Code
|
||||
}
|
||||
|
||||
// Sign signs the provided data using the private key of address via Geth's signature standard.
|
||||
|
||||
-38
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
// This is a test utility for Ethermint's Web3 JSON-RPC services.
|
||||
//
|
||||
// To run these tests please first ensure you have the emintd running
|
||||
// and have started the RPC service with `emintcl rest-server`.
|
||||
//
|
||||
// You can configure the desired port (or host) below.
|
||||
|
||||
package tester
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/cosmos/ethermint/version"
|
||||
"github.com/cosmos/ethermint/x/evm/types"
|
||||
"io/ioutil"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const (
|
||||
host = "127.0.0.1"
|
||||
port = 1317
|
||||
addrA = "0xc94770007dda54cF92009BFF0dE90c06F603a09f"
|
||||
addrAStoreKey = 0
|
||||
)
|
||||
|
||||
var addr = fmt.Sprintf("http://%s:%d/rpc", host, port)
|
||||
|
||||
type Request struct {
|
||||
Version string `json:"jsonrpc"`
|
||||
Method string `json:"method"`
|
||||
Params []string `json:"params"`
|
||||
Id int `json:"id"`
|
||||
}
|
||||
|
||||
func createRequest(method string, params []string) Request {
|
||||
return Request{
|
||||
Version: "2.0",
|
||||
Method: method,
|
||||
Params: params,
|
||||
Id: 1,
|
||||
}
|
||||
}
|
||||
|
||||
func call(t *testing.T, method string, params []string, resp interface{}) {
|
||||
req, err := json.Marshal(createRequest(method, params))
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
res, err := http.Post(addr, "application/json", bytes.NewBuffer(req))
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
body, err := ioutil.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
err = json.Unmarshal(body, resp)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEth_protocolVersion(t *testing.T) {
|
||||
expectedRes := version.ProtocolVersion
|
||||
|
||||
res := &types.QueryResProtocolVersion{}
|
||||
call(t, "eth_protocolVersion", []string{}, res)
|
||||
|
||||
t.Logf("Got protocol version: %s\n", res.Version)
|
||||
|
||||
if res.Version != expectedRes {
|
||||
t.Errorf("expected: %s got: %s\n", expectedRes, res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEth_blockNumber(t *testing.T) {
|
||||
res := &types.QueryResBlockNumber{}
|
||||
call(t, "eth_blockNumber", []string{}, res)
|
||||
|
||||
t.Logf("Got block number: %s\n", res.Number.String())
|
||||
|
||||
// -1 if x < y, 0 if x == y; where x is res, y is 0
|
||||
if res.Number.Cmp(big.NewInt(0)) < 1 {
|
||||
t.Errorf("Invalid block number got: %v", res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEth_GetBalance(t *testing.T) {
|
||||
//expectedRes := types.QueryResBalance{Balance:}
|
||||
res := &types.QueryResBalance{}
|
||||
call(t, "eth_getBalance", []string{addrA, "latest"}, res)
|
||||
|
||||
t.Logf("Got balance %s for %s\n", res.Balance.String(), addrA)
|
||||
|
||||
// 0 if x == y; where x is res, y is 0
|
||||
if res.Balance.ToInt().Cmp(big.NewInt(0)) != 0 {
|
||||
t.Errorf("expected balance: %d, got: %s", 0, res.Balance.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestEth_GetStorageAt(t *testing.T) {
|
||||
expectedRes := types.QueryResStorage{Value: []byte{}}
|
||||
res := &types.QueryResStorage{}
|
||||
call(t, "eth_getStorageAt", []string{addrA, string(addrAStoreKey), "latest"}, res)
|
||||
|
||||
t.Logf("Got value [%X] for %s with key %X\n", res.Value, addrA, addrAStoreKey)
|
||||
|
||||
if !bytes.Equal(res.Value, expectedRes.Value) {
|
||||
t.Errorf("expected: %X got: %X", expectedRes.Value, res.Value)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEth_GetCode(t *testing.T) {
|
||||
expectedRes := types.QueryResCode{Code: []byte{}}
|
||||
res := &types.QueryResCode{}
|
||||
call(t, "eth_getCode", []string{addrA, "latest"}, res)
|
||||
|
||||
t.Logf("Got code [%X] for %s\n", res.Code, addrA)
|
||||
if !bytes.Equal(expectedRes.Code, res.Code) {
|
||||
t.Errorf("expected: %X got: %X", expectedRes.Code, res.Code)
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -7,7 +7,7 @@ import (
|
||||
)
|
||||
|
||||
// PublicWeb3API is the web3_ prefixed set of APIs in the Web3 JSON-RPC spec.
|
||||
type PublicWeb3API struct {}
|
||||
type PublicWeb3API struct{}
|
||||
|
||||
// NewPublicWeb3API creates an instance of the Web3 API.
|
||||
func NewPublicWeb3API() *PublicWeb3API {
|
||||
|
||||
Reference in New Issue
Block a user