garage44.eu/jeroen/pinnacle

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

.. /bt/src/tests.rs

raw

//! Two hosts, each on a simulated controller, in one air: finding each
//! other, connecting, and GATT both ways.

use crate::gatt::{self, Characteristic, Service, Uuid};
use crate::hci::{self, Address, Framer, Packet};
use crate::host::{Event, Host};
use crate::sim::Air;
use crate::smp;
use alloc::vec::Vec;

/// Hosts and their controllers, run until nothing moves.
struct World {
    air: Air,
    hosts: Vec<Host>,
    now: u64,
    /// A host that has stopped talking to its controller.
    frozen: Option<usize>,
}

impl World {
    fn new(hosts: Vec<Host>) -> World {
        let mut air = Air::default();
        for (i, _) in hosts.iter().enumerate() {
            air.add(Address([i as u8 + 1, 0, 0, 0, 0, 0xc0]));
        }
        World {
            air,
            hosts,
            now: 0,
            frozen: None,
        }
    }

    /// Carries bytes both ways and steps the air until all is quiet.
    fn settle(&mut self) {
        for _ in 0..200 {
            let mut moved = false;
            for (i, host) in self.hosts.iter_mut().enumerate() {
                if self.frozen == Some(i) {
                    continue;
                }
                while let Some(bytes) = host.transmit() {
                    self.air.controllers[i].receive(&bytes);
                    moved = true;
                }
            }
            self.air.step();
            for (i, host) in self.hosts.iter_mut().enumerate() {
                if self.frozen == Some(i) {
                    continue;
                }
                while let Some(bytes) = self.air.controllers[i].transmit() {
                    host.receive(&bytes, self.now);
                    moved = true;
                }
            }
            self.now += 10;
            if !moved {
                return;
            }
        }
        panic!("the world did not settle");
    }

    fn events(&mut self, i: usize) -> Vec<Event> {
        let mut out = Vec::new();
        while let Some(e) = self.hosts[i].event() {
            out.push(e);
        }
        out
    }
}

fn battery_service(level: u8) -> Service {
    Service::new(
        Uuid::Short(gatt::BATTERY),
        alloc::vec![Characteristic::new(
            Uuid::Short(gatt::BATTERY_LEVEL),
            gatt::PROP_READ | gatt::PROP_NOTIFY,
            &[level],
        )],
    )
}

fn card_service(card: &[u8]) -> Service {
    Service::new(
        Uuid::Long(gatt::PINNACLE_SERVICE),
        alloc::vec![Characteristic::new(
            Uuid::Long(gatt::PINNACLE_CARD),
            gatt::PROP_READ | gatt::PROP_WRITE,
            card,
        )],
    )
}

#[test]
fn h4_frames_round_trip_and_split() {
    let packets = [
        Packet::Command {
            opcode: hci::RESET,
            parameters: Vec::new(),
        },
        Packet::Acl {
            handle: 0x41,
            continuing: true,
            data: alloc::vec![1, 2, 3],
        },
        Packet::Event {
            code: hci::EVT_COMMAND_COMPLETE,
            parameters: alloc::vec![1, 3, 0x0c, 0],
        },
    ];
    let mut bytes = Vec::new();
    for p in &packets {
        bytes.extend(p.to_h4());
    }
    let mut framer = Framer::default();
    let mut got = Vec::new();
    for b in bytes {
        framer.push(&[b]);
        while let Some(p) = framer.packet() {
            got.push(p);
        }
    }
    assert_eq!(got, packets);
}

#[test]
fn hosts_come_up_with_their_addresses() {
    let mut w = World::new(alloc::vec![
        Host::new("A", Vec::new()),
        Host::new("B", Vec::new())
    ]);
    w.settle();
    assert_eq!(
        w.events(0),
        alloc::vec![Event::Ready {
            address: Address([1, 0, 0, 0, 0, 0xc0])
        }]
    );
    assert!(w.hosts[1].ready());
    assert_eq!(w.hosts[1].address().text(), "c0:00:00:00:00:02");
}

#[test]
fn a_scanner_finds_an_advertiser_by_name() {
    let mut w = World::new(alloc::vec![
        Host::new("Scanner", Vec::new()),
        Host::new("Pinnacle Bo", Vec::new())
    ]);
    w.hosts[1].advertise(true);
    w.hosts[0].start_scan();
    w.settle();
    let found: Vec<Event> = w
        .events(0)
        .into_iter()
        .filter(|e| matches!(e, Event::Found { .. }))
        .collect();
    assert_eq!(
        found,
        alloc::vec![Event::Found {
            address: Address([2, 0, 0, 0, 0, 0xc0]),
            name: Some("Pinnacle Bo".into()),
            rssi: -47,
        }]
    );
    assert_eq!(w.hosts[0].found().len(), 1);
    // A long name is shortened to what the 31 bytes hold.
    let data = hci::advertising_data("A device with a very long name indeed");
    assert_eq!(data.len(), 31);
    assert_eq!(hci::ad_name(&data), Some("A device with a very long "));
}

