← All Workshops

MudEngine Part 11: Peer-to-Peer with iroh

Step 7 / 14

The P2P network layer

This is the heart of Part 11: net.rs, ~500 lines that turn every process into a peer on one gossip topic. Read it top to bottom before applying it — it packs several ideas that each earned their own debugging session:

  1. Role — Host or Client. The host owns the engine and answers; clients dial and render.
  2. Packet — the wire type. Action { player_id, msg } travels client → host; Server(msg) travels host → everyone.
  3. Session — the uniform handle the UI consumes: role, ids, the host's node id, and an UnboundedSender you push actions into. The receiver side of the event stream is deliberately separate so Session stays Clone for Dioxus.
  4. connect(role, name, host_id) — endpoint setup, gossip subscribe, glue tasks, returns (Session, event_receiver).
  5. Host vs client glue — two different select! loops, described below.
  6. The test module — a host + client in one process proving the two gossip hops (Join→State, Move→PlayerMoved).

The iroh-specific gotchas are flagged in the callouts after the code.

mud-engine/src/game/net.rs
//! P2P networking layer.
//!
//! One gossip topic (`TOPIC_NAME`) carries two kinds of [`Packet`]:
//!
//! - **`Action`** — a player's request, sent client → host. The player's
//!   identity travels with it, so the host's `GameEngine` can act on it.
//! - **`Server`** — an authoritative [`ServerMessage`] broadcast host → everyone.
//!
//! The host runs the `GameEngine` and answers every `Action` with `Server`
//! broadcasts. Desktop peers carry their own actions into the topic with
//! iroh (QUIC + gossip); the browser path (Part 11 step 2) does the same
//! through a WebSocket relay.

use serde::{Deserialize, Serialize};
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};

use super::engine::GameEngine;
use super::messages::{ClientMessage, ServerMessage};

/// Name of the gossip topic every peer subscribes to.
pub const TOPIC_NAME: &str = "mud-engine";

/// The two roles a process can play.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Role {
    /// Owns the authoritative `GameEngine` and the gossip topic's genesis.
    Host,
    /// Dials the host and renders the state it broadcasts.
    Client,
}

/// Wire protocol on the gossip topic.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Packet {
    /// Player → host: a request carrying the sender's identity.
    Action {
        player_id: String,
        msg: ClientMessage,
    },
    /// Host → everyone: an authoritative state change.
    Server(ServerMessage),
}

/// The uniform transport handle the UI consumes and feeds. The same
/// `Session` shape is used on host, desktop client, and (step 2) browser.
#[derive(Clone)]
pub struct Session {
    pub role: Role,
    /// This process's player id (a fresh uuid per session).
    pub my_id: String,
    /// The player name typed on the connection screen.
    pub my_name: String,
    /// Our iroh node id — the string a host shares so others can join.
    pub node_id: String,
    /// The host's node id (empty for the host itself).
    pub host_id: String,
    /// Queue for our own actions (player id + request).
    pub send: UnboundedSender<(String, ClientMessage)>,
}

/// Build a session for the given role, dialing `host_id` when joining.
/// Returns the session *and* the authoritative event stream the UI renders —
/// the receiver is deliberately not part of `Session` so that handle stays
/// `Clone` and can live in a Dioxus signal.
pub async fn connect(
    role: Role,
    my_name: String,
    host_id: Option<String>,
) -> Result<(Session, UnboundedReceiver<ServerMessage>), String> {
    let my_id = uuid::Uuid::new_v4().to_string();

    #[cfg(not(target_arch = "wasm32"))]
    {
        iroh::connect(role, my_name, host_id, &my_id).await
    }

    #[cfg(target_arch = "wasm32")]
    {
        // Step 2: browsers cannot speak QUIC, so they reach the host's gossip
        // topic through the WebSocket relay instead.
        let host_id = host_id.as_deref().unwrap_or("");
        crate::game::relay::connect(&my_name, &my_id, host_id).await
    }
}

/// The iroh (desktop) implementation of [`connect`].
#[cfg(not(target_arch = "wasm32"))]
mod iroh {
    use std::collections::HashMap;
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

    use iroh::endpoint::presets::N0;
    use iroh::protocol::Router;
    use iroh::{Endpoint, EndpointId, SecretKey};
    use iroh_gossip::api::Event;
    use iroh_gossip::proto::TopicId;
    use iroh_gossip::{ALPN, Gossip};
    use iroh_mdns_address_lookup::MdnsAddressLookup;
    use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
    use tokio::time::{MissedTickBehavior, interval};

    use super::super::engine;
    use super::super::messages::{ClientMessage, ServerMessage};
    use super::{Packet, Role, Session, TOPIC_NAME};

