Skip to content

Commit 7a63faf

Browse files
author
Nishant Das
authored
p2p/discover: add helper methods to UDPv5 (#20918)
This adds two new methods to UDPv5, AllNodes and LocalNode. AllNodes returns all the nodes stored in the local table; this is useful for the purposes of metrics collection and also debugging any potential issues with other discovery v5 implementations. LocalNode returns the local node object. The reason for exposing this is so that users can modify and set/delete new key-value entries in the local record.
1 parent 3bf1054 commit 7a63faf

2 files changed

Lines changed: 42 additions & 0 deletions

File tree

‎p2p/discover/v5_udp.go‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,26 @@ func (t *UDPv5) Resolve(n *enode.Node) *enode.Node {
216216
return n
217217
}
218218

219+
// AllNodes returns all the nodes stored in the local table.
220+
func (t *UDPv5) AllNodes() []*enode.Node {
221+
t.tab.mutex.Lock()
222+
defer t.tab.mutex.Unlock()
223+
nodes := make([]*enode.Node, 0)
224+
225+
for _, b := range &t.tab.buckets {
226+
for _, n := range b.entries {
227+
nodes = append(nodes, unwrapNode(n))
228+
}
229+
}
230+
return nodes
231+
}
232+
233+
// LocalNode returns the current local node running the
234+
// protocol.
235+
func (t *UDPv5) LocalNode() *enode.LocalNode {
236+
return t.localNode
237+
}
238+
219239
func (t *UDPv5) RandomNodes() enode.Iterator {
220240
if t.tab.len() == 0 {
221241
// All nodes were dropped, refresh. The very first query will hit this

‎p2p/discover/v5_udp_test.go‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -445,6 +445,28 @@ func TestUDPv5_lookup(t *testing.T) {
445445
checkLookupResults(t, lookupTestnet, <-resultC)
446446
}
447447

448+
// This test checks the local node can be utilised to set key-values.
449+
func TestUDPv5_LocalNode(t *testing.T) {
450+
t.Parallel()
451+
var cfg Config
452+
node := startLocalhostV5(t, cfg)
453+
defer node.Close()
454+
localNd := node.LocalNode()
455+
456+
// set value in node's local record
457+
testVal := [4]byte{'A', 'B', 'C', 'D'}
458+
localNd.Set(enr.WithEntry("testing", &testVal))
459+
460+
// retrieve the value from self to make sure it matches.
461+
outputVal := [4]byte{}
462+
if err := node.Self().Load(enr.WithEntry("testing", &outputVal)); err != nil {
463+
t.Errorf("Could not load value from record: %v", err)
464+
}
465+
if testVal != outputVal {
466+
t.Errorf("Wanted %#x to be retrieved from the record but instead got %#x", testVal, outputVal)
467+
}
468+
}
469+
448470
// udpV5Test is the framework for all tests above.
449471
// It runs the UDPv5 transport on a virtual socket and allows testing outgoing packets.
450472
type udpV5Test struct {

0 commit comments

Comments
 (0)