garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /p2p/src/tests.rs

raw

extern crate std;

use super::*;
use std::vec;

fn node(n: u8, name: &str) -> Node {
    Node::new(Identity::from_seed([n; 32]), name, [n.wrapping_add(100); 32])
}

fn addr(n: u8) -> Addr {
    Addr {
        ip: [10, 0, 0, n],
        port: 7000,
    }
}

/// Delivers datagrams between nodes (index i is at addr(i + 1)) until
/// quiet, advancing time and polling; `drop` loses the datagrams it picks.
fn run(nodes: &mut [&mut Node], mut now: u64, rounds: usize, drop: &mut dyn FnMut(&[u8]) -> bool) -> u64 {
    for _ in 0..rounds {
        let mut moved = true;
        while moved {
            moved = false;
            for from in 0..nodes.len() {
                while let Some((to, data)) = nodes[from].transmit() {
                    moved = true;
                    if drop(&data) {
                        continue;
                    }
                    let target = usize::from(to.ip[3]) - 1;
                    if target < nodes.len() {
                        nodes[target].receive(addr(from as u8 + 1), &data, now);
                    }
                }
            }
        }
        now += 500;
        for n in nodes.iter_mut() {
            n.poll(now);
        }
    }
    now
}

/// A network whose devices can change address, which loses one datagram
/// in `loss` (0: none) and delivers each step's datagrams shuffled.
struct Net {
    addrs: Vec<Addr>,
    now: u64,
    loss: u64,
    seed: u64,
    /// Datagrams sent, by kind (the first byte), for what a test counts.
    shuffle: bool,
    sent: Vec<(usize, u8)>,
}

impl Net {
    fn new(n: usize, loss: u64) -> Net {
        Net {
            addrs: (0..n).map(|i| addr(i as u8 + 1)).collect(),
            now: 0,
            loss,
            seed: 0x2545_f491_4f6c_dd1d,
            sent: Vec::new(),
            shuffle: true,
        }
    }

    fn random(&mut self) -> u64 {
        // xorshift64: the same run every time.
        self.seed ^= self.seed << 13;
        self.seed ^= self.seed >> 7;
        self.seed ^= self.seed << 17;
        self.seed
    }

    /// Runs `ms` of time in steps of 100 ms; `drop` may lose a datagram
    /// (from, to, data) besides the network's own losses.
    fn run(&mut self, nodes: &mut [&mut Node], ms: u64, drop: &mut dyn FnMut(usize, Addr, &[u8]) -> bool) {
        let end = self.now + ms;
        while self.now < end {
            loop {
                let mut batch = Vec::new();
                for (from, n) in nodes.iter_mut().enumerate() {
                    while let Some((to, data)) = n.transmit() {
                        batch.push((from, to, data));
                    }
                }
                if batch.is_empty() {
                    break;
                }
                for k in (1..batch.len()).rev() {
                    let j = (self.random() % (k as u64 + 1)) as usize;
                    if self.shuffle {
                        batch.swap(k, j);
                    }
                }
                for (from, to, data) in batch {
                    self.sent.push((from, data[0]));
                    if self.loss > 0 && self.random().is_multiple_of(self.loss) || drop(from, to, &data) {
                        continue;
                    }
                    if let Some(target) = self.addrs.iter().position(|a| *a == to) {
                        nodes[target].receive(self.addrs[from], &data, self.now);
                    }
                }
            }
            self.now += 100;
            for n in nodes.iter_mut() {
                n.poll(self.now);
            }
        }
    }

    fn quiet(&mut self, nodes: &mut [&mut Node], ms: u64) {
        self.run(nodes, ms, &mut |_, _, _| false);
    }
}

fn events(n: &mut Node) -> Vec<Event> {
    core::iter::from_fn(|| n.event()).collect()
}

/// What a stream delivered to `n`, its data joined, and whether it finished.
fn stream_bytes(evs: &[Event], stream: u32) -> (Vec<u8>, bool) {
    let mut bytes = Vec::new();
    let mut finished = false;
    for e in evs {
        match e {
            Event::StreamData { stream: s, data, .. } if *s == stream => bytes.extend_from_slice(data),
            Event::StreamFinished { stream: s, .. } if *s == stream => finished = true,
            _ => {}
        }
    }
    (bytes, finished)
}