    /// How often the host flushes its state to Players.toml.
    const AUTOSAVE_INTERVAL: Duration = Duration::from_secs(60);

    /// File that stores the host's persistent identity (a 32-byte secret key).
    /// Keeping it stable means the host's node id (`Session::node_id`) survives
    /// restarts — otherwise players would need a new id every launch.
    const SECRET_FILE: &str = "host.secret";

    /// One event from the gossip topic, forwarded through a plain mpsc so the
    /// host glue task can `select!` over it together with the UI's send queue.
    enum NetEvent {
        Message(Option<EndpointId>, Packet),
        NeighborDown(EndpointId),
    }

    pub async fn connect(
        role: Role,
        my_name: String,
        host_id: Option<String>,
        my_id: &str,
    ) -> Result<(Session, UnboundedReceiver<ServerMessage>), String> {
        // Only the host persists a stable identity (its world's node id stays
        // fixed between launches); a client's key is ephemeral — it dials out.
        let secret_key = match role {
            Role::Host => load_secret_key(),
            Role::Client => SecretKey::generate(),
        };

        // The relay (n0's public server, baked into `N0`) is the mesh's fallback:
        // it punches a hole when direct fails and relays packets across NATs.
        // `MdnsAddressLookup` adds a LAN shortcut — peers on the same network
        // (or the same machine) dial the host's broadcast address directly
        // without touching the relay.
        let endpoint = Endpoint::builder(N0)
            .secret_key(secret_key)
            .address_lookup(MdnsAddressLookup::builder().service_name(TOPIC_NAME))
            .bind()
            .await
            .map_err(|e| format!("endpoint bind failed: {e}"))?;
        // Wait for the first network report (it needs to reach one relay
        // server, so the client can dial whatever the host's node id resolves
        // to). Without this the dial below stalls before sending a byte.
        endpoint.online().await;

        let full_node_id = endpoint.id();
        let node_id_text = full_node_id.to_string();

        let gossip = Gossip::builder().spawn(endpoint.clone());
        // Accept the gossip protocol on our endpoint; without this the
        // incoming QUIC connections for gossip would never be answered.
        // Note: the `Router` handle *must* stay alive — dropping it (as with
        // a bare `_router =`) aborts the accept loop and kills the endpoint.
        let router = Router::builder(endpoint.clone())
            .accept(ALPN, gossip.clone())
            .spawn();
        tokio::spawn(async move {
            let _router = router;
            std::future::pending::<()>().await;
        });

        let topic: TopicId = blake3::hash(TOPIC_NAME.as_bytes()).into();

        // The host is the mesh's genesis and subscribes to nothing; peers
        // bootstrap onto the topic by dialing the host's node id, whose LAN
        // address is found via mDNS.
        let bootstrap: Vec<EndpointId> = match role {
            Role::Host => Vec::new(),
            Role::Client => {
                let node = host_id
                    .as_deref()
                    .ok_or_else(|| "joining requires the host's node id".to_string())?
                    .parse::<EndpointId>()
                    .map_err(|e| format!("bad host node id: {e}"))?;
                vec![node]
            }
        };

        let mut topic_handle = gossip
            .subscribe(topic, bootstrap)
            .await
            .map_err(|e| format!("topic subscribe failed: {e}"))?;

        // A client waits until it actually reaches the host — otherwise it
        // would sit in a silent, empty topic forever.
        if role == Role::Client {
            topic_handle
                .joined()
                .await
                .map_err(|e| format!("host {host_id:?} unreachable: {e}"))?;
        }

        let (sender, receiver) = topic_handle.split();

        let (events_tx, events_rx) = unbounded_channel();
        let (send_tx, send_rx) = unbounded_channel();

        match role {
            Role::Host => {
                spawn_host_glue(sender, receiver, events_tx, send_rx);
            }
            Role::Client => spawn_client_glue(sender, receiver, events_tx, send_rx),
        }

        Ok((
            Session {
                role,
                my_id: my_id.to_string(),
                my_name,
                node_id: node_id_text,
                host_id: host_id.unwrap_or_default(),
                send: send_tx,
            },
            events_rx,
        ))
    }

    /// Load the persistent host key, generating and saving one on first run.
    fn load_secret_key() -> SecretKey {
        if let Ok(hex) = std::fs::read_to_string(SECRET_FILE)
            && let Ok(bytes) = hex_to_bytes(hex.trim())
        {
            return SecretKey::from_bytes(&bytes);
        }
        let key = SecretKey::generate();
        let _ = std::fs::write(SECRET_FILE, bytes_to_hex(key.to_bytes()));
        key
    }