#[test]
fn connect_discover_read_write_notify() {
    let mut w = World::new(alloc::vec![
        Host::new("Ada's phone", alloc::vec![card_service(b"ada-card")]),
        Host::new(
            "Bo's phone",
            alloc::vec![battery_service(87), card_service(b"bo-card")]
        ),
    ]);
    w.hosts[1].advertise(true);
    w.hosts[0].start_scan();
    w.settle();
    let bo = Address([2, 0, 0, 0, 0, 0xc0]);
    w.hosts[0].connect(bo);
    w.settle();
    let connected = w.events(0);
    let Some(Event::Connected {
        connection,
        peer,
        central: true,
    }) = connected.iter().find(|e| matches!(e, Event::Connected { .. }))
    else {
        panic!("no connection: {connected:?}");
    };
    assert_eq!(*peer, bo);
    let connection = *connection;
    assert!(
        w.events(1)
            .iter()
            .any(|e| matches!(e, Event::Connected { central: false, .. }))
    );

    w.hosts[0].discover(connection);
    w.settle();
    let discovered = w.events(0);
    let Some(Event::Discovered { services, .. }) =
        discovered.iter().find(|e| matches!(e, Event::Discovered { .. }))
    else {
        panic!("nothing discovered: {discovered:?}");
    };
    let uuids: Vec<Uuid> = services.iter().map(|s| s.uuid).collect();
    assert_eq!(
        uuids,
        alloc::vec![
            Uuid::Short(gatt::GENERIC_ACCESS),
            Uuid::Short(gatt::BATTERY),
            Uuid::Long(gatt::PINNACLE_SERVICE)
        ]
    );
    let battery = &services[1].characteristics[0];
    assert_eq!(battery.uuid, Uuid::Short(gatt::BATTERY_LEVEL));
    assert_eq!(battery.configuration, Some(battery.handle + 1));
    let name = &services[0].characteristics[0];
    let card = &services[2].characteristics[0];
    assert_eq!(card.uuid, Uuid::Long(gatt::PINNACLE_CARD));
    assert_eq!(Uuid::Long(gatt::PINNACLE_CARD).name(), Some("Contact Card"));

    // Reads: the name, the battery level, the card; a write of the card.
    w.hosts[0].read(connection, name.handle);
    w.hosts[0].read(connection, battery.handle);
    w.hosts[0].read(connection, card.handle);
    w.hosts[0].write(connection, card.handle, b"ada-card");
    w.hosts[0].subscribe(connection, battery.configuration.unwrap(), true);
    w.settle();
    let values: Vec<Vec<u8>> = w
        .events(0)
        .into_iter()
        .filter_map(|e| match e {
            Event::Read { value, .. } => Some(value),
            _ => None,
        })
        .collect();
    assert_eq!(
        values,
        alloc::vec![b"Bo's phone".to_vec(), alloc::vec![87], b"bo-card".to_vec()]
    );
    let bo_events = w.events(1);
    assert!(bo_events.contains(&Event::Changed {
        connection: 0x40,
        handle: card.handle,
        value: b"ada-card".to_vec(),
    }));
    assert!(bo_events.contains(&Event::Subscribed {
        connection: 0x40,
        handle: battery.handle,
        on: true,
    }));

    // Bo's battery drops: Ada is told.
    w.hosts[1].set_value(battery.handle, &[86]);
    w.settle();
    assert_eq!(
        w.events(0),
        alloc::vec![Event::Notified {
            connection,
            handle: battery.handle,
            value: alloc::vec![86],
        }]
    );

    // Ada hangs up; Bo advertises again, and Ada, scanning since the
    // connection was made, hears it.
    w.hosts[0].forget_found();
    w.hosts[0].disconnect(connection);
    w.settle();
    assert!(
        w.events(0)
            .contains(&Event::Disconnected { connection, peer: bo })
    );
    assert!(
        w.events(1)
            .iter()
            .any(|e| matches!(e, Event::Disconnected { .. }))
    );
    assert!(w.air.controllers[1].address() == bo);
    assert_eq!(
        w.hosts[0].found().len(),
        1,
        "Bo advertises again after the disconnection"
    );
}

#[test]
fn a_large_value_crosses_in_fragments() {
    let card: Vec<u8> = (0..160u8).collect();
    let mut w = World::new(alloc::vec![
        Host::new("Reader", Vec::new()),
        Host::new("Card holder", alloc::vec![card_service(&card)]),
    ]);
    w.hosts[1].advertise(true);
    w.hosts[0].start_scan();
    w.settle();
    w.hosts[0].connect(Address([2, 0, 0, 0, 0, 0xc0]));
    w.settle();
    w.events(0);
    w.hosts[0].discover(0x40);
    w.settle();
    let Some(Event::Discovered { services, .. }) = w
        .events(0)
        .into_iter()
        .find(|e| matches!(e, Event::Discovered { .. }))
    else {
        panic!("nothing discovered");
    };
    let handle = services[1].characteristics[0].handle;
    w.hosts[0].read(0x40, handle);
    w.settle();
    // The MTU was raised to 247 on connecting, so the whole card comes in one
    // read, carried as ACL fragments of 251 bytes at most.
    assert_eq!(
        w.events(0),
        alloc::vec![Event::Read {
            connection: 0x40,
            handle,
            value: card,
        }]
    );
}

