Echo Demo
This example demonstrates a simple echo protocol.
$ python -m pip install libp2p
Collecting libp2p
...
Successfully installed libp2p-x.x.x
$ echo-demo
Run this from the same folder in another console:
echo-demo -p 8001 -d /ip4/127.0.0.1/tcp/8000/p2p/16Uiu2HAmAsbxRR1HiGJRNVPQLNMeNsBCsXT3rDjoYBQzgzNpM5mJ
Waiting for incoming connection...
Copy the line that starts with echo-demo -p 8001, open a new terminal in the same
folder and paste it in:
$ echo-demo -p 8001 -d /ip4/127.0.0.1/tcp/8000/p2p/16Uiu2HAmAsbxRR1HiGJRNVPQLNMeNsBCsXT3rDjoYBQzgzNpM5mJ
I am 16Uiu2HAmE3N7KauPTmHddYPsbMcBp2C6XAmprELX3YcFEN9iXiBu
Sent: hi, there!
Got: hi, there!
1import argparse
2import logging
3import random
4import secrets
5
6import multiaddr
7import trio
8
9from libp2p import (
10 new_host,
11)
12from libp2p.crypto.secp256k1 import (
13 create_new_key_pair,
14)
15from libp2p.custom_types import (
16 TProtocol,
17)
18from libp2p.network.stream.exceptions import (
19 StreamEOF,
20)
21from libp2p.network.stream.net_stream import (
22 INetStream,
23)
24from libp2p.peer.peerinfo import (
25 info_from_p2p_addr,
26)
27from libp2p.utils.address_validation import (
28 find_free_port,
29 get_available_interfaces,
30 get_optimal_binding_address,
31)
32
33# Configure minimal logging
34logging.basicConfig(level=logging.WARNING)
35logging.getLogger("multiaddr").setLevel(logging.WARNING)
36logging.getLogger("libp2p").setLevel(logging.WARNING)
37
38PROTOCOL_ID = TProtocol("/echo/1.0.0")
39MAX_READ_LEN = 2**32 - 1
40
41
42async def _echo_stream_handler(stream: INetStream) -> None:
43 try:
44 peer_id = stream.muxed_conn.peer_id
45 print(f"Received connection from {peer_id}")
46 # Wait until EOF
47 msg = await stream.read(MAX_READ_LEN)
48 print(f"Echoing message: {msg.decode('utf-8')}")
49 await stream.write(msg)
50 except StreamEOF:
51 print("Stream closed by remote peer.")
52 except Exception as e:
53 print(f"Error in echo handler: {e}")
54 finally:
55 await stream.close()
56
57
58async def run(port: int, destination: str, seed: int | None = None) -> None:
59 if port <= 0:
60 port = find_free_port()
61 listen_addr = get_available_interfaces(port)
62
63 if seed:
64 random.seed(seed)
65 secret_number = random.getrandbits(32 * 8)
66 secret = secret_number.to_bytes(length=32, byteorder="big")
67 else:
68 secret = secrets.token_bytes(32)
69
70 host = new_host(key_pair=create_new_key_pair(secret))
71 async with host.run(listen_addrs=listen_addr), trio.open_nursery() as nursery:
72 # Start the peer-store cleanup task
73 nursery.start_soon(host.get_peerstore().start_cleanup_task, 60)
74
75 print(f"I am {host.get_id().to_string()}")
76
77 if not destination: # its the server
78 host.set_stream_handler(PROTOCOL_ID, _echo_stream_handler)
79
80 # Print all listen addresses with peer ID (JS parity)
81 print("Listener ready, listening on:\n")
82 peer_id = host.get_id().to_string()
83 for addr in listen_addr:
84 print(f"{addr}/p2p/{peer_id}")
85
86 # Get optimal address for display
87 optimal_addr = get_optimal_binding_address(port)
88 optimal_addr_with_peer = f"{optimal_addr}/p2p/{peer_id}"
89
90 print(
91 "\nRun this from the same folder in another console:\n\n"
92 f"echo-demo -d {optimal_addr_with_peer}\n"
93 )
94 print("Waiting for incoming connections...")
95 await trio.sleep_forever()
96
97 else: # its the client
98 maddr = multiaddr.Multiaddr(destination)
99 info = info_from_p2p_addr(maddr)
100 # Associate the peer with local ip address
101 await host.connect(info)
102
103 # Start a stream with the destination.
104 # Multiaddress of the destination peer is fetched from the peerstore
105 # using 'peerId'.
106 stream = await host.new_stream(info.peer_id, [PROTOCOL_ID])
107
108 msg = b"hi, there!\n"
109
110 await stream.write(msg)
111 response = await stream.read()
112 await stream.close()
113
114 print(f"Sent: {msg.decode('utf-8')}")
115 print(f"Got: {response.decode('utf-8')}")
116
117
118def main() -> None:
119 description = """
120 This program demonstrates a simple echo protocol where a peer listens for
121 connections and copies back any input received on a stream.
122
123 To use it, first run 'python ./echo -p <PORT>', where <PORT> is the port number.
124 Then, run another host with 'python ./chat -p <ANOTHER_PORT> -d <DESTINATION>',
125 where <DESTINATION> is the multiaddress of the previous listener host.
126 """
127 example_maddr = (
128 "/ip4/[HOST_IP]/tcp/8000/p2p/QmQn4SwGkDZKkUEpBRBvTmheQycxAHJUNmVEnjA2v1qe8Q"
129 )
130 parser = argparse.ArgumentParser(description=description)
131 parser.add_argument("-p", "--port", default=0, type=int, help="source port number")
132 parser.add_argument(
133 "-d",
134 "--destination",
135 type=str,
136 help=f"destination multiaddr string, e.g. {example_maddr}",
137 )
138 parser.add_argument(
139 "-s",
140 "--seed",
141 type=int,
142 help="provide a seed to the random number generator (e.g. to fix peer IDs across runs)", # noqa: E501
143 )
144 args = parser.parse_args()
145 try:
146 trio.run(run, args.port, args.destination, args.seed)
147 except KeyboardInterrupt:
148 pass
149
150
151if __name__ == "__main__":
152 main()