2019-09-25 10:15:32 +08:00
|
|
|
import asyncio
|
2019-09-25 09:21:04 +08:00
|
|
|
import logging
|
|
|
|
|
2019-09-25 10:04:18 +08:00
|
|
|
from libp2p.network.stream.exceptions import StreamEOF, StreamReset
|
2019-09-25 09:21:04 +08:00
|
|
|
from libp2p.network.stream.net_stream_interface import INetStream
|
2019-09-25 10:15:32 +08:00
|
|
|
from libp2p.peer.id import ID as PeerID
|
2019-09-25 09:21:04 +08:00
|
|
|
|
|
|
|
ID = "/ipfs/ping/1.0.0"
|
|
|
|
PING_LENGTH = 32
|
|
|
|
RESP_TIMEOUT = 60
|
|
|
|
|
|
|
|
logger = logging.getLogger("libp2p.host.ping")
|
|
|
|
|
|
|
|
|
2019-10-24 18:44:52 +08:00
|
|
|
async def _handle_ping(stream: INetStream, peer_id: PeerID) -> bool:
|
2019-11-06 09:50:43 +08:00
|
|
|
"""Return a boolean indicating if we expect more pings from the peer at
|
|
|
|
``peer_id``."""
|
2019-09-25 09:21:04 +08:00
|
|
|
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
|
2019-10-24 18:44:52 +08:00
|
|
|
except StreamEOF:
|
|
|
|
logger.debug("Other side closed while waiting for ping from %s", peer_id)
|
|
|
|
return False
|
|
|
|
except StreamReset as error:
|
2019-09-25 10:04:18 +08:00
|
|
|
logger.debug(
|
2019-10-24 18:44:52 +08:00
|
|
|
"Other side reset while waiting for ping from %s: %s", peer_id, error
|
2019-09-25 10:04:18 +08:00
|
|
|
)
|
|
|
|
raise
|
2019-09-25 09:21:04 +08:00
|
|
|
except Exception as error:
|
|
|
|
logger.debug("Error while waiting to read ping for %s: %s", peer_id, error)
|
|
|
|
raise
|
|
|
|
|
|
|
|
logger.debug("Received ping from %s with data: 0x%s", peer_id, payload.hex())
|
|
|
|
|
|
|
|
await stream.write(payload)
|
2019-10-24 18:44:52 +08:00
|
|
|
return True
|
2019-09-25 09:21:04 +08:00
|
|
|
|
|
|
|
|
2019-09-25 10:15:32 +08:00
|
|
|
async def handle_ping(stream: INetStream) -> None:
|
2019-11-06 09:50:43 +08:00
|
|
|
"""``handle_ping`` responds to incoming ping requests until one side errors
|
|
|
|
or closes the ``stream``."""
|
2019-09-25 09:21:04 +08:00
|
|
|
peer_id = stream.muxed_conn.peer_id
|
|
|
|
|
|
|
|
while True:
|
|
|
|
try:
|
2019-10-24 18:44:52 +08:00
|
|
|
should_continue = await _handle_ping(stream, peer_id)
|
|
|
|
if not should_continue:
|
|
|
|
return
|
2019-09-25 09:21:04 +08:00
|
|
|
except Exception:
|
|
|
|
await stream.reset()
|
|
|
|
return
|