#[test]
fn a_request_unanswered_drops_the_connection() {
    let mut w = World::new(alloc::vec![
        Host::new("A", Vec::new()),
        Host::new("B", Vec::new())
    ]);
    w.hosts[1].advertise(true);
    w.hosts[0].start_scan();
    w.settle();
    w.hosts[0].connect(Address([2, 0, 0, 0, 0, 0xc0]));
    w.settle();
    w.events(0);
    // B stops answering: its host no longer talks to its controller.
    w.frozen = Some(1);
    w.hosts[0].read(0x40, 3);
    w.settle();
    assert!(w.events(0).is_empty());
    w.now += 31_000;
    w.hosts[0].poll(w.now);
    w.settle();
    assert!(
        w.events(0)
            .iter()
            .any(|e| matches!(e, Event::Disconnected { .. }))
    );
    assert_eq!(w.hosts[0].next_deadline(), None);
}

/// Bytes from hex, as written.
fn bytes<const N: usize>(hex: &str) -> [u8; N] {
    let mut out = [0u8; N];
    for (i, b) in out.iter_mut().enumerate() {
        *b = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).unwrap();
    }
    out
}

/// The spec's sample data for f4, f5, f6 and g2 (Vol 3 Part H, Appendix
/// D), as Linux's self-test has it: over-the-air order, LSB first.
#[test]
fn pairing_functions_match_the_spec() {
    use crate::smp;
    let u = bytes::<32>("e69d350e480103ccdbfdf4ac1191f4efb9a5f9e9a7832c5e2cbe97f2d203b020");
    let v = bytes::<32>("fdc57ff449dd4f6bfb7c9df1c29acb592ae7d4eefbfc0a909abbf6323d8b1855");
    let x = bytes::<16>("abae2b71ecb2ffff3e7377d15484cbd5");
    assert_eq!(smp::f4(&u, &v, &x, 0), bytes("2d8774a9bea1edf11cbda907f116c9f2"));
    let w = bytes::<32>("98a6bf73f3348d86f166f8b4136b79999b7d390aa610103405adc857a33402ec");
    let n1 = x;
    let n2 = bytes::<16>("cfc43dfff78365216e5fa725cce7e8a6");
    let a1 = bytes::<7>("cebf3737125600");
    let a2 = bytes::<7>("c1cf2d7013a700");
    let (mac_key, ltk) = smp::f5(&w, &n1, &n2, &a1, &a2);
    assert_eq!(mac_key, bytes("206e63ce206a3ffd024a08a176f16529"));
    assert_eq!(ltk, bytes("380a7594b522059823cdd76911798669"));
    let r = bytes::<16>("c80f2d0cd242da0854bb53b43b34a312");
    let io = [0x02, 0x01, 0x01];
    assert_eq!(
        smp::f6(&mac_key, &n1, &n2, &r, &io, &a1, &a2),
        bytes("618f95da090b6cd2c5e8d09c9873c4e3")
    );
    assert_eq!(smp::g2(&u, &v, &x, &n2), 0x2f9ed5ba % 1_000_000);
}

const A: Address = Address([1, 0, 0, 0, 0, 0xc0]);
const B: Address = Address([2, 0, 0, 0, 0, 0xc0]);

/// Two hosts that may pair, `io` what each can show; B advertises a
/// writable characteristic. Each has an identity ([`irk`]) to hand over.
fn pairing_world(io: [u8; 2]) -> World {
    pairing_world_with(io, [true; 2])
}

/// The identity resolving key of the `i`th host.
fn irk(i: usize) -> [u8; 16] {
    [0xa0 + i as u8; 16]
}

/// As [`pairing_world`], an identity only where `identities` says.
fn pairing_world_with(io: [u8; 2], identities: [bool; 2]) -> World {
    let mut hosts = alloc::vec![
        Host::new("Ada's phone", Vec::new()),
        Host::new("Bo's phone", alloc::vec![card_service(b"bo-card")]),
    ];
    for (i, host) in hosts.iter_mut().enumerate() {
        host.enable_pairing([i as u8 + 0x51; 32], io[i]);
        if identities[i] {
            host.set_identity(irk(i));
        }
    }
    let mut w = World::new(hosts);
    w.hosts[1].advertise(true);
    w.settle();
    w
}

/// A connects to B: the two sides' connection handles.
fn connect(w: &mut World) -> (u16, u16) {
    let (ca, cb, _, _) = connect_seeing(w);
    (ca, cb)
}