/// A helper, Ada and Bo, at addr(1..=3), who know each other's cards and
/// joined the DHT through the helper; none told its public address.
fn three() -> (Node, Node, Node, Net) {
    let (mut helper, mut ada, mut bo) = (node(1, "helper"), node(2, "Ada"), node(3, "Bo"));
    ada.add_contact(*bo.card());
    bo.add_contact(*ada.card());
    ada.bootstrap(addr(1), 0);
    bo.bootstrap(addr(1), 0);
    let mut net = Net::new(3, 0);
    net.quiet(&mut [&mut helper, &mut ada, &mut bo], 3000);
    (helper, ada, bo, net)
}

#[test]
fn a_session_needs_no_server() {
    // Three devices: one only helps; Ada and Bo know each other's cards.
    let (mut helper, mut ada, mut bo) = (node(1, "helper"), node(2, "Ada"), node(3, "Bo"));
    ada.set_public_address(addr(2));
    bo.set_public_address(addr(3));
    ada.add_contact(*bo.card());
    bo.add_contact(*ada.card());
    ada.bootstrap(addr(1), 0);
    bo.bootstrap(addr(1), 0);
    let now = run(&mut [&mut helper, &mut ada, &mut bo], 0, 4, &mut |_| false);

    // Ada finds Bo through the DHT and writes; Bo answers.
    let bo_key = bo.card().key;
    ada.send(&bo_key, b"hello Bo".to_vec(), now);
    let now = run(&mut [&mut helper, &mut ada, &mut bo], now, 8, &mut |_| false);
    let got = events(&mut bo);
    assert!(
        got.contains(&Event::Received {
            from: ada.card().key,
            payload: b"hello Bo".to_vec()
        }),
        "{got:?}"
    );
    bo.send(&ada.card().key, b"hi Ada".to_vec(), now);
    run(&mut [&mut helper, &mut ada, &mut bo], now, 2, &mut |_| false);
    assert!(events(&mut ada).contains(&Event::Received {
        from: bo_key,
        payload: b"hi Ada".to_vec()
    }));
}

#[test]
fn a_withdrawn_payload_never_goes() {
    let (mut helper, mut ada, mut bo) = (node(1, "helper"), node(2, "Ada"), node(3, "Bo"));
    ada.set_public_address(addr(2));
    bo.set_public_address(addr(3));
    ada.add_contact(*bo.card());
    bo.add_contact(*ada.card());
    ada.bootstrap(addr(1), 0);
    bo.bootstrap(addr(1), 0);
    let now = run(&mut [&mut helper, &mut ada, &mut bo], 0, 4, &mut |_| false);
    // Two wait for the session; one went by text meanwhile.
    let bo_key = bo.card().key;
    ada.send(&bo_key, b"texted instead".to_vec(), now);
    ada.send(&bo_key, b"still to go".to_vec(), now);
    ada.withdraw(&bo_key, |p| p.starts_with(b"texted"));
    run(&mut [&mut helper, &mut ada, &mut bo], now, 8, &mut |_| false);
    let got: Vec<Vec<u8>> = events(&mut bo)
        .into_iter()
        .filter_map(|e| match e {
            Event::Received { payload, .. } => Some(payload),
            _ => None,
        })
        .collect();
    assert_eq!(got, vec![b"still to go".to_vec()]);
}

#[test]
fn a_device_learns_its_address_from_the_nodes() {
    let (helper, ada, bo, _) = three();
    let _ = helper;
    assert_eq!(ada.address(), Some(addr(2)));
    assert_eq!(bo.address(), Some(addr(3)));
}

#[test]
fn strangers_cannot_open_a_session() {
    let (mut ada, mut eve) = (node(2, "Ada"), node(5, "Eve"));
    eve.add_contact(*ada.card());
    eve.set_public_address(addr(2));
    // Eve knows where Ada is, but Ada does not know Eve.
    eve.peers[0].addr = Some(addr(1));
    eve.send(&ada.card().key, b"let me in".to_vec(), 0);
    run(&mut [&mut ada, &mut eve], 0, 3, &mut |_| false);
    assert!(events(&mut ada).is_empty());
}

