aboutsummaryrefslogtreecommitdiffstats
path: root/p2p/server_test.go
diff options
context:
space:
mode:
authorFelix Lange <fjl@users.noreply.github.com>2018-09-25 06:59:00 +0800
committerGitHub <noreply@github.com>2018-09-25 06:59:00 +0800
commit30cd5c18549f645002aedb4c00e5bab683cb0835 (patch)
tree9a9098c6ff5a746758660295dfc1880d22e75434 /p2p/server_test.go
parent0ae462fb80b8a95e38af08d894ea9ecf9e45f2e7 (diff)
downloaddexon-30cd5c18549f645002aedb4c00e5bab683cb0835.tar.gz
dexon-30cd5c18549f645002aedb4c00e5bab683cb0835.tar.zst
dexon-30cd5c18549f645002aedb4c00e5bab683cb0835.zip
all: new p2p node representation (#17643)
Package p2p/enode provides a generalized representation of p2p nodes which can contain arbitrary information in key/value pairs. It is also the new home for the node database. The "v4" identity scheme is also moved here from p2p/enr to remove the dependency on Ethereum crypto from that package. Record signature handling is changed significantly. The identity scheme registry is removed and acceptable schemes must be passed to any method that needs identity. This means records must now be validated explicitly after decoding. The enode API is designed to make signature handling easy and safe: most APIs around the codebase work with enode.Node, which is a wrapper around a valid record. Going from enr.Record to enode.Node requires a valid signature. * p2p/discover: port to p2p/enode This ports the discovery code to the new node representation in p2p/enode. The wire protocol is unchanged, this can be considered a refactoring change. The Kademlia table can now deal with nodes using an arbitrary identity scheme. This requires a few incompatible API changes: - Table.Lookup is not available anymore. It used to take a public key as argument because v4 protocol requires one. Its replacement is LookupRandom. - Table.Resolve takes *enode.Node instead of NodeID. This is also for v4 protocol compatibility because nodes cannot be looked up by ID alone. - Types Node and NodeID are gone. Further commits in the series will be fixes all over the the codebase to deal with those removals. * p2p: port to p2p/enode and discovery changes This adapts package p2p to the changes in p2p/discover. All uses of discover.Node and discover.NodeID are replaced by their equivalents from p2p/enode. New API is added to retrieve the enode.Node instance of a peer. The behavior of Server.Self with discovery disabled is improved. It now tries much harder to report a working IP address, falling back to 127.0.0.1 if no suitable address can be determined through other means. These changes were needed for tests of other packages later in the series. * 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. * whisper/whisperv5, whisper/whisperv6: port to p2p/enode This port was easy because whisper uses []byte for node IDs and URL strings in the API. * eth: port to p2p/enode Again, easy to port because eth uses strings for node IDs and doesn't care about node information in any way. * les: port to p2p/enode Apart from replacing discover.NodeID with enode.ID, most changes are in the server pool code. It now deals with complete nodes instead of (Pubkey, IP, Port) triples. The database format is unchanged for now, but we should probably change it to use the node database later. * node: port to p2p/enode This change simply replaces discover.Node and discover.NodeID with their new equivalents. * swarm/network: port to p2p/enode Swarm has its own node address representation, BzzAddr, containing both an overlay address (the hash of a secp256k1 public key) and an underlay address (enode:// URL). There are no changes to the BzzAddr format in this commit, but certain operations such as creating a BzzAddr from a node ID are now impossible because node IDs aren't public keys anymore. Most swarm-related changes in the series remove uses of NewAddrFromNodeID, replacing it with NewAddr which takes a complete node as argument. ToOverlayAddr is removed because we can just use the node ID directly.
Diffstat (limited to 'p2p/server_test.go')
-rw-r--r--p2p/server_test.go130
1 files changed, 66 insertions, 64 deletions
diff --git a/p2p/server_test.go b/p2p/server_test.go
index 3f24a79ba..e0b1fc122 100644
--- a/p2p/server_test.go
+++ b/p2p/server_test.go
@@ -28,21 +28,22 @@ import (
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/crypto/sha3"
"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/enr"
)
-func init() {
- // log.Root().SetHandler(log.LvlFilterHandler(log.LvlError, log.StreamHandler(os.Stderr, log.TerminalFormat(false))))
-}
+// func init() {
+// log.Root().SetHandler(log.LvlFilterHandler(log.LvlTrace, log.StreamHandler(os.Stderr, log.TerminalFormat(false))))
+// }
type testTransport struct {
- id discover.NodeID
+ rpub *ecdsa.PublicKey
*rlpx
closeErr error
}
-func newTestTransport(id discover.NodeID, fd net.Conn) transport {
+func newTestTransport(rpub *ecdsa.PublicKey, fd net.Conn) transport {
wrapped := newRLPX(fd).(*rlpx)
wrapped.rw = newRLPXFrameRW(fd, secrets{
MAC: zero16,
@@ -50,15 +51,16 @@ func newTestTransport(id discover.NodeID, fd net.Conn) transport {
IngressMAC: sha3.NewKeccak256(),
EgressMAC: sha3.NewKeccak256(),
})
- return &testTransport{id: id, rlpx: wrapped}
+ return &testTransport{rpub: rpub, rlpx: wrapped}
}
-func (c *testTransport) doEncHandshake(prv *ecdsa.PrivateKey, dialDest *discover.Node) (discover.NodeID, error) {
- return c.id, nil
+func (c *testTransport) doEncHandshake(prv *ecdsa.PrivateKey, dialDest *ecdsa.PublicKey) (*ecdsa.PublicKey, error) {
+ return c.rpub, nil
}
func (c *testTransport) doProtoHandshake(our *protoHandshake) (*protoHandshake, error) {
- return &protoHandshake{ID: c.id, Name: "test"}, nil
+ pubkey := crypto.FromECDSAPub(c.rpub)[1:]
+ return &protoHandshake{ID: pubkey, Name: "test"}, nil
}
func (c *testTransport) close(err error) {
@@ -66,7 +68,7 @@ func (c *testTransport) close(err error) {
c.closeErr = err
}
-func startTestServer(t *testing.T, id discover.NodeID, pf func(*Peer)) *Server {
+func startTestServer(t *testing.T, remoteKey *ecdsa.PublicKey, pf func(*Peer)) *Server {
config := Config{
Name: "test",
MaxPeers: 10,
@@ -76,7 +78,7 @@ func startTestServer(t *testing.T, id discover.NodeID, pf func(*Peer)) *Server {
server := &Server{
Config: config,
newPeerHook: pf,
- newTransport: func(fd net.Conn) transport { return newTestTransport(id, fd) },
+ newTransport: func(fd net.Conn) transport { return newTestTransport(remoteKey, fd) },
}
if err := server.Start(); err != nil {
t.Fatalf("Could not start server: %v", err)
@@ -87,14 +89,11 @@ func startTestServer(t *testing.T, id discover.NodeID, pf func(*Peer)) *Server {
func TestServerListen(t *testing.T) {
// start the test server
connected := make(chan *Peer)
- remid := randomID()
+ remid := &newkey().PublicKey
srv := startTestServer(t, remid, func(p *Peer) {
- if p.ID() != remid {
+ if p.ID() != enode.PubkeyToIDV4(remid) {
t.Error("peer func called with wrong node id")
}
- if p == nil {
- t.Error("peer func called with nil conn")
- }
connected <- p
})
defer close(connected)
@@ -141,14 +140,14 @@ func TestServerDial(t *testing.T) {
// start the server
connected := make(chan *Peer)
- remid := randomID()
+ remid := &newkey().PublicKey
srv := startTestServer(t, remid, func(p *Peer) { connected <- p })
defer close(connected)
defer srv.Stop()
// tell the server to connect
tcpAddr := listener.Addr().(*net.TCPAddr)
- node := &discover.Node{ID: remid, IP: tcpAddr.IP, TCP: uint16(tcpAddr.Port)}
+ node := enode.NewV4(remid, tcpAddr.IP, tcpAddr.Port, 0)
srv.AddPeer(node)
select {
@@ -157,7 +156,7 @@ func TestServerDial(t *testing.T) {
select {
case peer := <-connected:
- if peer.ID() != remid {
+ if peer.ID() != enode.PubkeyToIDV4(remid) {
t.Errorf("peer has wrong id")
}
if peer.Name() != "test" {
@@ -211,7 +210,7 @@ func TestServerTaskScheduling(t *testing.T) {
quit, returned = make(chan struct{}), make(chan struct{})
tc = 0
tg = taskgen{
- newFunc: func(running int, peers map[discover.NodeID]*Peer) []task {
+ newFunc: func(running int, peers map[enode.ID]*Peer) []task {
tc++
return []task{&testTask{index: tc - 1}}
},
@@ -284,7 +283,7 @@ func TestServerManyTasks(t *testing.T) {
defer srv.Stop()
srv.loopWG.Add(1)
go srv.run(taskgen{
- newFunc: func(running int, peers map[discover.NodeID]*Peer) []task {
+ newFunc: func(running int, peers map[enode.ID]*Peer) []task {
start, end = end, end+maxActiveDialTasks+10
if end > len(alltasks) {
end = len(alltasks)
@@ -319,19 +318,19 @@ func TestServerManyTasks(t *testing.T) {
}
type taskgen struct {
- newFunc func(running int, peers map[discover.NodeID]*Peer) []task
+ newFunc func(running int, peers map[enode.ID]*Peer) []task
doneFunc func(task)
}
-func (tg taskgen) newTasks(running int, peers map[discover.NodeID]*Peer, now time.Time) []task {
+func (tg taskgen) newTasks(running int, peers map[enode.ID]*Peer, now time.Time) []task {
return tg.newFunc(running, peers)
}
func (tg taskgen) taskDone(t task, now time.Time) {
tg.doneFunc(t)
}
-func (tg taskgen) addStatic(*discover.Node) {
+func (tg taskgen) addStatic(*enode.Node) {
}
-func (tg taskgen) removeStatic(*discover.Node) {
+func (tg taskgen) removeStatic(*enode.Node) {
}
type testTask struct {
@@ -347,13 +346,14 @@ func (t *testTask) Do(srv *Server) {
// just after the encryption handshake when the server is
// at capacity. Trusted connections should still be accepted.
func TestServerAtCap(t *testing.T) {
- trustedID := randomID()
+ trustedNode := newkey()
+ trustedID := enode.PubkeyToIDV4(&trustedNode.PublicKey)
srv := &Server{
Config: Config{
PrivateKey: newkey(),
MaxPeers: 10,
NoDial: true,
- TrustedNodes: []*discover.Node{{ID: trustedID}},
+ TrustedNodes: []*enode.Node{newNode(trustedID, nil)},
},
}
if err := srv.Start(); err != nil {
@@ -361,10 +361,11 @@ func TestServerAtCap(t *testing.T) {
}
defer srv.Stop()
- newconn := func(id discover.NodeID) *conn {
+ newconn := func(id enode.ID) *conn {
fd, _ := net.Pipe()
- tx := newTestTransport(id, fd)
- return &conn{fd: fd, transport: tx, flags: inboundConn, id: id, cont: make(chan error)}
+ tx := newTestTransport(&trustedNode.PublicKey, fd)
+ node := enode.SignNull(new(enr.Record), id)
+ return &conn{fd: fd, transport: tx, flags: inboundConn, node: node, cont: make(chan error)}
}
// Inject a few connections to fill up the peer set.
@@ -390,14 +391,14 @@ func TestServerAtCap(t *testing.T) {
}
// Remove from trusted set and try again
- srv.RemoveTrustedPeer(&discover.Node{ID: trustedID})
+ srv.RemoveTrustedPeer(newNode(trustedID, nil))
c = newconn(trustedID)
if err := srv.checkpoint(c, srv.posthandshake); err != DiscTooManyPeers {
t.Error("wrong error for insert:", err)
}
// Add anotherID to trusted set and try again
- srv.AddTrustedPeer(&discover.Node{ID: anotherID})
+ srv.AddTrustedPeer(newNode(anotherID, nil))
c = newconn(anotherID)
if err := srv.checkpoint(c, srv.posthandshake); err != nil {
t.Error("unexpected error for trusted conn @posthandshake:", err)
@@ -409,20 +410,17 @@ func TestServerAtCap(t *testing.T) {
func TestServerPeerLimits(t *testing.T) {
srvkey := newkey()
+ clientkey := newkey()
+ clientnode := enode.NewV4(&clientkey.PublicKey, nil, 0, 0)
- clientid := randomID()
- clientnode := &discover.Node{ID: clientid}
-
- var tp *setupTransport = &setupTransport{
- id: clientid,
- phs: &protoHandshake{
- ID: clientid,
+ var tp = &setupTransport{
+ pubkey: &clientkey.PublicKey,
+ phs: protoHandshake{
+ ID: crypto.FromECDSAPub(&clientkey.PublicKey)[1:],
// Force "DiscUselessPeer" due to unmatching caps
// Caps: []Cap{discard.cap()},
},
}
- var flags connFlag = dynDialedConn
- var dialDest *discover.Node = &discover.Node{ID: clientid}
srv := &Server{
Config: Config{
@@ -440,6 +438,8 @@ func TestServerPeerLimits(t *testing.T) {
defer srv.Stop()
// Check that server is full (MaxPeers=0)
+ flags := dynDialedConn
+ dialDest := clientnode
conn, _ := net.Pipe()
srv.SetupConn(conn, flags, dialDest)
if tp.closeErr != DiscTooManyPeers {
@@ -473,59 +473,61 @@ func TestServerPeerLimits(t *testing.T) {
}
func TestServerSetupConn(t *testing.T) {
- id := randomID()
- srvkey := newkey()
- srvid := discover.PubkeyID(&srvkey.PublicKey)
+ var (
+ clientkey, srvkey = newkey(), newkey()
+ clientpub = &clientkey.PublicKey
+ srvpub = &srvkey.PublicKey
+ )
tests := []struct {
dontstart bool
tt *setupTransport
flags connFlag
- dialDest *discover.Node
+ dialDest *enode.Node
wantCloseErr error
wantCalls string
}{
{
dontstart: true,
- tt: &setupTransport{id: id},
+ tt: &setupTransport{pubkey: clientpub},
wantCalls: "close,",
wantCloseErr: errServerStopped,
},
{
- tt: &setupTransport{id: id, encHandshakeErr: errors.New("read error")},
+ tt: &setupTransport{pubkey: clientpub, encHandshakeErr: errors.New("read error")},
flags: inboundConn,
wantCalls: "doEncHandshake,close,",
wantCloseErr: errors.New("read error"),
},
{
- tt: &setupTransport{id: id},
- dialDest: &discover.Node{ID: randomID()},
+ tt: &setupTransport{pubkey: clientpub},
+ dialDest: enode.NewV4(&newkey().PublicKey, nil, 0, 0),
flags: dynDialedConn,
wantCalls: "doEncHandshake,close,",
wantCloseErr: DiscUnexpectedIdentity,
},
{
- tt: &setupTransport{id: id, phs: &protoHandshake{ID: randomID()}},
- dialDest: &discover.Node{ID: id},
+ tt: &setupTransport{pubkey: clientpub, phs: protoHandshake{ID: randomID().Bytes()}},
+ dialDest: enode.NewV4(clientpub, nil, 0, 0),
flags: dynDialedConn,
wantCalls: "doEncHandshake,doProtoHandshake,close,",
wantCloseErr: DiscUnexpectedIdentity,
},
{
- tt: &setupTransport{id: id, protoHandshakeErr: errors.New("foo")},
- dialDest: &discover.Node{ID: id},
+ tt: &setupTransport{pubkey: clientpub, protoHandshakeErr: errors.New("foo")},
+ dialDest: enode.NewV4(clientpub, nil, 0, 0),
flags: dynDialedConn,
wantCalls: "doEncHandshake,doProtoHandshake,close,",
wantCloseErr: errors.New("foo"),
},
{
- tt: &setupTransport{id: srvid, phs: &protoHandshake{ID: srvid}},
+ tt: &setupTransport{pubkey: srvpub, phs: protoHandshake{ID: crypto.FromECDSAPub(srvpub)[1:]}},
flags: inboundConn,
wantCalls: "doEncHandshake,close,",
wantCloseErr: DiscSelf,
},
{
- tt: &setupTransport{id: id, phs: &protoHandshake{ID: id}},
+ tt: &setupTransport{pubkey: clientpub, phs: protoHandshake{ID: crypto.FromECDSAPub(clientpub)[1:]}},
flags: inboundConn,
wantCalls: "doEncHandshake,doProtoHandshake,close,",
wantCloseErr: DiscUselessPeer,
@@ -560,26 +562,26 @@ func TestServerSetupConn(t *testing.T) {
}
type setupTransport struct {
- id discover.NodeID
- encHandshakeErr error
-
- phs *protoHandshake
+ pubkey *ecdsa.PublicKey
+ encHandshakeErr error
+ phs protoHandshake
protoHandshakeErr error
calls string
closeErr error
}
-func (c *setupTransport) doEncHandshake(prv *ecdsa.PrivateKey, dialDest *discover.Node) (discover.NodeID, error) {
+func (c *setupTransport) doEncHandshake(prv *ecdsa.PrivateKey, dialDest *ecdsa.PublicKey) (*ecdsa.PublicKey, error) {
c.calls += "doEncHandshake,"
- return c.id, c.encHandshakeErr
+ return c.pubkey, c.encHandshakeErr
}
+
func (c *setupTransport) doProtoHandshake(our *protoHandshake) (*protoHandshake, error) {
c.calls += "doProtoHandshake,"
if c.protoHandshakeErr != nil {
return nil, c.protoHandshakeErr
}
- return c.phs, nil
+ return &c.phs, nil
}
func (c *setupTransport) close(err error) {
c.calls += "close,"
@@ -602,7 +604,7 @@ func newkey() *ecdsa.PrivateKey {
return key
}
-func randomID() (id discover.NodeID) {
+func randomID() (id enode.ID) {
for i := range id {
id[i] = byte(rand.Intn(255))
}