/// As [`connect`], with what each side heard meanwhile.
fn connect_seeing(w: &mut World) -> (u16, u16, Vec<Event>, Vec<Event>) {
    w.hosts[0].connect(B);
    w.settle();
    let handle = |events: &[Event]| {
        events
            .iter()
            .find_map(|e| match e {
                Event::Connected { connection, .. } => Some(*connection),
                _ => None,
            })
            .expect("not connected")
    };
    let (ea, eb) = (w.events(0), w.events(1));
    (handle(&ea), handle(&eb), ea, eb)
}

fn disconnect(w: &mut World, connection: u16) {
    w.hosts[0].disconnect(connection);
    w.settle();
    w.events(0);
    w.events(1);
    w.hosts[1].advertise(true);
    w.settle();
}

fn code(events: &[Event]) -> Option<Option<u32>> {
    events.iter().find_map(|e| match e {
        Event::Confirm { code, .. } => Some(*code),
        _ => None,
    })
}

fn has(events: &[Event], f: impl Fn(&Event) -> bool) -> bool {
    events.iter().any(f)
}

fn heard(w: &World, what: &[u8]) -> bool {
    w.air
        .heard
        .iter()
        .any(|p| p.windows(what.len()).any(|x| x == what))
}

#[test]
fn numeric_comparison_pairs_and_the_air_hears_nothing_after() {
    let mut w = pairing_world([smp::DISPLAY_YES_NO; 2]);
    let (ca, cb) = connect(&mut w);
    let card = w.hosts[1]
        .table()
        .value_handle(
            Uuid::Long(gatt::PINNACLE_SERVICE),
            Uuid::Long(gatt::PINNACLE_CARD),
        )
        .unwrap();
    // In the open, a listener hears what is written.
    w.hosts[0].write(ca, card, b"before-pairing");
    w.settle();
    assert!(heard(&w, b"before-pairing"));

    w.hosts[0].pair(ca);
    w.settle();
    let (ea, eb) = (w.events(0), w.events(1));
    let (Some(Some(a)), Some(Some(b))) = (code(&ea), code(&eb)) else {
        panic!("both should be asked to compare: {ea:?} {eb:?}");
    };
    assert_eq!(a, b, "both screens show one number");
    assert!(a < 1_000_000);
    w.hosts[1].confirm(cb, true);
    w.hosts[0].confirm(ca, true);
    w.settle();
    let (ea, eb) = (w.events(0), w.events(1));
    for (events, peer) in [(&ea, B), (&eb, A)] {
        assert!(
            has(
                events,
                |e| matches!(e, Event::Paired { bond, .. } if bond.address == peer && bond.compared)
            ),
            "{events:?}"
        );
        assert!(has(events, |e| matches!(e, Event::Encrypted { .. })));
    }
    assert!(w.hosts[0].encrypted(ca) && w.hosts[1].encrypted(cb));
    assert_eq!(w.hosts[0].bonds()[0].key, w.hosts[1].bonds()[0].key);

    // Encrypted: the same write reaches B, and the air hears none of it.
    w.events(1);
    w.hosts[0].write(ca, card, b"after-pairing");
    w.settle();
    assert!(!heard(&w, b"after-pairing"));
    assert!(has(
        &w.events(1),
        |e| matches!(e, Event::Changed { value, .. } if value == b"after-pairing")
    ));
    assert!(has(&w.events(0), |e| matches!(
        e,
        Event::Written { ok: true, .. }
    )));
}

#[test]
fn a_bonded_device_is_private_again_on_reconnecting() {
    let mut w = pairing_world([smp::DISPLAY_YES_NO; 2]);
    let (ca, cb) = connect(&mut w);
    w.hosts[0].pair(ca);
    w.settle();
    w.events(0);
    w.events(1);
    w.hosts[1].confirm(cb, true);
    w.hosts[0].confirm(ca, true);
    w.settle();
    w.events(0);
    w.events(1);
    disconnect(&mut w, ca);

    // As the person sees it: connect, and it is private, no question asked.
    let (ca, cb, ea, eb) = connect_seeing(&mut w);
    for events in [&ea, &eb] {
        assert!(
            has(events, |e| matches!(e, Event::Encrypted { .. })),
            "{events:?}"
        );
        assert!(!has(events, |e| matches!(
            e,
            Event::Confirm { .. } | Event::Paired { .. }
        )));
    }
    assert!(w.hosts[0].encrypted(ca) && w.hosts[1].encrypted(cb));
    w.hosts[0].write(ca, 0x0003, b"still-private");
    w.settle();
    assert!(!heard(&w, b"still-private"));

    // B forgets A: A's key is refused, and A hears so.
    disconnect(&mut w, ca);
    w.hosts[1].forget(A);
    let (ca, _, ea, _) = connect_seeing(&mut w);
    assert!(
        has(&ea, |e| matches!(
            e,
            Event::EncryptionFailed {
                status: hci::KEY_MISSING,
                ..
            }
        )),
        "{ea:?}"
    );
    assert!(!w.hosts[0].encrypted(ca));
}

