From e77c5fcd83d5230de39a67d7d18177d7af26caa4 Mon Sep 17 00:00:00 2001 From: mnovak Date: Fri, 4 Dec 2026 12:24:14 +0100 Subject: [PATCH] [domistream] ENet host: tests first (client against host over an in-memory lossy wire), API stubs EnetHostPeer is the accepting side, one peer per client address. The tests drive our EnetClient against it with simulated time, loss, duplication and reordering, plus a scripted client for the stock ENet 1.3 facts (verify connect fields, session ids, what is acknowledged when). They fail against the stubs. --- crates/domistream/src/enet/host.rs | 200 ++++++ crates/domistream/src/enet/mod.rs | 3 + crates/domistream/tests/common/mod.rs | 2 + crates/domistream/tests/common/wire.rs | 197 +++++ crates/domistream/tests/enet_host.rs | 950 +++++++++++++++++++++++++ 5 files changed, 1352 insertions(+) create mode 100644 crates/domistream/src/enet/host.rs create mode 100644 crates/domistream/tests/common/wire.rs create mode 100644 crates/domistream/tests/enet_host.rs diff --git a/crates/domistream/src/enet/host.rs b/crates/domistream/src/enet/host.rs new file mode 100644 index 0000000..d37f3bf --- /dev/null +++ b/crates/domistream/src/enet/host.rs @@ -0,0 +1,200 @@ +//! The accepting side of the ENet 1.3 layer (`docs/PROTOCOL.md` 3.1): one host-side peer per client. +//! +//! The caller owns the UDP socket and **demultiplexes by source address**: a datagram from an address it does not +//! know yet goes to [`EnetHostPeer::accept`] (which takes only a CONNECT); every later datagram from that address +//! goes to [`EnetHostPeer::handle_datagram`] of the peer it created. A CONNECT with a new connect id from a known +//! address is a new connection (the client restarted): [`parse_connect_request`] lets the caller see that and +//! replace the old peer. +//! +//! ```text +//! on datagram d from addr: +//! peer = peers[addr] or EnetHostPeer::accept(config, now, &d)? // refused: drop d +//! peer.handle_datagram(now, &d) // (accept already took d) +//! loop { +//! while let Some(d) = peer.poll_transmit(now) { socket.send_to(&d, addr) } +//! while let Some(e) = peer.poll_event() { … } +//! wake at peer.poll_timeout() → peer.handle_timeout(now) +//! } +//! ``` + +use core::time::Duration; + +use super::Delivery; +use crate::{Error, Instant, Result}; + +/// Settings of the host side. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct EnetHostConfig { + /// Our peer id, which the client puts in the header of every datagram it sends us (0..=0xFFE). + pub peer_id: u16, + /// Most channels we grant (the client's request is capped to this; at least 1). + pub channel_limit: u8, + /// Our MTU (576..=4096); the connection uses the smaller of this and the client's. + pub mtu: u16, + /// Send a ping when nothing was sent for this long. + pub ping_interval: Duration, + /// Give up when a reliable command stays unacknowledged this long. + pub timeout: Duration, +} + +/// State of the host-side peer. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum EnetHostState { + /// Verify connect sent, waiting for the client to acknowledge it. + AcknowledgingConnect, + /// Connected. + Connected, + /// Our disconnect sent, waiting for its acknowledgement. + Disconnecting, + /// Closed (by either side or by timeout). + Disconnected, +} + +/// What happened. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum EnetHostEvent { + /// The client acknowledged our verify connect. + Connected { + /// The connect command's user data word. + data: u32, + }, + /// A packet arrived (reassembled, in order for reliable and unreliable delivery). + Received { + /// Channel. + channel: u8, + /// The packet. + data: Vec, + }, + /// The client closed the connection. + Disconnected { + /// The client's disconnect data word. + data: u32, + }, + /// The client stopped answering. + TimedOut, +} + +/// A client's CONNECT, as [`parse_connect_request`] finds it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct ConnectRequest { + /// The connect parameters. + pub params: super::protocol::ConnectParams, + /// The connect command's user data word. + pub data: u32, +} + +/// The CONNECT in a datagram addressed to "no peer yet", if it holds one. +/// +/// # Errors +/// Parser errors as [`super::protocol::parse_datagram`]; [`Error::UnexpectedValue`] when the datagram is addressed +/// to a peer or holds no CONNECT, or the channel count is outside 1..=255. +pub fn parse_connect_request(datagram: &[u8]) -> Result { + let _ = datagram; + Err(Error::Unimplemented) +} + +/// The host-side ENet peer of one client. +#[derive(Debug)] +pub struct EnetHostPeer { + config: EnetHostConfig, +} + +impl EnetHostPeer { + /// Accepts a client's CONNECT datagram: queues the verify connect. + /// + /// # Errors + /// [`Error::Malformed`] for a config outside ENet's limits; anything [`parse_connect_request`] refuses. + pub fn accept(config: EnetHostConfig, now: Instant, datagram: &[u8]) -> Result { + let _ = (config, now, datagram); + Err(Error::Unimplemented) + } + + /// Feeds one datagram from the client. + /// + /// # Errors + /// Parser errors; [`Error::Closed`] once disconnected. + pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> { + let _ = (now, datagram); + Err(Error::Unimplemented) + } + + /// Queues a packet. + /// + /// # Errors + /// [`Error::State`] unless connected. + pub fn send(&mut self, now: Instant, channel: u8, delivery: Delivery, data: &[u8]) -> Result<()> { + let _ = (now, channel, delivery, data); + Err(Error::Unimplemented) + } + + /// Starts a graceful disconnect. + /// + /// # Errors + /// [`Error::Closed`] when already disconnected or disconnecting. + pub fn disconnect(&mut self, now: Instant, data: u32) -> Result<()> { + let _ = (now, data); + Err(Error::Unimplemented) + } + + /// The next datagram to send. + pub fn poll_transmit(&mut self, now: Instant) -> Option> { + let _ = now; + None + } + + /// The next event. + pub fn poll_event(&mut self) -> Option { + None + } + + /// When [`Self::handle_timeout`] is due. + #[must_use] + pub fn poll_timeout(&self) -> Option { + None + } + + /// Advances timers. + /// + /// # Errors + /// None today. + pub fn handle_timeout(&mut self, now: Instant) -> Result<()> { + let _ = now; + Err(Error::Unimplemented) + } + + /// Connection state. + #[must_use] + pub const fn state(&self) -> EnetHostState { + EnetHostState::Disconnected + } + + /// The connect id of this connection. + #[must_use] + pub const fn connect_id(&self) -> u32 { + 0 + } + + /// Channels granted. + #[must_use] + pub const fn channel_count(&self) -> u8 { + 0 + } + + /// The MTU in use. + #[must_use] + pub const fn mtu(&self) -> usize { + 0 + } + + /// Smoothed round-trip time, once measured. + #[must_use] + pub const fn round_trip_time(&self) -> Option { + None + } + + /// The configuration. + #[must_use] + pub const fn config(&self) -> &EnetHostConfig { + &self.config + } +} diff --git a/crates/domistream/src/enet/mod.rs b/crates/domistream/src/enet/mod.rs index 8448d93..f7b5f35 100644 --- a/crates/domistream/src/enet/mod.rs +++ b/crates/domistream/src/enet/mod.rs @@ -24,8 +24,11 @@ use protocol::{Command, CommandBody, ConnectParams, Datagram, Fragment, MAX_DATA use crate::util::malformed; use crate::{Error, Instant, RandomSource, Result}; +pub mod host; pub mod protocol; +pub use host::{ConnectRequest, EnetHostConfig, EnetHostEvent, EnetHostPeer, EnetHostState, parse_connect_request}; + /// Maximum size of one reassembled packet, in bytes (control messages are small; this caps fragment memory). pub const MAX_PACKET_BYTES: usize = 64 * 1024; /// Maximum number of packets queued for sending before [`EnetClient::send`] refuses more. diff --git a/crates/domistream/tests/common/mod.rs b/crates/domistream/tests/common/mod.rs index 8838ee0..10f33d4 100644 --- a/crates/domistream/tests/common/mod.rs +++ b/crates/domistream/tests/common/mod.rs @@ -7,6 +7,8 @@ use std::collections::HashMap; use domistream::RandomSource; +pub mod wire; + // ------------------------------------------------------------------------------------------------ assertions /// Asserts that `$e` is `Err` matching `$p` (an `Error` pattern), printing the actual value otherwise. diff --git a/crates/domistream/tests/common/wire.rs b/crates/domistream/tests/common/wire.rs new file mode 100644 index 0000000..104b6ba --- /dev/null +++ b/crates/domistream/tests/common/wire.rs @@ -0,0 +1,197 @@ +//! An in-memory, simulated-time network for client-against-host tests: two one-way links with optional loss, +//! duplication and reordering (all from a seeded [`SeqRng`], so every run is the same), and a driver that shuttles +//! datagrams between two sans-I/O endpoints, advancing the clock to the next delivery or deadline. + +use domistream::Instant; + +use super::SeqRng; + +/// One side of a session, as the wire drives it. +pub trait Endpoint { + /// The next datagram this side wants to send. + fn transmit(&mut self, now: Instant) -> Option>; + /// A datagram arrived. + fn receive(&mut self, now: Instant, datagram: &[u8]); + /// When this side wants [`Endpoint::tick`]. + fn deadline(&self) -> Option; + /// Timers. + fn tick(&mut self, now: Instant); +} + +/// What a one-way link does to datagrams. Rates are per mille. +#[derive(Clone, Copy, Debug, Default)] +pub struct Impair { + pub loss: u32, + pub duplicate: u32, + /// Chance that a datagram is held back by up to `reorder_ms` extra. + pub reorder: u32, + pub reorder_ms: u64, + /// Fixed one-way latency, ms. + pub latency_ms: u64, +} + +impl Impair { + pub fn clean(latency_ms: u64) -> Self { + Self { latency_ms, ..Self::default() } + } + + pub fn lossy(loss: u32, latency_ms: u64) -> Self { + Self { loss, duplicate: 20, reorder: 100, reorder_ms: 30, latency_ms } + } +} + +/// A one-way link. +#[derive(Debug)] +pub struct Link { + pub impair: Impair, + rng: SeqRng, + queue: Vec<(u64, u64, Vec)>, + order: u64, + /// Datagrams handed to the link, and the ones it dropped. + pub sent: usize, + pub lost: usize, + /// When set, every datagram is dropped (a peer that vanished). + pub cut: bool, +} + +impl Link { + pub fn new(impair: Impair, seed: u64) -> Self { + Self { impair, rng: SeqRng::new(seed), queue: Vec::new(), order: 0, sent: 0, lost: 0, cut: false } + } + + fn chance(&mut self, per_mille: u32) -> bool { + per_mille > 0 && (self.rng.below(1000) as u32) < per_mille + } + + pub fn send(&mut self, now_ms: u64, datagram: Vec) { + self.sent += 1; + if self.cut || self.chance(self.impair.loss) { + self.lost += 1; + return; + } + let copies = if self.chance(self.impair.duplicate) { 2 } else { 1 }; + for _ in 0..copies { + let mut due = now_ms + self.impair.latency_ms; + if self.impair.reorder_ms > 0 && self.chance(self.impair.reorder) { + due += 1 + self.rng.below(self.impair.reorder_ms as usize) as u64; + } + self.order += 1; + self.queue.push((due, self.order, datagram.clone())); + } + } + + pub fn next_due(&self) -> Option { + self.queue.iter().map(|(d, _, _)| *d).min() + } + + /// Datagrams due by `now_ms`, in delivery order. + pub fn due(&mut self, now_ms: u64) -> Vec> { + let mut ready: Vec<(u64, u64, Vec)> = Vec::new(); + let mut rest = Vec::new(); + for item in self.queue.drain(..) { + if item.0 <= now_ms { ready.push(item) } else { rest.push(item) } + } + self.queue = rest; + ready.sort_by_key(|(d, o, _)| (*d, *o)); + ready.into_iter().map(|(_, _, d)| d).collect() + } +} + +pub fn ms(t: Instant) -> u64 { + t.as_micros().div_ceil(1000) +} + +pub fn at(ms: u64) -> Instant { + Instant::from_micros(ms * 1000) +} + +/// A client, a host and the two links between them. +pub struct Wire { + pub client: C, + pub host: H, + pub to_host: Link, + pub to_client: Link, + pub now_ms: u64, +} + +impl Wire { + pub fn new(client: C, host: H, to_host: Impair, to_client: Impair, seed: u64) -> Self { + Self { + client, + host, + to_host: Link::new(to_host, seed ^ 0xC2C2), + to_client: Link::new(to_client, seed ^ 0x4848), + now_ms: 0, + } + } + + /// Moves everything that can move at the current time (transmit, deliver, timers), until quiet. + pub fn settle(&mut self) { + for _ in 0..10_000 { + let now = at(self.now_ms); + let mut moved = false; + if self.client.deadline().is_some_and(|t| t <= now) { + self.client.tick(now); + } + if self.host.deadline().is_some_and(|t| t <= now) { + self.host.tick(now); + } + while let Some(d) = self.client.transmit(now) { + self.to_host.send(self.now_ms, d); + moved = true; + } + while let Some(d) = self.host.transmit(now) { + self.to_client.send(self.now_ms, d); + moved = true; + } + for d in self.to_host.due(self.now_ms) { + self.host.receive(now, &d); + moved = true; + } + for d in self.to_client.due(self.now_ms) { + self.client.receive(now, &d); + moved = true; + } + if !moved { + return; + } + } + panic!("the wire never settles at {} ms", self.now_ms); + } + + /// The next moment anything happens, if anything ever does. + pub fn next_event(&self) -> Option { + [ + self.to_host.next_due(), + self.to_client.next_due(), + self.client.deadline().map(ms), + self.host.deadline().map(ms), + ] + .into_iter() + .flatten() + .min() + } + + /// Runs until `done` holds or `limit_ms` passes; returns whether `done` held. + pub fn run_until(&mut self, limit_ms: u64, mut done: impl FnMut(&mut Self) -> bool) -> bool { + loop { + self.settle(); + if done(self) { + return true; + } + let next = self.next_event().unwrap_or(u64::MAX).max(self.now_ms + 1); + if next > limit_ms { + self.now_ms = limit_ms.max(self.now_ms); + self.settle(); + return done(self); + } + self.now_ms = next; + } + } + + /// Runs for `duration_ms` of simulated time. + pub fn run_for(&mut self, duration_ms: u64) { + let end = self.now_ms + duration_ms; + self.run_until(end, |w| w.now_ms >= end); + } +} diff --git a/crates/domistream/tests/enet_host.rs b/crates/domistream/tests/enet_host.rs new file mode 100644 index 0000000..f7d5b0a --- /dev/null +++ b/crates/domistream/tests/enet_host.rs @@ -0,0 +1,950 @@ +//! The host side of ENet (`docs/PROTOCOL.md` 3.1, `enet::host`): our own [`EnetClient`] talks to an +//! [`EnetHostPeer`] over an in-memory wire with simulated time, loss, duplication and reordering; plus a scripted +//! client for the wire facts of stock ENet 1.3 (verify connect fields, session ids, what is acknowledged when). + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)] + +mod common; + +use core::time::Duration; + +use common::wire::{Endpoint, Impair, Wire, at}; +use domistream::enet::protocol::{ + Command, CommandBody, ConnectParams, Datagram, MAX_DATAGRAM_BYTES, NO_PEER_ID, encode_datagram, parse_datagram, +}; +use domistream::enet::{ + Delivery, EnetClient, EnetConfig, EnetEvent, EnetHostConfig, EnetHostEvent, EnetHostPeer, EnetHostState, + EnetState, MAX_PACKET_BYTES, MAX_SEND_QUEUE, parse_connect_request, +}; +use domistream::{Error, Instant}; +use proptest::prelude::*; + +// ================================================================================================ setup + +const HOST_PEER_ID: u16 = 7; + +fn host_config() -> EnetHostConfig { + EnetHostConfig { + peer_id: HOST_PEER_ID, + channel_limit: 0x30, + mtu: 1400, + ping_interval: Duration::from_millis(500), + timeout: Duration::from_secs(10), + } +} + +fn client_config() -> EnetConfig { + EnetConfig { + channel_count: 2, + mtu: 1400, + connect_data: 0x0000_1234, + ping_interval: Duration::from_millis(500), + timeout: Duration::from_secs(10), + } +} + +struct Client { + peer: EnetClient, + events: Vec, + count: usize, +} + +impl Client { + fn new(config: EnetConfig, seed: u64) -> Self { + let peer = EnetClient::connect(config, Instant::ZERO, &mut common::SeqRng::new(seed)).unwrap(); + Self { peer, events: Vec::new(), count: 0 } + } + + fn drain(&mut self) { + while let Some(e) = self.peer.poll_event() { + self.count += usize::from(matches!(e, EnetEvent::Received { .. })); + self.events.push(e); + } + } + + fn received(&self, channel: u8) -> Vec> { + self.events + .iter() + .filter_map(|e| match e { + EnetEvent::Received { channel: c, data } if *c == channel => Some(data.clone()), + _ => None, + }) + .collect() + } +} + +impl Endpoint for Client { + fn transmit(&mut self, now: Instant) -> Option> { + self.peer.poll_transmit(now) + } + fn receive(&mut self, now: Instant, datagram: &[u8]) { + let _ = self.peer.handle_datagram(now, datagram); + self.drain(); + } + fn deadline(&self) -> Option { + self.peer.poll_timeout() + } + fn tick(&mut self, now: Instant) { + self.peer.handle_timeout(now).unwrap(); + self.drain(); + } +} + +/// The caller of the host: one address, so one slot; the first datagram goes to `accept`. +struct Host { + config: EnetHostConfig, + peer: Option, + events: Vec, + refused: usize, + /// Every datagram the host sent, parsed. + sent: Vec, + count: usize, +} + +impl Host { + fn new(config: EnetHostConfig) -> Self { + Self { config, peer: None, events: Vec::new(), refused: 0, sent: Vec::new(), count: 0 } + } + + fn peer(&mut self) -> &mut EnetHostPeer { + self.peer.as_mut().expect("accepted") + } + + fn drain(&mut self) { + if let Some(p) = self.peer.as_mut() { + while let Some(e) = p.poll_event() { + self.count += usize::from(matches!(e, EnetHostEvent::Received { .. })); + self.events.push(e); + } + } + } + + fn received(&self, channel: u8) -> Vec> { + self.events + .iter() + .filter_map(|e| match e { + EnetHostEvent::Received { channel: c, data } if *c == channel => Some(data.clone()), + _ => None, + }) + .collect() + } + + fn connected(&self) -> bool { + self.peer.as_ref().is_some_and(|p| p.state() == EnetHostState::Connected) + } +} + +impl Endpoint for Host { + fn transmit(&mut self, now: Instant) -> Option> { + let d = self.peer.as_mut()?.poll_transmit(now)?; + let mtu = self.peer.as_ref().unwrap().mtu(); + assert!(d.len() <= mtu, "host datagram of {} over the MTU {mtu}", d.len()); + self.sent.push(parse_datagram(&d).expect("the host's datagrams parse")); + Some(d) + } + fn receive(&mut self, now: Instant, datagram: &[u8]) { + match self.peer.as_mut() { + None => match EnetHostPeer::accept(self.config, now, datagram) { + Ok(p) => self.peer = Some(p), + Err(_) => self.refused += 1, + }, + Some(p) => { + let _ = p.handle_datagram(now, datagram); + } + } + self.drain(); + } + fn deadline(&self) -> Option { + self.peer.as_ref()?.poll_timeout() + } + fn tick(&mut self, now: Instant) { + if let Some(p) = self.peer.as_mut() { + p.handle_timeout(now).unwrap(); + } + self.drain(); + } +} + +type W = Wire; + +fn wire(to_host: Impair, to_client: Impair, seed: u64) -> W { + wire_with(client_config(), host_config(), to_host, to_client, seed) +} + +fn wire_with(client: EnetConfig, host: EnetHostConfig, to_host: Impair, to_client: Impair, seed: u64) -> W { + Wire::new(Client::new(client, seed), Host::new(host), to_host, to_client, seed) +} + +/// Long timeouts for the loss tests: a command lost many times in a row must not end the connection. +fn lossy_wire(to_host: Impair, to_client: Impair, seed: u64) -> W { + let client = EnetConfig { timeout: Duration::from_secs(60), ..client_config() }; + let host = EnetHostConfig { timeout: Duration::from_secs(60), ..host_config() }; + wire_with(client, host, to_host, to_client, seed) +} + +fn both_connected(w: &mut W) -> bool { + w.client.peer.state() == EnetState::Connected && w.host.connected() +} + +fn connected_wire(to_host: Impair, to_client: Impair, seed: u64) -> W { + let mut w = wire(to_host, to_client, seed); + assert!(w.run_until(30_000, both_connected), "no connection (seed {seed})"); + w +} + +fn now(w: &W) -> Instant { + at(w.now_ms) +} + +// ================================================================================================ scripted client + +fn cmd(acknowledge: bool, channel_id: u8, reliable_sequence: u16, body: CommandBody) -> Command { + Command { acknowledge, channel_id, reliable_sequence, body } +} + +fn connect_params(connect_id: u32) -> ConnectParams { + ConnectParams { + outgoing_peer_id: 0, + incoming_session_id: 0xFF, + outgoing_session_id: 0xFF, + mtu: 1400, + window_size: 65536, + channel_count: 2, + incoming_bandwidth: 0, + outgoing_bandwidth: 0, + packet_throttle_interval: 5000, + packet_throttle_acceleration: 2, + packet_throttle_deceleration: 2, + connect_id, + } +} + +fn connect_datagram(params: ConnectParams, data: u32) -> Vec { + encode_datagram(&Datagram { + peer_id: NO_PEER_ID, + session_id: 0, + sent_time: Some(1), + commands: vec![cmd(true, 0xFF, 1, CommandBody::Connect { params, data })], + }) + .unwrap() +} + +fn to_host(session_id: u8, sent_time: Option, commands: Vec) -> Vec { + encode_datagram(&Datagram { peer_id: HOST_PEER_ID, session_id, sent_time, commands }).unwrap() +} + +fn transmitted(peer: &mut EnetHostPeer, t: Instant) -> Vec { + let mut out = Vec::new(); + while let Some(d) = peer.poll_transmit(t) { + assert!(d.len() <= peer.mtu()); + out.push(parse_datagram(&d).expect("host datagrams parse")); + assert!(out.len() < 10_000, "poll_transmit never ends"); + } + out +} + +fn events(peer: &mut EnetHostPeer) -> Vec { + let mut out = Vec::new(); + while let Some(e) = peer.poll_event() { + out.push(e); + assert!(out.len() < 100_000); + } + out +} + +fn verify_of(ds: &[Datagram]) -> (Command, ConnectParams) { + ds.iter() + .flat_map(|d| &d.commands) + .find_map(|c| match &c.body { + CommandBody::VerifyConnect(p) => Some((c.clone(), *p)), + _ => None, + }) + .expect("a verify connect") +} + +/// A host that accepted a hand-built connect and had its verify acknowledged at 2 ms. +fn scripted_connected() -> EnetHostPeer { + let mut h = EnetHostPeer::accept(host_config(), at(1), &connect_datagram(connect_params(0xABCD), 9)).unwrap(); + let sent = transmitted(&mut h, at(1)); + let (v, _) = verify_of(&sent); + let ack = cmd( + false, + 0xFF, + v.reliable_sequence, + CommandBody::Acknowledge { + received_reliable_sequence: v.reliable_sequence, + received_sent_time: sent[0].sent_time.unwrap(), + }, + ); + h.handle_datagram(at(2), &to_host(0, Some(2), vec![ack])).unwrap(); + assert_eq!(events(&mut h), vec![EnetHostEvent::Connected { data: 9 }]); + assert_eq!(h.state(), EnetHostState::Connected); + h +} + +// ================================================================================================ handshake + +#[test] +fn handshake_over_a_clean_wire() { + let mut w = wire(Impair::clean(5), Impair::clean(5), 1); + assert!(w.run_until(1_000, both_connected)); + assert_eq!(w.host.events, vec![EnetHostEvent::Connected { data: client_config().connect_data }]); + assert_eq!(w.client.events, vec![EnetEvent::Connected]); + let p = w.host.peer(); + assert_eq!(p.channel_count(), 2, "min(client 2, limit 0x30)"); + assert_eq!(p.mtu(), 1400); + assert_eq!(w.host.refused, 0); + // Every host datagram is addressed to the client's peer id (0) after the handshake. + assert!(w.host.sent.iter().all(|d| d.peer_id == 0)); +} + +#[test] +fn verify_connect_fields() { + let params = connect_params(0xDEAD_BEEF); + let d = connect_datagram(params, 0x55); + assert_eq!(parse_connect_request(&d).unwrap().params, params); + assert_eq!(parse_connect_request(&d).unwrap().data, 0x55); + let cfg = EnetHostConfig { mtu: 1200, ..host_config() }; + let mut h = EnetHostPeer::accept(cfg, at(3), &d).unwrap(); + assert_eq!(h.state(), EnetHostState::AcknowledgingConnect); + assert_eq!(h.connect_id(), 0xDEAD_BEEF); + assert!(events(&mut h).is_empty(), "connected only once the verify is acknowledged"); + let sent = transmitted(&mut h, at(3)); + assert_eq!(sent.len(), 1); + let dg = &sent[0]; + assert_eq!(dg.peer_id, params.outgoing_peer_id, "addressed to the client's peer id"); + assert_eq!(dg.session_id, 0); + assert_eq!(dg.sent_time, Some(3)); + // Stock ENet answers a connect with the verify only: the verify itself retires the client's connect. + assert_eq!(dg.commands.len(), 1, "{:?}", dg.commands); + let (c, v) = verify_of(&sent); + assert!(c.acknowledge, "verify connect is reliable"); + assert_eq!(c.channel_id, 0xFF); + assert_eq!(c.reliable_sequence, 1); + assert_eq!(v.outgoing_peer_id, HOST_PEER_ID); + assert_eq!(v.connect_id, 0xDEAD_BEEF); + assert_eq!((v.incoming_session_id, v.outgoing_session_id), (0, 0)); + assert_eq!(v.mtu, 1200, "min(client, host)"); + assert_eq!(v.window_size, 65536); + assert_eq!(v.channel_count, 2); + assert_eq!((v.incoming_bandwidth, v.outgoing_bandwidth), (0, 0), "our bandwidth: unlimited"); + assert_eq!( + (v.packet_throttle_interval, v.packet_throttle_acceleration, v.packet_throttle_deceleration), + (5000, 2, 2), + "throttle echoed" + ); + assert_eq!(h.mtu(), 1200); +} + +#[test] +fn verify_clamps_what_the_client_offers() { + for (mtu, window, channels, want_mtu, want_window, want_channels) in [ + (100u32, 1000u32, 200u32, 576u32, 4096u32, 0x30u32), + (9000, 1 << 20, 1, 1400, 65536, 1), + (576, 4096, 255, 576, 4096, 0x30), + (u32::MAX, 0, 0x30, 1400, 4096, 0x30), + ] { + let p = ConnectParams { mtu, window_size: window, channel_count: channels, ..connect_params(1) }; + let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(p, 0)).unwrap(); + let (_, v) = verify_of(&transmitted(&mut h, at(0))); + assert_eq!((v.mtu, v.window_size, v.channel_count), (want_mtu, want_window, want_channels), "{p:?}"); + assert_eq!(u32::from(h.channel_count()), want_channels); + } +} + +#[test] +fn session_ids_follow_stock_enet() { + // (client's incoming, outgoing) -> (verify incoming = host's outgoing, verify outgoing = host's incoming). + for (inc, out, want_in, want_out) in [(0xFFu8, 0xFFu8, 0u8, 0u8), (1, 2, 2, 3), (3, 0, 0, 1), (2, 2, 3, 3)] { + let p = ConnectParams { incoming_session_id: inc, outgoing_session_id: out, ..connect_params(5) }; + let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(p, 0)).unwrap(); + let sent = transmitted(&mut h, at(0)); + let (c, v) = verify_of(&sent); + assert_eq!((v.incoming_session_id, v.outgoing_session_id), (want_in, want_out), "connect {inc}/{out}"); + assert_eq!(sent[0].session_id, want_in, "the host sends with the session the client takes as incoming"); + // The client must send with the host's incoming session id; anything else is ignored. + let ack = cmd( + false, + 0xFF, + 1, + CommandBody::Acknowledge { received_reliable_sequence: c.reliable_sequence, received_sent_time: 0 }, + ); + let wrong = (want_out + 1) & 3; + h.handle_datagram(at(1), &to_host(wrong, Some(1), vec![ack.clone()])).unwrap(); + assert_eq!(h.state(), EnetHostState::AcknowledgingConnect, "wrong session {wrong} ignored"); + h.handle_datagram(at(1), &to_host(want_out, Some(1), vec![ack])).unwrap(); + assert_eq!(h.state(), EnetHostState::Connected); + assert_eq!(events(&mut h), vec![EnetHostEvent::Connected { data: 0 }]); + } +} + +#[test] +fn accept_refuses_what_is_not_a_connect() { + let good = connect_datagram(connect_params(1), 0); + assert!(EnetHostPeer::accept(host_config(), at(0), &good).is_ok()); + assert!(EnetHostPeer::accept(host_config(), at(0), &[]).is_err()); + assert!(EnetHostPeer::accept(host_config(), at(0), &[0xFF; 3]).is_err()); + let ping = encode_datagram(&Datagram { + peer_id: NO_PEER_ID, + session_id: 0, + sent_time: Some(0), + commands: vec![cmd(true, 0xFF, 1, CommandBody::Ping)], + }) + .unwrap(); + assert_err!(EnetHostPeer::accept(host_config(), at(0), &ping), Error::UnexpectedValue { .. }, "no connect"); + let mut addressed = parse_datagram(&good).unwrap(); + addressed.peer_id = HOST_PEER_ID; + assert_err!( + EnetHostPeer::accept(host_config(), at(0), &encode_datagram(&addressed).unwrap()), + Error::UnexpectedValue { .. }, + "a connect addressed to a peer" + ); + for channels in [0u32, 256, u32::MAX] { + let p = ConnectParams { channel_count: channels, ..connect_params(1) }; + assert_err!( + EnetHostPeer::accept(host_config(), at(0), &connect_datagram(p, 0)), + Error::UnexpectedValue { .. }, + "{channels} channels" + ); + assert!(parse_connect_request(&connect_datagram(p, 0)).is_err()); + } + for bad in [ + EnetHostConfig { mtu: 575, ..host_config() }, + EnetHostConfig { mtu: 4097, ..host_config() }, + EnetHostConfig { channel_limit: 0, ..host_config() }, + EnetHostConfig { peer_id: NO_PEER_ID, ..host_config() }, + EnetHostConfig { peer_id: 0xFFFF, ..host_config() }, + ] { + assert_err!(EnetHostPeer::accept(bad, at(0), &good), Error::Malformed { .. }, "{bad:?}"); + } +} + +#[test] +fn repeated_connect_is_ignored_and_a_new_connect_id_is_visible() { + let d = connect_datagram(connect_params(77), 0); + let mut h = EnetHostPeer::accept(host_config(), at(0), &d).unwrap(); + let first = transmitted(&mut h, at(0)); + assert_eq!(first.len(), 1); + // The client's connect retransmitted: no second verify, no new state. + assert_eq!(h.handle_datagram(at(5), &d), Ok(())); + assert!(transmitted(&mut h, at(5)).is_empty()); + assert_eq!(h.state(), EnetHostState::AcknowledgingConnect); + // A client that restarted: the caller sees another connect id and replaces the peer. + let again = connect_datagram(connect_params(78), 0); + assert_eq!(h.handle_datagram(at(6), &again), Ok(())); + assert_eq!(h.connect_id(), 77); + assert_ne!(parse_connect_request(&again).unwrap().params.connect_id, h.connect_id()); +} + +#[test] +fn data_before_the_verify_ack_is_not_taken() { + let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(connect_params(3), 0)).unwrap(); + let sent = transmitted(&mut h, at(0)); + let (v, _) = verify_of(&sent); + let data = cmd(true, 0, 1, CommandBody::SendReliable(b"early".to_vec())); + h.handle_datagram(at(1), &to_host(0, Some(1), vec![data.clone()])).unwrap(); + assert!(events(&mut h).is_empty()); + assert!( + !transmitted(&mut h, at(1)).iter().flat_map(|d| &d.commands).any(|c| matches!(c.body, CommandBody::Acknowledge { .. })), + "not acknowledged, so the client sends it again" + ); + let ack = cmd( + false, + 0xFF, + 1, + CommandBody::Acknowledge { received_reliable_sequence: v.reliable_sequence, received_sent_time: 0 }, + ); + h.handle_datagram(at(2), &to_host(0, Some(2), vec![ack, data])).unwrap(); + assert_eq!( + events(&mut h), + vec![EnetHostEvent::Connected { data: 0 }, EnetHostEvent::Received { channel: 0, data: b"early".to_vec() }] + ); +} + +#[test] +fn lost_verify_is_retransmitted() { + let mut w = wire(Impair::clean(5), Impair::clean(5), 2); + w.to_client.cut = true; + w.run_for(50); + assert!(w.host.peer.is_some() && !both_connected(&mut w)); + w.to_client.cut = false; + assert!(w.run_until(5_000, both_connected), "the verify is sent again"); +} + +#[test] +fn verify_never_acknowledged_times_out() { + let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(connect_params(3), 0)).unwrap(); + let mut verifies = 0; + let mut guard = 0; + while h.state() != EnetHostState::Disconnected { + let t = h.poll_timeout().expect("a deadline while waiting"); + assert!(t <= at(host_config().timeout.as_millis() as u64 + 1), "no timeout by {t:?}"); + h.handle_timeout(t).unwrap(); + verifies += transmitted(&mut h, t) + .iter() + .flat_map(|d| &d.commands) + .filter(|c| matches!(c.body, CommandBody::VerifyConnect(_))) + .count(); + guard += 1; + assert!(guard < 10_000); + } + assert!(verifies >= 3, "the verify was retransmitted ({verifies})"); + assert_eq!(events(&mut h), vec![EnetHostEvent::TimedOut]); + assert_eq!(h.poll_timeout(), None); + assert_err!(h.handle_datagram(at(20_000), &[0x00, 0x07]), Error::Closed); +} + +// ================================================================================================ data + +#[test] +fn reliable_both_ways_in_order() { + let mut w = connected_wire(Impair::clean(3), Impair::clean(3), 3); + let t = now(&w); + for i in 0..50u32 { + w.client.peer.send(t, (i % 2) as u8, Delivery::Reliable, &i.to_le_bytes()).unwrap(); + w.host.peer().send(t, (i % 2) as u8, Delivery::Reliable, &(1000 + i).to_le_bytes()).unwrap(); + } + w.run_for(1_000); + for ch in 0..2u8 { + let want: Vec> = (0..50u32).filter(|i| i % 2 == u32::from(ch)).map(|i| i.to_le_bytes().to_vec()).collect(); + assert_eq!(w.host.received(ch), want, "host, channel {ch}"); + let want: Vec> = + (0..50u32).filter(|i| i % 2 == u32::from(ch)).map(|i| (1000 + i).to_le_bytes().to_vec()).collect(); + assert_eq!(w.client.received(ch), want, "client, channel {ch}"); + } +} + +#[test] +fn large_packets_fragment_both_ways() { + let mut w = connected_wire(Impair::clean(2), Impair::clean(2), 4); + let up: Vec = (0..5000u32).map(|i| (i * 7) as u8).collect(); + let down: Vec = (0..MAX_PACKET_BYTES as u32).map(|i| (i * 13 + 1) as u8).collect(); + let t = now(&w); + w.client.peer.send(t, 1, Delivery::Reliable, &up).unwrap(); + w.host.peer().send(t, 0, Delivery::Reliable, &down).unwrap(); + w.run_for(2_000); + assert_eq!(w.host.received(1), vec![up]); + assert_eq!(w.client.received(0), vec![down]); + let frags = w.host.sent.iter().flat_map(|d| &d.commands).filter(|c| matches!(c.body, CommandBody::SendFragment(_))).count(); + assert!(frags > 40, "the host fragmented its 64 KiB packet ({frags})"); +} + +#[test] +fn unreliable_and_unsequenced_from_the_client() { + let mut w = connected_wire(Impair::clean(2), Impair::clean(2), 5); + let t = now(&w); + for i in 0..3u8 { + w.client.peer.send(t, 0, Delivery::Unreliable, &[b'u', i]).unwrap(); + w.client.peer.send(t, 1, Delivery::Unsequenced, &[b's', i]).unwrap(); + } + w.run_for(200); + assert_eq!(w.host.received(0), vec![vec![b'u', 0], vec![b'u', 1], vec![b'u', 2]]); + assert_eq!(w.host.received(1), vec![vec![b's', 0], vec![b's', 1], vec![b's', 2]]); +} + +#[test] +fn unreliable_from_the_host() { + let mut w = connected_wire(Impair::clean(2), Impair::clean(2), 6); + let t = now(&w); + w.host.peer().send(t, 0, Delivery::Unreliable, b"u1").unwrap(); + w.host.peer().send(t, 0, Delivery::Unsequenced, b"s1").unwrap(); + w.run_for(100); + assert_eq!(w.client.received(0), vec![b"u1".to_vec(), b"s1".to_vec()]); +} + +#[test] +fn duplicated_and_stale_datagrams_are_delivered_once() { + let mut h = scripted_connected(); + let unseq = |group: u16, data: &[u8]| cmd(false, 0, 0, CommandBody::SendUnsequenced { unsequenced_group: group, data: data.to_vec() }); + let unrel = |seq: u16, data: &[u8]| cmd(false, 0, 0, CommandBody::SendUnreliable { unreliable_sequence: seq, data: data.to_vec() }); + let feed = |h: &mut EnetHostPeer, c: Command| h.handle_datagram(at(10), &to_host(0, Some(10), vec![c])).unwrap(); + feed(&mut h, unseq(1, b"a")); + feed(&mut h, unseq(1, b"a")); + feed(&mut h, unseq(2, b"b")); + feed(&mut h, unseq(1, b"a")); + feed(&mut h, unrel(5, b"x")); + feed(&mut h, unrel(5, b"x")); + feed(&mut h, unrel(4, b"old")); + feed(&mut h, unrel(6, b"y")); + let got: Vec> = events(&mut h) + .into_iter() + .map(|e| match e { + EnetHostEvent::Received { data, .. } => data, + other => panic!("{other:?}"), + }) + .collect(); + assert_eq!(got, vec![b"a".to_vec(), b"b".to_vec(), b"x".to_vec(), b"y".to_vec()]); + // Far ahead of the unsequenced window: dropped. + feed(&mut h, unseq(40_000, b"far")); + assert!(events(&mut h).is_empty()); + // The window moves forward with groups within reach. + feed(&mut h, unseq(3000, b"c")); + feed(&mut h, unseq(3000, b"c")); + feed(&mut h, unseq(2, b"b")); + assert_eq!(events(&mut h), vec![EnetHostEvent::Received { channel: 0, data: b"c".to_vec() }]); +} + +#[test] +fn reliable_from_the_client_reordered_and_duplicated() { + let mut h = scripted_connected(); + let rel = |seq: u16, data: &[u8]| cmd(true, 0, seq, CommandBody::SendReliable(data.to_vec())); + h.handle_datagram(at(10), &to_host(0, Some(10), vec![rel(3, b"3"), rel(2, b"2")])).unwrap(); + assert!(events(&mut h).is_empty()); + h.handle_datagram(at(11), &to_host(0, Some(11), vec![rel(1, b"1"), rel(2, b"2")])).unwrap(); + h.handle_datagram(at(12), &to_host(0, Some(12), vec![rel(1, b"1")])).unwrap(); + let got: Vec = events(&mut h); + assert_eq!( + got, + [b"1", b"2", b"3"].iter().map(|d| EnetHostEvent::Received { channel: 0, data: d.to_vec() }).collect::>() + ); + let acks: Vec<(u16, u16)> = transmitted(&mut h, at(12)) + .iter() + .flat_map(|d| d.commands.clone()) + .filter_map(|c| match c.body { + CommandBody::Acknowledge { received_reliable_sequence, received_sent_time } => { + Some((received_reliable_sequence, received_sent_time)) + } + _ => None, + }) + .collect(); + for want in [(3, 10), (2, 10), (1, 11), (2, 11), (1, 12)] { + assert!(acks.contains(&want), "ack {want:?} (with the datagram's sent time) in {acks:?}"); + } + // Far future and channels outside the grant: never delivered. + h.handle_datagram(at(13), &to_host(0, Some(13), vec![rel(40_000, b"evil")])).unwrap(); + let _ = h.handle_datagram(at(13), &to_host(0, Some(13), vec![cmd(true, 9, 1, CommandBody::SendReliable(b"ch9".to_vec()))])); + assert!(events(&mut h).is_empty()); + assert_eq!(h.state(), EnetHostState::Connected); +} + +#[test] +fn acknowledged_commands_need_the_sent_time() { + // Stock ENet: a command that wants an acknowledgement in a datagram without sent time is handled but not + // acknowledged, and the rest of the datagram is skipped. + let mut h = scripted_connected(); + let d = to_host( + 0, + None, + vec![ + cmd(true, 0, 1, CommandBody::SendReliable(b"a".to_vec())), + cmd(true, 0, 2, CommandBody::SendReliable(b"b".to_vec())), + ], + ); + h.handle_datagram(at(10), &d).unwrap(); + assert_eq!(events(&mut h), vec![EnetHostEvent::Received { channel: 0, data: b"a".to_vec() }]); + assert!( + !transmitted(&mut h, at(10)).iter().flat_map(|d| &d.commands).any(|c| matches!(c.body, CommandBody::Acknowledge { .. })) + ); +} + +#[test] +fn connection_commands_are_acknowledged() { + let mut h = scripted_connected(); + let d = to_host( + 0, + Some(0x0102), + vec![ + cmd(true, 0xFF, 2, CommandBody::Ping), + cmd(true, 0xFF, 3, CommandBody::BandwidthLimit { incoming: 1_000_000, outgoing: 2_000_000 }), + cmd(true, 0xFF, 4, CommandBody::ThrottleConfigure { interval: 1000, acceleration: 3, deceleration: 4 }), + ], + ); + h.handle_datagram(at(10), &d).unwrap(); + let acks: Vec = transmitted(&mut h, at(10)) + .into_iter() + .flat_map(|d| d.commands) + .filter(|c| matches!(c.body, CommandBody::Acknowledge { .. })) + .collect(); + for seq in [2u16, 3, 4] { + assert!( + acks.iter().any(|c| c.channel_id == 0xFF + && c.body == CommandBody::Acknowledge { received_reliable_sequence: seq, received_sent_time: 0x0102 }), + "ack of {seq} in {acks:?}" + ); + } + assert!(events(&mut h).is_empty()); + assert_eq!(h.state(), EnetHostState::Connected); +} + +#[test] +fn reliable_sequence_wraps_at_0xffff() { + let mut w = connected_wire(Impair::clean(1), Impair::clean(1), 7); + let total = 66_000u32; + let mut sent = 0u32; + while sent < total { + let t = now(&w); + for _ in 0..200 { + if sent < total { + w.client.peer.send(t, 0, Delivery::Reliable, &sent.to_le_bytes()).unwrap(); + w.host.peer().send(t, 0, Delivery::Reliable, &sent.to_le_bytes()).unwrap(); + sent += 1; + } + } + let want = sent as usize; + assert!(w.run_until(w.now_ms + 5_000, |w| w.host.count >= want && w.client.count >= want)); + } + let got = w.host.received(0); + assert_eq!(got.len(), total as usize); + assert!(got.iter().enumerate().all(|(i, d)| *d == (i as u32).to_le_bytes()), "host order"); + let got = w.client.received(0); + assert_eq!(got.len(), total as usize); + assert!(got.iter().enumerate().all(|(i, d)| *d == (i as u32).to_le_bytes()), "client order"); +} + +// ================================================================================================ loss and timers + +/// Sends `n` reliable messages each way, a few at a time, over a lossy wire; returns what arrived. +fn exchange(w: &mut W, n: u32) -> (Vec>, Vec>) { + let mut i = 0; + while i < n { + let t = now(w); + for _ in 0..5 { + if i < n { + let _ = w.client.peer.send(t, 0, Delivery::Reliable, &i.to_le_bytes()); + if let Some(p) = w.host.peer.as_mut() { + let _ = p.send(t, 0, Delivery::Reliable, &(i + 10_000).to_le_bytes()); + } + i += 1; + } + } + w.run_for(30); + } + let n = n as usize; + w.run_until(w.now_ms + 120_000, |w| w.host.count >= n && w.client.count >= n); + (w.host.received(0), w.client.received(0)) +} + +#[test] +fn retransmission_under_loss_delivers_everything_in_order() { + let mut w = lossy_wire(Impair::lossy(200, 10), Impair::lossy(200, 10), 8); + assert!(w.run_until(60_000, both_connected)); + let (up, down) = exchange(&mut w, 200); + assert_eq!(up, (0..200u32).map(|i| i.to_le_bytes().to_vec()).collect::>()); + assert_eq!(down, (0..200u32).map(|i| (i + 10_000).to_le_bytes().to_vec()).collect::>()); + assert!(w.to_host.lost > 0 && w.to_client.lost > 0, "the wire did lose datagrams"); + assert!(!w.host.events.contains(&EnetHostEvent::TimedOut)); + assert!(w.host.peer().round_trip_time().is_some()); +} + +#[test] +fn idle_connection_stays_up() { + let mut w = connected_wire(Impair::clean(20), Impair::clean(20), 9); + w.run_for(60_000); + assert!(both_connected(&mut w)); + assert!(!w.host.events.contains(&EnetHostEvent::TimedOut)); + assert!(!w.client.events.contains(&EnetEvent::TimedOut)); +} + +#[test] +fn the_host_pings_a_quiet_client() { + // A client that never pings by itself (only acknowledges): the host's pings keep the connection checked. + let quiet = EnetConfig { ping_interval: Duration::from_secs(3600), ..client_config() }; + let mut w = wire_with(quiet, host_config(), Impair::clean(20), Impair::clean(20), 13); + assert!(w.run_until(1_000, both_connected)); + let start = w.host.sent.len(); + w.run_for(30_000); + assert!(both_connected(&mut w)); + let pings = + w.host.sent[start..].iter().flat_map(|d| &d.commands).filter(|c| c.body == CommandBody::Ping && c.acknowledge).count(); + assert!(pings >= 30, "the host pings an idle client ({pings})"); + // And when nothing comes back at all, its ping times out. + let mut h = scripted_connected(); + let t = h.poll_timeout().expect("a ping deadline"); + assert!(t <= at(2 + host_config().ping_interval.as_millis() as u64)); + h.handle_timeout(t).unwrap(); + assert!(transmitted(&mut h, t).iter().flat_map(|d| &d.commands).any(|c| c.body == CommandBody::Ping && c.channel_id == 0xFF)); +} + +#[test] +fn vanished_client_times_out() { + let mut w = connected_wire(Impair::clean(5), Impair::clean(5), 10); + let cut_at = w.now_ms; + w.to_host.cut = true; + let limit = cut_at + host_config().ping_interval.as_millis() as u64 + host_config().timeout.as_millis() as u64 + 1_000; + assert!(w.run_until(limit, |w| w.host.events.contains(&EnetHostEvent::TimedOut)), "no timeout by {limit} ms"); + let earliest = cut_at + host_config().timeout.as_millis() as u64 - host_config().ping_interval.as_millis() as u64; + assert!(w.now_ms >= earliest, "not before the timeout"); + assert_eq!(w.host.peer().state(), EnetHostState::Disconnected); + assert_eq!(w.host.peer().poll_timeout(), None); + let t = now(&w); + assert_err!(w.host.peer().send(t, 0, Delivery::Reliable, b"x"), Error::State { .. }); +} + +// ================================================================================================ disconnect + +#[test] +fn client_disconnect_reaches_the_host() { + let mut w = connected_wire(Impair::clean(5), Impair::clean(5), 11); + let t = now(&w); + w.client.peer.disconnect(t, 77).unwrap(); + assert!(w.run_until(w.now_ms + 2_000, |w| w.host.events.contains(&EnetHostEvent::Disconnected { data: 77 }))); + assert_eq!(w.host.peer().state(), EnetHostState::Disconnected); + assert!( + w.run_until(w.now_ms + 2_000, |w| w.client.peer.state() == EnetState::Disconnected), + "the host acknowledged the disconnect after closing" + ); + assert!(!w.client.events.contains(&EnetEvent::TimedOut)); +} + +#[test] +fn host_disconnect_reaches_the_client() { + let mut w = connected_wire(Impair::clean(5), Impair::clean(5), 12); + let t = now(&w); + w.host.peer().disconnect(t, 42).unwrap(); + assert_eq!(w.host.peer().state(), EnetHostState::Disconnecting); + assert_err!(w.host.peer().disconnect(t, 1), Error::Closed); + assert_err!(w.host.peer().send(t, 0, Delivery::Reliable, b"late"), Error::State { .. }); + assert!(w.run_until(w.now_ms + 2_000, |w| w.client.events.contains(&EnetEvent::Disconnected { data: 42 }))); + assert!(w.run_until(w.now_ms + 2_000, |w| w.host.peer.as_ref().unwrap().state() == EnetHostState::Disconnected)); + assert!(!w.host.events.contains(&EnetHostEvent::TimedOut)); +} + +#[test] +fn disconnect_during_the_handshake() { + let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(connect_params(3), 0)).unwrap(); + let _ = transmitted(&mut h, at(0)); + h.handle_datagram(at(1), &to_host(0, Some(1), vec![cmd(true, 0xFF, 2, CommandBody::Disconnect { data: 5 })])) + .unwrap(); + assert_eq!(h.state(), EnetHostState::Disconnected); + assert_eq!(events(&mut h), vec![EnetHostEvent::Disconnected { data: 5 }]); +} + +// ================================================================================================ rules + +#[test] +fn send_rules() { + let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(connect_params(3), 0)).unwrap(); + assert_err!(h.send(at(0), 0, Delivery::Reliable, b"x"), Error::State { .. }, "before the verify is acknowledged"); + let mut h = scripted_connected(); + assert_err!(h.send(at(3), 2, Delivery::Reliable, b"x"), Error::UnexpectedValue { .. }, "channel 2 of 2"); + assert_too_large!(h.send(at(3), 0, Delivery::Reliable, &vec![0; MAX_PACKET_BYTES + 1]), MAX_PACKET_BYTES, MAX_PACKET_BYTES + 1); + assert!(matches!(h.send(at(3), 0, Delivery::Unsequenced, &[0; 1500]), Err(Error::TooLarge { .. }))); + for i in 0..MAX_SEND_QUEUE { + h.send(at(3), 0, Delivery::Reliable, &[i as u8]).unwrap_or_else(|e| panic!("packet {i}: {e:?}")); + } + match h.send(at(3), 0, Delivery::Reliable, b"one too many") { + Err(Error::TooLarge { max, .. }) => assert_eq!(max, MAX_SEND_QUEUE), + other => panic!("{other:?}"), + } + // The queue drains within the MTU, and each datagram parses. + let sent = transmitted(&mut h, at(4)); + assert!(!sent.is_empty()); +} + +#[test] +fn garbage_never_changes_state() { + let mut h = scripted_connected(); + for bad in [&[][..], &[0x00][..], &[0x40, 0x07, 0x85, 0xFF, 0, 1][..], &[0x00, 0x07, 0x8F, 0, 0, 0][..]] { + assert!(h.handle_datagram(at(5), bad).is_err(), "{bad:?}"); + assert_eq!(h.state(), EnetHostState::Connected); + } + assert_too_large!(h.handle_datagram(at(5), &vec![0; MAX_DATAGRAM_BYTES + 1]), MAX_DATAGRAM_BYTES, MAX_DATAGRAM_BYTES + 1); + // Another peer id: dropped without error. + let other = encode_datagram(&Datagram { + peer_id: HOST_PEER_ID + 1, + session_id: 0, + sent_time: Some(1), + commands: vec![cmd(true, 0, 1, CommandBody::SendReliable(b"not for us".to_vec()))], + }) + .unwrap(); + assert_eq!(h.handle_datagram(at(5), &other), Ok(())); + assert!(events(&mut h).is_empty()); + assert_eq!(h.state(), EnetHostState::Connected); +} + +#[test] +fn fragments_with_lying_lengths() { + let frag = |count: u32, number: u32, total: u32, offset: u32, len: usize| { + cmd( + true, + 0, + 1, + CommandBody::SendFragment(domistream::enet::protocol::Fragment { + start_sequence: 1u16.wrapping_sub(number as u16), + fragment_count: count, + fragment_number: number, + total_length: total, + fragment_offset: offset, + data: vec![0; len], + }), + ) + }; + let mut h = scripted_connected(); + assert_too_large!( + h.handle_datagram(at(5), &to_host(0, Some(5), vec![frag(2, 0, MAX_PACKET_BYTES as u32 + 1, 0, 100)])), + MAX_PACKET_BYTES, + MAX_PACKET_BYTES + 1 + ); + for f in [frag(0, 0, 10, 0, 10), frag(2, 2, 20, 0, 10), frag(2, 0, 20, 15, 10), frag(2, 0, 5, 0, 10), frag(u32::MAX, 0, 100, 0, 10), frag(2, 0, u32::MAX, 0, 10)] { + let mut h = scripted_connected(); + let _ = h.handle_datagram(at(5), &to_host(0, Some(5), vec![f.clone()])); + assert!(events(&mut h).is_empty(), "{f:?}"); + assert_eq!(h.state(), EnetHostState::Connected); + } +} + +// ================================================================================================ properties + +proptest! { + #![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })] + + /// Arbitrary bytes never panic `accept`, and what it accepts it answers with datagrams that parse. + #[test] + fn accept_never_panics(data in proptest::collection::vec(any::(), 0..200)) { + let r = EnetHostPeer::accept(host_config(), at(0), &data); + prop_assert!(common::implemented(&r)); + if let Ok(mut h) = r { + prop_assert!(!transmitted(&mut h, at(0)).is_empty()); + } + } + + /// A connected host fed arbitrary datagrams (raw, or with our header so they reach the command loop) never + /// panics; what it delivers fits the cap; what it sends parses and fits the MTU. + #[test] + fn host_survives_arbitrary_datagrams( + datagrams in proptest::collection::vec((any::(), proptest::collection::vec(any::(), 0..200)), 1..20) + ) { + let mut h = scripted_connected(); + for (i, (headed, d)) in datagrams.into_iter().enumerate() { + let t = at(10 + i as u64 * 50); + let bytes = if headed { + let mut b = vec![0x80, HOST_PEER_ID as u8, 0, 10]; + b.extend_from_slice(&d); + b + } else { + d + }; + let r = h.handle_datagram(t, &bytes); + prop_assert!(common::implemented(&r)); + let _ = h.handle_timeout(t); + let _ = transmitted(&mut h, t); + for e in events(&mut h) { + if let EnetHostEvent::Received { data, .. } = e { + prop_assert!(data.len() <= MAX_PACKET_BYTES); + } + } + } + } +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 24, ..ProptestConfig::default() })] + + /// Random loss, duplication, reordering and latency: the connection comes up and every reliable message + /// arrives exactly once, in order, both ways. + #[test] + fn random_loss_patterns_deliver_reliable_messages_in_order( + seed in any::(), + loss in 0u32..300, + duplicate in 0u32..150, + reorder in 0u32..400, + latency in 1u64..60, + ) { + let impair = Impair { loss, duplicate, reorder, reorder_ms: 40, latency_ms: latency }; + let mut w = lossy_wire(impair, impair, seed); + prop_assert!(w.run_until(60_000, both_connected), "no connection"); + let (up, down) = exchange(&mut w, 40); + prop_assert_eq!(up, (0..40u32).map(|i| i.to_le_bytes().to_vec()).collect::>()); + prop_assert_eq!(down, (0..40u32).map(|i| (i + 10_000).to_le_bytes().to_vec()).collect::>()); + } +}