Skip to content

Commit fa538ee

Browse files
fjlkaralabe
authored andcommitted
p2p/discover: improve randomness of ReadRandomNodes (#19799)
Make it select from all live nodes instead of selecting the heads of random buckets.
1 parent 983f923 commit fa538ee

File tree

1 file changed

+8
-25
lines changed

1 file changed

+8
-25
lines changed

p2p/discover/table.go

Lines changed: 8 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -147,35 +147,18 @@ func (tab *Table) ReadRandomNodes(buf []*enode.Node) (n int) {
147147
tab.mutex.Lock()
148148
defer tab.mutex.Unlock()
149149

150-
// Find all non-empty buckets and get a fresh slice of their entries.
151-
var buckets [][]*node
150+
var nodes []*enode.Node
152151
for _, b := range &tab.buckets {
153-
if len(b.entries) > 0 {
154-
buckets = append(buckets, b.entries)
152+
for _, n := range b.entries {
153+
nodes = append(nodes, unwrapNode(n))
155154
}
156155
}
157-
if len(buckets) == 0 {
158-
return 0
159-
}
160-
// Shuffle the buckets.
161-
for i := len(buckets) - 1; i > 0; i-- {
162-
j := tab.rand.Intn(len(buckets))
163-
buckets[i], buckets[j] = buckets[j], buckets[i]
164-
}
165-
// Move head of each bucket into buf, removing buckets that become empty.
166-
var i, j int
167-
for ; i < len(buf); i, j = i+1, (j+1)%len(buckets) {
168-
b := buckets[j]
169-
buf[i] = unwrapNode(b[0])
170-
buckets[j] = b[1:]
171-
if len(b) == 1 {
172-
buckets = append(buckets[:j], buckets[j+1:]...)
173-
}
174-
if len(buckets) == 0 {
175-
break
176-
}
156+
// Shuffle.
157+
for i := 0; i < len(nodes); i++ {
158+
j := tab.rand.Intn(len(nodes))
159+
nodes[i], nodes[j] = nodes[j], nodes[i]
177160
}
178-
return i + 1
161+
return copy(buf, nodes)
179162
}
180163

181164
// getNode returns the node with the given ID or nil if it isn't in the table.

0 commit comments

Comments
 (0)