/// The spec's sample for the address hash (Vol 3 Part H, Appendix D.7),
/// over-the-air order; an address made from an IRK resolves by it alone.
#[test]
fn private_addresses_resolve_by_their_irk() {
    let k = bytes::<16>("9b7d390aa610103405adc857a33402ec");
    assert_eq!(smp::ah(&k, &[0x94, 0x81, 0x70]), [0xaa, 0xfb, 0x0d]);
    let a = smp::private_address(&k, [0x12, 0x34, 0xff]);
    assert_eq!(a[5] >> 6, 0b01, "a resolvable one's top bits");
    assert!(smp::resolves(&k, &a));
    assert!(!smp::resolves(&irk(0), &a));
    assert!(!smp::resolves(&k, &B.0));
}

/// Pairs A and B on a connection, both people saying yes.
fn pair(w: &mut World, ca: u16, cb: u16) {
    w.hosts[0].pair(ca);
    w.settle();
    w.events(0);
    w.events(1);
    w.hosts[1].confirm(cb, true);
    w.hosts[0].confirm(ca, true);
    w.settle();
}

/// A phone or a watch moves to a new private address every few minutes.
/// Paired, it is still known: found by its identity, as its bond is kept,
/// and private again on connecting, with no number to compare.
#[test]
fn a_paired_device_that_moves_address_is_still_known() {
    let mut w = pairing_world([smp::DISPLAY_YES_NO; 2]);
    let (ca, cb) = connect(&mut w);
    pair(&mut w, ca, cb);
    let (ea, eb) = (w.events(0), w.events(1));
    // Each kept the other's identity.
    assert!(
        has(
            &ea,
            |e| matches!(e, Event::Paired { bond, .. } if bond.address == B && bond.irk == Some(irk(1)))
        ),
        "{ea:?}"
    );
    assert!(
        has(
            &eb,
            |e| matches!(e, Event::Paired { bond, .. } if bond.address == A && bond.irk == Some(irk(0)))
        ),
        "{eb:?}"
    );
    disconnect(&mut w, ca);

    let moved = Address(smp::private_address(&irk(1), [0x12, 0x34, 0x56]));
    w.air.controllers[1].move_to(moved);
    w.hosts[0].start_scan();
    w.settle();
    // Heard at its new address, it is the paired B.
    let found = w.hosts[0]
        .found()
        .iter()
        .find(|f| f.air == moved)
        .expect("heard at its new address");
    assert_eq!(found.address, B);
    assert!(w.hosts[0].bonds().iter().any(|b| b.address == found.address));
    assert!(has(
        &w.events(0),
        |e| matches!(e, Event::Found { address, .. } if *address == B)
    ));

    // Connected by its identity: private at once, nothing asked.
    let (ca, cb, ea, eb) = connect_seeing(&mut w);
    assert!(has(
        &ea,
        |e| matches!(e, Event::Connected { peer, .. } if *peer == B)
    ));
    for events in [&ea, &eb] {
        assert!(
            has(events, |e| matches!(e, Event::Encrypted { .. })),
            "{events:?}"
        );
        assert!(!has(events, |e| matches!(
            e,
            Event::Confirm { .. } | Event::Paired { .. }
        )));
    }
    assert!(w.hosts[0].encrypted(ca) && w.hosts[1].encrypted(cb));
    w.hosts[0].write(ca, 0x0003, b"moved-and-private");
    w.settle();
    assert!(!heard(&w, b"moved-and-private"));
}

/// A device that gives no identity is known only at the address it paired
/// from: moved, it is a stranger again, and nothing is encrypted.
#[test]
fn a_device_without_an_identity_is_not_followed() {
    let mut w = pairing_world_with([smp::DISPLAY_YES_NO; 2], [true, false]);
    let (ca, cb) = connect(&mut w);
    pair(&mut w, ca, cb);
    let ea = w.events(0);
    assert!(
        has(
            &ea,
            |e| matches!(e, Event::Paired { bond, .. } if bond.address == B && bond.irk.is_none())
        ),
        "{ea:?}"
    );
    disconnect(&mut w, ca);
    let moved = Address(smp::private_address(&[0x77; 16], [1, 2, 3]));
    w.air.controllers[1].move_to(moved);
    w.hosts[0].start_scan();
    w.settle();
    let found = w.hosts[0].found().iter().find(|f| f.air == moved).unwrap();
    assert_eq!(found.address, moved);
}

/// Bonds kept before identities (24 bytes) still read; one with an IRK
/// round-trips.
#[test]
fn bonds_keep_their_identity_on_disk() {
    use crate::Bond;
    let old = Bond {
        address: B,
        kind: 0,
        key: [7; 16],
        compared: true,
        irk: None,
    };
    let bytes = old.to_bytes();
    assert_eq!(bytes.len(), 24);
    assert_eq!(Bond::from_bytes(&bytes), Some((old, 24)));
    let new = Bond {
        irk: Some(irk(1)),
        ..old
    };
    let mut bytes = new.to_bytes();
    bytes.push(0x42);
    assert_eq!(Bond::from_bytes(&bytes), Some((new, 40)));
    assert_eq!(Bond::from_bytes(&bytes[..30]), None);
}

