From 30476de038a1c6f77df9a05498fe47e40d3c68b2 Mon Sep 17 00:00:00 2001 From: Csaba Kiraly Date: Thu, 24 Oct 2024 17:24:53 +0200 Subject: [PATCH] fix potential infinite loop in randomNodes (#754) Signed-off-by: Csaba Kiraly --- eth/p2p/discoveryv5/routing_table.nim | 3 ++- tests/p2p/test_discoveryv5.nim | 3 +++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/eth/p2p/discoveryv5/routing_table.nim b/eth/p2p/discoveryv5/routing_table.nim index 08b202d..7385c08 100644 --- a/eth/p2p/discoveryv5/routing_table.nim +++ b/eth/p2p/discoveryv5/routing_table.nim @@ -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) diff --git a/tests/p2p/test_discoveryv5.nim b/tests/p2p/test_discoveryv5.nim index 4115739..8c8e5e1 100644 --- a/tests/p2p/test_discoveryv5.nim +++ b/tests/p2p/test_discoveryv5.nim @@ -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()