py-libp2p/examples/echo/echo.py

118 lines
3.5 KiB
Python
Raw Normal View History

2019-09-04 13:21:01 +08:00
import argparse
import multiaddr
import trio
2019-09-04 13:21:01 +08:00
from libp2p import new_host_trio
2019-09-04 13:21:01 +08:00
from libp2p.crypto.secp256k1 import create_new_key_pair
from libp2p.network.stream.net_stream_interface import INetStream
from libp2p.peer.peerinfo import info_from_p2p_addr
from libp2p.typing import TProtocol
PROTOCOL_ID = TProtocol("/echo/1.0.0")
async def _echo_stream_handler(stream: INetStream) -> None:
2019-09-06 17:26:40 +08:00
# Wait until EOF
2019-09-04 13:21:01 +08:00
msg = await stream.read()
await stream.write(msg)
await stream.close()
async def run(port: int, destination: str, seed: int = None) -> None:
localhost_ip = "127.0.0.1"
listen_addr = multiaddr.Multiaddr(f"/ip4/0.0.0.0/tcp/{port}")
2019-09-04 13:21:01 +08:00
if seed:
import random
random.seed(seed)
secret_number = random.getrandbits(32 * 8)
secret = secret_number.to_bytes(length=32, byteorder="big")
else:
import secrets
secret = secrets.token_bytes(32)
async with new_host_trio(
listen_addrs=[listen_addr], key_pair=create_new_key_pair(secret)
) as host:
2019-09-04 13:21:01 +08:00
print(f"I am {host.get_id().to_string()}")
2019-09-04 13:21:01 +08:00
if not destination: # its the server
2019-09-04 13:21:01 +08:00
host.set_stream_handler(PROTOCOL_ID, _echo_stream_handler)
2019-09-04 13:21:01 +08:00
print(
f"Run 'python ./examples/echo/echo.py "
f"-p {int(port) + 1} "
f"-d /ip4/{localhost_ip}/tcp/{port}/p2p/{host.get_id().pretty()}' "
"on another console."
)
print("Waiting for incoming connections...")
await trio.sleep_forever()
2019-09-04 13:21:01 +08:00
else: # its the client
maddr = multiaddr.Multiaddr(destination)
info = info_from_p2p_addr(maddr)
# Associate the peer with local ip address
await host.connect(info)
2019-09-04 13:21:01 +08:00
# Start a stream with the destination.
# Multiaddress of the destination peer is fetched from the peerstore using 'peerId'.
stream = await host.new_stream(info.peer_id, [PROTOCOL_ID])
2019-09-04 13:21:01 +08:00
msg = b"hi, there!\n"
2019-09-04 13:21:01 +08:00
await stream.write(msg)
# Notify the other side about EOF
await stream.close()
response = await stream.read()
2019-09-04 13:21:01 +08:00
print(f"Sent: {msg}")
print(f"Got: {response}")
2019-09-04 13:21:01 +08:00
def main() -> None:
description = """
This program demonstrates a simple echo protocol where a peer listens for
connections and copies back any input received on a stream.
To use it, first run 'python ./echo -p <PORT>', where <PORT> is the port number.
Then, run another host with 'python ./chat -p <ANOTHER_PORT> -d <DESTINATION>',
where <DESTINATION> 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}",
)
parser.add_argument(
"-s",
"--seed",
type=int,
help="provide a seed to the random number generator (e.g. to fix peer IDs across runs)",
)
args = parser.parse_args()
if not args.port:
raise RuntimeError("was not able to determine a local port")
try:
trio.run(run, args.port, args.destination, args.seed)
2019-09-04 13:21:01 +08:00
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()