fix potential infinite loop in randomNodes (#754)

Signed-off-by: Csaba Kiraly <csaba.kiraly@gmail.com>
This commit is contained in:
Csaba Kiraly 2024-10-24 17:24:53 +02:00 committed by GitHub
parent 66297c5c0a
commit 30476de038
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 5 additions and 1 deletions

View File

@ -545,7 +545,8 @@ proc randomNodes*(r: RoutingTable, maxAmount: int,
# while it will take less total time compared to e.g. an (async) # while it will take less total time compared to e.g. an (async)
# randomLookup, the time might be wasted as all nodes are possibly seen # randomLookup, the time might be wasted as all nodes are possibly seen
# already. # already.
while len(seen) < maxAmount: # We check against the number of nodes to avoid an infinite loop in case of a filter.
while len(result) < maxAmount and len(seen) < sz:
let bucket = r.rng[].sample(r.buckets) let bucket = r.rng[].sample(r.buckets)
if bucket.nodes.len != 0: if bucket.nodes.len != 0:
let node = r.rng[].sample(bucket.nodes) let node = r.rng[].sample(bucket.nodes)

View File

@ -417,6 +417,9 @@ suite "Discovery v5 Tests":
let discoveredFiltered = lookupNode.randomNodes(10, let discoveredFiltered = lookupNode.randomNodes(10,
("test", @[byte 1,2,3,4])) ("test", @[byte 1,2,3,4]))
check discoveredFiltered.len == 1 and discoveredFiltered.contains(targetNode) check discoveredFiltered.len == 1 and discoveredFiltered.contains(targetNode)
let discoveredEmpty = lookupNode.randomNodes(10,
proc(n: Node) : bool = false)
check discoveredEmpty.len == 0
await lookupNode.closeWait() await lookupNode.closeWait()