p2p/simulations, p2p/testing: port to p2p/enode

No surprises here, mostly replacements of discover.Node, discover.NodeID
with their new equivalents. The 'interesting' API changes are:

 - testing.ProtocolSession tracks complete nodes, not just their IDs.
 - adapters.NodeConfig has a new method to create a complete node.

These changes were needed to make swarm tests work.

Note that the NodeID change makes the code incompatible with old
simulation snapshots.
This commit is contained in:
Felix Lange 2018-09-11 18:12:14 +02:00
parent 9cd4879228
commit 81f98e8a08
16 changed files with 149 additions and 144 deletions

View file

@ -24,7 +24,7 @@ import (
"time" "time"
"github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/simulations/adapters" "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
p2ptest "github.com/ethereum/go-ethereum/p2p/testing" p2ptest "github.com/ethereum/go-ethereum/p2p/testing"
) )
@ -36,7 +36,7 @@ type hs0 struct {
// message to kill/drop the peer with nodeID // message to kill/drop the peer with nodeID
type kill struct { type kill struct {
C discover.NodeID C enode.ID
} }
// message to drop connection // message to drop connection
@ -144,7 +144,7 @@ func protocolTester(t *testing.T, pp *p2ptest.TestPeerPool) *p2ptest.ProtocolTes
return p2ptest.NewProtocolTester(t, conf.ID, 2, newProtocol(pp)) return p2ptest.NewProtocolTester(t, conf.ID, 2, newProtocol(pp))
} }
func protoHandshakeExchange(id discover.NodeID, proto *protoHandshake) []p2ptest.Exchange { func protoHandshakeExchange(id enode.ID, proto *protoHandshake) []p2ptest.Exchange {
return []p2ptest.Exchange{ return []p2ptest.Exchange{
{ {
@ -172,13 +172,13 @@ func runProtoHandshake(t *testing.T, proto *protoHandshake, errs ...error) {
pp := p2ptest.NewTestPeerPool() pp := p2ptest.NewTestPeerPool()
s := protocolTester(t, pp) s := protocolTester(t, pp)
// TODO: make this more than one handshake // TODO: make this more than one handshake
id := s.IDs[0] node := s.Nodes[0]
if err := s.TestExchanges(protoHandshakeExchange(id, proto)...); err != nil { if err := s.TestExchanges(protoHandshakeExchange(node.ID(), proto)...); err != nil {
t.Fatal(err) t.Fatal(err)
} }
var disconnects []*p2ptest.Disconnect var disconnects []*p2ptest.Disconnect
for i, err := range errs { for i, err := range errs {
disconnects = append(disconnects, &p2ptest.Disconnect{Peer: s.IDs[i], Error: err}) disconnects = append(disconnects, &p2ptest.Disconnect{Peer: s.Nodes[i].ID(), Error: err})
} }
if err := s.TestDisconnected(disconnects...); err != nil { if err := s.TestDisconnected(disconnects...); err != nil {
t.Fatal(err) t.Fatal(err)
@ -197,7 +197,7 @@ func TestProtoHandshakeSuccess(t *testing.T) {
runProtoHandshake(t, &protoHandshake{42, "420"}) runProtoHandshake(t, &protoHandshake{42, "420"})
} }
func moduleHandshakeExchange(id discover.NodeID, resp uint) []p2ptest.Exchange { func moduleHandshakeExchange(id enode.ID, resp uint) []p2ptest.Exchange {
return []p2ptest.Exchange{ return []p2ptest.Exchange{
{ {
@ -224,16 +224,16 @@ func moduleHandshakeExchange(id discover.NodeID, resp uint) []p2ptest.Exchange {
func runModuleHandshake(t *testing.T, resp uint, errs ...error) { func runModuleHandshake(t *testing.T, resp uint, errs ...error) {
pp := p2ptest.NewTestPeerPool() pp := p2ptest.NewTestPeerPool()
s := protocolTester(t, pp) s := protocolTester(t, pp)
id := s.IDs[0] node := s.Nodes[0]
if err := s.TestExchanges(protoHandshakeExchange(id, &protoHandshake{42, "420"})...); err != nil { if err := s.TestExchanges(protoHandshakeExchange(node.ID(), &protoHandshake{42, "420"})...); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := s.TestExchanges(moduleHandshakeExchange(id, resp)...); err != nil { if err := s.TestExchanges(moduleHandshakeExchange(node.ID(), resp)...); err != nil {
t.Fatal(err) t.Fatal(err)
} }
var disconnects []*p2ptest.Disconnect var disconnects []*p2ptest.Disconnect
for i, err := range errs { for i, err := range errs {
disconnects = append(disconnects, &p2ptest.Disconnect{Peer: s.IDs[i], Error: err}) disconnects = append(disconnects, &p2ptest.Disconnect{Peer: s.Nodes[i].ID(), Error: err})
} }
if err := s.TestDisconnected(disconnects...); err != nil { if err := s.TestDisconnected(disconnects...); err != nil {
t.Fatal(err) t.Fatal(err)
@ -249,7 +249,7 @@ func TestModuleHandshakeSuccess(t *testing.T) {
} }
// testing complex interactions over multiple peers, relaying, dropping // testing complex interactions over multiple peers, relaying, dropping
func testMultiPeerSetup(a, b discover.NodeID) []p2ptest.Exchange { func testMultiPeerSetup(a, b enode.ID) []p2ptest.Exchange {
return []p2ptest.Exchange{ return []p2ptest.Exchange{
{ {
@ -305,7 +305,7 @@ func runMultiplePeers(t *testing.T, peer int, errs ...error) {
pp := p2ptest.NewTestPeerPool() pp := p2ptest.NewTestPeerPool()
s := protocolTester(t, pp) s := protocolTester(t, pp)
if err := s.TestExchanges(testMultiPeerSetup(s.IDs[0], s.IDs[1])...); err != nil { if err := s.TestExchanges(testMultiPeerSetup(s.Nodes[0].ID(), s.Nodes[1].ID())...); err != nil {
t.Fatal(err) t.Fatal(err)
} }
// after some exchanges of messages, we can test state changes // after some exchanges of messages, we can test state changes
@ -318,15 +318,15 @@ WAIT:
for { for {
select { select {
case <-tick.C: case <-tick.C:
if pp.Has(s.IDs[0]) { if pp.Has(s.Nodes[0].ID()) {
break WAIT break WAIT
} }
case <-timeout.C: case <-timeout.C:
t.Fatal("timeout") t.Fatal("timeout")
} }
} }
if !pp.Has(s.IDs[1]) { if !pp.Has(s.Nodes[1].ID()) {
t.Fatalf("missing peer test-1: %v (%v)", pp, s.IDs) t.Fatalf("missing peer test-1: %v (%v)", pp, s.Nodes)
} }
// peer 0 sends kill request for peer with index <peer> // peer 0 sends kill request for peer with index <peer>
@ -334,8 +334,8 @@ WAIT:
Triggers: []p2ptest.Trigger{ Triggers: []p2ptest.Trigger{
{ {
Code: 2, Code: 2,
Msg: &kill{s.IDs[peer]}, Msg: &kill{s.Nodes[peer].ID()},
Peer: s.IDs[0], Peer: s.Nodes[0].ID(),
}, },
}, },
}) })
@ -350,7 +350,7 @@ WAIT:
{ {
Code: 3, Code: 3,
Msg: &drop{}, Msg: &drop{},
Peer: s.IDs[(peer+1)%2], Peer: s.Nodes[(peer+1)%2].ID(),
}, },
}, },
}) })
@ -362,14 +362,14 @@ WAIT:
// check the actual discconnect errors on the individual peers // check the actual discconnect errors on the individual peers
var disconnects []*p2ptest.Disconnect var disconnects []*p2ptest.Disconnect
for i, err := range errs { for i, err := range errs {
disconnects = append(disconnects, &p2ptest.Disconnect{Peer: s.IDs[i], Error: err}) disconnects = append(disconnects, &p2ptest.Disconnect{Peer: s.Nodes[i].ID(), Error: err})
} }
if err := s.TestDisconnected(disconnects...); err != nil { if err := s.TestDisconnected(disconnects...); err != nil {
t.Fatal(err) t.Fatal(err)
} }
// test if disconnected peers have been removed from peerPool // test if disconnected peers have been removed from peerPool
if pp.Has(s.IDs[peer]) { if pp.Has(s.Nodes[peer].ID()) {
t.Fatalf("peer test-%v not dropped: %v (%v)", peer, pp, s.IDs) t.Fatalf("peer test-%v not dropped: %v (%v)", peer, pp, s.Nodes)
} }
} }

View file

@ -29,7 +29,7 @@ import (
"github.com/docker/docker/pkg/reexec" "github.com/docker/docker/pkg/reexec"
"github.com/ethereum/go-ethereum/node" "github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/enode"
) )
var ( var (
@ -64,7 +64,7 @@ func NewDockerAdapter() (*DockerAdapter, error) {
return &DockerAdapter{ return &DockerAdapter{
ExecAdapter{ ExecAdapter{
nodes: make(map[discover.NodeID]*ExecNode), nodes: make(map[enode.ID]*ExecNode),
}, },
}, nil }, nil
} }

View file

@ -38,7 +38,7 @@ import (
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/node" "github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"golang.org/x/net/websocket" "golang.org/x/net/websocket"
) )
@ -54,7 +54,7 @@ type ExecAdapter struct {
// simulation node are created. // simulation node are created.
BaseDir string BaseDir string
nodes map[discover.NodeID]*ExecNode nodes map[enode.ID]*ExecNode
} }
// NewExecAdapter returns an ExecAdapter which stores node data in // NewExecAdapter returns an ExecAdapter which stores node data in
@ -62,7 +62,7 @@ type ExecAdapter struct {
func NewExecAdapter(baseDir string) *ExecAdapter { func NewExecAdapter(baseDir string) *ExecAdapter {
return &ExecAdapter{ return &ExecAdapter{
BaseDir: baseDir, BaseDir: baseDir,
nodes: make(map[discover.NodeID]*ExecNode), nodes: make(map[enode.ID]*ExecNode),
} }
} }
@ -122,7 +122,7 @@ func (e *ExecAdapter) NewNode(config *NodeConfig) (Node, error) {
// ExecNode starts a simulation node by exec'ing the current binary and // ExecNode starts a simulation node by exec'ing the current binary and
// running the configured services // running the configured services
type ExecNode struct { type ExecNode struct {
ID discover.NodeID ID enode.ID
Dir string Dir string
Config *execNodeConfig Config *execNodeConfig
Cmd *exec.Cmd Cmd *exec.Cmd
@ -492,7 +492,7 @@ type wsRPCDialer struct {
// DialRPC implements the RPCDialer interface by creating a WebSocket RPC // DialRPC implements the RPCDialer interface by creating a WebSocket RPC
// client of the given node // client of the given node
func (w *wsRPCDialer) DialRPC(id discover.NodeID) (*rpc.Client, error) { func (w *wsRPCDialer) DialRPC(id enode.ID) (*rpc.Client, error) {
addr, ok := w.addrs[id.String()] addr, ok := w.addrs[id.String()]
if !ok { if !ok {
return nil, fmt.Errorf("unknown node: %s", id) return nil, fmt.Errorf("unknown node: %s", id)

View file

@ -27,7 +27,7 @@ import (
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/node" "github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/simulations/pipes" "github.com/ethereum/go-ethereum/p2p/simulations/pipes"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
) )
@ -37,7 +37,7 @@ import (
type SimAdapter struct { type SimAdapter struct {
pipe func() (net.Conn, net.Conn, error) pipe func() (net.Conn, net.Conn, error)
mtx sync.RWMutex mtx sync.RWMutex
nodes map[discover.NodeID]*SimNode nodes map[enode.ID]*SimNode
services map[string]ServiceFunc services map[string]ServiceFunc
} }
@ -48,7 +48,7 @@ type SimAdapter struct {
func NewSimAdapter(services map[string]ServiceFunc) *SimAdapter { func NewSimAdapter(services map[string]ServiceFunc) *SimAdapter {
return &SimAdapter{ return &SimAdapter{
pipe: pipes.NetPipe, pipe: pipes.NetPipe,
nodes: make(map[discover.NodeID]*SimNode), nodes: make(map[enode.ID]*SimNode),
services: services, services: services,
} }
} }
@ -56,7 +56,7 @@ func NewSimAdapter(services map[string]ServiceFunc) *SimAdapter {
func NewTCPAdapter(services map[string]ServiceFunc) *SimAdapter { func NewTCPAdapter(services map[string]ServiceFunc) *SimAdapter {
return &SimAdapter{ return &SimAdapter{
pipe: pipes.TCPPipe, pipe: pipes.TCPPipe,
nodes: make(map[discover.NodeID]*SimNode), nodes: make(map[enode.ID]*SimNode),
services: services, services: services,
} }
} }
@ -115,14 +115,14 @@ func (s *SimAdapter) NewNode(config *NodeConfig) (Node, error) {
// Dial implements the p2p.NodeDialer interface by connecting to the node using // Dial implements the p2p.NodeDialer interface by connecting to the node using
// an in-memory net.Pipe // an in-memory net.Pipe
func (s *SimAdapter) Dial(dest *discover.Node) (conn net.Conn, err error) { func (s *SimAdapter) Dial(dest *enode.Node) (conn net.Conn, err error) {
node, ok := s.GetNode(dest.ID) node, ok := s.GetNode(dest.ID())
if !ok { if !ok {
return nil, fmt.Errorf("unknown node: %s", dest.ID) return nil, fmt.Errorf("unknown node: %s", dest.ID())
} }
srv := node.Server() srv := node.Server()
if srv == nil { if srv == nil {
return nil, fmt.Errorf("node not running: %s", dest.ID) return nil, fmt.Errorf("node not running: %s", dest.ID())
} }
// SimAdapter.pipe is net.Pipe (NewSimAdapter) // SimAdapter.pipe is net.Pipe (NewSimAdapter)
pipe1, pipe2, err := s.pipe() pipe1, pipe2, err := s.pipe()
@ -138,7 +138,7 @@ func (s *SimAdapter) Dial(dest *discover.Node) (conn net.Conn, err error) {
// DialRPC implements the RPCDialer interface by creating an in-memory RPC // DialRPC implements the RPCDialer interface by creating an in-memory RPC
// client of the given node // client of the given node
func (s *SimAdapter) DialRPC(id discover.NodeID) (*rpc.Client, error) { func (s *SimAdapter) DialRPC(id enode.ID) (*rpc.Client, error) {
node, ok := s.GetNode(id) node, ok := s.GetNode(id)
if !ok { if !ok {
return nil, fmt.Errorf("unknown node: %s", id) return nil, fmt.Errorf("unknown node: %s", id)
@ -151,7 +151,7 @@ func (s *SimAdapter) DialRPC(id discover.NodeID) (*rpc.Client, error) {
} }
// GetNode returns the node with the given ID if it exists // GetNode returns the node with the given ID if it exists
func (s *SimAdapter) GetNode(id discover.NodeID) (*SimNode, bool) { func (s *SimAdapter) GetNode(id enode.ID) (*SimNode, bool) {
s.mtx.RLock() s.mtx.RLock()
defer s.mtx.RUnlock() defer s.mtx.RUnlock()
node, ok := s.nodes[id] node, ok := s.nodes[id]
@ -163,7 +163,7 @@ func (s *SimAdapter) GetNode(id discover.NodeID) (*SimNode, bool) {
// pipe // pipe
type SimNode struct { type SimNode struct {
lock sync.RWMutex lock sync.RWMutex
ID discover.NodeID ID enode.ID
config *NodeConfig config *NodeConfig
adapter *SimAdapter adapter *SimAdapter
node *node.Node node *node.Node
@ -177,9 +177,9 @@ func (sn *SimNode) Addr() []byte {
return []byte(sn.Node().String()) return []byte(sn.Node().String())
} }
// Node returns a discover.Node representing the SimNode // Node returns a node descriptor representing the SimNode
func (sn *SimNode) Node() *discover.Node { func (sn *SimNode) Node() *enode.Node {
return discover.NewNode(sn.ID, net.IP{127, 0, 0, 1}, 30303, 30303) return sn.config.Node()
} }
// Client returns an rpc.Client which can be used to communicate with the // Client returns an rpc.Client which can be used to communicate with the

View file

@ -29,7 +29,7 @@ import (
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/node" "github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
) )
@ -78,7 +78,7 @@ type NodeAdapter interface {
type NodeConfig struct { type NodeConfig struct {
// ID is the node's ID which is used to identify the node in the // ID is the node's ID which is used to identify the node in the
// simulation network // simulation network
ID discover.NodeID ID enode.ID
// PrivateKey is the node's private key which is used by the devp2p // PrivateKey is the node's private key which is used by the devp2p
// stack to encrypt communications // stack to encrypt communications
@ -97,7 +97,7 @@ type NodeConfig struct {
Services []string Services []string
// function to sanction or prevent suggesting a peer // function to sanction or prevent suggesting a peer
Reachable func(id discover.NodeID) bool Reachable func(id enode.ID) bool
Port uint16 Port uint16
} }
@ -138,11 +138,9 @@ func (n *NodeConfig) UnmarshalJSON(data []byte) error {
} }
if confJSON.ID != "" { if confJSON.ID != "" {
nodeID, err := discover.HexID(confJSON.ID) if err := n.ID.UnmarshalText([]byte(confJSON.ID)); err != nil {
if err != nil {
return err return err
} }
n.ID = nodeID
} }
if confJSON.PrivateKey != "" { if confJSON.PrivateKey != "" {
@ -165,6 +163,11 @@ func (n *NodeConfig) UnmarshalJSON(data []byte) error {
return nil return nil
} }
// Node returns the node descriptor represented by the config.
func (n *NodeConfig) Node() *enode.Node {
return enode.NewV4(&n.PrivateKey.PublicKey, net.IP{127, 0, 0, 1}, int(n.Port), int(n.Port))
}
// RandomNodeConfig returns node configuration with a randomly generated ID and // RandomNodeConfig returns node configuration with a randomly generated ID and
// PrivateKey // PrivateKey
func RandomNodeConfig() *NodeConfig { func RandomNodeConfig() *NodeConfig {
@ -173,7 +176,7 @@ func RandomNodeConfig() *NodeConfig {
panic("unable to generate key") panic("unable to generate key")
} }
id := discover.PubkeyID(&key.PublicKey) id := enode.PubkeyToIDV4(&key.PublicKey)
port, err := assignTCPPort() port, err := assignTCPPort()
if err != nil { if err != nil {
panic("unable to assign tcp port") panic("unable to assign tcp port")
@ -218,7 +221,7 @@ type ServiceContext struct {
// other nodes in the network (for example a simulated Swarm node which needs // other nodes in the network (for example a simulated Swarm node which needs
// to connect to a Geth node to resolve ENS names) // to connect to a Geth node to resolve ENS names)
type RPCDialer interface { type RPCDialer interface {
DialRPC(id discover.NodeID) (*rpc.Client, error) DialRPC(id enode.ID) (*rpc.Client, error)
} }
// Services is a collection of services which can be run in a simulation // Services is a collection of services which can be run in a simulation

View file

@ -28,7 +28,7 @@ import (
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/node" "github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/simulations" "github.com/ethereum/go-ethereum/p2p/simulations"
"github.com/ethereum/go-ethereum/p2p/simulations/adapters" "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
@ -96,12 +96,12 @@ func main() {
// sends a ping to all its connected peers every 10s and receives a pong in // sends a ping to all its connected peers every 10s and receives a pong in
// return // return
type pingPongService struct { type pingPongService struct {
id discover.NodeID id enode.ID
log log.Logger log log.Logger
received int64 received int64
} }
func newPingPongService(id discover.NodeID) *pingPongService { func newPingPongService(id enode.ID) *pingPongService {
return &pingPongService{ return &pingPongService{
id: id, id: id,
log: log.New("node.id", id), log: log.New("node.id", id),

View file

@ -31,7 +31,7 @@ import (
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/simulations/adapters" "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"github.com/julienschmidt/httprouter" "github.com/julienschmidt/httprouter"
@ -709,8 +709,9 @@ func (s *Server) wrapHandler(handler http.HandlerFunc) httprouter.Handle {
ctx := context.Background() ctx := context.Background()
if id := params.ByName("nodeid"); id != "" { if id := params.ByName("nodeid"); id != "" {
var nodeID enode.ID
var node *Node var node *Node
if nodeID, err := discover.HexID(id); err == nil { if nodeID.UnmarshalText([]byte(id)) == nil {
node = s.network.GetNode(nodeID) node = s.network.GetNode(nodeID)
} else { } else {
node = s.network.GetNodeByName(id) node = s.network.GetNodeByName(id)
@ -723,8 +724,9 @@ func (s *Server) wrapHandler(handler http.HandlerFunc) httprouter.Handle {
} }
if id := params.ByName("peerid"); id != "" { if id := params.ByName("peerid"); id != "" {
var peerID enode.ID
var peer *Node var peer *Node
if peerID, err := discover.HexID(id); err == nil { if peerID.UnmarshalText([]byte(id)) == nil {
peer = s.network.GetNode(peerID) peer = s.network.GetNode(peerID)
} else { } else {
peer = s.network.GetNodeByName(id) peer = s.network.GetNodeByName(id)

View file

@ -30,7 +30,7 @@ import (
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/node" "github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/simulations/adapters" "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
) )
@ -38,12 +38,12 @@ import (
// testService implements the node.Service interface and provides protocols // testService implements the node.Service interface and provides protocols
// and APIs which are useful for testing nodes in a simulation network // and APIs which are useful for testing nodes in a simulation network
type testService struct { type testService struct {
id discover.NodeID id enode.ID
// peerCount is incremented once a peer handshake has been performed // peerCount is incremented once a peer handshake has been performed
peerCount int64 peerCount int64
peers map[discover.NodeID]*testPeer peers map[enode.ID]*testPeer
peersMtx sync.Mutex peersMtx sync.Mutex
// state stores []byte which is used to test creating and loading // state stores []byte which is used to test creating and loading
@ -54,7 +54,7 @@ type testService struct {
func newTestService(ctx *adapters.ServiceContext) (node.Service, error) { func newTestService(ctx *adapters.ServiceContext) (node.Service, error) {
svc := &testService{ svc := &testService{
id: ctx.Config.ID, id: ctx.Config.ID,
peers: make(map[discover.NodeID]*testPeer), peers: make(map[enode.ID]*testPeer),
} }
svc.state.Store(ctx.Snapshot) svc.state.Store(ctx.Snapshot)
return svc, nil return svc, nil
@ -65,7 +65,7 @@ type testPeer struct {
dumReady chan struct{} dumReady chan struct{}
} }
func (t *testService) peer(id discover.NodeID) *testPeer { func (t *testService) peer(id enode.ID) *testPeer {
t.peersMtx.Lock() t.peersMtx.Lock()
defer t.peersMtx.Unlock() defer t.peersMtx.Unlock()
if peer, ok := t.peers[id]; ok { if peer, ok := t.peers[id]; ok {
@ -410,7 +410,7 @@ func (t *expectEvents) nodeEvent(id string, up bool) *Event {
Type: EventTypeNode, Type: EventTypeNode,
Node: &Node{ Node: &Node{
Config: &adapters.NodeConfig{ Config: &adapters.NodeConfig{
ID: discover.MustHexID(id), ID: enode.HexID(id),
}, },
Up: up, Up: up,
}, },
@ -421,8 +421,8 @@ func (t *expectEvents) connEvent(one, other string, up bool) *Event {
return &Event{ return &Event{
Type: EventTypeConn, Type: EventTypeConn,
Conn: &Conn{ Conn: &Conn{
One: discover.MustHexID(one), One: enode.HexID(one),
Other: discover.MustHexID(other), Other: enode.HexID(other),
Up: up, Up: up,
}, },
} }

View file

@ -25,7 +25,7 @@ import (
"time" "time"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/simulations/adapters" "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
) )
@ -154,7 +154,7 @@ func probabilistic(net *Network, quit chan struct{}, nodeCount int) {
wg.Done() wg.Done()
continue continue
} }
go func(id discover.NodeID) { go func(id enode.ID) {
time.Sleep(randWait) time.Sleep(randWait)
err := net.Start(id) err := net.Start(id)
if err != nil { if err != nil {
@ -169,8 +169,8 @@ func probabilistic(net *Network, quit chan struct{}, nodeCount int) {
} }
//connect nodeCount number of nodes in a ring //connect nodeCount number of nodes in a ring
func connectNodesInRing(net *Network, nodeCount int) ([]discover.NodeID, error) { func connectNodesInRing(net *Network, nodeCount int) ([]enode.ID, error) {
ids := make([]discover.NodeID, nodeCount) ids := make([]enode.ID, nodeCount)
for i := 0; i < nodeCount; i++ { for i := 0; i < nodeCount; i++ {
conf := adapters.RandomNodeConfig() conf := adapters.RandomNodeConfig()
node, err := net.NewNodeWithConfig(conf) node, err := net.NewNodeWithConfig(conf)

View file

@ -27,7 +27,7 @@ import (
"testing" "testing"
"time" "time"
"github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/enode"
) )
func TestMocker(t *testing.T) { func TestMocker(t *testing.T) {
@ -82,7 +82,7 @@ func TestMocker(t *testing.T) {
defer sub.Unsubscribe() defer sub.Unsubscribe()
//wait until all nodes are started and connected //wait until all nodes are started and connected
//store every node up event in a map (value is irrelevant, mimic Set datatype) //store every node up event in a map (value is irrelevant, mimic Set datatype)
nodemap := make(map[discover.NodeID]bool) nodemap := make(map[enode.ID]bool)
wg.Add(1) wg.Add(1)
nodesComplete := false nodesComplete := false
connCount := 0 connCount := 0

View file

@ -27,7 +27,7 @@ import (
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/simulations/adapters" "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
) )
@ -51,7 +51,7 @@ type Network struct {
NetworkConfig NetworkConfig
Nodes []*Node `json:"nodes"` Nodes []*Node `json:"nodes"`
nodeMap map[discover.NodeID]int nodeMap map[enode.ID]int
Conns []*Conn `json:"conns"` Conns []*Conn `json:"conns"`
connMap map[string]int connMap map[string]int
@ -67,7 +67,7 @@ func NewNetwork(nodeAdapter adapters.NodeAdapter, conf *NetworkConfig) *Network
return &Network{ return &Network{
NetworkConfig: *conf, NetworkConfig: *conf,
nodeAdapter: nodeAdapter, nodeAdapter: nodeAdapter,
nodeMap: make(map[discover.NodeID]int), nodeMap: make(map[enode.ID]int),
connMap: make(map[string]int), connMap: make(map[string]int),
quitc: make(chan struct{}), quitc: make(chan struct{}),
} }
@ -85,7 +85,7 @@ func (net *Network) NewNodeWithConfig(conf *adapters.NodeConfig) (*Node, error)
defer net.lock.Unlock() defer net.lock.Unlock()
if conf.Reachable == nil { if conf.Reachable == nil {
conf.Reachable = func(otherID discover.NodeID) bool { conf.Reachable = func(otherID enode.ID) bool {
_, err := net.InitConn(conf.ID, otherID) _, err := net.InitConn(conf.ID, otherID)
if err != nil && bytes.Compare(conf.ID.Bytes(), otherID.Bytes()) < 0 { if err != nil && bytes.Compare(conf.ID.Bytes(), otherID.Bytes()) < 0 {
return false return false
@ -158,13 +158,13 @@ func (net *Network) StopAll() error {
} }
// Start starts the node with the given ID // Start starts the node with the given ID
func (net *Network) Start(id discover.NodeID) error { func (net *Network) Start(id enode.ID) error {
return net.startWithSnapshots(id, nil) return net.startWithSnapshots(id, nil)
} }
// startWithSnapshots starts the node with the given ID using the give // startWithSnapshots starts the node with the given ID using the give
// snapshots // snapshots
func (net *Network) startWithSnapshots(id discover.NodeID, snapshots map[string][]byte) error { func (net *Network) startWithSnapshots(id enode.ID, snapshots map[string][]byte) error {
net.lock.Lock() net.lock.Lock()
defer net.lock.Unlock() defer net.lock.Unlock()
node := net.getNode(id) node := net.getNode(id)
@ -200,7 +200,7 @@ func (net *Network) startWithSnapshots(id discover.NodeID, snapshots map[string]
// watchPeerEvents reads peer events from the given channel and emits // watchPeerEvents reads peer events from the given channel and emits
// corresponding network events // corresponding network events
func (net *Network) watchPeerEvents(id discover.NodeID, events chan *p2p.PeerEvent, sub event.Subscription) { func (net *Network) watchPeerEvents(id enode.ID, events chan *p2p.PeerEvent, sub event.Subscription) {
defer func() { defer func() {
sub.Unsubscribe() sub.Unsubscribe()
@ -248,7 +248,7 @@ func (net *Network) watchPeerEvents(id discover.NodeID, events chan *p2p.PeerEve
} }
// Stop stops the node with the given ID // Stop stops the node with the given ID
func (net *Network) Stop(id discover.NodeID) error { func (net *Network) Stop(id enode.ID) error {
net.lock.Lock() net.lock.Lock()
defer net.lock.Unlock() defer net.lock.Unlock()
node := net.getNode(id) node := net.getNode(id)
@ -270,7 +270,7 @@ func (net *Network) Stop(id discover.NodeID) error {
// Connect connects two nodes together by calling the "admin_addPeer" RPC // Connect connects two nodes together by calling the "admin_addPeer" RPC
// method on the "one" node so that it connects to the "other" node // method on the "one" node so that it connects to the "other" node
func (net *Network) Connect(oneID, otherID discover.NodeID) error { func (net *Network) Connect(oneID, otherID enode.ID) error {
log.Debug(fmt.Sprintf("connecting %s to %s", oneID, otherID)) log.Debug(fmt.Sprintf("connecting %s to %s", oneID, otherID))
conn, err := net.InitConn(oneID, otherID) conn, err := net.InitConn(oneID, otherID)
if err != nil { if err != nil {
@ -286,7 +286,7 @@ func (net *Network) Connect(oneID, otherID discover.NodeID) error {
// Disconnect disconnects two nodes by calling the "admin_removePeer" RPC // Disconnect disconnects two nodes by calling the "admin_removePeer" RPC
// method on the "one" node so that it disconnects from the "other" node // method on the "one" node so that it disconnects from the "other" node
func (net *Network) Disconnect(oneID, otherID discover.NodeID) error { func (net *Network) Disconnect(oneID, otherID enode.ID) error {
conn := net.GetConn(oneID, otherID) conn := net.GetConn(oneID, otherID)
if conn == nil { if conn == nil {
return fmt.Errorf("connection between %v and %v does not exist", oneID, otherID) return fmt.Errorf("connection between %v and %v does not exist", oneID, otherID)
@ -303,7 +303,7 @@ func (net *Network) Disconnect(oneID, otherID discover.NodeID) error {
} }
// DidConnect tracks the fact that the "one" node connected to the "other" node // DidConnect tracks the fact that the "one" node connected to the "other" node
func (net *Network) DidConnect(one, other discover.NodeID) error { func (net *Network) DidConnect(one, other enode.ID) error {
net.lock.Lock() net.lock.Lock()
defer net.lock.Unlock() defer net.lock.Unlock()
conn, err := net.getOrCreateConn(one, other) conn, err := net.getOrCreateConn(one, other)
@ -320,7 +320,7 @@ func (net *Network) DidConnect(one, other discover.NodeID) error {
// DidDisconnect tracks the fact that the "one" node disconnected from the // DidDisconnect tracks the fact that the "one" node disconnected from the
// "other" node // "other" node
func (net *Network) DidDisconnect(one, other discover.NodeID) error { func (net *Network) DidDisconnect(one, other enode.ID) error {
net.lock.Lock() net.lock.Lock()
defer net.lock.Unlock() defer net.lock.Unlock()
conn := net.getConn(one, other) conn := net.getConn(one, other)
@ -337,7 +337,7 @@ func (net *Network) DidDisconnect(one, other discover.NodeID) error {
} }
// DidSend tracks the fact that "sender" sent a message to "receiver" // DidSend tracks the fact that "sender" sent a message to "receiver"
func (net *Network) DidSend(sender, receiver discover.NodeID, proto string, code uint64) error { func (net *Network) DidSend(sender, receiver enode.ID, proto string, code uint64) error {
msg := &Msg{ msg := &Msg{
One: sender, One: sender,
Other: receiver, Other: receiver,
@ -350,7 +350,7 @@ func (net *Network) DidSend(sender, receiver discover.NodeID, proto string, code
} }
// DidReceive tracks the fact that "receiver" received a message from "sender" // DidReceive tracks the fact that "receiver" received a message from "sender"
func (net *Network) DidReceive(sender, receiver discover.NodeID, proto string, code uint64) error { func (net *Network) DidReceive(sender, receiver enode.ID, proto string, code uint64) error {
msg := &Msg{ msg := &Msg{
One: sender, One: sender,
Other: receiver, Other: receiver,
@ -364,7 +364,7 @@ func (net *Network) DidReceive(sender, receiver discover.NodeID, proto string, c
// GetNode gets the node with the given ID, returning nil if the node does not // GetNode gets the node with the given ID, returning nil if the node does not
// exist // exist
func (net *Network) GetNode(id discover.NodeID) *Node { func (net *Network) GetNode(id enode.ID) *Node {
net.lock.Lock() net.lock.Lock()
defer net.lock.Unlock() defer net.lock.Unlock()
return net.getNode(id) return net.getNode(id)
@ -387,7 +387,7 @@ func (net *Network) GetNodes() (nodes []*Node) {
return nodes return nodes
} }
func (net *Network) getNode(id discover.NodeID) *Node { func (net *Network) getNode(id enode.ID) *Node {
i, found := net.nodeMap[id] i, found := net.nodeMap[id]
if !found { if !found {
return nil return nil
@ -406,7 +406,7 @@ func (net *Network) getNodeByName(name string) *Node {
// GetConn returns the connection which exists between "one" and "other" // GetConn returns the connection which exists between "one" and "other"
// regardless of which node initiated the connection // regardless of which node initiated the connection
func (net *Network) GetConn(oneID, otherID discover.NodeID) *Conn { func (net *Network) GetConn(oneID, otherID enode.ID) *Conn {
net.lock.Lock() net.lock.Lock()
defer net.lock.Unlock() defer net.lock.Unlock()
return net.getConn(oneID, otherID) return net.getConn(oneID, otherID)
@ -414,13 +414,13 @@ func (net *Network) GetConn(oneID, otherID discover.NodeID) *Conn {
// GetOrCreateConn is like GetConn but creates the connection if it doesn't // GetOrCreateConn is like GetConn but creates the connection if it doesn't
// already exist // already exist
func (net *Network) GetOrCreateConn(oneID, otherID discover.NodeID) (*Conn, error) { func (net *Network) GetOrCreateConn(oneID, otherID enode.ID) (*Conn, error) {
net.lock.Lock() net.lock.Lock()
defer net.lock.Unlock() defer net.lock.Unlock()
return net.getOrCreateConn(oneID, otherID) return net.getOrCreateConn(oneID, otherID)
} }
func (net *Network) getOrCreateConn(oneID, otherID discover.NodeID) (*Conn, error) { func (net *Network) getOrCreateConn(oneID, otherID enode.ID) (*Conn, error) {
if conn := net.getConn(oneID, otherID); conn != nil { if conn := net.getConn(oneID, otherID); conn != nil {
return conn, nil return conn, nil
} }
@ -445,7 +445,7 @@ func (net *Network) getOrCreateConn(oneID, otherID discover.NodeID) (*Conn, erro
return conn, nil return conn, nil
} }
func (net *Network) getConn(oneID, otherID discover.NodeID) *Conn { func (net *Network) getConn(oneID, otherID enode.ID) *Conn {
label := ConnLabel(oneID, otherID) label := ConnLabel(oneID, otherID)
i, found := net.connMap[label] i, found := net.connMap[label]
if !found { if !found {
@ -462,7 +462,7 @@ func (net *Network) getConn(oneID, otherID discover.NodeID) *Conn {
// it also checks whether there has been recent attempt to connect the peers // it also checks whether there has been recent attempt to connect the peers
// this is cheating as the simulation is used as an oracle and know about // this is cheating as the simulation is used as an oracle and know about
// remote peers attempt to connect to a node which will then not initiate the connection // remote peers attempt to connect to a node which will then not initiate the connection
func (net *Network) InitConn(oneID, otherID discover.NodeID) (*Conn, error) { func (net *Network) InitConn(oneID, otherID enode.ID) (*Conn, error) {
net.lock.Lock() net.lock.Lock()
defer net.lock.Unlock() defer net.lock.Unlock()
if oneID == otherID { if oneID == otherID {
@ -508,7 +508,7 @@ func (net *Network) Reset() {
//re-initialize the maps //re-initialize the maps
net.connMap = make(map[string]int) net.connMap = make(map[string]int)
net.nodeMap = make(map[discover.NodeID]int) net.nodeMap = make(map[enode.ID]int)
net.Nodes = nil net.Nodes = nil
net.Conns = nil net.Conns = nil
@ -527,7 +527,7 @@ type Node struct {
} }
// ID returns the ID of the node // ID returns the ID of the node
func (n *Node) ID() discover.NodeID { func (n *Node) ID() enode.ID {
return n.Config.ID return n.Config.ID
} }
@ -564,10 +564,10 @@ func (n *Node) MarshalJSON() ([]byte, error) {
// Conn represents a connection between two nodes in the network // Conn represents a connection between two nodes in the network
type Conn struct { type Conn struct {
// One is the node which initiated the connection // One is the node which initiated the connection
One discover.NodeID `json:"one"` One enode.ID `json:"one"`
// Other is the node which the connection was made to // Other is the node which the connection was made to
Other discover.NodeID `json:"other"` Other enode.ID `json:"other"`
// Up tracks whether or not the connection is active // Up tracks whether or not the connection is active
Up bool `json:"up"` Up bool `json:"up"`
@ -596,8 +596,8 @@ func (c *Conn) String() string {
// Msg represents a p2p message sent between two nodes in the network // Msg represents a p2p message sent between two nodes in the network
type Msg struct { type Msg struct {
One discover.NodeID `json:"one"` One enode.ID `json:"one"`
Other discover.NodeID `json:"other"` Other enode.ID `json:"other"`
Protocol string `json:"protocol"` Protocol string `json:"protocol"`
Code uint64 `json:"code"` Code uint64 `json:"code"`
Received bool `json:"received"` Received bool `json:"received"`
@ -611,8 +611,8 @@ func (m *Msg) String() string {
// ConnLabel generates a deterministic string which represents a connection // ConnLabel generates a deterministic string which represents a connection
// between two nodes, used to compare if two connections are between the same // between two nodes, used to compare if two connections are between the same
// nodes // nodes
func ConnLabel(source, target discover.NodeID) string { func ConnLabel(source, target enode.ID) string {
var first, second discover.NodeID var first, second enode.ID
if bytes.Compare(source.Bytes(), target.Bytes()) > 0 { if bytes.Compare(source.Bytes(), target.Bytes()) > 0 {
first = target first = target
second = source second = source

View file

@ -22,7 +22,7 @@ import (
"testing" "testing"
"time" "time"
"github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/simulations/adapters" "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
) )
@ -39,7 +39,7 @@ func TestNetworkSimulation(t *testing.T) {
}) })
defer network.Shutdown() defer network.Shutdown()
nodeCount := 20 nodeCount := 20
ids := make([]discover.NodeID, nodeCount) ids := make([]enode.ID, nodeCount)
for i := 0; i < nodeCount; i++ { for i := 0; i < nodeCount; i++ {
conf := adapters.RandomNodeConfig() conf := adapters.RandomNodeConfig()
node, err := network.NewNodeWithConfig(conf) node, err := network.NewNodeWithConfig(conf)
@ -64,7 +64,7 @@ func TestNetworkSimulation(t *testing.T) {
} }
return nil return nil
} }
check := func(ctx context.Context, id discover.NodeID) (bool, error) { check := func(ctx context.Context, id enode.ID) (bool, error) {
// check we haven't run out of time // check we haven't run out of time
select { select {
case <-ctx.Done(): case <-ctx.Done():
@ -102,7 +102,7 @@ func TestNetworkSimulation(t *testing.T) {
defer cancel() defer cancel()
// trigger a check every 100ms // trigger a check every 100ms
trigger := make(chan discover.NodeID) trigger := make(chan enode.ID)
go triggerChecks(ctx, ids, trigger, 100*time.Millisecond) go triggerChecks(ctx, ids, trigger, 100*time.Millisecond)
result := NewSimulation(network).Run(ctx, &Step{ result := NewSimulation(network).Run(ctx, &Step{
@ -140,7 +140,7 @@ func TestNetworkSimulation(t *testing.T) {
} }
} }
func triggerChecks(ctx context.Context, ids []discover.NodeID, trigger chan discover.NodeID, interval time.Duration) { func triggerChecks(ctx context.Context, ids []enode.ID, trigger chan enode.ID, interval time.Duration) {
tick := time.NewTicker(interval) tick := time.NewTicker(interval)
defer tick.Stop() defer tick.Stop()
for { for {

View file

@ -20,7 +20,7 @@ import (
"context" "context"
"time" "time"
"github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/enode"
) )
// Simulation provides a framework for running actions in a simulated network // Simulation provides a framework for running actions in a simulated network
@ -55,7 +55,7 @@ func (s *Simulation) Run(ctx context.Context, step *Step) (result *StepResult) {
} }
// wait for all node expectations to either pass, error or timeout // wait for all node expectations to either pass, error or timeout
nodes := make(map[discover.NodeID]struct{}, len(step.Expect.Nodes)) nodes := make(map[enode.ID]struct{}, len(step.Expect.Nodes))
for _, id := range step.Expect.Nodes { for _, id := range step.Expect.Nodes {
nodes[id] = struct{}{} nodes[id] = struct{}{}
} }
@ -119,7 +119,7 @@ type Step struct {
// Trigger is a channel which receives node ids and triggers an // Trigger is a channel which receives node ids and triggers an
// expectation check for that node // expectation check for that node
Trigger chan discover.NodeID Trigger chan enode.ID
// Expect is the expectation to wait for when performing this step // Expect is the expectation to wait for when performing this step
Expect *Expectation Expect *Expectation
@ -127,15 +127,15 @@ type Step struct {
type Expectation struct { type Expectation struct {
// Nodes is a list of nodes to check // Nodes is a list of nodes to check
Nodes []discover.NodeID Nodes []enode.ID
// Check checks whether a given node meets the expectation // Check checks whether a given node meets the expectation
Check func(context.Context, discover.NodeID) (bool, error) Check func(context.Context, enode.ID) (bool, error)
} }
func newStepResult() *StepResult { func newStepResult() *StepResult {
return &StepResult{ return &StepResult{
Passes: make(map[discover.NodeID]time.Time), Passes: make(map[enode.ID]time.Time),
} }
} }
@ -150,7 +150,7 @@ type StepResult struct {
FinishedAt time.Time FinishedAt time.Time
// Passes are the timestamps of the successful node expectations // Passes are the timestamps of the successful node expectations
Passes map[discover.NodeID]time.Time Passes map[enode.ID]time.Time
// NetworkEvents are the network events which occurred during the step // NetworkEvents are the network events which occurred during the step
NetworkEvents []*Event NetworkEvents []*Event

View file

@ -21,22 +21,22 @@ import (
"sync" "sync"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/enode"
) )
type TestPeer interface { type TestPeer interface {
ID() discover.NodeID ID() enode.ID
Drop(error) Drop(error)
} }
// TestPeerPool is an example peerPool to demonstrate registration of peer connections // TestPeerPool is an example peerPool to demonstrate registration of peer connections
type TestPeerPool struct { type TestPeerPool struct {
lock sync.Mutex lock sync.Mutex
peers map[discover.NodeID]TestPeer peers map[enode.ID]TestPeer
} }
func NewTestPeerPool() *TestPeerPool { func NewTestPeerPool() *TestPeerPool {
return &TestPeerPool{peers: make(map[discover.NodeID]TestPeer)} return &TestPeerPool{peers: make(map[enode.ID]TestPeer)}
} }
func (p *TestPeerPool) Add(peer TestPeer) { func (p *TestPeerPool) Add(peer TestPeer) {
@ -53,14 +53,14 @@ func (p *TestPeerPool) Remove(peer TestPeer) {
delete(p.peers, peer.ID()) delete(p.peers, peer.ID())
} }
func (p *TestPeerPool) Has(id discover.NodeID) bool { func (p *TestPeerPool) Has(id enode.ID) bool {
p.lock.Lock() p.lock.Lock()
defer p.lock.Unlock() defer p.lock.Unlock()
_, ok := p.peers[id] _, ok := p.peers[id]
return ok return ok
} }
func (p *TestPeerPool) Get(id discover.NodeID) TestPeer { func (p *TestPeerPool) Get(id enode.ID) TestPeer {
p.lock.Lock() p.lock.Lock()
defer p.lock.Unlock() defer p.lock.Unlock()
return p.peers[id] return p.peers[id]

View file

@ -24,7 +24,7 @@ import (
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/simulations/adapters" "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
) )
@ -35,7 +35,7 @@ var errTimedOut = errors.New("timed out")
// receive (expect) messages // receive (expect) messages
type ProtocolSession struct { type ProtocolSession struct {
Server *p2p.Server Server *p2p.Server
IDs []discover.NodeID Nodes []*enode.Node
adapter *adapters.SimAdapter adapter *adapters.SimAdapter
events chan *p2p.PeerEvent events chan *p2p.PeerEvent
} }
@ -58,7 +58,7 @@ type Exchange struct {
type Trigger struct { type Trigger struct {
Msg interface{} // type of message to be sent Msg interface{} // type of message to be sent
Code uint64 // code of message is given Code uint64 // code of message is given
Peer discover.NodeID // the peer to send the message to Peer enode.ID // the peer to send the message to
Timeout time.Duration // timeout duration for the sending Timeout time.Duration // timeout duration for the sending
} }
@ -67,13 +67,13 @@ type Trigger struct {
type Expect struct { type Expect struct {
Msg interface{} // type of message to expect Msg interface{} // type of message to expect
Code uint64 // code of message is now given Code uint64 // code of message is now given
Peer discover.NodeID // the peer that expects the message Peer enode.ID // the peer that expects the message
Timeout time.Duration // timeout duration for receiving Timeout time.Duration // timeout duration for receiving
} }
// Disconnect represents a disconnect event, used and checked by TestDisconnected // Disconnect represents a disconnect event, used and checked by TestDisconnected
type Disconnect struct { type Disconnect struct {
Peer discover.NodeID // discconnected peer Peer enode.ID // discconnected peer
Error error // disconnect reason Error error // disconnect reason
} }
@ -81,7 +81,7 @@ type Disconnect struct {
func (s *ProtocolSession) trigger(trig Trigger) error { func (s *ProtocolSession) trigger(trig Trigger) error {
simNode, ok := s.adapter.GetNode(trig.Peer) simNode, ok := s.adapter.GetNode(trig.Peer)
if !ok { if !ok {
return fmt.Errorf("trigger: peer %v does not exist (1- %v)", trig.Peer, len(s.IDs)) return fmt.Errorf("trigger: peer %v does not exist (1- %v)", trig.Peer, len(s.Nodes))
} }
mockNode, ok := simNode.Services()[0].(*mockNode) mockNode, ok := simNode.Services()[0].(*mockNode)
if !ok { if !ok {
@ -111,7 +111,7 @@ func (s *ProtocolSession) trigger(trig Trigger) error {
// expect checks an expectation of a message sent out by the pivot node // expect checks an expectation of a message sent out by the pivot node
func (s *ProtocolSession) expect(exps []Expect) error { func (s *ProtocolSession) expect(exps []Expect) error {
// construct a map of expectations for each node // construct a map of expectations for each node
peerExpects := make(map[discover.NodeID][]Expect) peerExpects := make(map[enode.ID][]Expect)
for _, exp := range exps { for _, exp := range exps {
if exp.Msg == nil { if exp.Msg == nil {
return errors.New("no message to expect") return errors.New("no message to expect")
@ -120,11 +120,11 @@ func (s *ProtocolSession) expect(exps []Expect) error {
} }
// construct a map of mockNodes for each node // construct a map of mockNodes for each node
mockNodes := make(map[discover.NodeID]*mockNode) mockNodes := make(map[enode.ID]*mockNode)
for nodeID := range peerExpects { for nodeID := range peerExpects {
simNode, ok := s.adapter.GetNode(nodeID) simNode, ok := s.adapter.GetNode(nodeID)
if !ok { if !ok {
return fmt.Errorf("trigger: peer %v does not exist (1- %v)", nodeID, len(s.IDs)) return fmt.Errorf("trigger: peer %v does not exist (1- %v)", nodeID, len(s.Nodes))
} }
mockNode, ok := simNode.Services()[0].(*mockNode) mockNode, ok := simNode.Services()[0].(*mockNode)
if !ok { if !ok {
@ -253,7 +253,7 @@ func (s *ProtocolSession) testExchange(e Exchange) error {
// TestDisconnected tests the disconnections given as arguments // TestDisconnected tests the disconnections given as arguments
// the disconnect structs describe what disconnect error is expected on which peer // the disconnect structs describe what disconnect error is expected on which peer
func (s *ProtocolSession) TestDisconnected(disconnects ...*Disconnect) error { func (s *ProtocolSession) TestDisconnected(disconnects ...*Disconnect) error {
expects := make(map[discover.NodeID]error) expects := make(map[enode.ID]error)
for _, disconnect := range disconnects { for _, disconnect := range disconnects {
expects[disconnect.Peer] = disconnect.Error expects[disconnect.Peer] = disconnect.Error
} }

View file

@ -35,7 +35,7 @@ import (
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/node" "github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/simulations" "github.com/ethereum/go-ethereum/p2p/simulations"
"github.com/ethereum/go-ethereum/p2p/simulations/adapters" "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
@ -52,7 +52,7 @@ type ProtocolTester struct {
// NewProtocolTester constructs a new ProtocolTester // NewProtocolTester constructs a new ProtocolTester
// it takes as argument the pivot node id, the number of dummy peers and the // 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 // protocol run function called on a peer connection by the p2p server
func NewProtocolTester(t *testing.T, id discover.NodeID, n int, run func(*p2p.Peer, p2p.MsgReadWriter) error) *ProtocolTester { func NewProtocolTester(t *testing.T, id enode.ID, n int, run func(*p2p.Peer, p2p.MsgReadWriter) error) *ProtocolTester {
services := adapters.Services{ services := adapters.Services{
"test": func(ctx *adapters.ServiceContext) (node.Service, error) { "test": func(ctx *adapters.ServiceContext) (node.Service, error) {
return &testNode{run}, nil return &testNode{run}, nil
@ -76,17 +76,17 @@ func NewProtocolTester(t *testing.T, id discover.NodeID, n int, run func(*p2p.Pe
node := net.GetNode(id).Node.(*adapters.SimNode) node := net.GetNode(id).Node.(*adapters.SimNode)
peers := make([]*adapters.NodeConfig, n) peers := make([]*adapters.NodeConfig, n)
peerIDs := make([]discover.NodeID, n) nodes := make([]*enode.Node, n)
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
peers[i] = adapters.RandomNodeConfig() peers[i] = adapters.RandomNodeConfig()
peers[i].Services = []string{"mock"} peers[i].Services = []string{"mock"}
peerIDs[i] = peers[i].ID nodes[i] = peers[i].Node()
} }
events := make(chan *p2p.PeerEvent, 1000) events := make(chan *p2p.PeerEvent, 1000)
node.SubscribeEvents(events) node.SubscribeEvents(events)
ps := &ProtocolSession{ ps := &ProtocolSession{
Server: node.Server(), Server: node.Server(),
IDs: peerIDs, Nodes: nodes,
adapter: adapter, adapter: adapter,
events: events, events: events,
} }
@ -108,7 +108,7 @@ func (t *ProtocolTester) Stop() error {
// Connect brings up the remote peer node and connects it using the // Connect brings up the remote peer node and connects it using the
// p2p/simulations network connection with the in memory network adapter // p2p/simulations network connection with the in memory network adapter
func (t *ProtocolTester) Connect(selfID discover.NodeID, peers ...*adapters.NodeConfig) { func (t *ProtocolTester) Connect(selfID enode.ID, peers ...*adapters.NodeConfig) {
for _, peer := range peers { for _, peer := range peers {
log.Trace(fmt.Sprintf("start node %v", peer.ID)) log.Trace(fmt.Sprintf("start node %v", peer.ID))
if _, err := t.network.NewNodeWithConfig(peer); err != nil { if _, err := t.network.NewNodeWithConfig(peer); err != nil {