#[test]
fn a_removed_contact_is_a_stranger() {
    let (mut helper, mut ada, mut bo, mut net) = three();
    ada.send(&bo.card().key, b"before".to_vec(), net.now);
    net.quiet(&mut [&mut helper, &mut ada, &mut bo], 2000);
    assert!(
        events(&mut bo)
            .iter()
            .any(|e| matches!(e, Event::Received { .. }))
    );
    // Bo forgets Ada: her session goes, and what she sends is not taken.
    bo.remove_contact(&ada.card().key);
    assert_eq!(bo.contacts().count(), 0);
    ada.send(&bo.card().key, b"after".to_vec(), net.now);
    net.quiet(&mut [&mut helper, &mut ada, &mut bo], 30_000);
    assert!(
        !events(&mut bo)
            .iter()
            .any(|e| matches!(e, Event::Received { .. })),
        "a removed contact still reached Bo"
    );
}

#[test]
fn a_replayed_message_is_refused() {
    let (mut ada, mut bo) = (node(2, "Ada"), node(3, "Bo"));
    ada.add_contact(*bo.card());
    bo.add_contact(*ada.card());
    // Bo is node 0 below, at addr(1).
    ada.peers[0].addr = Some(addr(1));
    ada.send(&bo.card().key, b"once".to_vec(), 0);
    // Keep a copy of every DATA datagram on the way.
    let mut copies = vec![];
    run(&mut [&mut bo, &mut ada], 0, 2, &mut |d| {
        if d[0] == DATA {
            copies.push(d.to_vec());
        }
        false
    });
    assert_eq!(
        events(&mut bo)
            .iter()
            .filter(|e| matches!(e, Event::Received { .. }))
            .count(),
        1
    );
    for copy in copies {
        bo.receive(addr(2), &copy, 5000);
    }
    assert!(
        !events(&mut bo)
            .iter()
            .any(|e| matches!(e, Event::Received { .. })),
        "a replay got through"
    );
}

#[test]
fn a_replayed_hello_moves_nothing() {
    let (mut ada, mut bo) = (node(2, "Ada"), node(3, "Bo"));
    ada.add_contact(*bo.card());
    bo.add_contact(*ada.card());
    ada.peers[0].addr = Some(addr(1));
    ada.send(&bo.card().key, b"hi".to_vec(), 0);
    let mut hello = None;
    run(&mut [&mut bo, &mut ada], 0, 2, &mut |d| {
        if d[0] == HELLO {
            hello = Some(d.to_vec());
        }
        false
    });
    let session = bo.peers[0].session.as_ref().unwrap().id;
    while bo.transmit().is_some() {}
    // Someone recorded Ada's HELLO and plays it to Bo from elsewhere.
    bo.receive(addr(9), &hello.unwrap(), 10_000);
    assert!(bo.transmit().is_none(), "Bo answered a replayed HELLO");
    assert_eq!(bo.peers[0].session.as_ref().unwrap().id, session);
    assert_eq!(bo.peers[0].addr, Some(addr(2)));
}

#[test]
fn cards_are_signed() {
    let ada = node(2, "Ada");
    let mut bytes = ada.card().to_bytes();
    assert!(Card::from_bytes(&bytes).is_some());
    bytes[70] ^= 1;
    assert!(Card::from_bytes(&bytes).is_none());
}

#[test]
fn a_stream_arrives_whole_through_loss_and_reordering() {
    let (mut ada, mut bo) = (node(2, "Ada"), node(3, "Bo"));
    ada.add_contact(*bo.card());
    bo.add_contact(*ada.card());
    ada.peers[0].addr = Some(addr(2));
    // One datagram in five lost, every step's shuffled.
    let mut net = Net::new(2, 5);
    let bo_key = bo.card().key;
    let id = ada.open_stream(&bo_key, "test", 0).unwrap();
    let sent: Vec<u8> = (0..200_000u32).map(|i| (i * 7 + i / 251) as u8).collect();
    ada.stream_write(&bo_key, id, &sent, 0);
    ada.stream_finish(&bo_key, id, 0);
    net.quiet(&mut [&mut ada, &mut bo], 60_000);
    let got = events(&mut bo);
    assert!(got.contains(&Event::StreamOpened {
        contact: ada.card().key,
        stream: id,
        service: "test".into(),
    }));
    let (bytes, finished) = stream_bytes(&got, id);
    assert_eq!(bytes.len(), sent.len());
    assert!(bytes == sent, "the stream's bytes differ");
    assert!(finished);
    assert_eq!(ada.stream_backlog(&bo_key, id), 0);
}

