Skip to content

Commit 6f607de

Browse files
authored
p2p, p2p/discover: add signed ENR generation (#17753)
This PR adds enode.LocalNode and integrates it into the p2p subsystem. This new object is the keeper of the local node record. For now, a new version of the record is produced every time the client restarts. We'll make it smarter to avoid that in the future. There are a couple of other changes in this commit: discovery now waits for all of its goroutines at shutdown and the p2p server now closes the node database after discovery has shut down. This fixes a leveldb crash in tests. p2p server startup is faster because it doesn't need to wait for the external IP query anymore.
1 parent dcae0d3 commit 6f607de

24 files changed

Lines changed: 976 additions & 275 deletions

‎cmd/bootnode/main.go‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -119,16 +119,17 @@ func main() {
119119
}
120120

121121
if *runv5 {
122-
if _, err := discv5.ListenUDP(nodeKey, conn, realaddr, "", restrictList); err != nil {
122+
if _, err := discv5.ListenUDP(nodeKey, conn, "", restrictList); err != nil {
123123
utils.Fatalf("%v", err)
124124
}
125125
} else {
126+
db, _ := enode.OpenDB("")
127+
ln := enode.NewLocalNode(db, nodeKey)
126128
cfg := discover.Config{
127-
PrivateKey: nodeKey,
128-
AnnounceAddr: realaddr,
129-
NetRestrict: restrictList,
129+
PrivateKey: nodeKey,
130+
NetRestrict: restrictList,
130131
}
131-
if _, err := discover.ListenUDP(conn, cfg); err != nil {
132+
if _, err := discover.ListenUDP(conn, ln, cfg); err != nil {
132133
utils.Fatalf("%v", err)
133134
}
134135
}

‎node/node_test.go‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -454,9 +454,9 @@ func TestProtocolGather(t *testing.T) {
454454
Count int
455455
Maker InstrumentingWrapper
456456
}{
457-
"Zero Protocols": {0, InstrumentedServiceMakerA},
458-
"Single Protocol": {1, InstrumentedServiceMakerB},
459-
"Many Protocols": {25, InstrumentedServiceMakerC},
457+
"zero": {0, InstrumentedServiceMakerA},
458+
"one": {1, InstrumentedServiceMakerB},
459+
"many": {10, InstrumentedServiceMakerC},
460460
}
461461
for id, config := range services {
462462
protocols := make([]p2p.Protocol, config.Count)
@@ -480,7 +480,7 @@ func TestProtocolGather(t *testing.T) {
480480
defer stack.Stop()
481481

482482
protocols := stack.Server().Protocols
483-
if len(protocols) != 26 {
483+
if len(protocols) != 11 {
484484
t.Fatalf("mismatching number of protocols launched: have %d, want %d", len(protocols), 26)
485485
}
486486
for id, config := range services {

‎p2p/dial.go‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ type dialstate struct {
7171
maxDynDials int
7272
ntab discoverTable
7373
netrestrict *netutil.Netlist
74+
self enode.ID
7475

7576
lookupRunning bool
7677
dialing map[enode.ID]connFlag
@@ -84,7 +85,6 @@ type dialstate struct {
8485
}
8586

8687
type discoverTable interface {
87-
Self() *enode.Node
8888
Close()
8989
Resolve(*enode.Node) *enode.Node
9090
LookupRandom() []*enode.Node
@@ -126,10 +126,11 @@ type waitExpireTask struct {
126126
time.Duration
127127
}
128128

129-
func newDialState(static []*enode.Node, bootnodes []*enode.Node, ntab discoverTable, maxdyn int, netrestrict *netutil.Netlist) *dialstate {
129+
func newDialState(self enode.ID, static []*enode.Node, bootnodes []*enode.Node, ntab discoverTable, maxdyn int, netrestrict *netutil.Netlist) *dialstate {
130130
s := &dialstate{
131131
maxDynDials: maxdyn,
132132
ntab: ntab,
133+
self: self,
133134
netrestrict: netrestrict,
134135
static: make(map[enode.ID]*dialTask),
135136
dialing: make(map[enode.ID]connFlag),
@@ -266,7 +267,7 @@ func (s *dialstate) checkDial(n *enode.Node, peers map[enode.ID]*Peer) error {
266267
return errAlreadyDialing
267268
case peers[n.ID()] != nil:
268269
return errAlreadyConnected
269-
case s.ntab != nil && n.ID() == s.ntab.Self().ID():
270+
case n.ID() == s.self:
270271
return errSelf
271272
case s.netrestrict != nil && !s.netrestrict.Contains(n.IP()):
272273
return errNotWhitelisted

‎p2p/dial_test.go‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ func (t fakeTable) ReadRandomNodes(buf []*enode.Node) int { return copy(buf, t)
8989
// This test checks that dynamic dials are launched from discovery results.
9090
func TestDialStateDynDial(t *testing.T) {
9191
runDialTest(t, dialtest{
92-
init: newDialState(nil, nil, fakeTable{}, 5, nil),
92+
init: newDialState(enode.ID{}, nil, nil, fakeTable{}, 5, nil),
9393
rounds: []round{
9494
// A discovery query is launched.
9595
{
@@ -236,7 +236,7 @@ func TestDialStateDynDialBootnode(t *testing.T) {
236236
newNode(uintID(8), nil),
237237
}
238238
runDialTest(t, dialtest{
239-
init: newDialState(nil, bootnodes, table, 5, nil),
239+
init: newDialState(enode.ID{}, nil, bootnodes, table, 5, nil),
240240
rounds: []round{
241241
// 2 dynamic dials attempted, bootnodes pending fallback interval
242242
{
@@ -324,7 +324,7 @@ func TestDialStateDynDialFromTable(t *testing.T) {
324324
}
325325

326326
runDialTest(t, dialtest{
327-
init: newDialState(nil, nil, table, 10, nil),
327+
init: newDialState(enode.ID{}, nil, nil, table, 10, nil),
328328
rounds: []round{
329329
// 5 out of 8 of the nodes returned by ReadRandomNodes are dialed.
330330
{
@@ -430,7 +430,7 @@ func TestDialStateNetRestrict(t *testing.T) {
430430
restrict.Add("127.0.2.0/24")
431431

432432
runDialTest(t, dialtest{
433-
init: newDialState(nil, nil, table, 10, restrict),
433+
init: newDialState(enode.ID{}, nil, nil, table, 10, restrict),
434434
rounds: []round{
435435
{
436436
new: []task{
@@ -453,7 +453,7 @@ func TestDialStateStaticDial(t *testing.T) {
453453
}
454454

455455
runDialTest(t, dialtest{
456-
init: newDialState(wantStatic, nil, fakeTable{}, 0, nil),
456+
init: newDialState(enode.ID{}, wantStatic, nil, fakeTable{}, 0, nil),
457457
rounds: []round{
458458
// Static dials are launched for the nodes that
459459
// aren't yet connected.
@@ -557,7 +557,7 @@ func TestDialStaticAfterReset(t *testing.T) {
557557
},
558558
}
559559
dTest := dialtest{
560-
init: newDialState(wantStatic, nil, fakeTable{}, 0, nil),
560+
init: newDialState(enode.ID{}, wantStatic, nil, fakeTable{}, 0, nil),
561561
rounds: rounds,
562562
}
563563
runDialTest(t, dTest)
@@ -578,7 +578,7 @@ func TestDialStateCache(t *testing.T) {
578578
}
579579

580580
runDialTest(t, dialtest{
581-
init: newDialState(wantStatic, nil, fakeTable{}, 0, nil),
581+
init: newDialState(enode.ID{}, wantStatic, nil, fakeTable{}, 0, nil),
582582
rounds: []round{
583583
// Static dials are launched for the nodes that
584584
// aren't yet connected.
@@ -640,7 +640,7 @@ func TestDialStateCache(t *testing.T) {
640640
func TestDialResolve(t *testing.T) {
641641
resolved := newNode(uintID(1), net.IP{127, 0, 55, 234})
642642
table := &resolveMock{answer: resolved}
643-
state := newDialState(nil, nil, table, 0, nil)
643+
state := newDialState(enode.ID{}, nil, nil, table, 0, nil)
644644

645645
// Check that the task is generated with an incomplete ID.
646646
dest := newNode(uintID(1), nil)

‎p2p/discover/table.go‎

Lines changed: 22 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -72,21 +72,20 @@ type Table struct {
7272
ips netutil.DistinctNetSet
7373

7474
db *enode.DB // database of known nodes
75+
net transport
7576
refreshReq chan chan struct{}
7677
initDone chan struct{}
7778
closeReq chan struct{}
7879
closed chan struct{}
7980

8081
nodeAddedHook func(*node) // for testing
81-
82-
net transport
83-
self *node // metadata of the local node
8482
}
8583

8684
// transport is implemented by the UDP transport.
8785
// it is an interface so we can test without opening lots of UDP
8886
// sockets and without generating a private key.
8987
type transport interface {
88+
self() *enode.Node
9089
ping(enode.ID, *net.UDPAddr) error
9190
findnode(toid enode.ID, addr *net.UDPAddr, target encPubkey) ([]*node, error)
9291
close()
@@ -100,11 +99,10 @@ type bucket struct {
10099
ips netutil.DistinctNetSet
101100
}
102101

103-
func newTable(t transport, self *enode.Node, db *enode.DB, bootnodes []*enode.Node) (*Table, error) {
102+
func newTable(t transport, db *enode.DB, bootnodes []*enode.Node) (*Table, error) {
104103
tab := &Table{
105104
net: t,
106105
db: db,
107-
self: wrapNode(self),
108106
refreshReq: make(chan chan struct{}),
109107
initDone: make(chan struct{}),
110108
closeReq: make(chan struct{}),
@@ -127,6 +125,10 @@ func newTable(t transport, self *enode.Node, db *enode.DB, bootnodes []*enode.No
127125
return tab, nil
128126
}
129127

128+
func (tab *Table) self() *enode.Node {
129+
return tab.net.self()
130+
}
131+
130132
func (tab *Table) seedRand() {
131133
var b [8]byte
132134
crand.Read(b[:])
@@ -136,11 +138,6 @@ func (tab *Table) seedRand() {
136138
tab.mutex.Unlock()
137139
}
138140

139-
// Self returns the local node.
140-
func (tab *Table) Self() *enode.Node {
141-
return unwrapNode(tab.self)
142-
}
143-
144141
// ReadRandomNodes fills the given slice with random nodes from the table. The results
145142
// are guaranteed to be unique for a single invocation, no node will appear twice.
146143
func (tab *Table) ReadRandomNodes(buf []*enode.Node) (n int) {
@@ -183,6 +180,10 @@ func (tab *Table) ReadRandomNodes(buf []*enode.Node) (n int) {
183180

184181
// Close terminates the network listener and flushes the node database.
185182
func (tab *Table) Close() {
183+
if tab.net != nil {
184+
tab.net.close()
185+
}
186+
186187
select {
187188
case <-tab.closed:
188189
// already closed.
@@ -257,7 +258,7 @@ func (tab *Table) lookup(targetKey encPubkey, refreshIfEmpty bool) []*node {
257258
)
258259
// don't query further if we hit ourself.
259260
// unlikely to happen often in practice.
260-
asked[tab.self.ID()] = true
261+
asked[tab.self().ID()] = true
261262

262263
for {
263264
tab.mutex.Lock()
@@ -340,8 +341,8 @@ func (tab *Table) loop() {
340341
revalidate = time.NewTimer(tab.nextRevalidateTime())
341342
refresh = time.NewTicker(refreshInterval)
342343
copyNodes = time.NewTicker(copyNodesInterval)
343-
revalidateDone = make(chan struct{})
344344
refreshDone = make(chan struct{}) // where doRefresh reports completion
345+
revalidateDone chan struct{} // where doRevalidate reports completion
345346
waiting = []chan struct{}{tab.initDone} // holds waiting callers while doRefresh runs
346347
)
347348
defer refresh.Stop()
@@ -372,25 +373,27 @@ loop:
372373
}
373374
waiting, refreshDone = nil, nil
374375
case <-revalidate.C:
376+
revalidateDone = make(chan struct{})
375377
go tab.doRevalidate(revalidateDone)
376378
case <-revalidateDone:
377379
revalidate.Reset(tab.nextRevalidateTime())
380+
revalidateDone = nil
378381
case <-copyNodes.C:
379382
go tab.copyLiveNodes()
380383
case <-tab.closeReq:
381384
break loop
382385
}
383386
}
384387

385-
if tab.net != nil {
386-
tab.net.close()
387-
}
388388
if refreshDone != nil {
389389
<-refreshDone
390390
}
391391
for _, ch := range waiting {
392392
close(ch)
393393
}
394+
if revalidateDone != nil {
395+
<-revalidateDone
396+
}
394397
close(tab.closed)
395398
}
396399

@@ -408,7 +411,7 @@ func (tab *Table) doRefresh(done chan struct{}) {
408411
// Run self lookup to discover new neighbor nodes.
409412
// We can only do this if we have a secp256k1 identity.
410413
var key ecdsa.PublicKey
411-
if err := tab.self.Load((*enode.Secp256k1)(&key)); err == nil {
414+
if err := tab.self().Load((*enode.Secp256k1)(&key)); err == nil {
412415
tab.lookup(encodePubkey(&key), false)
413416
}
414417

@@ -530,7 +533,7 @@ func (tab *Table) len() (n int) {
530533

531534
// bucket returns the bucket for the given node ID hash.
532535
func (tab *Table) bucket(id enode.ID) *bucket {
533-
d := enode.LogDist(tab.self.ID(), id)
536+
d := enode.LogDist(tab.self().ID(), id)
534537
if d <= bucketMinDistance {
535538
return tab.buckets[0]
536539
}
@@ -543,7 +546,7 @@ func (tab *Table) bucket(id enode.ID) *bucket {
543546
//
544547
// The caller must not hold tab.mutex.
545548
func (tab *Table) add(n *node) {
546-
if n.ID() == tab.self.ID() {
549+
if n.ID() == tab.self().ID() {
547550
return
548551
}
549552

@@ -576,7 +579,7 @@ func (tab *Table) stuff(nodes []*node) {
576579
defer tab.mutex.Unlock()
577580

578581
for _, n := range nodes {
579-
if n.ID() == tab.self.ID() {
582+
if n.ID() == tab.self().ID() {
580583
continue // don't add self
581584
}
582585
b := tab.bucket(n.ID())

‎p2p/discover/table_test.go‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ func TestTable_IPLimit(t *testing.T) {
141141
defer db.Close()
142142

143143
for i := 0; i < tableIPLimit+1; i++ {
144-
n := nodeAtDistance(tab.self.ID(), i, net.IP{172, 0, 1, byte(i)})
144+
n := nodeAtDistance(tab.self().ID(), i, net.IP{172, 0, 1, byte(i)})
145145
tab.add(n)
146146
}
147147
if tab.len() > tableIPLimit {
@@ -158,7 +158,7 @@ func TestTable_BucketIPLimit(t *testing.T) {
158158

159159
d := 3
160160
for i := 0; i < bucketIPLimit+1; i++ {
161-
n := nodeAtDistance(tab.self.ID(), d, net.IP{172, 0, 1, byte(i)})
161+
n := nodeAtDistance(tab.self().ID(), d, net.IP{172, 0, 1, byte(i)})
162162
tab.add(n)
163163
}
164164
if tab.len() > bucketIPLimit {
@@ -240,7 +240,7 @@ func TestTable_ReadRandomNodesGetAll(t *testing.T) {
240240

241241
for i := 0; i < len(buf); i++ {
242242
ld := cfg.Rand.Intn(len(tab.buckets))
243-
tab.stuff([]*node{nodeAtDistance(tab.self.ID(), ld, intIP(ld))})
243+
tab.stuff([]*node{nodeAtDistance(tab.self().ID(), ld, intIP(ld))})
244244
}
245245
gotN := tab.ReadRandomNodes(buf)
246246
if gotN != tab.len() {
@@ -510,6 +510,10 @@ type preminedTestnet struct {
510510
dists [hashBits + 1][]encPubkey
511511
}
512512

513+
func (tn *preminedTestnet) self() *enode.Node {
514+
return nullNode
515+
}
516+
513517
func (tn *preminedTestnet) findnode(toid enode.ID, toaddr *net.UDPAddr, target encPubkey) ([]*node, error) {
514518
// current log distance is encoded in port number
515519
// fmt.Println("findnode query at dist", toaddr.Port)

0 commit comments

Comments
 (0)