Start RPC API implementation

This commit is contained in:
Matthew Slipper
2018-08-21 00:12:48 -07:00
parent c1e6ebf80a
commit 32504a866f
11 changed files with 248 additions and 7 deletions
+39
View File
@@ -0,0 +1,39 @@
// Package rpc contains RPC handler methods and utilities to start
// Ethermint's Web3-compatibly JSON-RPC server.
package rpc
import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/rpc"
"github.com/cosmos/ethermint/version"
)
// 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(),
},
}
}
// PublicWeb3API is the web3_ prefixed set of APIs in the WEB3 JSON-RPC spec.
type PublicWeb3API struct {
}
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)
}
+55
View File
@@ -0,0 +1,55 @@
package rpc
import (
"context"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"github.com/cosmos/ethermint/version"
"testing"
)
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 TestAPIsTestSuite(t *testing.T) {
suite.Run(t, new(apisTestSuite))
}
func startAPIServer() (context.CancelFunc, int, error) {
config := &Config{
RPCAddr: "127.0.0.1",
RPCPort: randomPort(),
}
ctx, cancel := context.WithCancel(context.Background())
_, err := StartHTTPEndpoint(ctx, config, GetRPCAPIs())
if err != nil {
return cancel, 0, err
}
return cancel, config.RPCPort, nil
}
+16
View File
@@ -0,0 +1,16 @@
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
}
+33
View File
@@ -0,0 +1,33 @@
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) (*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)
go func() {
<-ctx.Done()
fmt.Println("Shutting down server.")
server.Stop()
}()
return server, err
}
+74
View File
@@ -0,0 +1,74 @@
package rpc
import (
"context"
"encoding/json"
"fmt"
"github.com/ethereum/go-ethereum/rpc"
"github.com/stretchr/testify/require"
"io/ioutil"
"math/rand"
"net/http"
"strings"
"testing"
)
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,
},
})
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
}
-1
View File
@@ -1 +0,0 @@
package server