#[test]
fn a_device_that_moves_is_answered_where_it_went() {
    let (mut helper, mut ada, mut bo, mut net) = three();
    let (ada_key, bo_key) = (ada.card().key, bo.card().key);
    let id = ada.open_stream(&bo_key, "test", net.now).unwrap();
    ada.stream_write(&bo_key, id, b"before", net.now);
    net.quiet(&mut [&mut helper, &mut ada, &mut bo], 1000);
    assert_eq!(stream_bytes(&events(&mut bo), id).0, b"before");

    // Bo gets another address, and knows it.
    net.addrs[2] = addr(30);
    bo.network_changed(net.now);
    net.quiet(&mut [&mut helper, &mut ada, &mut bo], 500);
    assert_eq!(
        ada.peers[0].addr,
        Some(addr(30)),
        "Ada still answers the old address"
    );
    assert_eq!(bo.address(), Some(addr(30)));

    ada.stream_write(&bo_key, id, b" and after", net.now);
    bo.stream_write(&ada_key, id, b"from here", net.now);
    net.quiet(&mut [&mut helper, &mut ada, &mut bo], 1000);
    assert_eq!(stream_bytes(&events(&mut bo), id).0, b" and after");
    assert_eq!(stream_bytes(&events(&mut ada), id).0, b"from here");
}

#[test]
fn both_moving_at_once_meet_again_through_the_dht() {
    let (mut helper, mut ada, mut bo, mut net) = three();
    let (ada_key, bo_key) = (ada.card().key, bo.card().key);
    let id = ada.open_stream(&bo_key, "test", net.now).unwrap();
    net.quiet(&mut [&mut helper, &mut ada, &mut bo], 1000);

    // Both move, neither noticing (a NAT that gave them new ports): what
    // each sends the other goes to an address no longer there.
    net.addrs[1] = addr(20);
    net.addrs[2] = addr(30);
    let moved = net.now;
    ada.stream_write(&bo_key, id, b"still there?", net.now);
    let mut bytes = Vec::new();
    while bytes.is_empty() && net.now - moved < 120_000 {
        net.quiet(&mut [&mut helper, &mut ada, &mut bo], 1000);
        bytes = stream_bytes(&events(&mut bo), id).0;
    }
    assert_eq!(bytes, b"still there?");
    // Fifteen seconds unanswered, then found in the DHT.
    std::eprintln!("both moved: found again after {} ms", net.now - moved);
    assert!(net.now - moved <= 30_000, "took {} ms", net.now - moved);
    assert_eq!(ada.peers[0].addr, Some(addr(30)));
    bo.stream_write(&ada_key, id, b"yes", net.now);
    net.quiet(&mut [&mut helper, &mut ada, &mut bo], 2000);
    assert_eq!(stream_bytes(&events(&mut ada), id).0, b"yes");
    assert_eq!(bo.peers[0].addr, Some(addr(20)));
}

#[test]
fn a_restarted_contact_ends_its_streams() {
    let (mut helper, mut ada, mut bo, mut net) = three();
    let bo_key = bo.card().key;
    let id = ada.open_stream(&bo_key, "test", net.now).unwrap();
    net.quiet(&mut [&mut helper, &mut ada, &mut bo], 1000);
    events(&mut ada);

    // Bo starts again, as the same identity: its sessions and streams gone.
    let mut bo = node(3, "Bo");
    bo.set_epoch(1);
    bo.add_contact(*ada.card());
    bo.bootstrap(addr(1), net.now);
    ada.stream_write(&bo_key, id, b"hello?", net.now);
    net.quiet(&mut [&mut helper, &mut ada, &mut bo], 40_000);
    assert!(
        events(&mut ada).contains(&Event::StreamReset {
            contact: bo_key,
            stream: id
        }),
        "Ada still thinks the stream is open"
    );
}

