QUIC Echo Demo
This example demonstrates a simple echo protocol using QUIC transport.
QUIC provides built-in TLS security and stream multiplexing over UDP, making it an excellent transport choice for libp2p applications.
$ python -m pip install libp2p
Collecting libp2p
...
Successfully installed libp2p-x.x.x
$ echo-quic-demo
Run this from the same folder in another console:
echo-quic-demo -d /ip4/127.0.0.1/udp/8000/quic-v1/p2p/16Uiu2HAmAsbxRR1HiGJRNVPQLNMeNsBCsXT3rDjoYBQzgzNpM5mJ
Waiting for incoming connection...
Copy the line that starts with echo-quic-demo -p 8001, open a new terminal in the same
folder and paste it in:
$ echo-quic-demo -d /ip4/127.0.0.1/udp/8000/quic-v1/p2p/16Uiu2HAmE3N7KauPTmHddYPsbMcBp2C6XAmprELX3YcFEN9iXiBu
I am 16Uiu2HAmE3N7KauPTmHddYPsbMcBp2C6XAmprELX3YcFEN9iXiBu
STARTING CLIENT CONNECTION PROCESS
CLIENT CONNECTED TO SERVER
Sent: hi, there!
Got: ECHO: hi, there!
Key differences from TCP Echo:
Uses UDP instead of TCP:
/udp/8000instead of/tcp/8000Includes QUIC protocol identifier:
/quic-v1in the multiaddrBuilt-in TLS security (no separate security transport needed)
Native stream multiplexing over a single QUIC connection
1#!/usr/bin/env python3
2"""
3QUIC Echo Example - Fixed version with proper client/server separation
4
5This program demonstrates a simple echo protocol using QUIC transport where a peer
6listens for connections and copies back any input received on a stream.
7
8Fixed to properly separate client and server modes - clients don't start listeners.
9"""
10
11import argparse
12import logging
13
14from multiaddr import Multiaddr
15import trio
16
17from libp2p import new_host
18from libp2p.crypto.secp256k1 import create_new_key_pair
19from libp2p.custom_types import TProtocol
20from libp2p.network.stream.net_stream import INetStream
21from libp2p.peer.peerinfo import info_from_p2p_addr
22
23# Configure minimal logging
24logging.basicConfig(level=logging.WARNING)
25logging.getLogger("multiaddr").setLevel(logging.WARNING)
26logging.getLogger("libp2p").setLevel(logging.WARNING)
27
28PROTOCOL_ID = TProtocol("/echo/1.0.0")
29
30
31async def _echo_stream_handler(stream: INetStream) -> None:
32 try:
33 msg = await stream.read()
34 await stream.write(msg)
35 await stream.close()
36 except Exception as e:
37 print(f"Echo handler error: {e}")
38 try:
39 await stream.close()
40 except: # noqa: E722
41 pass
42
43
44async def run_server(port: int, seed: int | None = None) -> None:
45 """Run echo server with QUIC transport."""
46 from libp2p.utils.address_validation import (
47 find_free_port,
48 get_available_interfaces,
49 get_optimal_binding_address,
50 )
51
52 if port <= 0:
53 port = find_free_port()
54
55 # For QUIC, we need UDP addresses - use the new address paradigm
56 tcp_addrs = get_available_interfaces(port)
57 # Convert TCP addresses to QUIC addresses
58 quic_addrs = []
59 for addr in tcp_addrs:
60 addr_str = str(addr).replace("/tcp/", "/udp/") + "/quic"
61 quic_addrs.append(Multiaddr(addr_str))
62
63 if seed:
64 import random
65
66 random.seed(seed)
67 secret_number = random.getrandbits(32 * 8)
68 secret = secret_number.to_bytes(length=32, byteorder="big")
69 else:
70 import secrets
71
72 secret = secrets.token_bytes(32)
73
74 # Create host with QUIC transport
75 host = new_host(
76 enable_quic=True,
77 key_pair=create_new_key_pair(secret),
78 )
79
80 # Server mode: start listener
81 async with host.run(listen_addrs=quic_addrs):
82 try:
83 print(f"I am {host.get_id().to_string()}")
84 host.set_stream_handler(PROTOCOL_ID, _echo_stream_handler)
85
86 # Get all available addresses with peer ID
87 all_addrs = host.get_addrs()
88
89 print("Listener ready, listening on:")
90 for addr in all_addrs:
91 print(f"{addr}")
92
93 # Use optimal address for the client command
94 optimal_tcp = get_optimal_binding_address(port)
95 optimal_quic_str = str(optimal_tcp).replace("/tcp/", "/udp/") + "/quic"
96 peer_id = host.get_id().to_string()
97 optimal_quic_with_peer = f"{optimal_quic_str}/p2p/{peer_id}"
98 print(
99 f"\nRun this from the same folder in another console:\n\n"
100 f"python3 ./examples/echo/echo_quic.py -d {optimal_quic_with_peer}\n"
101 )
102 print("Waiting for incoming QUIC connections...")
103 await trio.sleep_forever()
104 except KeyboardInterrupt:
105 print("Closing server gracefully...")
106 await host.close()
107 return
108
109
110async def run_client(destination: str, seed: int | None = None) -> None:
111 """Run echo client with QUIC transport."""
112 if seed:
113 import random
114
115 random.seed(seed)
116 secret_number = random.getrandbits(32 * 8)
117 secret = secret_number.to_bytes(length=32, byteorder="big")
118 else:
119 import secrets
120
121 secret = secrets.token_bytes(32)
122
123 # Create host with QUIC transport
124 host = new_host(
125 enable_quic=True,
126 key_pair=create_new_key_pair(secret),
127 )
128
129 # Client mode: NO listener, just connect
130 async with host.run(listen_addrs=[]): # Empty listen_addrs for client
131 print(f"I am {host.get_id().to_string()}")
132
133 maddr = Multiaddr(destination)
134 info = info_from_p2p_addr(maddr)
135
136 # Connect to server
137 print("STARTING CLIENT CONNECTION PROCESS")
138 await host.connect(info)
139 print("CLIENT CONNECTED TO SERVER")
140
141 # Start a stream with the destination
142 stream = await host.new_stream(info.peer_id, [PROTOCOL_ID])
143
144 msg = b"hi, there!\n"
145
146 await stream.write(msg)
147 response = await stream.read()
148
149 print(f"Sent: {msg.decode('utf-8')}")
150 print(f"Got: {response.decode('utf-8')}")
151 await stream.close()
152 await host.disconnect(info.peer_id)
153
154
155async def run(port: int, destination: str, seed: int | None = None) -> None:
156 """
157 Run echo server or client with QUIC transport.
158
159 Fixed version that properly separates client and server modes.
160 """
161 if not destination: # Server mode
162 await run_server(port, seed)
163 else: # Client mode
164 await run_client(destination, seed)
165
166
167def main() -> None:
168 """Main function - help text updated for QUIC."""
169 description = """
170 This program demonstrates a simple echo protocol using QUIC
171 transport where a peer listens for connections and copies back
172 any input received on a stream.
173
174 QUIC provides built-in TLS security and stream multiplexing over UDP.
175
176 To use it, first run 'echo-quic-demo -p <PORT>', where <PORT> is
177 the UDP port number. Then, run another host with ,
178 'echo-quic-demo -d <DESTINATION>'
179 where <DESTINATION> is the QUIC multiaddress of the previous listener host.
180 """
181
182 example_maddr = "/ip4/[HOST_IP]/udp/8000/quic/p2p/QmQn4SwGkDZKkUEpBRBv"
183
184 parser = argparse.ArgumentParser(description=description)
185 parser.add_argument("-p", "--port", default=0, type=int, help="UDP port number")
186 parser.add_argument(
187 "-d",
188 "--destination",
189 type=str,
190 help=f"destination multiaddr string, e.g. {example_maddr}",
191 )
192 parser.add_argument(
193 "-s",
194 "--seed",
195 type=int,
196 help="provide a seed to the random number generator",
197 )
198 args = parser.parse_args()
199
200 try:
201 trio.run(run, args.port, args.destination, args.seed)
202 except KeyboardInterrupt:
203 pass
204
205
206if __name__ == "__main__":
207 main()