#[test]
fn just_works_with_a_device_that_has_no_display() {
    let mut w = pairing_world([smp::DISPLAY_YES_NO, smp::NO_INPUT_NO_OUTPUT]);
    let (ca, cb) = connect(&mut w);
    w.hosts[0].pair(ca);
    w.settle();
    // The one who tapped Pair is not asked again; the device's side asks
    // whether it may (a headset says yes by itself).
    assert_eq!(code(&w.events(0)), None);
    assert_eq!(code(&w.events(1)), Some(None));
    w.hosts[1].confirm(cb, true);
    w.settle();
    let ea = w.events(0);
    assert!(
        has(&ea, |e| matches!(e, Event::Paired { bond, .. } if !bond.compared)),
        "{ea:?}"
    );
    assert!(w.hosts[0].encrypted(ca));
}

fn passkey(events: &[Event]) -> Option<Option<u32>> {
    events.iter().find_map(|e| match e {
        Event::Passkey { passkey, .. } => Some(*passkey),
        _ => None,
    })
}

/// A phone pairs with a keyboard: the phone shows a passkey, the keyboard's
/// person types it, and the two pair as safely as by comparing numbers.
#[test]
fn a_keyboard_pairs_by_the_passkey_typed_on_it() {
    let mut w = pairing_world([smp::DISPLAY_YES_NO, smp::KEYBOARD_ONLY]);
    let (ca, cb) = connect(&mut w);
    w.hosts[0].pair(ca);
    w.settle();
    let (ea, eb) = (w.events(0), w.events(1));
    let Some(Some(shown)) = passkey(&ea) else {
        panic!("the phone should show a passkey: {ea:?}");
    };
    assert!(shown < 1_000_000);
    assert_eq!(passkey(&eb), Some(None), "the keyboard asks for it: {eb:?}");
    assert_eq!(code(&ea), None, "nothing to compare");
    assert!(!w.hosts[0].encrypted(ca));
    w.hosts[1].enter_passkey(cb, shown);
    w.settle();
    let (ea, eb) = (w.events(0), w.events(1));
    for (events, peer) in [(&ea, B), (&eb, A)] {
        assert!(
            has(
                events,
                |e| matches!(e, Event::Paired { bond, .. } if bond.address == peer && bond.compared)
            ),
            "{events:?}"
        );
    }
    assert!(w.hosts[0].encrypted(ca) && w.hosts[1].encrypted(cb));
    assert_eq!(w.hosts[0].bonds()[0].key, w.hosts[1].bonds()[0].key);
}

#[test]
fn a_wrong_passkey_pairs_nothing() {
    let mut w = pairing_world([smp::DISPLAY_YES_NO, smp::KEYBOARD_ONLY]);
    let (ca, cb) = connect(&mut w);
    w.hosts[0].pair(ca);
    w.settle();
    let Some(Some(shown)) = passkey(&w.events(0)) else {
        panic!("no passkey shown");
    };
    w.events(1);
    // One digit off: a bit of it differs, and that round's confirm fails.
    w.hosts[1].enter_passkey(cb, (shown + 1) % 1_000_000);
    w.settle();
    for i in 0..2 {
        let events = w.events(i);
        assert!(
            has(&events, |e| matches!(
                e,
                Event::PairingFailed {
                    reason: smp::CONFIRM_VALUE_FAILED,
                    ..
                }
            )),
            "{events:?}"
        );
        assert!(w.hosts[i].bonds().is_empty());
    }
    assert!(!w.hosts[0].encrypted(ca));
}

#[test]
fn a_passkey_shown_can_be_cancelled() {
    let mut w = pairing_world([smp::DISPLAY_YES_NO, smp::KEYBOARD_ONLY]);
    let (ca, _) = connect(&mut w);
    w.hosts[0].pair(ca);
    w.settle();
    w.events(0);
    w.events(1);
    w.hosts[0].confirm(ca, false);
    w.settle();
    assert!(has(&w.events(1), |e| matches!(
        e,
        Event::PairingFailed {
            reason: smp::PASSKEY_ENTRY_FAILED,
            ..
        }
    )));
}