#[test]
fn keys_are_renewed_without_losing_a_byte() {
    let (mut helper, mut ada, mut bo, mut net) = three();
    let bo_key = bo.card().key;
    let id = ada.open_stream(&bo_key, "test", net.now).unwrap();
    net.quiet(&mut [&mut helper, &mut ada, &mut bo], 1000);
    let first = ada.peers[0].session.as_ref().unwrap().id;
    let mut sent = Vec::new();
    let mut got = Vec::new();
    // Five minutes of a line a second; every WELCOME lost once.
    let mut lost_welcome = false;
    for second in 0..300u32 {
        let line = std::format!("line {second}\n");
        ada.stream_write(&bo_key, id, line.as_bytes(), net.now);
        sent.extend_from_slice(line.as_bytes());
        net.run(&mut [&mut helper, &mut ada, &mut bo], 1000, &mut |_, _, d| {
            let lose = d[0] == WELCOME && !lost_welcome;
            if d[0] == WELCOME {
                lost_welcome = !lost_welcome;
            }
            lose
        });
        got.extend(stream_bytes(&events(&mut bo), id).0);
    }
    net.quiet(&mut [&mut helper, &mut ada, &mut bo], 5000);
    got.extend(stream_bytes(&events(&mut bo), id).0);
    assert_ne!(
        ada.peers[0].session.as_ref().unwrap().id,
        first,
        "the keys were never renewed"
    );
    assert!(got == sent, "{} of {} bytes", got.len(), sent.len());
}

#[test]
fn an_unused_session_is_let_go() {
    let (mut helper, mut ada, mut bo, mut net) = three();
    ada.send(&bo.card().key, b"hi".to_vec(), net.now);
    net.quiet(&mut [&mut helper, &mut ada, &mut bo], 1000);
    assert!(ada.peers[0].session.is_some());
    net.quiet(&mut [&mut helper, &mut ada, &mut bo], IDLE_MS + 20_000);
    assert!(ada.peers[0].session.is_none() && bo.peers[0].session.is_none());
    // And then nothing more between them.
    net.sent.clear();
    net.quiet(&mut [&mut helper, &mut ada, &mut bo], 60_000);
    assert!(
        !net.sent.iter().any(|&(from, kind)| from > 0 && kind == DATA),
        "keepalives went on"
    );
}

#[test]
fn a_stream_says_which_service_it_is_for() {
    let (mut ada, mut bo) = (node(2, "Ada"), node(3, "Bo"));
    ada.add_contact(*bo.card());
    bo.add_contact(*ada.card());
    ada.peers[0].addr = Some(addr(2));
    let mut net = Net::new(2, 0);
    let bo_key = bo.card().key;
    assert_eq!(ada.open_stream(&bo_key, "", 0), None);
    assert_eq!(ada.open_stream(&bo_key, &"x".repeat(MAX_SERVICE + 1), 0), None);
    let id = ada.open_stream(&bo_key, "model", 0).unwrap();
    ada.stream_write(&bo_key, id, b"hello", 0);
    net.quiet(&mut [&mut ada, &mut bo], 10_000);
    let got = events(&mut bo);
    let opened: Vec<_> = got
        .iter()
        .filter_map(|e| match e {
            Event::StreamOpened { service, stream, .. } => Some((service.clone(), *stream)),
            _ => None,
        })
        .collect();
    assert_eq!(opened, vec![(String::from("model"), id)]);
    // The tag is not part of the data: the service's bytes start after it.
    assert_eq!(stream_bytes(&got, id).0, b"hello");
}

/// How a simulated router maps and filters, as RFC 4787 names them.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Nat {
    /// One mapping for everywhere, open to anyone once made.
    FullCone,
    /// One mapping for everywhere, open only to where it sent: most homes.
    PortRestricted,
    /// A mapping for each address it sends to, open only to that one:
    /// carrier-grade NATs, some firewalls.
    Symmetric,
}

/// A mapping forgotten after this long with nothing sent out on it.
const NAT_IDLE_MS: u64 = 30_000;

