Skip to content

Commit

Permalink
fix potential infinite loop in randomNodes (#754)
Browse files Browse the repository at this point in the history
Signed-off-by: Csaba Kiraly <csaba.kiraly@gmail.com>
  • Loading branch information
cskiraly authored Oct 24, 2024
1 parent 66297c5 commit 30476de
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 1 deletion.
3 changes: 2 additions & 1 deletion eth/p2p/discoveryv5/routing_table.nim
Original file line number Diff line number Diff line change
Expand Up @@ -545,7 +545,8 @@ proc randomNodes*(r: RoutingTable, maxAmount: int,
# 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
# 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)
if bucket.nodes.len != 0:
let node = r.rng[].sample(bucket.nodes)
Expand Down
3 changes: 3 additions & 0 deletions tests/p2p/test_discoveryv5.nim
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,9 @@ suite "Discovery v5 Tests":
let discoveredFiltered = lookupNode.randomNodes(10,
("test", @[byte 1,2,3,4]))
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()

Expand Down

0 comments on commit 30476de

Please sign in to comment.