/// Who shows and who types, the other way round: a keyboard that starts
/// the pairing types what a display shows; two keyboards both type one
/// number their people chose.
#[test]
fn passkey_entry_either_way_round() {
    let (a, b) = (smp::address_bytes(A.0, 0), smp::address_bytes(B.0, 0));
    for (io_a, io_b) in [
        (smp::KEYBOARD_ONLY, smp::DISPLAY_ONLY),
        (smp::KEYBOARD_ONLY, smp::KEYBOARD_ONLY),
        (smp::KEYBOARD_DISPLAY, smp::KEYBOARD_ONLY),
    ] {
        let (mut first, start) = smp::Pairing::start(io_a, a, b, None, &mut counter(1), 0);
        let smp::Output::Send(request) = &start[0] else {
            panic!()
        };
        let (mut second, out) = smp::Pairing::answer(io_b, b, a, None, request, &mut counter(2), 0);
        let (saw_a, saw_b) = pump(&mut first, &mut second, Vec::new(), out);
        let shown = |saw: &[smp::Output]| {
            saw.iter().find_map(|o| match o {
                smp::Output::Show(p) => Some(Some(*p)),
                smp::Output::Type => Some(None),
                _ => None,
            })
        };
        let (Some(pa), Some(pb)) = (shown(&saw_a), shown(&saw_b)) else {
            panic!("{io_a} {io_b}: both asked: {saw_a:?} {saw_b:?}");
        };
        let passkey = pa.or(pb).unwrap_or(123_456);
        let mut from_a = Vec::new();
        let mut from_b = Vec::new();
        if pa.is_none() {
            from_a = first.enter(passkey, 0);
        }
        if pb.is_none() {
            from_b = second.enter(passkey, 0);
        }
        let (saw_a, saw_b) = pump(&mut first, &mut second, from_a, from_b);
        let done = |saw: &[smp::Output]| {
            saw.iter().find_map(|o| match o {
                smp::Output::Done { key, compared: true } => Some(*key),
                _ => None,
            })
        };
        let (Some(ka), Some(kb)) = (done(&saw_a), done(&saw_b)) else {
            panic!("{io_a} {io_b}: not paired: {saw_a:?} {saw_b:?}");
        };
        assert_eq!(ka, kb);
    }
}

/// A keyboard over HID over GATT: found by its services, paired by the
/// passkey typed on it, then in the boot protocol, its keys notified over
/// the encrypted link and heard by no one else.
#[test]
fn a_paired_keyboard_sends_its_keys_privately() {
    use crate::hogp;
    let mut w = World::new(alloc::vec![
        Host::new("Phone", Vec::new()),
        Host::new("Keyboard", alloc::vec![hogp::keyboard_service()]),
    ]);
    w.hosts[0].enable_pairing([1; 32], smp::DISPLAY_YES_NO);
    w.hosts[1].enable_pairing([2; 32], smp::KEYBOARD_ONLY);
    w.hosts[1].advertise(true);
    w.settle();
    let (ca, cb) = connect(&mut w);
    w.hosts[0].discover(ca);
    w.settle();
    let services = w
        .events(0)
        .into_iter()
        .find_map(|e| match e {
            Event::Discovered { services, .. } => Some(services),
            _ => None,
        })
        .expect("services");
    let keyboard = hogp::boot_keyboard(&services).expect("a keyboard");
    assert!(keyboard.protocol_mode.is_some());
    w.hosts[0].pair(ca);
    w.settle();
    let Some(Some(shown)) = passkey(&w.events(0)) else {
        panic!("no passkey shown");
    };
    w.events(1);
    w.hosts[1].enter_passkey(cb, shown);
    w.settle();
    assert!(w.hosts[0].encrypted(ca));
    w.events(0);
    w.events(1);

    hogp::start(&mut w.hosts[0], ca, &keyboard);
    w.settle();
    let mode = w.hosts[1]
        .table()
        .value_handle(
            Uuid::Short(gatt::HUMAN_INTERFACE_DEVICE),
            Uuid::Short(gatt::PROTOCOL_MODE),
        )
        .unwrap();
    assert_eq!(
        w.hosts[1].table().get(mode).map(|a| a.value.clone()),
        Some(alloc::vec![hogp::BOOT_PROTOCOL]),
        "the boot protocol asked for"
    );
    let input = w.hosts[1]
        .table()
        .value_handle(
            Uuid::Short(gatt::HUMAN_INTERFACE_DEVICE),
            Uuid::Short(gatt::BOOT_KEYBOARD_INPUT),
        )
        .unwrap();
    assert_eq!(input, keyboard.input);
    // "q" held: usage 0x14, with Shift, an unlikely pattern on the air.
    let report = [0x02, 0, 0x14, 0x14, 0x14, 0x14, 0, 0];
    w.hosts[1].set_value(input, &report);
    w.settle();
    assert!(has(
        &w.events(0),
        |e| matches!(e, Event::Notified { handle, value, .. } if *handle == keyboard.input && value == &report)
    ));
    assert!(!heard(&w, &report));
}

#[test]
fn numbers_not_confirmed_pair_nothing() {
    let mut w = pairing_world([smp::DISPLAY_YES_NO; 2]);
    let (ca, cb) = connect(&mut w);
    w.hosts[0].pair(ca);
    w.settle();
    w.events(0);
    w.events(1);
    w.hosts[1].confirm(cb, false);
    w.settle();
    for i in 0..2 {
        let events = w.events(i);
        assert!(
            has(&events, |e| matches!(
                e,
                Event::PairingFailed {
                    reason: smp::NUMERIC_COMPARISON_FAILED,
                    ..
                }
            )),
            "{events:?}"
        );
        assert!(w.hosts[i].bonds().is_empty());
    }
    assert!(!w.hosts[0].encrypted(ca));
}

