forked from mirror/go-ethereum
node: refactor package node (#21105)
This PR significantly changes the APIs for instantiating Ethereum nodes in a Go program. The new APIs are not backwards-compatible, but we feel that this is made up for by the much simpler way of registering services on node.Node. You can find more information and rationale in the design document: https://gist.github.com/renaynay/5bec2de19fde66f4d04c535fd24f0775. There is also a new feature in Node's Go API: it is now possible to register arbitrary handlers on the user-facing HTTP server. In geth, this facility is used to enable GraphQL. There is a single minor change relevant for geth users in this PR: The GraphQL API is no longer available separately from the JSON-RPC HTTP server. If you want GraphQL, you need to enable it using the ./geth --http --graphql flag combination. The --graphql.port and --graphql.addr flags are no longer available.release/1.9
parent
b2b14e6ce3
commit
c0c01612e9
@ -0,0 +1,350 @@ |
||||
// Copyright 2020 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package node |
||||
|
||||
import ( |
||||
"bytes" |
||||
"io" |
||||
"net" |
||||
"net/http" |
||||
"net/url" |
||||
"strings" |
||||
"testing" |
||||
|
||||
"github.com/ethereum/go-ethereum/rpc" |
||||
"github.com/stretchr/testify/assert" |
||||
) |
||||
|
||||
// This test uses the admin_startRPC and admin_startWS APIs,
|
||||
// checking whether the HTTP server is started correctly.
|
||||
func TestStartRPC(t *testing.T) { |
||||
type test struct { |
||||
name string |
||||
cfg Config |
||||
fn func(*testing.T, *Node, *privateAdminAPI) |
||||
|
||||
// Checks. These run after the node is configured and all API calls have been made.
|
||||
wantReachable bool // whether the HTTP server should be reachable at all
|
||||
wantHandlers bool // whether RegisterHandler handlers should be accessible
|
||||
wantRPC bool // whether JSON-RPC/HTTP should be accessible
|
||||
wantWS bool // whether JSON-RPC/WS should be accessible
|
||||
} |
||||
|
||||
tests := []test{ |
||||
{ |
||||
name: "all off", |
||||
cfg: Config{}, |
||||
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { |
||||
}, |
||||
wantReachable: false, |
||||
wantHandlers: false, |
||||
wantRPC: false, |
||||
wantWS: false, |
||||
}, |
||||
{ |
||||
name: "rpc enabled through config", |
||||
cfg: Config{HTTPHost: "127.0.0.1"}, |
||||
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { |
||||
}, |
||||
wantReachable: true, |
||||
wantHandlers: true, |
||||
wantRPC: true, |
||||
wantWS: false, |
||||
}, |
||||
{ |
||||
name: "rpc enabled through API", |
||||
cfg: Config{}, |
||||
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { |
||||
_, err := api.StartRPC(sp("127.0.0.1"), ip(0), nil, nil, nil) |
||||
assert.NoError(t, err) |
||||
}, |
||||
wantReachable: true, |
||||
wantHandlers: true, |
||||
wantRPC: true, |
||||
wantWS: false, |
||||
}, |
||||
{ |
||||
name: "rpc start again after failure", |
||||
cfg: Config{}, |
||||
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { |
||||
// Listen on a random port.
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0") |
||||
if err != nil { |
||||
t.Fatal("can't listen:", err) |
||||
} |
||||
defer listener.Close() |
||||
port := listener.Addr().(*net.TCPAddr).Port |
||||
|
||||
// Now try to start RPC on that port. This should fail.
|
||||
_, err = api.StartRPC(sp("127.0.0.1"), ip(port), nil, nil, nil) |
||||
if err == nil { |
||||
t.Fatal("StartRPC should have failed on port", port) |
||||
} |
||||
|
||||
// Try again after unblocking the port. It should work this time.
|
||||
listener.Close() |
||||
_, err = api.StartRPC(sp("127.0.0.1"), ip(port), nil, nil, nil) |
||||
assert.NoError(t, err) |
||||
}, |
||||
wantReachable: true, |
||||
wantHandlers: true, |
||||
wantRPC: true, |
||||
wantWS: false, |
||||
}, |
||||
{ |
||||
name: "rpc stopped through API", |
||||
cfg: Config{HTTPHost: "127.0.0.1"}, |
||||
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { |
||||
_, err := api.StopRPC() |
||||
assert.NoError(t, err) |
||||
}, |
||||
wantReachable: false, |
||||
wantHandlers: false, |
||||
wantRPC: false, |
||||
wantWS: false, |
||||
}, |
||||
{ |
||||
name: "rpc stopped twice", |
||||
cfg: Config{HTTPHost: "127.0.0.1"}, |
||||
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { |
||||
_, err := api.StopRPC() |
||||
assert.NoError(t, err) |
||||
|
||||
_, err = api.StopRPC() |
||||
assert.NoError(t, err) |
||||
}, |
||||
wantReachable: false, |
||||
wantHandlers: false, |
||||
wantRPC: false, |
||||
wantWS: false, |
||||
}, |
||||
{ |
||||
name: "ws enabled through config", |
||||
cfg: Config{WSHost: "127.0.0.1"}, |
||||
wantReachable: true, |
||||
wantHandlers: false, |
||||
wantRPC: false, |
||||
wantWS: true, |
||||
}, |
||||
{ |
||||
name: "ws enabled through API", |
||||
cfg: Config{}, |
||||
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { |
||||
_, err := api.StartWS(sp("127.0.0.1"), ip(0), nil, nil) |
||||
assert.NoError(t, err) |
||||
}, |
||||
wantReachable: true, |
||||
wantHandlers: false, |
||||
wantRPC: false, |
||||
wantWS: true, |
||||
}, |
||||
{ |
||||
name: "ws stopped through API", |
||||
cfg: Config{WSHost: "127.0.0.1"}, |
||||
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { |
||||
_, err := api.StopWS() |
||||
assert.NoError(t, err) |
||||
}, |
||||
wantReachable: false, |
||||
wantHandlers: false, |
||||
wantRPC: false, |
||||
wantWS: false, |
||||
}, |
||||
{ |
||||
name: "ws stopped twice", |
||||
cfg: Config{WSHost: "127.0.0.1"}, |
||||
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { |
||||
_, err := api.StopWS() |
||||
assert.NoError(t, err) |
||||
|
||||
_, err = api.StopWS() |
||||
assert.NoError(t, err) |
||||
}, |
||||
wantReachable: false, |
||||
wantHandlers: false, |
||||
wantRPC: false, |
||||
wantWS: false, |
||||
}, |
||||
{ |
||||
name: "ws enabled after RPC", |
||||
cfg: Config{HTTPHost: "127.0.0.1"}, |
||||
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { |
||||
wsport := n.http.port |
||||
_, err := api.StartWS(sp("127.0.0.1"), ip(wsport), nil, nil) |
||||
assert.NoError(t, err) |
||||
}, |
||||
wantReachable: true, |
||||
wantHandlers: true, |
||||
wantRPC: true, |
||||
wantWS: true, |
||||
}, |
||||
{ |
||||
name: "ws enabled after RPC then stopped", |
||||
cfg: Config{HTTPHost: "127.0.0.1"}, |
||||
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { |
||||
wsport := n.http.port |
||||
_, err := api.StartWS(sp("127.0.0.1"), ip(wsport), nil, nil) |
||||
assert.NoError(t, err) |
||||
|
||||
_, err = api.StopWS() |
||||
assert.NoError(t, err) |
||||
}, |
||||
wantReachable: true, |
||||
wantHandlers: true, |
||||
wantRPC: true, |
||||
wantWS: false, |
||||
}, |
||||
{ |
||||
name: "rpc stopped with ws enabled", |
||||
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { |
||||
_, err := api.StartRPC(sp("127.0.0.1"), ip(0), nil, nil, nil) |
||||
assert.NoError(t, err) |
||||
|
||||
wsport := n.http.port |
||||
_, err = api.StartWS(sp("127.0.0.1"), ip(wsport), nil, nil) |
||||
assert.NoError(t, err) |
||||
|
||||
_, err = api.StopRPC() |
||||
assert.NoError(t, err) |
||||
}, |
||||
wantReachable: false, |
||||
wantHandlers: false, |
||||
wantRPC: false, |
||||
wantWS: false, |
||||
}, |
||||
{ |
||||
name: "rpc enabled after ws", |
||||
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { |
||||
_, err := api.StartWS(sp("127.0.0.1"), ip(0), nil, nil) |
||||
assert.NoError(t, err) |
||||
|
||||
wsport := n.http.port |
||||
_, err = api.StartRPC(sp("127.0.0.1"), ip(wsport), nil, nil, nil) |
||||
assert.NoError(t, err) |
||||
}, |
||||
wantReachable: true, |
||||
wantHandlers: true, |
||||
wantRPC: true, |
||||
wantWS: true, |
||||
}, |
||||
} |
||||
|
||||
for _, test := range tests { |
||||
t.Run(test.name, func(t *testing.T) { |
||||
// Apply some sane defaults.
|
||||
config := test.cfg |
||||
// config.Logger = testlog.Logger(t, log.LvlDebug)
|
||||
config.NoUSB = true |
||||
config.P2P.NoDiscovery = true |
||||
|
||||
// Create Node.
|
||||
stack, err := New(&config) |
||||
if err != nil { |
||||
t.Fatal("can't create node:", err) |
||||
} |
||||
defer stack.Close() |
||||
|
||||
// Register the test handler.
|
||||
stack.RegisterHandler("test", "/test", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
||||
w.Write([]byte("OK")) |
||||
})) |
||||
|
||||
if err := stack.Start(); err != nil { |
||||
t.Fatal("can't start node:", err) |
||||
} |
||||
|
||||
// Run the API call hook.
|
||||
if test.fn != nil { |
||||
test.fn(t, stack, &privateAdminAPI{stack}) |
||||
} |
||||
|
||||
// Check if the HTTP endpoints are available.
|
||||
baseURL := stack.HTTPEndpoint() |
||||
reachable := checkReachable(baseURL) |
||||
handlersAvailable := checkBodyOK(baseURL + "/test") |
||||
rpcAvailable := checkRPC(baseURL) |
||||
wsAvailable := checkRPC(strings.Replace(baseURL, "http://", "ws://", 1)) |
||||
if reachable != test.wantReachable { |
||||
t.Errorf("HTTP server is %sreachable, want it %sreachable", not(reachable), not(test.wantReachable)) |
||||
} |
||||
if handlersAvailable != test.wantHandlers { |
||||
t.Errorf("RegisterHandler handlers %savailable, want them %savailable", not(handlersAvailable), not(test.wantHandlers)) |
||||
} |
||||
if rpcAvailable != test.wantRPC { |
||||
t.Errorf("HTTP RPC %savailable, want it %savailable", not(rpcAvailable), not(test.wantRPC)) |
||||
} |
||||
if wsAvailable != test.wantWS { |
||||
t.Errorf("WS RPC %savailable, want it %savailable", not(wsAvailable), not(test.wantWS)) |
||||
} |
||||
}) |
||||
} |
||||
} |
||||
|
||||
// checkReachable checks if the TCP endpoint in rawurl is open.
|
||||
func checkReachable(rawurl string) bool { |
||||
u, err := url.Parse(rawurl) |
||||
if err != nil { |
||||
panic(err) |
||||
} |
||||
conn, err := net.Dial("tcp", u.Host) |
||||
if err != nil { |
||||
return false |
||||
} |
||||
conn.Close() |
||||
return true |
||||
} |
||||
|
||||
// checkBodyOK checks whether the given HTTP URL responds with 200 OK and body "OK".
|
||||
func checkBodyOK(url string) bool { |
||||
resp, err := http.Get(url) |
||||
if err != nil { |
||||
return false |
||||
} |
||||
defer resp.Body.Close() |
||||
|
||||
if resp.StatusCode != 200 { |
||||
return false |
||||
} |
||||
buf := make([]byte, 2) |
||||
if _, err = io.ReadFull(resp.Body, buf); err != nil { |
||||
return false |
||||
} |
||||
return bytes.Equal(buf, []byte("OK")) |
||||
} |
||||
|
||||
// checkRPC checks whether JSON-RPC works against the given URL.
|
||||
func checkRPC(url string) bool { |
||||
c, err := rpc.Dial(url) |
||||
if err != nil { |
||||
return false |
||||
} |
||||
defer c.Close() |
||||
|
||||
_, err = c.SupportedModules() |
||||
return err == nil |
||||
} |
||||
|
||||
// string/int pointer helpers.
|
||||
func sp(s string) *string { return &s } |
||||
func ip(i int) *int { return &i } |
||||
|
||||
func not(ok bool) string { |
||||
if ok { |
||||
return "" |
||||
} |
||||
return "not " |
||||
} |
@ -0,0 +1,31 @@ |
||||
// Copyright 2020 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package node |
||||
|
||||
// Lifecycle encompasses the behavior of services that can be started and stopped
|
||||
// on the node. Lifecycle management is delegated to the node, but it is the
|
||||
// responsibility of the service-specific package to configure and register the
|
||||
// service on the node using the `RegisterLifecycle` method.
|
||||
type Lifecycle interface { |
||||
// Start is called after all services have been constructed and the networking
|
||||
// layer was also initialized to spawn any goroutines required by the service.
|
||||
Start() error |
||||
|
||||
// Stop terminates all goroutines belonging to the service, blocking until they
|
||||
// are all terminated.
|
||||
Stop() error |
||||
} |
File diff suppressed because it is too large
Load Diff
@ -1,38 +1,110 @@ |
||||
// Copyright 2020 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package node |
||||
|
||||
import ( |
||||
"bytes" |
||||
"net/http" |
||||
"net/http/httptest" |
||||
"testing" |
||||
|
||||
"github.com/ethereum/go-ethereum/internal/testlog" |
||||
"github.com/ethereum/go-ethereum/log" |
||||
"github.com/ethereum/go-ethereum/rpc" |
||||
"github.com/gorilla/websocket" |
||||
"github.com/stretchr/testify/assert" |
||||
) |
||||
|
||||
func TestNewWebsocketUpgradeHandler_websocket(t *testing.T) { |
||||
srv := rpc.NewServer() |
||||
// TestCorsHandler makes sure CORS are properly handled on the http server.
|
||||
func TestCorsHandler(t *testing.T) { |
||||
srv := createAndStartServer(t, httpConfig{CorsAllowedOrigins: []string{"test", "test.com"}}, false, wsConfig{}) |
||||
defer srv.stop() |
||||
|
||||
resp := testRequest(t, "origin", "test.com", "", srv) |
||||
assert.Equal(t, "test.com", resp.Header.Get("Access-Control-Allow-Origin")) |
||||
|
||||
resp2 := testRequest(t, "origin", "bad", "", srv) |
||||
assert.Equal(t, "", resp2.Header.Get("Access-Control-Allow-Origin")) |
||||
} |
||||
|
||||
// TestVhosts makes sure vhosts are properly handled on the http server.
|
||||
func TestVhosts(t *testing.T) { |
||||
srv := createAndStartServer(t, httpConfig{Vhosts: []string{"test"}}, false, wsConfig{}) |
||||
defer srv.stop() |
||||
|
||||
resp := testRequest(t, "", "", "test", srv) |
||||
assert.Equal(t, resp.StatusCode, http.StatusOK) |
||||
|
||||
resp2 := testRequest(t, "", "", "bad", srv) |
||||
assert.Equal(t, resp2.StatusCode, http.StatusForbidden) |
||||
} |
||||
|
||||
handler := NewWebsocketUpgradeHandler(nil, srv.WebsocketHandler([]string{})) |
||||
ts := httptest.NewServer(handler) |
||||
defer ts.Close() |
||||
// TestWebsocketOrigins makes sure the websocket origins are properly handled on the websocket server.
|
||||
func TestWebsocketOrigins(t *testing.T) { |
||||
srv := createAndStartServer(t, httpConfig{}, true, wsConfig{Origins: []string{"test"}}) |
||||
defer srv.stop() |
||||
|
||||
responses := make(chan *http.Response) |
||||
go func(responses chan *http.Response) { |
||||
client := &http.Client{} |
||||
dialer := websocket.DefaultDialer |
||||
_, _, err := dialer.Dial("ws://"+srv.listenAddr(), http.Header{ |
||||
"Content-type": []string{"application/json"}, |
||||
"Sec-WebSocket-Version": []string{"13"}, |
||||
"Origin": []string{"test"}, |
||||
}) |
||||
assert.NoError(t, err) |
||||
|
||||
_, _, err = dialer.Dial("ws://"+srv.listenAddr(), http.Header{ |
||||
"Content-type": []string{"application/json"}, |
||||
"Sec-WebSocket-Version": []string{"13"}, |
||||
"Origin": []string{"bad"}, |
||||
}) |
||||
assert.Error(t, err) |
||||
} |
||||
|
||||
func createAndStartServer(t *testing.T, conf httpConfig, ws bool, wsConf wsConfig) *httpServer { |
||||
t.Helper() |
||||
|
||||
srv := newHTTPServer(testlog.Logger(t, log.LvlDebug), rpc.DefaultHTTPTimeouts) |
||||
|
||||
assert.NoError(t, srv.enableRPC(nil, conf)) |
||||
if ws { |
||||
assert.NoError(t, srv.enableWS(nil, wsConf)) |
||||
} |
||||
assert.NoError(t, srv.setListenAddr("localhost", 0)) |
||||
assert.NoError(t, srv.start()) |
||||
|
||||
return srv |
||||
} |
||||
|
||||
req, _ := http.NewRequest(http.MethodGet, ts.URL, nil) |
||||
req.Header.Set("Connection", "upgrade") |
||||
req.Header.Set("Upgrade", "websocket") |
||||
req.Header.Set("Sec-WebSocket-Version", "13") |
||||
req.Header.Set("Sec-Websocket-Key", "SGVsbG8sIHdvcmxkIQ==") |
||||
func testRequest(t *testing.T, key, value, host string, srv *httpServer) *http.Response { |
||||
t.Helper() |
||||
|
||||
resp, err := client.Do(req) |
||||
if err != nil { |
||||
t.Error("could not issue a GET request to the test http server", err) |
||||
} |
||||
responses <- resp |
||||
}(responses) |
||||
body := bytes.NewReader([]byte(`{"jsonrpc":"2.0","id":1,method":"rpc_modules"}`)) |
||||
req, _ := http.NewRequest("POST", "http://"+srv.listenAddr(), body) |
||||
req.Header.Set("content-type", "application/json") |
||||
if key != "" && value != "" { |
||||
req.Header.Set(key, value) |
||||
} |
||||
if host != "" { |
||||
req.Host = host |
||||
} |
||||
|
||||
response := <-responses |
||||
assert.Equal(t, "websocket", response.Header.Get("Upgrade")) |
||||
client := http.DefaultClient |
||||
resp, err := client.Do(req) |
||||
if err != nil { |
||||
t.Fatal(err) |
||||
} |
||||
return resp |
||||
} |
||||
|
@ -1,122 +0,0 @@ |
||||
// Copyright 2015 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package node |
||||
|
||||
import ( |
||||
"path/filepath" |
||||
"reflect" |
||||
|
||||
"github.com/ethereum/go-ethereum/accounts" |
||||
"github.com/ethereum/go-ethereum/core/rawdb" |
||||
"github.com/ethereum/go-ethereum/ethdb" |
||||
"github.com/ethereum/go-ethereum/event" |
||||
"github.com/ethereum/go-ethereum/p2p" |
||||
"github.com/ethereum/go-ethereum/rpc" |
||||
) |
||||
|
||||
// ServiceContext is a collection of service independent options inherited from
|
||||
// the protocol stack, that is passed to all constructors to be optionally used;
|
||||
// as well as utility methods to operate on the service environment.
|
||||
type ServiceContext struct { |
||||
services map[reflect.Type]Service // Index of the already constructed services
|
||||
Config Config |
||||
EventMux *event.TypeMux // Event multiplexer used for decoupled notifications
|
||||
AccountManager *accounts.Manager // Account manager created by the node.
|
||||
} |
||||
|
||||
// OpenDatabase opens an existing database with the given name (or creates one
|
||||
// if no previous can be found) from within the node's data directory. If the
|
||||
// node is an ephemeral one, a memory database is returned.
|
||||
func (ctx *ServiceContext) OpenDatabase(name string, cache int, handles int, namespace string) (ethdb.Database, error) { |
||||
if ctx.Config.DataDir == "" { |
||||
return rawdb.NewMemoryDatabase(), nil |
||||
} |
||||
return rawdb.NewLevelDBDatabase(ctx.Config.ResolvePath(name), cache, handles, namespace) |
||||
} |
||||
|
||||
// OpenDatabaseWithFreezer opens an existing database with the given name (or
|
||||
// creates one if no previous can be found) from within the node's data directory,
|
||||
// also attaching a chain freezer to it that moves ancient chain data from the
|
||||
// database to immutable append-only files. If the node is an ephemeral one, a
|
||||
// memory database is returned.
|
||||
func (ctx *ServiceContext) OpenDatabaseWithFreezer(name string, cache int, handles int, freezer string, namespace string) (ethdb.Database, error) { |
||||
if ctx.Config.DataDir == "" { |
||||
return rawdb.NewMemoryDatabase(), nil |
||||
} |
||||
root := ctx.Config.ResolvePath(name) |
||||
|
||||
switch { |
||||
case freezer == "": |
||||
freezer = filepath.Join(root, "ancient") |
||||
case !filepath.IsAbs(freezer): |
||||
freezer = ctx.Config.ResolvePath(freezer) |
||||
} |
||||
return rawdb.NewLevelDBDatabaseWithFreezer(root, cache, handles, freezer, namespace) |
||||
} |
||||
|
||||
// ResolvePath resolves a user path into the data directory if that was relative
|
||||
// and if the user actually uses persistent storage. It will return an empty string
|
||||
// for emphemeral storage and the user's own input for absolute paths.
|
||||
func (ctx *ServiceContext) ResolvePath(path string) string { |
||||
return ctx.Config.ResolvePath(path) |
||||
} |
||||
|
||||
// Service retrieves a currently running service registered of a specific type.
|
||||
func (ctx *ServiceContext) Service(service interface{}) error { |
||||
element := reflect.ValueOf(service).Elem() |
||||
if running, ok := ctx.services[element.Type()]; ok { |
||||
element.Set(reflect.ValueOf(running)) |
||||
return nil |
||||
} |
||||
return ErrServiceUnknown |
||||
} |
||||
|
||||
// ExtRPCEnabled returns the indicator whether node enables the external
|
||||
// RPC(http, ws or graphql).
|
||||
func (ctx *ServiceContext) ExtRPCEnabled() bool { |
||||
return ctx.Config.ExtRPCEnabled() |
||||
} |
||||
|
||||
// ServiceConstructor is the function signature of the constructors needed to be
|
||||
// registered for service instantiation.
|
||||
type ServiceConstructor func(ctx *ServiceContext) (Service, error) |
||||
|
||||
// Service is an individual protocol that can be registered into a node.
|
||||
//
|
||||
// Notes:
|
||||
//
|
||||
// • Service life-cycle management is delegated to the node. The service is allowed to
|
||||
// initialize itself upon creation, but no goroutines should be spun up outside of the
|
||||
// Start method.
|
||||
//
|
||||
// • Restart logic is not required as the node will create a fresh instance
|
||||
// every time a service is started.
|
||||
type Service interface { |
||||
// Protocols retrieves the P2P protocols the service wishes to start.
|
||||
Protocols() []p2p.Protocol |
||||
|
||||
// APIs retrieves the list of RPC descriptors the service provides
|
||||
APIs() []rpc.API |
||||
|
||||
// Start is called after all services have been constructed and the networking
|
||||
// layer was also initialized to spawn any goroutines required by the service.
|
||||
Start(server *p2p.Server) error |
||||
|
||||
// Stop terminates all goroutines belonging to the service, blocking until they
|
||||
// are all terminated.
|
||||
Stop() error |
||||
} |
@ -1,98 +0,0 @@ |
||||
// Copyright 2015 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package node |
||||
|
||||
import ( |
||||
"fmt" |
||||
"io/ioutil" |
||||
"os" |
||||
"path/filepath" |
||||
"testing" |
||||
) |
||||
|
||||
// Tests that databases are correctly created persistent or ephemeral based on
|
||||
// the configured service context.
|
||||
func TestContextDatabases(t *testing.T) { |
||||
// Create a temporary folder and ensure no database is contained within
|
||||
dir, err := ioutil.TempDir("", "") |
||||
if err != nil { |
||||
t.Fatalf("failed to create temporary data directory: %v", err) |
||||
} |
||||
defer os.RemoveAll(dir) |
||||
|
||||
if _, err := os.Stat(filepath.Join(dir, "database")); err == nil { |
||||
t.Fatalf("non-created database already exists") |
||||
} |
||||
// Request the opening/creation of a database and ensure it persists to disk
|
||||
ctx := &ServiceContext{Config: Config{Name: "unit-test", DataDir: dir}} |
||||
db, err := ctx.OpenDatabase("persistent", 0, 0, "") |
||||
if err != nil { |
||||
t.Fatalf("failed to open persistent database: %v", err) |
||||
} |
||||
db.Close() |
||||
|
||||
if _, err := os.Stat(filepath.Join(dir, "unit-test", "persistent")); err != nil { |
||||
t.Fatalf("persistent database doesn't exists: %v", err) |
||||
} |
||||
// Request th opening/creation of an ephemeral database and ensure it's not persisted
|
||||
ctx = &ServiceContext{Config: Config{DataDir: ""}} |
||||
db, err = ctx.OpenDatabase("ephemeral", 0, 0, "") |
||||
if err != nil { |
||||
t.Fatalf("failed to open ephemeral database: %v", err) |
||||
} |
||||
db.Close() |
||||
|
||||
if _, err := os.Stat(filepath.Join(dir, "ephemeral")); err == nil { |
||||
t.Fatalf("ephemeral database exists") |
||||
} |
||||
} |
||||
|
||||
// Tests that already constructed services can be retrieves by later ones.
|
||||
func TestContextServices(t *testing.T) { |
||||
stack, err := New(testNodeConfig()) |
||||
if err != nil { |
||||
t.Fatalf("failed to create protocol stack: %v", err) |
||||
} |
||||
defer stack.Close() |
||||
// Define a verifier that ensures a NoopA is before it and NoopB after
|
||||
verifier := func(ctx *ServiceContext) (Service, error) { |
||||
var objA *NoopServiceA |
||||
if ctx.Service(&objA) != nil { |
||||
return nil, fmt.Errorf("former service not found") |
||||
} |
||||
var objB *NoopServiceB |
||||
if err := ctx.Service(&objB); err != ErrServiceUnknown { |
||||
return nil, fmt.Errorf("latters lookup error mismatch: have %v, want %v", err, ErrServiceUnknown) |
||||
} |
||||
return new(NoopService), nil |
||||
} |
||||
// Register the collection of services
|
||||
if err := stack.Register(NewNoopServiceA); err != nil { |
||||
t.Fatalf("former failed to register service: %v", err) |
||||
} |
||||
if err := stack.Register(verifier); err != nil { |
||||
t.Fatalf("failed to register service verifier: %v", err) |
||||
} |
||||
if err := stack.Register(NewNoopServiceB); err != nil { |
||||
t.Fatalf("latter failed to register service: %v", err) |
||||
} |
||||
// Start the protocol stack and ensure services are constructed in order
|
||||
if err := stack.Start(); err != nil { |
||||
t.Fatalf("failed to start stack: %v", err) |
||||
} |
||||
defer stack.Stop() |
||||
} |
@ -1,67 +0,0 @@ |
||||
// Copyright 2018 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package testing |
||||
|
||||
import ( |
||||
"fmt" |
||||
"sync" |
||||
|
||||
"github.com/ethereum/go-ethereum/log" |
||||
"github.com/ethereum/go-ethereum/p2p/enode" |
||||
) |
||||
|
||||
type TestPeer interface { |
||||
ID() enode.ID |
||||
Drop() |
||||
} |
||||
|
||||
// TestPeerPool is an example peerPool to demonstrate registration of peer connections
|
||||
type TestPeerPool struct { |
||||
lock sync.Mutex |
||||
peers map[enode.ID]TestPeer |
||||
} |
||||
|
||||
func NewTestPeerPool() *TestPeerPool { |
||||
return &TestPeerPool{peers: make(map[enode.ID]TestPeer)} |
||||
} |
||||
|
||||
func (p *TestPeerPool) Add(peer TestPeer) { |
||||
p.lock.Lock() |
||||
defer p.lock.Unlock() |
||||
log.Trace(fmt.Sprintf("pp add peer %v", peer.ID())) |
||||
p.peers[peer.ID()] = peer |
||||
|
||||
} |
||||
|
||||
func (p *TestPeerPool) Remove(peer TestPeer) { |
||||
p.lock.Lock() |
||||
defer p.lock.Unlock() |
||||
delete(p.peers, peer.ID()) |
||||
} |
||||
|
||||
func (p *TestPeerPool) Has(id enode.ID) bool { |
||||
p.lock.Lock() |
||||
defer p.lock.Unlock() |
||||
_, ok := p.peers[id] |
||||
return ok |
||||
} |
||||
|
||||
func (p *TestPeerPool) Get(id enode.ID) TestPeer { |
||||
p.lock.Lock() |
||||
defer p.lock.Unlock() |
||||
return p.peers[id] |
||||
} |
@ -1,283 +0,0 @@ |
||||
// Copyright 2018 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package testing |
||||
|
||||
import ( |
||||
"errors" |
||||
"fmt" |
||||
"sync" |
||||
"time" |
||||
|
||||
"github.com/ethereum/go-ethereum/log" |
||||
"github.com/ethereum/go-ethereum/p2p" |
||||
"github.com/ethereum/go-ethereum/p2p/enode" |
||||
"github.com/ethereum/go-ethereum/p2p/simulations/adapters" |
||||
) |
||||
|
||||
var errTimedOut = errors.New("timed out") |
||||
|
||||
// ProtocolSession is a quasi simulation of a pivot node running
|
||||
// a service and a number of dummy peers that can send (trigger) or
|
||||
// receive (expect) messages
|
||||
type ProtocolSession struct { |
||||
Server *p2p.Server |
||||
Nodes []*enode.Node |
||||
adapter *adapters.SimAdapter |
||||
events chan *p2p.PeerEvent |
||||
} |
||||
|
||||
// Exchange is the basic units of protocol tests
|
||||
// the triggers and expects in the arrays are run immediately and asynchronously
|
||||
// thus one cannot have multiple expects for the SAME peer with DIFFERENT message types
|
||||
// because it's unpredictable which expect will receive which message
|
||||
// (with expect #1 and #2, messages might be sent #2 and #1, and both expects will complain about wrong message code)
|
||||
// an exchange is defined on a session
|
||||
type Exchange struct { |
||||
Label string |
||||
Triggers []Trigger |
||||
Expects []Expect |
||||
Timeout time.Duration |
||||
} |
||||
|
||||
// Trigger is part of the exchange, incoming message for the pivot node
|
||||
// sent by a peer
|
||||
type Trigger struct { |
||||
Msg interface{} // type of message to be sent
|
||||
Code uint64 // code of message is given
|
||||
Peer enode.ID // the peer to send the message to
|
||||
Timeout time.Duration // timeout duration for the sending
|
||||
} |
||||
|
||||
// Expect is part of an exchange, outgoing message from the pivot node
|
||||
// received by a peer
|
||||
type Expect struct { |
||||
Msg interface{} // type of message to expect
|
||||
Code uint64 // code of message is now given
|
||||
Peer enode.ID // the peer that expects the message
|
||||
Timeout time.Duration // timeout duration for receiving
|
||||
} |
||||
|
||||
// Disconnect represents a disconnect event, used and checked by TestDisconnected
|
||||
type Disconnect struct { |
||||
Peer enode.ID // discconnected peer
|
||||
Error error // disconnect reason
|
||||
} |
||||
|
||||
// trigger sends messages from peers
|
||||
func (s *ProtocolSession) trigger(trig Trigger) error { |
||||
simNode, ok := s.adapter.GetNode(trig.Peer) |
||||
if !ok { |
||||
return fmt.Errorf("trigger: peer %v does not exist (1- %v)", trig.Peer, len(s.Nodes)) |
||||
} |
||||
mockNode, ok := simNode.Services()[0].(*mockNode) |
||||
if !ok { |
||||
return fmt.Errorf("trigger: peer %v is not a mock", trig.Peer) |
||||
} |
||||
|
||||
errc := make(chan error) |
||||
|
||||
go func() { |
||||
log.Trace(fmt.Sprintf("trigger %v (%v)....", trig.Msg, trig.Code)) |
||||
errc <- mockNode.Trigger(&trig) |
||||
log.Trace(fmt.Sprintf("triggered %v (%v)", trig.Msg, trig.Code)) |
||||
}() |
||||
|
||||
t := trig.Timeout |
||||
if t == time.Duration(0) { |
||||
t = 1000 * time.Millisecond |
||||
} |
||||
select { |
||||
case err := <-errc: |
||||
return err |
||||
case <-time.After(t): |
||||
return fmt.Errorf("timout expecting %v to send to peer %v", trig.Msg, trig.Peer) |
||||
} |
||||
} |
||||
|
||||
// expect checks an expectation of a message sent out by the pivot node
|
||||
func (s *ProtocolSession) expect(exps []Expect) error { |
||||
// construct a map of expectations for each node
|
||||
peerExpects := make(map[enode.ID][]Expect) |
||||
for _, exp := range exps { |
||||
if exp.Msg == nil { |
||||
return errors.New("no message to expect") |
||||
} |
||||
peerExpects[exp.Peer] = append(peerExpects[exp.Peer], exp) |
||||
} |
||||
|
||||
// construct a map of mockNodes for each node
|
||||
mockNodes := make(map[enode.ID]*mockNode) |
||||
for nodeID := range peerExpects { |
||||
simNode, ok := s.adapter.GetNode(nodeID) |
||||
if !ok { |
||||
return fmt.Errorf("trigger: peer %v does not exist (1- %v)", nodeID, len(s.Nodes)) |
||||
} |
||||
mockNode, ok := simNode.Services()[0].(*mockNode) |
||||
if !ok { |
||||
return fmt.Errorf("trigger: peer %v is not a mock", nodeID) |
||||
} |
||||
mockNodes[nodeID] = mockNode |
||||
} |
||||
|
||||
// done chanell cancels all created goroutines when function returns
|
||||
done := make(chan struct{}) |
||||
defer close(done) |
||||
// errc catches the first error from
|
||||
errc := make(chan error) |
||||
|
||||
wg := &sync.WaitGroup{} |
||||
wg.Add(len(mockNodes)) |
||||
for nodeID, mockNode := range mockNodes { |
||||
nodeID := nodeID |
||||
mockNode := mockNode |
||||
go func() { |
||||
defer wg.Done() |
||||
|
||||
// Sum all Expect timeouts to give the maximum
|
||||
// time for all expectations to finish.
|
||||
// mockNode.Expect checks all received messages against
|
||||
// a list of expected messages and timeout for each
|
||||
// of them can not be checked separately.
|
||||
var t time.Duration |
||||
for _, exp := range peerExpects[nodeID] { |
||||
if exp.Timeout == time.Duration(0) { |
||||
t += 2000 * time.Millisecond |
||||
} else { |
||||
t += exp.Timeout |
||||
} |
||||
} |
||||
alarm := time.NewTimer(t) |
||||
defer alarm.Stop() |
||||
|
||||
// expectErrc is used to check if error returned
|
||||
// from mockNode.Expect is not nil and to send it to
|
||||
// errc only in that case.
|
||||
// done channel will be closed when function
|
||||
expectErrc := make(chan error) |
||||
go func() { |
||||
select { |
||||
case expectErrc <- mockNode.Expect(peerExpects[nodeID]...): |
||||
case <-done: |
||||
case <-alarm.C: |
||||
} |
||||
}() |
||||
|
||||
select { |
||||
case err := <-expectErrc: |
||||
if err != nil { |
||||
select { |
||||
case errc <- err: |
||||
case <-done: |
||||
case <-alarm.C: |
||||
errc <- errTimedOut |
||||
} |
||||
} |
||||
case <-done: |
||||
case <-alarm.C: |
||||
errc <- errTimedOut |
||||
} |
||||
|
||||
}() |
||||
} |
||||
|
||||
go func() { |
||||
wg.Wait() |
||||
// close errc when all goroutines finish to return nill err from errc
|
||||
close(errc) |
||||
}() |
||||
|
||||
return <-errc |
||||
} |
||||
|
||||
// TestExchanges tests a series of exchanges against the session
|
||||
func (s *ProtocolSession) TestExchanges(exchanges ...Exchange) error { |
||||
for i, e := range exchanges { |
||||
if err := s.testExchange(e); err != nil { |
||||
return fmt.Errorf("exchange #%d %q: %v", i, e.Label, err) |
||||
} |
||||
log.Trace(fmt.Sprintf("exchange #%d %q: run successfully", i, e.Label)) |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
// testExchange tests a single Exchange.
|
||||
// Default timeout value is 2 seconds.
|
||||
func (s *ProtocolSession) testExchange(e Exchange) error { |
||||
errc := make(chan error) |
||||
done := make(chan struct{}) |
||||
defer close(done) |
||||
|
||||
go func() { |
||||
for _, trig := range e.Triggers { |
||||
err := s.trigger(trig) |
||||
if err != nil { |
||||
errc <- err |
||||
return |
||||
} |
||||
} |
||||
|
||||
select { |
||||
case errc <- s.expect(e.Expects): |
||||
case <-done: |
||||
} |
||||
}() |
||||
|
||||
// time out globally or finish when all expectations satisfied
|
||||
t := e.Timeout |
||||
if t == 0 { |
||||
t = 2000 * time.Millisecond |
||||
} |
||||
alarm := time.NewTimer(t) |
||||
defer alarm.Stop() |
||||
select { |
||||
case err := <-errc: |
||||
return err |
||||
case <-alarm.C: |
||||
return errTimedOut |
||||
} |
||||
} |
||||
|
||||
// TestDisconnected tests the disconnections given as arguments
|
||||
// the disconnect structs describe what disconnect error is expected on which peer
|
||||
func (s *ProtocolSession) TestDisconnected(disconnects ...*Disconnect) error { |
||||
expects := make(map[enode.ID]error) |
||||
for _, disconnect := range disconnects { |
||||
expects[disconnect.Peer] = disconnect.Error |
||||
} |
||||
|
||||
timeout := time.After(time.Second) |
||||
for len(expects) > 0 { |
||||
select { |
||||
case event := <-s.events: |
||||
if event.Type != p2p.PeerEventTypeDrop { |
||||
continue |
||||
} |
||||
expectErr, ok := expects[event.Peer] |
||||
if !ok { |
||||
continue |
||||
} |
||||
|
||||
if !(expectErr == nil && event.Error == "" || expectErr != nil && expectErr.Error() == event.Error) { |
||||
return fmt.Errorf("unexpected error on peer %v. expected '%v', got '%v'", event.Peer, expectErr, event.Error) |
||||
} |
||||
delete(expects, event.Peer) |
||||
case <-timeout: |
||||
return fmt.Errorf("timed out waiting for peers to disconnect") |
||||
} |
||||
} |
||||
return nil |
||||
} |
@ -1,284 +0,0 @@ |
||||
// Copyright 2018 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
/* |
||||
the p2p/testing package provides a unit test scheme to check simple |
||||
protocol message exchanges with one pivot node and a number of dummy peers |
||||
The pivot test node runs a node.Service, the dummy peers run a mock node |
||||
that can be used to send and receive messages |
||||
*/ |
||||
|
||||
package testing |
||||
|
||||
import ( |
||||
"bytes" |
||||
"crypto/ecdsa" |
||||
"fmt" |
||||
"io" |
||||
"io/ioutil" |
||||
"strings" |
||||
"sync" |
||||
|
||||
"github.com/ethereum/go-ethereum/log" |
||||
"github.com/ethereum/go-ethereum/node" |
||||
"github.com/ethereum/go-ethereum/p2p" |
||||
"github.com/ethereum/go-ethereum/p2p/enode" |
||||
"github.com/ethereum/go-ethereum/p2p/simulations" |
||||
"github.com/ethereum/go-ethereum/p2p/simulations/adapters" |
||||
"github.com/ethereum/go-ethereum/rlp" |
||||
"github.com/ethereum/go-ethereum/rpc" |
||||
) |
||||
|
||||
// ProtocolTester is the tester environment used for unit testing protocol
|
||||
// message exchanges. It uses p2p/simulations framework
|
||||
type ProtocolTester struct { |
||||
*ProtocolSession |
||||
network *simulations.Network |
||||
} |
||||
|
||||
// NewProtocolTester constructs a new ProtocolTester
|
||||
// it takes as argument the pivot node id, the number of dummy peers and the
|
||||
// protocol run function called on a peer connection by the p2p server
|
||||
func NewProtocolTester(prvkey *ecdsa.PrivateKey, nodeCount int, run func(*p2p.Peer, p2p.MsgReadWriter) error) *ProtocolTester { |
||||
services := adapters.Services{ |
||||
"test": func(ctx *adapters.ServiceContext) (node.Service, error) { |
||||
return &testNode{run}, nil |
||||
}, |
||||
"mock": func(ctx *adapters.ServiceContext) (node.Service, error) { |
||||
return newMockNode(), nil |
||||
}, |
||||
} |
||||
adapter := adapters.NewSimAdapter(services) |
||||
net := simulations.NewNetwork(adapter, &simulations.NetworkConfig{}) |
||||
nodeConfig := &adapters.NodeConfig{ |
||||
PrivateKey: prvkey, |
||||
EnableMsgEvents: true, |
||||
Services: []string{"test"}, |
||||
} |
||||
if _, err := net.NewNodeWithConfig(nodeConfig); err != nil { |
||||
panic(err.Error()) |
||||
} |
||||
if err := net.Start(nodeConfig.ID); err != nil { |
||||
panic(err.Error()) |
||||
} |
||||
|
||||
node := net.GetNode(nodeConfig.ID).Node.(*adapters.SimNode) |
||||
peers := make([]*adapters.NodeConfig, nodeCount) |
||||
nodes := make([]*enode.Node, nodeCount) |
||||
for i := 0; i < nodeCount; i++ { |
||||
peers[i] = adapters.RandomNodeConfig() |
||||
peers[i].Services = []string{"mock"} |
||||
if _, err := net.NewNodeWithConfig(peers[i]); err != nil { |
||||
panic(fmt.Sprintf("error initializing peer %v: %v", peers[i].ID, err)) |
||||
} |
||||
if err := net.Start(peers[i].ID); err != nil { |
||||
panic(fmt.Sprintf("error starting peer %v: %v", peers[i].ID, err)) |
||||
} |
||||
nodes[i] = peers[i].Node() |
||||
} |
||||
events := make(chan *p2p.PeerEvent, 1000) |
||||
node.SubscribeEvents(events) |
||||
ps := &ProtocolSession{ |
||||
Server: node.Server(), |
||||
Nodes: nodes, |
||||
adapter: adapter, |
||||
events: events, |
||||
} |
||||
self := &ProtocolTester{ |
||||
ProtocolSession: ps, |
||||
network: net, |
||||
} |
||||
|
||||
self.Connect(nodeConfig.ID, peers...) |
||||
|
||||
return self |
||||
} |
||||
|
||||
// Stop stops the p2p server
|
||||
func (t *ProtocolTester) Stop() { |
||||
t.Server.Stop() |
||||
t.network.Shutdown() |
||||
} |
||||
|
||||
// Connect brings up the remote peer node and connects it using the
|
||||
// p2p/simulations network connection with the in memory network adapter
|
||||
func (t *ProtocolTester) Connect(selfID enode.ID, peers ...*adapters.NodeConfig) { |
||||
for _, peer := range peers { |
||||
log.Trace(fmt.Sprintf("connect to %v", peer.ID)) |
||||
if err := t.network.Connect(selfID, peer.ID); err != nil { |
||||
panic(fmt.Sprintf("error connecting to peer %v: %v", peer.ID, err)) |
||||
} |
||||
} |
||||
|
||||
} |
||||
|
||||
// testNode wraps a protocol run function and implements the node.Service
|
||||
// interface
|
||||
type testNode struct { |
||||
run func(*p2p.Peer, p2p.MsgReadWriter) error |
||||
} |
||||
|
||||
func (t *testNode) Protocols() []p2p.Protocol { |
||||
return []p2p.Protocol{{ |
||||
Length: 100, |
||||
Run: t.run, |
||||
}} |
||||
} |
||||
|
||||
func (t *testNode) APIs() []rpc.API { |
||||
return nil |
||||
} |
||||
|
||||
func (t *testNode) Start(server *p2p.Server) error { |
||||
return nil |
||||
} |
||||
|
||||
func (t *testNode) Stop() error { |
||||
return nil |
||||
} |
||||
|
||||
// mockNode is a testNode which doesn't actually run a protocol, instead
|
||||
// exposing channels so that tests can manually trigger and expect certain
|
||||
// messages
|
||||
type mockNode struct { |
||||
testNode |
||||
|
||||
trigger chan *Trigger |
||||
expect chan []Expect |
||||
err chan error |
||||
stop chan struct{} |
||||
stopOnce sync.Once |
||||
} |
||||
|
||||
func newMockNode() *mockNode { |
||||
mock := &mockNode{ |
||||
trigger: make(chan *Trigger), |
||||
expect: make(chan []Expect), |
||||
err: make(chan error), |
||||
stop: make(chan struct{}), |
||||
} |
||||
mock.testNode.run = mock.Run |
||||
return mock |
||||
} |
||||
|
||||
// Run is a protocol run function which just loops waiting for tests to
|
||||
// instruct it to either trigger or expect a message from the peer
|
||||
func (m *mockNode) Run(peer *p2p.Peer, rw p2p.MsgReadWriter) error { |
||||
for { |
||||
select { |
||||
case trig := <-m.trigger: |
||||
wmsg := Wrap(trig.Msg) |
||||
m.err <- p2p.Send(rw, trig.Code, wmsg) |
||||
case exps := <-m.expect: |
||||
m.err <- expectMsgs(rw, exps) |
||||
case <-m.stop: |
||||
return nil |
||||
} |
||||
} |
||||
} |
||||
|
||||
func (m *mockNode) Trigger(trig *Trigger) error { |
||||
m.trigger <- trig |
||||
return <-m.err |
||||
} |
||||
|
||||
func (m *mockNode) Expect(exp ...Expect) error { |
||||
m.expect <- exp |
||||
return <-m.err |
||||
} |
||||
|
||||
func (m *mockNode) Stop() error { |
||||
m.stopOnce.Do(func() { close(m.stop) }) |
||||
return nil |
||||
} |
||||
|
||||
func expectMsgs(rw p2p.MsgReadWriter, exps []Expect) error { |
||||
matched := make([]bool, len(exps)) |
||||
for { |
||||
msg, err := rw.ReadMsg() |
||||
if err != nil { |
||||
if err == io.EOF { |
||||
break |
||||
} |
||||
return err |
||||
} |
||||
actualContent, err := ioutil.ReadAll(msg.Payload) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
var found bool |
||||
for i, exp := range exps { |
||||
if exp.Code == msg.Code && bytes.Equal(actualContent, mustEncodeMsg(Wrap(exp.Msg))) { |
||||
if matched[i] { |
||||
return fmt.Errorf("message #%d received two times", i) |
||||
} |
||||
matched[i] = true |
||||
found = true |
||||
break |
||||
} |
||||
} |
||||
if !found { |
||||
expected := make([]string, 0) |
||||
for i, exp := range exps { |
||||
if matched[i] { |
||||
continue |
||||
} |
||||
expected = append(expected, fmt.Sprintf("code %d payload %x", exp.Code, mustEncodeMsg(Wrap(exp.Msg)))) |
||||
} |
||||
return fmt.Errorf("unexpected message code %d payload %x, expected %s", msg.Code, actualContent, strings.Join(expected, " or ")) |
||||
} |
||||
done := true |
||||
for _, m := range matched { |
||||
if !m { |
||||
done = false |
||||
break |
||||
} |
||||
} |
||||
if done { |
||||
return nil |
||||
} |
||||
} |
||||
for i, m := range matched { |
||||
if !m { |
||||
return fmt.Errorf("expected message #%d not received", i) |
||||
} |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
// mustEncodeMsg uses rlp to encode a message.
|
||||
// In case of error it panics.
|
||||
func mustEncodeMsg(msg interface{}) []byte { |
||||
contentEnc, err := rlp.EncodeToBytes(msg) |
||||
if err != nil { |
||||
panic("content encode error: " + err.Error()) |
||||
} |
||||
return contentEnc |
||||
} |
||||
|
||||
type WrappedMsg struct { |
||||
Context []byte |
||||
Size uint32 |
||||
Payload []byte |
||||
} |
||||
|
||||
func Wrap(msg interface{}) interface{} { |
||||
data, _ := rlp.EncodeToBytes(msg) |
||||
return &WrappedMsg{ |
||||
Size: uint32(len(data)), |
||||
Payload: data, |
||||
} |
||||
} |
Loading…
Reference in new issue