From 96bc7e315cf256613748c24d754c1026958ae104 Mon Sep 17 00:00:00 2001 From: mystical-prog Date: Fri, 18 Oct 2024 22:14:29 +0530 Subject: [PATCH 1/3] added ping example --- examples/ping/__init__.py | 0 examples/ping/ping.py | 109 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 109 insertions(+) create mode 100644 examples/ping/__init__.py create mode 100644 examples/ping/ping.py diff --git a/examples/ping/__init__.py b/examples/ping/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/examples/ping/ping.py b/examples/ping/ping.py new file mode 100644 index 000000000..7ec68092a --- /dev/null +++ b/examples/ping/ping.py @@ -0,0 +1,109 @@ +import argparse +import sys + +import multiaddr +import trio + +from libp2p import new_host +from libp2p.network.stream.net_stream_interface import INetStream +from libp2p.peer.peerinfo import info_from_p2p_addr +from libp2p.typing import TProtocol + +PING_PROTOCOL_ID = TProtocol("/ipfs/ping/1.0.0") +PING_LENGTH = 32 +RESP_TIMEOUT = 60 + +async def handle_ping(stream: INetStream) -> None: + while True: + try: + payload = await stream.read(PING_LENGTH) + peer_id = stream.muxed_conn.peer_id + if payload != None: + print(f"received ping from {peer_id}") + + await stream.write(payload) + print(f"responded with pong to {peer_id}") + + except: + await stream.reset() + +async def send_ping(stream: INetStream) -> None: + try: + payload = b"\x01" * PING_LENGTH + print(f"sending ping to {stream.muxed_conn.peer_id}") + + await stream.write(payload) + + with trio.fail_after(RESP_TIMEOUT): + response = await stream.read(PING_LENGTH) + + if response == payload: + print(f"received pong from {stream.muxed_conn.peer_id}") + + except Exception as e: + print(f"error occurred : {e}") + +async def run(port: int, destination: str) -> None: + localhost_ip = "127.0.0.1" + listen_addr = multiaddr.Multiaddr(f"/ip4/0.0.0.0/tcp/{port}") + host = new_host() + + async with host.run(listen_addrs=[listen_addr]), trio.open_nursery() as nursery: + if not destination: + host.set_stream_handler(PING_PROTOCOL_ID, handle_ping) + + print( + "Run this from the same folder in another console:\n\n" + f"python ping.py -p {int(port) + 1} " + f"-d /ip4/{localhost_ip}/tcp/{port}/p2p/{host.get_id().pretty()}\n" + ) + print("Waiting for incoming connection...") + + else: + maddr = multiaddr.Multiaddr(destination) + info = info_from_p2p_addr(maddr) + await host.connect(info) + stream = await host.new_stream(info.peer_id, [PING_PROTOCOL_ID]) + + nursery.start_soon(send_ping, stream) + + return + + await trio.sleep_forever() + +def main() -> None: + + description = """ + This program demonstrates a simple p2p ping application using libp2p. + To use it, first run 'python ping.py -p ', where is the port number. + Then, run another instance with 'python ping.py -p -d ', + where is the multiaddress of the previous listener host. + """ + + example_maddr = ( + "/ip4/127.0.0.1/tcp/8000/p2p/QmQn4SwGkDZKkUEpBRBvTmheQycxAHJUNmVEnjA2v1qe8Q" + ) + + parser = argparse.ArgumentParser(description=description) + + parser.add_argument( + "-p", "--port", default=8000, type=int, help="source port number" + ) + parser.add_argument( + "-d", + "--destination", + type=str, + help=f"destination multiaddr string, e.g. {example_maddr}", + ) + args = parser.parse_args() + + if not args.port: + raise RuntimeError("failed to determine local port") + + try: + trio.run(run, *(args.port, args.destination)) + except KeyboardInterrupt: + pass + +if __name__ == "__main__": + main() \ No newline at end of file From 35ef9211e048228c5db458b552953790e8722e69 Mon Sep 17 00:00:00 2001 From: mystical-prog Date: Fri, 18 Oct 2024 22:35:06 +0530 Subject: [PATCH 2/3] ran make lint --- examples/ping/ping.py | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/examples/ping/ping.py b/examples/ping/ping.py index 7ec68092a..3b99f78ac 100644 --- a/examples/ping/ping.py +++ b/examples/ping/ping.py @@ -1,18 +1,26 @@ import argparse -import sys import multiaddr import trio -from libp2p import new_host -from libp2p.network.stream.net_stream_interface import INetStream -from libp2p.peer.peerinfo import info_from_p2p_addr -from libp2p.typing import TProtocol +from libp2p import ( + new_host, +) +from libp2p.network.stream.net_stream_interface import ( + INetStream, +) +from libp2p.peer.peerinfo import ( + info_from_p2p_addr, +) +from libp2p.typing import ( + TProtocol, +) PING_PROTOCOL_ID = TProtocol("/ipfs/ping/1.0.0") PING_LENGTH = 32 RESP_TIMEOUT = 60 + async def handle_ping(stream: INetStream) -> None: while True: try: @@ -27,11 +35,12 @@ async def handle_ping(stream: INetStream) -> None: except: await stream.reset() + async def send_ping(stream: INetStream) -> None: try: payload = b"\x01" * PING_LENGTH print(f"sending ping to {stream.muxed_conn.peer_id}") - + await stream.write(payload) with trio.fail_after(RESP_TIMEOUT): @@ -39,10 +48,11 @@ async def send_ping(stream: INetStream) -> None: if response == payload: print(f"received pong from {stream.muxed_conn.peer_id}") - + except Exception as e: print(f"error occurred : {e}") + async def run(port: int, destination: str) -> None: localhost_ip = "127.0.0.1" listen_addr = multiaddr.Multiaddr(f"/ip4/0.0.0.0/tcp/{port}") @@ -58,7 +68,7 @@ async def run(port: int, destination: str) -> None: f"-d /ip4/{localhost_ip}/tcp/{port}/p2p/{host.get_id().pretty()}\n" ) print("Waiting for incoming connection...") - + else: maddr = multiaddr.Multiaddr(destination) info = info_from_p2p_addr(maddr) @@ -66,20 +76,20 @@ async def run(port: int, destination: str) -> None: stream = await host.new_stream(info.peer_id, [PING_PROTOCOL_ID]) nursery.start_soon(send_ping, stream) - + return await trio.sleep_forever() + def main() -> None: - description = """ This program demonstrates a simple p2p ping application using libp2p. To use it, first run 'python ping.py -p ', where is the port number. Then, run another instance with 'python ping.py -p -d ', where is the multiaddress of the previous listener host. """ - + example_maddr = ( "/ip4/127.0.0.1/tcp/8000/p2p/QmQn4SwGkDZKkUEpBRBvTmheQycxAHJUNmVEnjA2v1qe8Q" ) @@ -99,11 +109,12 @@ def main() -> None: if not args.port: raise RuntimeError("failed to determine local port") - + try: trio.run(run, *(args.port, args.destination)) except KeyboardInterrupt: pass + if __name__ == "__main__": - main() \ No newline at end of file + main() From 8eee16da3baf940a97fd50b9d294266cfdfabe96 Mon Sep 17 00:00:00 2001 From: mystical-prog Date: Sat, 19 Oct 2024 14:51:43 +0530 Subject: [PATCH 3/3] added ping docs --- docs/examples.ping.rst | 18 ++++++++++++++++++ docs/examples.rst | 1 + 2 files changed, 19 insertions(+) create mode 100644 docs/examples.ping.rst diff --git a/docs/examples.ping.rst b/docs/examples.ping.rst new file mode 100644 index 000000000..a5af648f1 --- /dev/null +++ b/docs/examples.ping.rst @@ -0,0 +1,18 @@ +Ping Demo +========= + +Copy the code below into a file called ``ping.py``. +Install dependencies, preferably in a virtual environment, with: + +.. code-block:: bash + + python -m pip install libp2p + +Run the demo with ``python ping.py`` and copy the output. + +Open a second terminal, navigate to the folder that contains ``ping.py``, then paste +and run the copied line. + +.. literalinclude:: ../examples/echo/echo.py + :language: python + :linenos: diff --git a/docs/examples.rst b/docs/examples.rst index 04b4917af..91909d057 100644 --- a/docs/examples.rst +++ b/docs/examples.rst @@ -12,6 +12,7 @@ Example Scripts examples.chat examples.echo + examples.ping Module contents ---------------