struct Router {
    public: [u8; 4],
    kind: Nat,
    /// (inside node, the remote it is for (symmetric only), public port,
    /// when last used outward, the remotes it was sent to).
    maps: Vec<(usize, Option<Addr>, u16, u64, Vec<Addr>)>,
    next_port: u16,
}

/// A network of nodes, some on the internet at addr(i + 1), some behind
/// routers at 192.168.1.x of their own (two networks may use the same).
struct NatNet {
    private: Vec<Addr>,
    behind: Vec<Option<usize>>,
    routers: Vec<Router>,
    now: u64,
    /// Two nodes whose DHT traffic to each other is lost, as in a network
    /// of many, where two contacts are seldom each other's nodes: here
    /// pings between them would open their NATs by chance.
    apart: Option<(usize, usize)>,
}

impl NatNet {
    /// `homes[i]`: the router node i is behind, if any (an index into
    /// `nats`, whose routers are at 100.64.0.1, .2, …).
    fn new(homes: &[Option<usize>], nats: &[Nat]) -> NatNet {
        NatNet {
            private: homes
                .iter()
                .enumerate()
                .map(|(i, home)| match home {
                    None => addr(i as u8 + 1),
                    Some(_) => Addr {
                        ip: [192, 168, 1, i as u8 + 1],
                        port: 7000,
                    },
                })
                .collect(),
            behind: homes.to_vec(),
            routers: nats
                .iter()
                .enumerate()
                .map(|(r, &kind)| Router {
                    public: [100, 64, 0, r as u8 + 1],
                    kind,
                    maps: Vec::new(),
                    next_port: 40_000,
                })
                .collect(),
            now: 0,
            apart: None,
        }
    }

    /// Where `from`'s datagram to `to` appears to come from, mapping it on
    /// the way out; None where it goes nowhere (a router's own public
    /// address from inside: no hairpinning).
    fn outward(&mut self, from: usize, to: Addr) -> Option<Addr> {
        let Some(r) = self.behind[from] else {
            return Some(self.private[from]);
        };
        let same_network =
            (0..self.private.len()).any(|j| self.behind[j] == Some(r) && self.private[j] == to);
        if same_network {
            return Some(self.private[from]);
        }
        let now = self.now;
        let router = &mut self.routers[r];
        if to.ip == router.public {
            return None;
        }
        router.maps.retain(|m| now - m.3 < NAT_IDLE_MS);
        let key = (router.kind == Nat::Symmetric).then_some(to);
        let at = match router.maps.iter().position(|m| m.0 == from && m.1 == key) {
            Some(at) => at,
            None => {
                router.next_port += 1;
                router.maps.push((from, key, router.next_port, now, Vec::new()));
                router.maps.len() - 1
            }
        };
        let m = &mut router.maps[at];
        m.3 = now;
        if !m.4.contains(&to) {
            m.4.push(to);
        }
        Some(Addr {
            ip: router.public,
            port: m.2,
        })
    }

    /// Who gets a datagram for `to` that came from `src`, by its sender's
    /// network: a router lets in only what its mappings and filter allow.
    fn inward(&mut self, from: usize, src: Addr, to: Addr) -> Option<usize> {
        if let Some(j) = (0..self.private.len()).find(|&j| self.private[j] == to) {
            let reachable = self.behind[j].is_none() || self.behind[j] == self.behind[from];
            return reachable.then_some(j);
        }
        let now = self.now;
        let router = self.routers.iter_mut().find(|r| r.public == to.ip)?;
        router.maps.retain(|m| now - m.3 < NAT_IDLE_MS);
        let m = router.maps.iter().find(|m| m.2 == to.port)?;
        let open = match router.kind {
            Nat::FullCone => true,
            Nat::PortRestricted | Nat::Symmetric => m.4.contains(&src),
        };
        open.then_some(m.0)
    }

    /// The node an address is, or maps to.
    fn owner(&self, to: Addr) -> Option<usize> {
        (0..self.private.len())
            .find(|&j| self.private[j] == to)
            .or_else(|| {
                let router = self.routers.iter().find(|r| r.public == to.ip)?;
                router.maps.iter().find(|m| m.2 == to.port).map(|m| m.0)
            })
    }

