2019-09-25 09:21:04 +08:00
|
|
|
import logging
|
|
|
|
|
2019-12-06 17:06:37 +08:00
|
|
|
import trio
|
|
|
|
|
2019-11-12 18:33:44 +08:00
|
|
|
from libp2p.network.stream.exceptions import StreamClosed, 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-11-07 07:21:30 +08:00
|
|
|
from libp2p.typing import TProtocol
|
2019-09-25 09:21:04 +08:00
|
|
|
|
2019-11-07 07:21:30 +08:00
|
|
|
ID = TProtocol("/ipfs/ping/1.0.0")
|
2019-09-25 09:21:04 +08:00
|
|
|
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-12-01 19:17:32 +08:00
|
|
|
with trio.fail_after(RESP_TIMEOUT):
|
|
|
|
try:
|
|
|
|
payload = await stream.read(PING_LENGTH)
|
|
|
|
except trio.TooSlowError as error:
|
|
|
|
logger.debug("Timed out waiting for ping from %s: %s", peer_id, error)
|
|
|
|
raise
|
|
|
|
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 reset while waiting for ping from %s: %s", peer_id, error
|
|
|
|
)
|
|
|
|
raise
|
|
|
|
except Exception as error:
|
|
|
|
logger.debug("Error while waiting to read ping for %s: %s", peer_id, error)
|
|
|
|
raise
|
2019-09-25 09:21:04 +08:00
|
|
|
|
|
|
|
logger.debug("Received ping from %s with data: 0x%s", peer_id, payload.hex())
|
|
|
|
|
2019-11-12 18:33:44 +08:00
|
|
|
try:
|
|
|
|
await stream.write(payload)
|
|
|
|
except StreamClosed:
|
|
|
|
logger.debug("Fail to respond to ping from %s: stream closed", peer_id)
|
|
|
|
raise
|
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
|