    fn hex_to_bytes(hex: &str) -> Result<[u8; 32], ()> {
        if hex.len() != 64 {
            return Err(());
        }
        let mut out = [0u8; 32];
        for (i, b) in out.iter_mut().enumerate() {
            *b = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).map_err(|_| ())?;
        }
        Ok(out)
    }

    fn bytes_to_hex(bytes: [u8; 32]) -> String {
        bytes.iter().map(|b| format!("{b:02x}")).collect()
    }

    /// Convert the gossip event stream into a plain mpsc so `.await` on a
    /// receiver works alongside the UI's send queue in a `select!`.
    fn fork_events(mut receiver: iroh_gossip::api::GossipReceiver, tx: UnboundedSender<NetEvent>) {
        tokio::spawn(async move {
            use n0_future::StreamExt;
            while let Some(Ok(event)) = receiver.next().await {
                match event {
                    Event::Received(msg) => {
                        let from = Some(msg.delivered_from);
                        match serde_json::from_slice(&msg.content) {
                            Ok(packet) => {
                                if tx.send(NetEvent::Message(from, packet)).is_err() {
                                    break;
                                }
                            }
                            // Packets we don't understand (a future workshop
                            // version, another app on the same topic) are noise.
                            Err(_) => continue,
                        }
                    }
                    Event::NeighborDown(endpoint_id) => {
                        if tx.send(NetEvent::NeighborDown(endpoint_id)).is_err() {
                            break;
                        }
                    }
                    _ => {}
                }
            }
        });
    }

    /// Send a batch of authoritative messages to everyone (gossip) and, if this
    /// process is the host, also into the local UI event pipe.
    async fn publish(
        sender: &iroh_gossip::api::GossipSender,
        messages: Vec<ServerMessage>,
        events_tx: &UnboundedSender<ServerMessage>,
    ) {
        for message in messages {
            let payload = serde_json::to_vec(&Packet::Server(message.clone()))
                .expect("serialize packet")
                .into();
            let _ = sender.broadcast(payload).await;
            let _ = events_tx.send(message);
        }
    }

    /// The host never publishes — it *answers* actions and broadcasts the
    /// results. Its own local actions travel to the engine through `send_rx`
    /// just like a remote player's do through gossip.
    fn spawn_host_glue(
        sender: iroh_gossip::api::GossipSender,
        receiver: iroh_gossip::api::GossipReceiver,
        events_tx: UnboundedSender<ServerMessage>,
        send_rx: UnboundedReceiver<(String, ClientMessage)>,
    ) {
        let engine = Arc::new(Mutex::new(engine::GameEngine::load()));
        spawn_autosave(engine.clone());

        let (net_tx, mut net_rx) = unbounded_channel();
        fork_events(receiver, net_tx);
        let mut send_rx = send_rx;

        let mut player_nodes: HashMap<EndpointId, String> = HashMap::new();

        // The host's own actions are local — but the host's engine task still
        // needs to react to them. Because iroh-gossip does not echo a node's
        // own broadcast back to it, the UI's send queue feeds the engine
        // directly through `send_rx`, indistinguishable from a remote action.
        let engine_task = tokio::spawn(async move {
            loop {
                let event = tokio::select! {
                    ev = net_rx.recv() => match ev {
                        Some(ev) => ev,
                        None => break,
                    },
                    msg = send_rx.recv() => {
                        match msg {
                            Some((player_id, request)) => {
                                NetEvent::Message(None, Packet::Action { player_id, msg: request })
                            }
                            None => break,
                        }
                    }
                };

                let messages = match event {
                    NetEvent::Message(Some(node), Packet::Action { player_id, msg }) => {
                        player_nodes.insert(node, player_id.clone());
                        let mut eng = engine.lock().unwrap();
                        eng.handle(&player_id, msg)
                    }
                    NetEvent::Message(None, Packet::Action { player_id, msg }) => {
                        let mut eng = engine.lock().unwrap();
                        eng.handle(&player_id, msg)
                    }
                    NetEvent::Message(_, Packet::Server(_)) => Vec::new(),
                    NetEvent::NeighborDown(node) => {
                        // A peer's node left the mesh → their player left.
                        let Some(player_id) = player_nodes.remove(&node) else {
                            continue;
                        };
                        let mut eng = engine.lock().unwrap();
                        eng.leave(&player_id)
                    }
                };

                publish(&sender, messages, &events_tx).await;
            }
        });

        // Spawned for its side effect: the engine loop keeps answering actions
        // for as long as this session lives (tokio tasks run independently, so
        // the dropped JoinHandle only detaches it, never cancels it).
    }

    /// A client renders whatever the host broadcasts and forwards its own
    /// actions into the gossip topic.
    fn spawn_client_glue(
        sender: iroh_gossip::api::GossipSender,
        receiver: iroh_gossip::api::GossipReceiver,
        events_tx: UnboundedSender<ServerMessage>,
        send_rx: UnboundedReceiver<(String, ClientMessage)>,
    ) {
        let (net_tx, mut net_rx) = unbounded_channel();
        fork_events(receiver, net_tx.clone());

        // UI actions → gossip
        tokio::spawn(async move {
            let mut send_rx = send_rx;
            while let Some((player_id, msg)) = send_rx.recv().await {
                let payload = serde_json::to_vec(&Packet::Action { player_id, msg })
                    .expect("serialize packet")
                    .into();
                let _ = sender.broadcast(payload).await;
            }
        });

        // gossip → UI events
        tokio::spawn(async move {
            while let Some(event) = net_rx.recv().await {
                if let NetEvent::Message(_, Packet::Server(message)) = event
                    && events_tx.send(message).is_err()
                {
                    break;
                }
            }
        });
    }

    fn spawn_autosave(engine: Arc<Mutex<engine::GameEngine>>) {
        tokio::spawn(async move {
            let mut tick = interval(AUTOSAVE_INTERVAL);
            tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
            tick.tick().await; // first tick fires immediately — wait a full interval

            loop {
                tick.tick().await;
                let snapshot = {
                    let engine = engine.lock().unwrap();
                    super::super::persistence::snapshot(&engine.state)
                };
                super::super::persistence::write_players(&snapshot);
            }
        });
    }
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use super::*;
    use std::time::Duration;

    /// Spin up a host and a client in one process and check the two gossip
    /// hops: client Join → host engine → broadcast State back to the client,
    /// then client Move → host engine → broadcast PlayerMoved to the client.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn host_and_client_exchange_state_over_gossip() {
        tracing_subscriber::fmt()
            .with_env_filter(std::env::var("RUST_LOG").unwrap_or_else(|_| "info".into()))
            .try_init()
            .ok();
        let (host, mut _host_events) =
            connect(Role::Host, "Host".into(), None).await.expect("host connects");
        let (client, mut client_events) = tokio::time::timeout(
            Duration::from_secs(20),
            connect(
                Role::Client,
                "Client".into(),
                Some(host.node_id.clone()),
            ),
        )
        .await
        .expect("client dials host within 20s")
        .expect("client dials host");

        let _ = client.send.send((
            client.my_id.clone(),
            ClientMessage::Join { name: "Client".into() },
        ));

        let mut joined = false;
        let mut state = false;
        let deadline = tokio::time::sleep(Duration::from_secs(15));
        tokio::pin!(deadline);
        loop {
            tokio::select! {
                _ = &mut deadline => panic!("timed out waiting for join (joined={joined} state={state})"),
                maybe = client_events.recv() => {
                    let Some(msg) = maybe else { panic!("event stream closed"); };
                    match msg {
                        ServerMessage::PlayerJoined(p) if p.name == "Client" => joined = true,
                        ServerMessage::State { your_id, players, .. } => {
                            assert_eq!(your_id, client.my_id);
                            // The host is a referee, not a player: only clients
                            // appear in the player list once they join.
                            assert!(players.iter().any(|p| p.name == "Client"));
                            state = true;
                        }
                        _ => {}
                    }
                    if joined && state {
                        break;
                    }
                }
            }
        }

        // A move from the client should round-trip through the host engine.
        let _ = client.send.send((
            client.my_id.clone(),
            ClientMessage::Move { direction: "east".into() },
        ));
        let deadline = tokio::time::sleep(Duration::from_secs(15));
        tokio::pin!(deadline);
        loop {
            tokio::select! {
                _ = &mut deadline => panic!("timed out waiting for the move echo"),
                maybe = client_events.recv() => {
                    let Some(msg) = maybe else { panic!("event stream closed"); };
                    if let ServerMessage::PlayerMoved(p) = msg {
                        assert_eq!(p.id, client.my_id);
                        break;
                    }
                }
            }
        }
    }
}
🧠 The relay, online(), and why direct-only stalls

