|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +QUIC Echo Example - Fixed version with proper client/server separation |
| 4 | +
|
| 5 | +This program demonstrates a simple echo protocol using QUIC transport where a peer |
| 6 | +listens for connections and copies back any input received on a stream. |
| 7 | +
|
| 8 | +Fixed to properly separate client and server modes - clients don't start listeners. |
| 9 | +""" |
| 10 | + |
| 11 | +import argparse |
| 12 | +import logging |
| 13 | + |
| 14 | +from multiaddr import Multiaddr |
| 15 | +import trio |
| 16 | + |
| 17 | +from libp2p import new_host |
| 18 | +from libp2p.crypto.secp256k1 import create_new_key_pair |
| 19 | +from libp2p.custom_types import TProtocol |
| 20 | +from libp2p.network.stream.net_stream import INetStream |
| 21 | +from libp2p.peer.peerinfo import info_from_p2p_addr |
| 22 | +from libp2p.transport.quic.config import QUICTransportConfig |
| 23 | + |
| 24 | +PROTOCOL_ID = TProtocol("/echo/1.0.0") |
| 25 | + |
| 26 | + |
| 27 | +async def _echo_stream_handler(stream: INetStream) -> None: |
| 28 | + try: |
| 29 | + msg = await stream.read() |
| 30 | + await stream.write(msg) |
| 31 | + await stream.close() |
| 32 | + except Exception as e: |
| 33 | + print(f"Echo handler error: {e}") |
| 34 | + try: |
| 35 | + await stream.close() |
| 36 | + except: # noqa: E722 |
| 37 | + pass |
| 38 | + |
| 39 | + |
| 40 | +async def run_server(port: int, seed: int | None = None) -> None: |
| 41 | + """Run echo server with QUIC transport.""" |
| 42 | + listen_addr = Multiaddr(f"/ip4/0.0.0.0/udp/{port}/quic") |
| 43 | + |
| 44 | + if seed: |
| 45 | + import random |
| 46 | + |
| 47 | + random.seed(seed) |
| 48 | + secret_number = random.getrandbits(32 * 8) |
| 49 | + secret = secret_number.to_bytes(length=32, byteorder="big") |
| 50 | + else: |
| 51 | + import secrets |
| 52 | + |
| 53 | + secret = secrets.token_bytes(32) |
| 54 | + |
| 55 | + # QUIC transport configuration |
| 56 | + quic_config = QUICTransportConfig( |
| 57 | + idle_timeout=30.0, |
| 58 | + max_concurrent_streams=100, |
| 59 | + connection_timeout=10.0, |
| 60 | + enable_draft29=False, |
| 61 | + ) |
| 62 | + |
| 63 | + # Create host with QUIC transport |
| 64 | + host = new_host( |
| 65 | + key_pair=create_new_key_pair(secret), |
| 66 | + transport_opt={"quic_config": quic_config}, |
| 67 | + ) |
| 68 | + |
| 69 | + # Server mode: start listener |
| 70 | + async with host.run(listen_addrs=[listen_addr]): |
| 71 | + try: |
| 72 | + print(f"I am {host.get_id().to_string()}") |
| 73 | + host.set_stream_handler(PROTOCOL_ID, _echo_stream_handler) |
| 74 | + |
| 75 | + print( |
| 76 | + "Run this from the same folder in another console:\n\n" |
| 77 | + f"python3 ./examples/echo/echo_quic.py " |
| 78 | + f"-d {host.get_addrs()[0]}\n" |
| 79 | + ) |
| 80 | + print("Waiting for incoming QUIC connections...") |
| 81 | + await trio.sleep_forever() |
| 82 | + except KeyboardInterrupt: |
| 83 | + print("Closing server gracefully...") |
| 84 | + await host.close() |
| 85 | + return |
| 86 | + |
| 87 | + |
| 88 | +async def run_client(destination: str, seed: int | None = None) -> None: |
| 89 | + """Run echo client with QUIC transport.""" |
| 90 | + if seed: |
| 91 | + import random |
| 92 | + |
| 93 | + random.seed(seed) |
| 94 | + secret_number = random.getrandbits(32 * 8) |
| 95 | + secret = secret_number.to_bytes(length=32, byteorder="big") |
| 96 | + else: |
| 97 | + import secrets |
| 98 | + |
| 99 | + secret = secrets.token_bytes(32) |
| 100 | + |
| 101 | + # QUIC transport configuration |
| 102 | + quic_config = QUICTransportConfig( |
| 103 | + idle_timeout=30.0, |
| 104 | + max_concurrent_streams=100, |
| 105 | + connection_timeout=10.0, |
| 106 | + enable_draft29=False, |
| 107 | + ) |
| 108 | + |
| 109 | + # Create host with QUIC transport |
| 110 | + host = new_host( |
| 111 | + key_pair=create_new_key_pair(secret), |
| 112 | + transport_opt={"quic_config": quic_config}, |
| 113 | + ) |
| 114 | + |
| 115 | + # Client mode: NO listener, just connect |
| 116 | + async with host.run(listen_addrs=[]): # Empty listen_addrs for client |
| 117 | + print(f"I am {host.get_id().to_string()}") |
| 118 | + |
| 119 | + maddr = Multiaddr(destination) |
| 120 | + info = info_from_p2p_addr(maddr) |
| 121 | + |
| 122 | + # Connect to server |
| 123 | + print("STARTING CLIENT CONNECTION PROCESS") |
| 124 | + await host.connect(info) |
| 125 | + print("CLIENT CONNECTED TO SERVER") |
| 126 | + |
| 127 | + # Start a stream with the destination |
| 128 | + stream = await host.new_stream(info.peer_id, [PROTOCOL_ID]) |
| 129 | + |
| 130 | + msg = b"hi, there!\n" |
| 131 | + |
| 132 | + await stream.write(msg) |
| 133 | + response = await stream.read() |
| 134 | + |
| 135 | + print(f"Sent: {msg.decode('utf-8')}") |
| 136 | + print(f"Got: {response.decode('utf-8')}") |
| 137 | + await stream.close() |
| 138 | + await host.disconnect(info.peer_id) |
| 139 | + |
| 140 | + |
| 141 | +async def run(port: int, destination: str, seed: int | None = None) -> None: |
| 142 | + """ |
| 143 | + Run echo server or client with QUIC transport. |
| 144 | +
|
| 145 | + Fixed version that properly separates client and server modes. |
| 146 | + """ |
| 147 | + if not destination: # Server mode |
| 148 | + await run_server(port, seed) |
| 149 | + else: # Client mode |
| 150 | + await run_client(destination, seed) |
| 151 | + |
| 152 | + |
| 153 | +def main() -> None: |
| 154 | + """Main function - help text updated for QUIC.""" |
| 155 | + description = """ |
| 156 | + This program demonstrates a simple echo protocol using QUIC |
| 157 | + transport where a peer listens for connections and copies back |
| 158 | + any input received on a stream. |
| 159 | +
|
| 160 | + QUIC provides built-in TLS security and stream multiplexing over UDP. |
| 161 | +
|
| 162 | + To use it, first run 'python ./echo_quic_fixed.py -p <PORT>', where <PORT> is |
| 163 | + the UDP port number. Then, run another host with , |
| 164 | + 'python ./echo_quic_fixed.py -d <DESTINATION>' |
| 165 | + where <DESTINATION> is the QUIC multiaddress of the previous listener host. |
| 166 | + """ |
| 167 | + |
| 168 | + example_maddr = "/ip4/127.0.0.1/udp/8000/quic/p2p/QmQn4SwGkDZKkUEpBRBv" |
| 169 | + |
| 170 | + parser = argparse.ArgumentParser(description=description) |
| 171 | + parser.add_argument("-p", "--port", default=0, type=int, help="UDP port number") |
| 172 | + parser.add_argument( |
| 173 | + "-d", |
| 174 | + "--destination", |
| 175 | + type=str, |
| 176 | + help=f"destination multiaddr string, e.g. {example_maddr}", |
| 177 | + ) |
| 178 | + parser.add_argument( |
| 179 | + "-s", |
| 180 | + "--seed", |
| 181 | + type=int, |
| 182 | + help="provide a seed to the random number generator", |
| 183 | + ) |
| 184 | + args = parser.parse_args() |
| 185 | + |
| 186 | + try: |
| 187 | + trio.run(run, args.port, args.destination, args.seed) |
| 188 | + except KeyboardInterrupt: |
| 189 | + pass |
| 190 | + |
| 191 | + |
| 192 | +if __name__ == "__main__": |
| 193 | + logging.basicConfig(level=logging.DEBUG) |
| 194 | + logging.getLogger("aioquic").setLevel(logging.DEBUG) |
| 195 | + main() |
0 commit comments