    fn run(&mut self, nodes: &mut [&mut Node], ms: u64) {
        let end = self.now + ms;
        while self.now < end {
            loop {
                let mut batch = Vec::new();
                for (from, n) in nodes.iter_mut().enumerate() {
                    while let Some((to, data)) = n.transmit() {
                        batch.push((from, to, data));
                    }
                }
                if batch.is_empty() {
                    break;
                }
                for (from, to, data) in batch {
                    let dht = (PING..=STORE).contains(&data[0]);
                    if dht
                        && let (Some((a, b)), Some(j)) = (self.apart, self.owner(to))
                        && (a, b) == (from.min(j), from.max(j))
                    {
                        // Lost before any router saw it go.
                        continue;
                    }
                    let Some(src) = self.outward(from, to) else {
                        continue;
                    };
                    if let Some(j) = self.inward(from, src, to) {
                        nodes[j].receive(src, &data, self.now);
                    }
                }
            }
            self.now += 100;
            for n in nodes.iter_mut() {
                n.poll(self.now);
            }
        }
    }
}

/// A helper on the internet, Ada and Bo behind the routers `homes` names
/// (indices into `nats`), contacts of each other, each knowing only its
/// local address; after `settle` ms Ada writes and Bo answers. Whether
/// each message arrived.
fn through(homes: [Option<usize>; 2], nats: &[Nat], settle: u64) -> (bool, bool) {
    let (mut helper, mut ada, mut bo) = (node(1, "helper"), node(2, "Ada"), node(3, "Bo"));
    let mut net = NatNet::new(&[None, homes[0], homes[1]], nats);
    net.apart = Some((1, 2));
    ada.set_local_address(net.private[1]);
    bo.set_local_address(net.private[2]);
    ada.add_contact(*bo.card());
    bo.add_contact(*ada.card());
    ada.bootstrap(addr(1), 0);
    bo.bootstrap(addr(1), 0);
    net.run(&mut [&mut helper, &mut ada, &mut bo], settle);
    let (ada_key, bo_key) = (ada.card().key, bo.card().key);
    ada.send(&bo_key, b"hoi Bo".to_vec(), net.now);
    net.run(&mut [&mut helper, &mut ada, &mut bo], 10_000);
    let to_bo = events(&mut bo).contains(&Event::Received {
        from: ada_key,
        payload: b"hoi Bo".to_vec(),
    });
    bo.send(&ada_key, b"hoi Ada".to_vec(), net.now);
    net.run(&mut [&mut helper, &mut ada, &mut bo], 10_000);
    let to_ada = events(&mut ada).contains(&Event::Received {
        from: bo_key,
        payload: b"hoi Ada".to_vec(),
    });
    (to_bo, to_ada)
}

#[test]
fn two_homes_behind_nats_meet_through_an_introducer() {
    use Nat::*;
    for nats in [
        [PortRestricted, PortRestricted],
        [FullCone, PortRestricted],
        [Symmetric, FullCone],
    ] {
        assert_eq!(through([Some(0), Some(1)], &nats, 5000), (true, true), "{nats:?}");
    }
}

#[test]
fn a_way_in_stays_open_while_nothing_is_said() {
    // Five minutes after joining: the routers would have forgotten every
    // mapping, but the introducers' pings kept theirs.
    use Nat::*;
    assert_eq!(
        through([Some(0), Some(1)], &[PortRestricted, PortRestricted], 300_000),
        (true, true)
    );
}

#[test]
fn behind_the_same_router_they_meet_on_its_network() {
    // No hairpinning: the router's public address is no way between them.
    assert_eq!(
        through([Some(0), Some(0)], &[Nat::PortRestricted], 5000),
        (true, true)
    );
}

#[test]
fn a_device_on_the_internet_is_reached_from_behind_a_nat() {
    assert_eq!(through([Some(0), None], &[Nat::Symmetric], 5000), (true, true));
    assert_eq!(through([None, Some(0)], &[Nat::Symmetric], 5000), (true, true));
}

#[test]
fn two_symmetric_or_restricted_nats_need_a_relay() {
    // Each maps anew for the other, so no punch finds the way: what a
    // relay is for, which is not built.
    use Nat::*;
    assert_eq!(
        through([Some(0), Some(1)], &[Symmetric, PortRestricted], 5000),
        (false, false)
    );
}