#[test]
fn a_device_that_cannot_pair_says_so() {
    let mut w = World::new(alloc::vec![
        Host::new("A", Vec::new()),
        Host::new("B", Vec::new())
    ]);
    w.hosts[0].enable_pairing([1; 32], smp::DISPLAY_YES_NO);
    w.hosts[1].advertise(true);
    w.settle();
    let (ca, _) = connect(&mut w);
    w.hosts[0].pair(ca);
    w.settle();
    let ea = w.events(0);
    assert!(
        has(&ea, |e| matches!(
            e,
            Event::PairingFailed {
                reason: smp::NOT_SUPPORTED,
                ..
            }
        )),
        "{ea:?}"
    );
}

#[test]
fn a_pairing_left_unanswered_times_out() {
    let mut w = pairing_world([smp::DISPLAY_YES_NO; 2]);
    let (ca, _) = connect(&mut w);
    w.hosts[0].pair(ca);
    w.settle();
    w.events(0);
    let later = w.now + smp::TIMEOUT_MS;
    w.hosts[0].poll(later);
    assert!(has(&w.events(0), |e| matches!(
        e,
        Event::PairingFailed {
            reason: smp::TIMED_OUT,
            ..
        }
    )));
}

/// Runs two pairing machines against each other until neither sends:
/// what each produced besides PDUs (its questions, its outcome).
fn pump(
    a: &mut smp::Pairing,
    b: &mut smp::Pairing,
    mut from_a: Vec<smp::Output>,
    mut from_b: Vec<smp::Output>,
) -> (Vec<smp::Output>, Vec<smp::Output>) {
    let (mut seen_a, mut seen_b) = (Vec::new(), Vec::new());
    // Passkey entry's twenty rounds take three PDUs each.
    for _ in 0..200 {
        let mut next_b = Vec::new();
        for o in from_a.drain(..) {
            match o {
                smp::Output::Send(pdu) => next_b.extend(b.receive(&pdu, 0)),
                o => seen_a.push(o),
            }
        }
        let mut next_a = Vec::new();
        for o in from_b.drain(..) {
            match o {
                smp::Output::Send(pdu) => next_a.extend(a.receive(&pdu, 0)),
                o => seen_b.push(o),
            }
        }
        (from_a, from_b) = (next_a, next_b);
        if from_a.is_empty() && from_b.is_empty() {
            break;
        }
    }
    (seen_a, seen_b)
}

fn counter(seed: u8) -> impl FnMut(&mut [u8]) {
    let mut n = 0u8;
    move |b: &mut [u8]| {
        for x in b.iter_mut() {
            n = n.wrapping_add(1);
            *x = n ^ seed;
        }
    }
}

fn asked(outputs: &[smp::Output]) -> Option<u32> {
    outputs.iter().find_map(|o| match o {
        smp::Output::Ask(Some(c)) => Some(*c),
        _ => None,
    })
}

/// A device in the middle pairs with each side on its own: the two people
/// then see different numbers, and saying no stops it.
#[test]
fn a_device_in_the_middle_shows_different_numbers() {
    let (a, m, b) = (
        smp::address_bytes(A.0, 0),
        smp::address_bytes([9; 6], 0),
        smp::address_bytes(B.0, 0),
    );
    let io = smp::DISPLAY_YES_NO;
    // A pairs with the middle (thinking it B); the middle with B.
    let (mut alice, start_a) = smp::Pairing::start(io, a, m, None, &mut counter(1), 0);
    let smp::Output::Send(request) = &start_a[0] else {
        panic!()
    };
    let (mut middle_to_a, out) = smp::Pairing::answer(io, m, a, None, request, &mut counter(2), 0);
    let (alice_saw, _) = pump(&mut alice, &mut middle_to_a, Vec::new(), out);
    let (mut middle_to_b, start_b) = smp::Pairing::start(io, m, b, None, &mut counter(3), 0);
    let smp::Output::Send(request) = &start_b[0] else {
        panic!()
    };
    let (mut bob, out) = smp::Pairing::answer(io, b, m, None, request, &mut counter(4), 0);
    let (_, bob_saw) = pump(&mut middle_to_b, &mut bob, Vec::new(), out);
    let (Some(x), Some(y)) = (asked(&alice_saw), asked(&bob_saw)) else {
        panic!("both asked: {alice_saw:?} {bob_saw:?}");
    };
    assert_ne!(x, y);
    // A legacy request (no Secure Connections bit) is refused outright.
    let mut legacy = request.clone();
    legacy[3] &= !0x08;
    let (_, out) = smp::Pairing::answer(io, b, m, None, &legacy, &mut counter(5), 0);
    assert!(out.contains(&smp::Output::Failed(smp::AUTHENTICATION_REQUIREMENTS)));
}