The block uses Endpoint::builder(N0) + endpoint.online().await — two choices that each look unnecessary and each broke the mesh when removed:

  • N0 is the relay preset. iroh's public relay network (n0's relay.n0.iroh.link) is the mesh's fallback: it punches the hole when direct dialing fails and relays packets across NATs. N0 makes your node id resolvable, which is what clients dial.

  • endpoint.online() waits for the first net report, which needs one relay reach. On machines with many docker bridges (172.16–172.27 interfaces), endpoint.addr() advertises addresses whose ports match no real socket; dialing those before online() times out instead of falling through to the relay. Keep N0, call online() before connect() returns the session, and the dial succeeds in tens of milliseconds. (Direct-only play — N0DisableRelay — plus a multi-interface host is the one combination that reliably stalls the join.)

  • mDNS is a shortcut, not a fix. MdnsAddressLookup::builder().service_name(...) lets a client find the host's LAN address from its node id alone, so same-network and same-machine peers dial directly. Keep it — but on the LAN it is the cherry on top, not the mechanism that makes joining work. (That is online() + the relay, above.)

🧠 The Router guard — drop it and the mesh dies

Router::spawn() is #[must_use] for a reason: dropping the Router handle aborts the accept loop and kills the endpoint. A bare _router = ... looks harmless, compiles clean, and is the classic "host starts, then silently dies a second later" bug. The code keeps the router alive for the session's lifetime by detaching it into a task that just waits forever:

