diff --git a/libp2p/host/ping.py b/libp2p/host/ping.py index 110a083..f47e83d 100644 --- a/libp2p/host/ping.py +++ b/libp2p/host/ping.py @@ -12,15 +12,21 @@ RESP_TIMEOUT = 60 logger = logging.getLogger("libp2p.host.ping") -async def _handle_ping(stream: INetStream, peer_id: PeerID) -> None: +async def _handle_ping(stream: INetStream, peer_id: PeerID) -> bool: + """ + Return a boolean indicating if we expect more pings from the peer at ``peer_id``. + """ try: payload = await asyncio.wait_for(stream.read(PING_LENGTH), RESP_TIMEOUT) except asyncio.TimeoutError as error: logger.debug("Timed out waiting for ping from %s: %s", peer_id, error) raise - except (StreamEOF, StreamReset) as error: + except StreamEOF: + logger.debug("Other side closed while waiting for ping from %s", peer_id) + return False + except StreamReset as error: logger.debug( - "Other side closed while waiting for ping from %s: %s", peer_id, error + "Other side reset while waiting for ping from %s: %s", peer_id, error ) raise except Exception as error: @@ -30,6 +36,7 @@ async def _handle_ping(stream: INetStream, peer_id: PeerID) -> None: logger.debug("Received ping from %s with data: 0x%s", peer_id, payload.hex()) await stream.write(payload) + return True async def handle_ping(stream: INetStream) -> None: @@ -41,7 +48,9 @@ async def handle_ping(stream: INetStream) -> None: while True: try: - await _handle_ping(stream, peer_id) + should_continue = await _handle_ping(stream, peer_id) + if not should_continue: + return except Exception: await stream.reset() return