#[test]
fn a_presence_record_names_its_introducers_and_local_address() {
    let (helper, mut ada, _, _) = three();
    ada.set_local_address(Addr {
        ip: [192, 168, 1, 2],
        port: 7000,
    });
    let record = ada.presence(10_000).unwrap();
    let p = check_presence(&record).unwrap();
    assert_eq!(p.local.map(|l| l.ip), Some([192, 168, 1, 2]));
    // The helper and Bo, the two nodes that answered Ada's pings.
    assert_eq!(p.introducers, vec![addr(1), addr(3)]);
    assert_eq!(p.identity, ada.card().key);
    let _ = helper;
    // Changed after signing: refused.
    let mut forged = record.clone();
    forged[85] ^= 1;
    assert!(check_presence(&forged).is_none());
}

#[test]
fn two_strangers_link_by_a_code() {
    // Ada's laptop and her new phone know nothing of each other; both
    // joined the DHT through a helper.
    let (mut helper, mut laptop, mut phone) = (node(1, "helper"), node(2, "Laptop"), node(3, "Phone"));
    laptop.bootstrap(addr(1), 0);
    phone.bootstrap(addr(1), 0);
    let mut net = Net::new(3, 0);
    net.quiet(&mut [&mut helper, &mut laptop, &mut phone], 3000);

    // The laptop shows a code and puts its card at the offer.
    let code = link::Code::new([0x5a; 8]);
    let offer = code.offer();
    laptop.put_link(offer, code.seal(&offer, laptop.card(), [1; 12]), net.now);
    net.quiet(&mut [&mut helper, &mut laptop, &mut phone], 2000);

    // The phone is given it, typed loosely, and finds the laptop's card.
    let typed = code.text().to_lowercase().replace('-', " ");
    let given = link::Code::parse(&typed).unwrap();
    assert_eq!(given, code);
    phone.find_link(given.offer(), net.now);
    net.quiet(&mut [&mut helper, &mut laptop, &mut phone], 2000);
    let record = events(&mut phone)
        .into_iter()
        .find_map(|e| match e {
            Event::LinkFound { place, record } if place == offer => Some(record),
            _ => None,
        })
        .expect("the offer found");
    let card = given.open(&offer, &record).expect("the offer opens");
    assert_eq!(card, *laptop.card());
    // Under another code, or at the other place, it does not open.
    assert!(link::Code::new([0x5b; 8]).open(&offer, &record).is_none());
    assert!(given.open(&given.answer(), &record).is_none());

    // The phone answers; the laptop finds it.
    let answer = given.answer();
    phone.add_contact(card);
    phone.put_link(answer, given.seal(&answer, phone.card(), [2; 12]), net.now);
    net.quiet(&mut [&mut helper, &mut laptop, &mut phone], 2000);
    laptop.find_link(code.answer(), net.now);
    net.quiet(&mut [&mut helper, &mut laptop, &mut phone], 2000);
    let record = events(&mut laptop)
        .into_iter()
        .find_map(|e| match e {
            Event::LinkFound { place, record } if place == answer => Some(record),
            _ => None,
        })
        .expect("the answer found");
    laptop.add_contact(code.open(&answer, &record).unwrap());

    // Now they are contacts: a session opens.
    laptop.send(&phone.card().key, b"in step".to_vec(), net.now);
    net.quiet(&mut [&mut helper, &mut laptop, &mut phone], 5000);
    assert!(events(&mut phone).contains(&Event::Received {
        from: laptop.card().key,
        payload: b"in step".to_vec()
    }));
}

#[test]
fn a_code_is_read_as_meant() {
    let code = link::Code::new([0xff; 8]);
    assert_eq!(code.text().len(), 14);
    assert_eq!(
        link::Code::parse("0000-0000-000O"),
        link::Code::parse("000000000000")
    );
    assert_eq!(
        link::Code::parse("IL00-0000-0000"),
        link::Code::parse("1100 0000 0000")
    );
    assert!(link::Code::parse("0000-0000-00").is_none());
    assert!(link::Code::parse("0000-0000-000U").is_none());
}