let router = Router::builder(endpoint.clone())
    .accept(ALPN, gossip.clone())
    .spawn();
tokio::spawn(async move {
    let _router = router;
    std::future::pending::<()>().await;
});

The router task holds the handle; the tokio::spawn outer task lives until the session is torn down. The same guard runs on host and client — a client needs its own accept loop, not for peers but so that gossip's stream setup completes.

🧠 Keys: host persists, client is ephemeral

A node id is derived from an Ed25519 secret key, so a process's node id changes whenever its key does. The host must keep its node id stable between launches — otherwise players would need a new id every time you restart. The host's key is a hex host.secret file in the working directory (load_secret_key reads it, SecretKey::from_bytes), created on first launch.

Clients don't need that: they dial out, nothing dials them. So a client role simply does SecretKey::generate() — a fresh ephemeral identity per session.

🧠 The topic id is a blake3 hash

TopicId::from_string can panic on invalid input and is version-sensitive. Instead the topic id is derived deterministically:

let topic: TopicId = blake3::hash(TOPIC_NAME.as_bytes()).into();

Any peer that agrees on TOPIC_NAME ("mud-engine") derives the same 32-byte id, so there is no serialization, no config sync, and no way to mistype it.

🧠 How the host glue answers

The host's engine task select!s over two sources: gossip events (NetEvent::Message / NetEvent::NeighborDown via fork_events) and the UI's own action queue (send_rx). Every Action gets routed through the engine, and the resulting Vec<ServerMessage> is both broadcast to the mesh and pushed into the local UI's event pipe (publish).

Two details worth noticing:

  • Players are tracked by node id. player_nodes: HashMap<EndpointId, String> maps each gossiper's QUIC node to its player_id. The engine never sees the node id; the glue resolves it. When NeighborDown(node) arrives (a peer dropped from the mesh), the glue looks the player up and calls engine.leave().
  • The host plays through the same engine task as everyone else. iroh-gossip does not echo your own broadcast back to you, so the host's own actions go through send_rx — indistinguishable from a remote action. This is why the host can actually play (its actions are just Action packets too), even though it is also the referee.
🧠 Client glue is a dumb pipe

The client forks two tasks: actions travel UI → gossip (send_rx → Packet::Action broadcasts), and gossip events travel mesh → UI (NetEvent → Packet::Server → the ServerMessage stream). Anything that isn't a ServerMessage (another client's Action, garbage bytes, a future protocol version) is ignored — clients render authority, they don't forward player actions.

🧠 The gossip round-trip test

At the bottom of net.rs a #[cfg(all(test, not(target_arch = "wasm32")))] module spins up one host and one client in a single test process and proves the two gossip hops:

  1. client broadcasts Join → host engine registers it → host broadcasts State (client applies it when your_id matches) and PlayerJoined
  2. client broadcasts Move { east } → host engine moves it → host broadcasts PlayerMoved back

Three traps baked into the test, each a lesson:

  • It must be multi_thread. With tokio's default single-thread current_thread runtime, the mesh's internal tasks starve the join: the test hangs until the 15s deadline. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] joins in ~100ms. The same rule applies to the real app — the desktop runtime is a multi-thread tokio runtime, so this never bites there.
  • The host is a referee, not a player. The State snapshot's players must contain "Client" but must not contain a host player id. The old Axum server showed the host as a player; on the mesh the host participates through its own actions but never registers under a name.
  • The teardown noise is benign. When the two Sessions drop at test end you see ERROR … Endpoint dropped without calling Endpoint::close — that's just the endpoints going down mid-flight; the test has already passed.
Step 7 / 14