From 5de09ed8a1f06fae6f60b26ef5956b0f5c64385d Mon Sep 17 00:00:00 2001 From: varun-r-mallya Date: Tue, 19 Aug 2025 04:53:50 +0530 Subject: [PATCH] Improve relay selection to prioritize active reservations Signed-off-by: varun-r-mallya --- libp2p/relay/circuit_v2/transport.py | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/libp2p/relay/circuit_v2/transport.py b/libp2p/relay/circuit_v2/transport.py index ffd31090..2ba0aa90 100644 --- a/libp2p/relay/circuit_v2/transport.py +++ b/libp2p/relay/circuit_v2/transport.py @@ -219,11 +219,25 @@ class CircuitV2Transport(ITransport): # Get a relay from the list of discovered relays relays = self.discovery.get_relays() if relays: - # TODO: Implement more sophisticated relay selection - # For now, just return the first available relay - return relays[0] + # Prioritize relays with active reservations + relays_with_reservations = [] + other_relays = [] + + for relay_id in relays: + relay_info = self.discovery.get_relay_info(relay_id) + if relay_info and relay_info.has_reservation: + relays_with_reservations.append(relay_id) + else: + other_relays.append(relay_id) + + # Return first available relay with reservation, or fallback to others + if relays_with_reservations: + return relays_with_reservations[ + attempts % len(relays_with_reservations) + ] + elif other_relays: + return other_relays[attempts % len(other_relays)] - # Wait and try discovery await trio.sleep(1) attempts += 1