Skip to main content

matter_kit/
messaging.rs

1//! Message processing: a datagram in, a protocol message out (Core §4.7).
2//!
3//! Everything below this module is sans-I/O and, until now, unconnected. [`msg`](crate::msg)
4//! frames and encrypts, [`session`](crate::session) holds the keys, [`exchange`](crate::exchange)
5//! holds the conversations and their reliability state — and nothing put the three together.
6//! This is that seam, and it is the whole of §4.7.1 "Message Transmission" and §4.7.2 "Message
7//! Reception".
8//!
9//! # Why it is a type and not a function
10//!
11//! Reception is not a pure decode. Three pieces of state change on the way through, and all
12//! three are security-relevant:
13//!
14//! * the **session's** replay window (§4.6.5), which decides whether a counter is new;
15//! * the **exchange's** MRP state (§4.12), which decides whether an acknowledgement is owed
16//!   and whether a retransmission is still outstanding;
17//! * the **exchange table** itself, since a message may open an exchange the peer initiated.
18//!
19//! A receiver that decoded without updating them would accept replays. One that updated them
20//! before authenticating would let an unauthenticated sender move a window it has no key for
21//! — which is why the order here is fixed: find the session, **decrypt**, and only then touch
22//! any counter.
23//!
24//! # A duplicate is acknowledged and dropped
25//!
26//! §4.12.2.2 is emphatic, and it is the rule most easily got wrong in the direction that
27//! looks like it works:
28//!
29//! > The receiver SHALL send an acknowledgment message to the sender for each instance of an
30//! > authenticated, reliable message, including duplicates. The reliability layer SHALL only
31//! > propagate the first instance of a message to the next higher layer.
32//!
33//! Drop a duplicate silently and the sender retransmits until it gives up; deliver it twice
34//! and the application acts on it twice. [`Received::Duplicate`] is neither.
35
36use crate::config::Config;
37use crate::error::{Error, ErrorCode, Result, bail};
38use crate::exchange::{EXCHANGE_IDLE_TIMEOUT, ExchangeKey, ExchangeTable, MrpParams, OnTimeout};
39use crate::msg::{CounterKind, CounterWindow, MessageCounter, Verdict};
40use crate::msg::{
41    Destination, MessageHeader, NonceSource, ProtocolHeader, ProtocolId, SessionId, SessionType,
42    preview, protect, unprotect,
43};
44use crate::platform::{Instant, Peer};
45use crate::session::{SecureSession, SessionKind, SessionTable};
46
47/// The largest a Protocol Header can be (§4.4.3): the exchange flags, the opcode, the
48/// exchange id, a 32-bit protocol id and an acknowledged counter.
49///
50/// Only [`Messaging::acknowledge`] needs it: a standalone acknowledgement has no payload, so
51/// the body it frames is the header on its own.
52const PROTOCOL_HEADER_MAX: usize = 16;
53
54/// What arrived, once the message has been authenticated and routed.
55#[derive(Debug)]
56#[non_exhaustive]
57pub enum Received<'a> {
58    /// A group datagram (§4.16), which belongs to the group key store rather than here.
59    ///
60    /// Nothing about it has been decrypted or authenticated: a group message is keyed by an
61    /// operational group key, and which key it is has to be found by trying every installed
62    /// one whose session id matches (§4.17.3.6). Hand `buf` — unchanged — to
63    /// [`group::wire::receive`](crate::group::wire::receive), which does that and returns the
64    /// payload; a node that holds no group keys drops it.
65    Group {
66        /// The Group Session Id from the header, which selects the candidate keys.
67        session_id: SessionId,
68        /// Where it came from.
69        from: Peer,
70    },
71    /// The peer closed the session, and this node has done the same (§4.11.1.4).
72    ///
73    /// The session, its keys and its exchanges are gone by the time this is returned — that
74    /// is what "SHALL remove all state associated with the session" means, and it is done
75    /// here rather than left to the caller because none of that state is the caller's.
76    ///
77    /// What *is* the caller's is everything keyed on a session above this layer: §8.5's
78    /// subscriptions above all, which report on a session and have nowhere to go once it has
79    /// gone, and the §5.5 commissioning channel, which a closed PASE session releases.
80    SessionClosed {
81        /// The session that was closed.
82        session: SessionId,
83    },
84    /// A protocol message for the layer above.
85    Message {
86        /// The exchange it belongs to.
87        exchange: ExchangeKey,
88        /// The protocol header it carried.
89        header: ProtocolHeader,
90        /// Whether an acknowledgement is owed, which [`Messaging::acknowledge`] sends.
91        needs_ack: bool,
92        /// The application payload, decrypted in place.
93        payload: &'a [u8],
94    },
95    /// An authenticated message this node has already seen (§4.12.2.2).
96    ///
97    /// Not delivered upward. Still acknowledged, because the sender's retransmission means
98    /// its last acknowledgement was lost, not that its message was.
99    Duplicate {
100        /// The exchange it belongs to.
101        exchange: ExchangeKey,
102        /// Whether an acknowledgement is owed.
103        needs_ack: bool,
104    },
105    /// A standalone acknowledgement, consumed entirely by the reliability layer.
106    Acknowledged {
107        /// The exchange it acknowledged.
108        exchange: ExchangeKey,
109    },
110}
111
112/// What a timer expiry asks the caller to do.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum Due {
115    /// Retransmit the message with this counter on this exchange (§4.12.2.1).
116    ///
117    /// "Logical retransmission is of a given message as identified by its message counter",
118    /// so the caller resends the *same bytes*, not a re-encoding: a new counter would be a
119    /// new message and would reuse a nonce.
120    Retransmit {
121        /// Which exchange.
122        exchange: ExchangeKey,
123        /// The counter of the message to resend.
124        counter: u32,
125    },
126    /// An acknowledgement has waited long enough for a message to ride on (§4.12.5.2.2).
127    ///
128    /// [`Messaging::acknowledge`] writes it.
129    Acknowledge {
130        /// Which exchange owes it.
131        exchange: ExchangeKey,
132    },
133    /// `MRP_MAX_TRANSMISSIONS` passed with no acknowledgement; the exchange is closed.
134    Abandoned {
135        /// Which exchange was given up on.
136        exchange: ExchangeKey,
137    },
138}
139
140/// Which protocols the upper layer will accept (§4.10.3.1).
141///
142/// "The Interaction Model layer indicates to the Exchange Layer which Protocols it will accept.
143/// Any message for a Protocol ID that is not registered with the Exchange Layer SHALL be
144/// dropped."
145///
146/// This is not bookkeeping. §4.10.5.2 opens an exchange for any unsolicited message with the
147/// **I** flag, and on the unsecured session that is any datagram at all — so the set of
148/// protocols a node answers is also the set an attacker can make it allocate for. A node that
149/// registers only what it serves refuses the rest before the exchange table is touched.
150#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
151pub struct Protocols(u8);
152
153impl Protocols {
154    const fn bit(protocol: ProtocolId) -> Option<u8> {
155        if protocol.vendor.0 != crate::msg::VendorId::COMMON.0 {
156            return None;
157        }
158        match protocol.id {
159            0x0000..=0x0004 => Some(1u8 << protocol.id),
160            _ => None,
161        }
162    }
163
164    /// Nothing registered — every unsolicited message is dropped.
165    pub const NONE: Self = Self(0);
166
167    /// Secure Channel (§4.11). Every node needs it: it is how sessions are established.
168    pub const SECURE_CHANNEL: Self = Self(1 << 0);
169    /// The Interaction Model (ch. 8) — what a node that serves clusters registers.
170    pub const INTERACTION_MODEL: Self = Self(1 << 1);
171    /// BDX (§11.22), for a node that transfers files.
172    pub const BDX: Self = Self(1 << 2);
173    /// User Directed Commissioning (§5.3).
174    pub const USER_DIRECTED_COMMISSIONING: Self = Self(1 << 3);
175    /// The range reserved for testing.
176    pub const FOR_TESTING: Self = Self(1 << 4);
177
178    /// What an ordinary device registers: Secure Channel and the Interaction Model.
179    pub const DEVICE: Self = Self(Self::SECURE_CHANNEL.0 | Self::INTERACTION_MODEL.0);
180
181    /// Both of these, registered.
182    #[must_use]
183    pub const fn with(self, other: Self) -> Self {
184        Self(self.0 | other.0)
185    }
186
187    /// Whether `protocol` is registered.
188    ///
189    /// A vendor-specific protocol id is never registered: §4.10.3.1's registration is by
190    /// identity, and this node serves none.
191    #[must_use]
192    pub const fn contains(self, protocol: ProtocolId) -> bool {
193        match Self::bit(protocol) {
194            Some(bit) => self.0 & bit != 0,
195            None => false,
196        }
197    }
198}
199
200/// §4.13.2.1's Unsecured Session Context, reduced to what framing needs.
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202struct UnsecuredPeer {
203    /// The Ephemeral Initiator Node ID, whichever end chose it.
204    ephemeral_initiator: crate::msg::NodeId,
205    /// Whether *this* node is the initiator, which decides which header field carries it.
206    we_initiated: bool,
207}
208
209/// A session that was evicted to make room for a new one (§4.11.1.1).
210///
211/// The session and its exchanges are already gone. What is left is the `CLOSE_SESSION`
212/// status report the specification owes the evicted peer, framed and ready in the caller's
213/// output buffer.
214#[derive(Debug, Clone, Copy)]
215#[must_use = "§4.11.1.1 step 2a owes the evicted peer a CloseSession status report"]
216pub struct Evicted {
217    /// The session that was removed.
218    pub session: SessionId,
219    /// Where its peer was, if the session knew — nothing to send to if it did not.
220    pub peer: Option<Peer>,
221    /// How many octets of the output buffer the report occupies. Zero if it could not be
222    /// framed, which is not a reason to abandon the eviction.
223    pub len: usize,
224}
225
226/// A node's message processing: sessions, exchanges, and the framing between them.
227///
228/// `S` is [`Config::SESSIONS`] and `X` is `SESSIONS * EXCHANGES_PER_SESSION`.
229#[derive(Debug)]
230pub struct Messaging<C: Config, const S: usize, const X: usize> {
231    sessions: SessionTable<C, S>,
232    exchanges: ExchangeTable<C, X>,
233    /// The counter for messages sent on the unsecured session (§4.6.1.2).
234    unsecured_counter: MessageCounter,
235    /// Duplicate detection for the unsecured session.
236    ///
237    /// §4.6.5 applies to unencrypted messages too, and this is the window that makes a PASE
238    /// handshake replay-resistant before any key exists.
239    unsecured_window: CounterWindow,
240    /// §4.13.2.1's Unsecured Session Context: the **Ephemeral Initiator Node ID**, and which
241    /// end of it this node is.
242    ///
243    /// "Randomly selected for each session by the initiator from the Operational Node ID range
244    /// and enclosed by initiator as Source Node ID and responder as Destination Node ID."
245    ///
246    /// One context, not a table. §4.13.2.1 allows several, keyed by ephemeral id, but a device
247    /// answers one session establishment at a time — which
248    /// [`PaseAdmission`](crate::commissioning::PaseAdmission) now enforces — and a controller
249    /// commissions one device at a time.
250    unsecured_peer: Option<UnsecuredPeer>,
251    /// Whether to apply §4.9's privacy processing to outgoing secure unicast messages.
252    privacy: bool,
253    /// §4.10.3.1's registered protocols.
254    protocols: Protocols,
255}
256
257impl<C: Config, const S: usize, const X: usize> Messaging<C, S, X> {
258    /// A node with no sessions and no exchanges.
259    ///
260    /// `first_session_id`, `first_exchange_id` and `initial_counter` should all come from
261    /// [`Rng`](crate::platform::Rng). §4.6.1.1 requires the counter to start at random: one
262    /// that always starts at zero leaks how many times a device has rebooted and makes nonce
263    /// reuse across a factory reset far too easy. A full-width random number is what to pass —
264    /// [`MessageCounter::new`](crate::msg::MessageCounter::new) narrows it to the twenty-eight
265    /// bits §4.6.1.1 allows, so the caller does not have to know that it must.
266    #[must_use]
267    pub fn new(first_session_id: u16, first_exchange_id: u16, initial_counter: u32) -> Self {
268        Self {
269            sessions: SessionTable::new(first_session_id),
270            exchanges: ExchangeTable::new(first_exchange_id),
271            unsecured_counter: MessageCounter::new(initial_counter),
272            unsecured_window: CounterWindow::new(CounterKind::Rollover),
273            unsecured_peer: None,
274            privacy: false,
275            protocols: Protocols::DEVICE,
276        }
277    }
278
279    /// Registers the protocols this node's upper layer will accept (§4.10.3.1).
280    ///
281    /// Defaults to [`Protocols::DEVICE`] — Secure Channel and the Interaction Model — which is
282    /// what a node that serves clusters needs. A node that also transfers files registers
283    /// [`Protocols::BDX`] on top; one that does neither registers less.
284    pub const fn register(&mut self, protocols: Protocols) {
285        self.protocols = protocols;
286    }
287
288    /// Which protocols are registered.
289    #[must_use]
290    pub const fn protocols(&self) -> Protocols {
291        self.protocols
292    }
293
294    /// Applies §4.9's privacy processing to outgoing secure unicast messages.
295    ///
296    /// Off by default, and deliberately. The **P** flag is only *required* on group messages
297    /// (§4.16.2 step 2c, §4.18): on a secure unicast session it is the sender's choice, and what it
298    /// buys is hiding the message counter from a passive observer on the link — the counter
299    /// is already authenticated, and anyone with the key can read it either way. What it
300    /// costs is depending on every peer having exercised its deobfuscation path, which is
301    /// not a bet worth making by default for a property this small.
302    ///
303    /// Receiving a private message never needs this: the flag is in the message, and
304    /// [`Messaging::receive`] honours it whatever this is set to.
305    pub const fn set_privacy(&mut self, privacy: bool) {
306        self.privacy = privacy;
307    }
308
309    /// Opens §4.13.2.1's Unsecured Session Context as the **initiator**.
310    ///
311    /// `ephemeral` is the Ephemeral Initiator Node ID this node encloses as the Source Node ID
312    /// of every unsecured message it sends, and which the responder will echo back as the
313    /// Destination Node ID. §4.13.2.1: "Initiators SHALL select a new random ephemeral node ID
314    /// for each unsecured session", from the Operational Node ID range — so it comes from
315    /// [`Rng`](crate::platform::Rng) and is *not* the node's operational identity. A node that
316    /// reused one identity across sessions would let a passive observer link them.
317    ///
318    /// # Errors
319    ///
320    /// [`ErrorCode::InvalidArgument`] unless `ephemeral` is in the Operational Node ID range.
321    pub fn open_unsecured_as_initiator(&mut self, ephemeral: crate::msg::NodeId) -> Result<()> {
322        if !ephemeral.is_operational() {
323            bail!(InvalidArgument)
324        }
325        self.unsecured_peer = Some(UnsecuredPeer {
326            ephemeral_initiator: ephemeral,
327            we_initiated: true,
328        });
329        Ok(())
330    }
331
332    /// Forgets the Unsecured Session Context, so the next handshake starts a new one.
333    pub const fn close_unsecured(&mut self) {
334        self.unsecured_peer = None;
335    }
336
337    /// The Ephemeral Initiator Node ID of the current Unsecured Session Context, if there is one.
338    #[must_use]
339    pub const fn unsecured_ephemeral_id(&self) -> Option<crate::msg::NodeId> {
340        match self.unsecured_peer {
341            Some(peer) => Some(peer.ephemeral_initiator),
342            None => None,
343        }
344    }
345
346    /// The session table.
347    pub const fn sessions(&self) -> &SessionTable<C, S> {
348        &self.sessions
349    }
350
351    /// The session table, mutably — for the fields a completed handshake fills in
352    /// afterwards, such as §11.18.6.8 step 10a's accessing fabric.
353    ///
354    /// Installing a session goes through [`Messaging::install_session`] instead: a session
355    /// and its exchanges are one lifetime, and this reference only reaches one of them.
356    pub const fn sessions_mut(&mut self) -> &mut SessionTable<C, S> {
357        &mut self.sessions
358    }
359
360    /// Installs the session a handshake produced, evicting one if there is no room
361    /// (§4.11.1.1).
362    ///
363    /// A session table that answers `NoSpace` is a node that can be commissioned exactly
364    /// `Config::SESSIONS` times and then never again — and the failure appears at the
365    /// *next* administrator, not at the one who filled it. §4.11.1.1 is explicit about the
366    /// alternative and about its three steps, in order:
367    ///
368    /// 1. the least recently used session, by `SessionTimestamp`;
369    /// 2. a `StatusReport(SUCCESS, SECURE_CHANNEL, CLOSE_SESSION)` **to that peer**, and
370    ///    only then "remove all state associated with the session";
371    /// 3. the new session's own establishment message, which the caller was sending anyway.
372    ///
373    /// Step 2's two halves are why this takes buffers and returns an [`Evicted`]: the report
374    /// has to be framed while the session that encrypts it still exists, and put on the wire
375    /// by whoever owns the socket. The removal has already happened when this returns; what
376    /// is left is a datagram the caller sends to [`Evicted::peer`]. Dropping it costs the
377    /// peer nothing worse than a session it believes in until its next message fails, which
378    /// is why this is `must_use` rather than an error.
379    ///
380    /// `Ok(None)` is the ordinary case: there was room and nothing was evicted.
381    pub fn install_session(
382        &mut self,
383        session: SecureSession,
384        now: Instant,
385        randomness: u32,
386        scratch: &mut [u8],
387        out: &mut [u8],
388    ) -> Result<Option<Evicted>> {
389        if self.sessions.len() < S {
390            self.sessions.insert(session)?;
391            return Ok(None);
392        }
393        let Some(victim) = self.sessions.least_recently_used() else {
394            // No room and nothing to evict means `S == 0`, which `AssertValid` forbids.
395            bail!(NoSpace)
396        };
397        let peer = self.sessions.find(victim).and_then(|s| s.peer);
398        // Framed before the removal, because it is encrypted under the evicted session's own
399        // keys: a report built afterwards has nothing to encrypt it with.
400        let report = crate::sc::status::StatusReport {
401            general: crate::sc::status::GeneralCode::Success,
402            protocol: ProtocolId::SECURE_CHANNEL,
403            protocol_code: crate::sc::status::SecureChannelCode::CloseSession as u16,
404            data: &[],
405        };
406        let mut body = [0u8; 16];
407        let len = report.encode(&mut body)?;
408        let Some(body) = body.get(..len) else {
409            bail!(BufferTooSmall)
410        };
411        let exchange = self.open(victim, ProtocolId::SECURE_CHANNEL, now)?;
412        let framed = self
413            .send(
414                exchange,
415                crate::sc::opcode::STATUS_REPORT,
416                false,
417                body,
418                now,
419                randomness,
420                scratch,
421                out,
422            )
423            .map(|(n, _)| n);
424        // §4.13.3.1: "remove all state associated with the session" — the exchanges on it
425        // included, and including the one just used to say goodbye.
426        self.close_session(victim);
427        self.sessions.insert(session)?;
428        Ok(Some(Evicted {
429            session: victim,
430            peer,
431            len: framed.unwrap_or(0),
432        }))
433    }
434
435    /// Removes a session and everything associated with it (§4.13.3.1).
436    ///
437    /// Returns whether there was one. The exchanges on that session go with it: an exchange
438    /// outlives its session only as an entry nothing can ever answer on, holding a slot in a
439    /// fixed-capacity table until it times out.
440    pub fn close_session(&mut self, session: SessionId) -> bool {
441        self.exchanges.close_session(session);
442        self.sessions.remove(session)
443    }
444
445    /// Removes every session on a fabric, and their exchanges — what `RemoveFabric`
446    /// (§11.18.6.12) owes at the message layer.
447    ///
448    /// Returns how many sessions went. The clusters' half of the same command is
449    /// [`Lifecycle::FabricRemoved`](crate::im::Lifecycle::FabricRemoved).
450    pub fn remove_fabric(&mut self, fabric: crate::msg::FabricIndex) -> usize {
451        let doomed: heapless::Vec<SessionId, S> = self
452            .sessions
453            .iter()
454            .filter(|s| s.fabric_index == fabric)
455            .map(|s| s.local_session_id)
456            .collect();
457        for session in &doomed {
458            self.exchanges.close_session(*session);
459        }
460        self.sessions.remove_fabric(fabric)
461    }
462
463    /// The exchange table.
464    pub const fn exchanges(&self) -> &ExchangeTable<C, X> {
465        &self.exchanges
466    }
467
468    /// The exchange table, mutably.
469    pub const fn exchanges_mut(&mut self) -> &mut ExchangeTable<C, X> {
470        &mut self.exchanges
471    }
472
473    /// Opens an exchange this node initiates, to a peer it has not named yet.
474    ///
475    /// The peer is learned from the first message that comes back. Prefer
476    /// [`Messaging::open_to`] where it is already known: until it is, this node assumes UDP
477    /// and runs MRP, which is right for UDP and one wasted round trip on BTP.
478    pub fn open(
479        &mut self,
480        session: SessionId,
481        protocol: ProtocolId,
482        now: Instant,
483    ) -> Result<ExchangeKey> {
484        let params = self.mrp_params(session);
485        // Where the peer last was, which is the only answer available and the right one: a
486        // session exists because that peer authenticated itself from there. Opening with no
487        // peer produces an exchange that cannot send — [`Stack::send`] builds the message and
488        // [`Stack::peer`] then has no address to give the caller, so the message is built,
489        // counted, and dropped, with no error anywhere. Use [`Stack::open_to`] to name a
490        // different address, for a peer just rediscovered at a new one.
491        let peer = self.sessions.find(session).and_then(|s| s.peer);
492        self.exchanges
493            .open_initiator(session, protocol, params, peer, now)
494    }
495
496    /// Opens an exchange to a peer this node has already found.
497    ///
498    /// Naming the transport is what lets §4.12.4 be honoured: a BLE peer's exchange never
499    /// sets the **R** flag, because BTP has already delivered the message or closed the
500    /// session trying.
501    pub fn open_to(
502        &mut self,
503        session: SessionId,
504        protocol: ProtocolId,
505        peer: Peer,
506        now: Instant,
507    ) -> Result<ExchangeKey> {
508        let params = self.mrp_params(session);
509        self.exchanges
510            .open_initiator(session, protocol, params, Some(peer), now)
511    }
512
513    /// Where an exchange's peer is, once it is known.
514    #[must_use]
515    pub fn peer(&self, exchange: ExchangeKey) -> Option<Peer> {
516        self.exchanges.find(exchange).and_then(|e| e.peer)
517    }
518
519    fn mrp_params(&self, session: SessionId) -> MrpParams {
520        self.sessions
521            .find(session)
522            .map_or_else(MrpParams::default, |s| s.mrp)
523    }
524
525    /// Closes an exchange.
526    pub fn close(&mut self, exchange: ExchangeKey) -> bool {
527        self.exchanges.close(exchange)
528    }
529
530    /// Processes one arriving datagram, in place (§4.7.2).
531    ///
532    /// `buf` is decrypted in place, so the returned payload borrows it. On any failure the
533    /// contents of `buf` are unspecified — §3.6.2 says a failed tag check leaves the payload
534    /// undefined — and nothing in this node's state has moved.
535    pub fn receive<'b>(
536        &mut self,
537        buf: &'b mut [u8],
538        from: Peer,
539        now: Instant,
540    ) -> Result<Received<'b>> {
541        let head = preview(buf)?;
542        if matches!(head.session_type, SessionType::Group) {
543            // §4.16: a group message is keyed by an *operational group key* and belongs to no
544            // session, so none of this function's machinery applies to it — there is no
545            // session to find, no replay window of a session's to move, and no exchange, since
546            // §4.16.2 step 2c sets only the P flag, so a group message is never
547            // reliable and never acknowledged.
548            //
549            // It is handed back rather than refused. A device with a group key store routes it
550            // to [`group::wire::receive`](crate::group::wire::receive), which is the same layer
551            // as this one for keys it holds rather than sessions; a device without one drops
552            // it. Answering `Unsupported` here made the two halves look like one missing one.
553            return Ok(Received::Group {
554                session_id: head.session_id,
555                from,
556            });
557        }
558
559        let (header, range) = if head.session_id == SessionId::UNSECURED {
560            let (header, rest) = MessageHeader::decode(buf)?;
561            if !header.is_unsecured() {
562                bail!(MessageReserved)
563            }
564            let start = buf.len().saturating_sub(rest.len());
565            (header, start..buf.len())
566        } else {
567            let session = self
568                .sessions
569                .find(head.session_id)
570                .ok_or(Error::new(ErrorCode::NoSession))?;
571            // §4.8.1.1's nonce depends on how the session was established, and getting it
572            // wrong fails the tag rather than silently mis-decrypting — but naming it here
573            // keeps the two readings from ever being confused.
574            let nonce_source = match session.kind {
575                SessionKind::Pase => NonceSource::Pase,
576                SessionKind::Case => NonceSource::Case(session.peer_node_id),
577            };
578            let keys = session.keys.receiving(session.role).clone();
579            unprotect(buf, &keys, nonce_source)?
580        };
581
582        // Authenticated. Only now may any counter move.
583        let verdict = if header.is_unsecured() {
584            self.unsecured_window.accept(header.message_counter)
585        } else {
586            let session = self
587                .sessions
588                .find_mut(head.session_id)
589                .ok_or(Error::new(ErrorCode::NoSession))?;
590            // Authenticated, so it is the peer and this is where it is. A node that opens an
591            // exchange of its own — §8.5.3's subscription reports above all — has no other way
592            // to learn the address, and an exchange with no peer sends nothing.
593            session.peer = Some(from);
594            session.accept_counter(header.message_counter, now)
595        };
596
597        let Some(payload) = buf.get(range) else {
598            bail!(MessageTruncated)
599        };
600        let (protocol_header, body) = ProtocolHeader::decode(payload)?;
601
602        // §4.13.2.1's context matching: "Else if the message carries a Source Node ID … Set
603        // Session Role to responder … Record the incoming message's Source Node ID as Ephemeral
604        // Initiator Node ID." Recorded here, before the exchange is routed, so that the very
605        // first reply carries it back as the Destination Node ID.
606        if header.is_unsecured()
607            && let Some(source) = header.source
608            && self
609                .unsecured_peer
610                .is_none_or(|peer| peer.ephemeral_initiator != source)
611        {
612            // §4.13.2.1 matches a context by Ephemeral Initiator Node ID and creates a *new*
613            // one when no context matches. A different id is a different session — a second
614            // commissioner, or the same one returning for CASE after PASE — so the context is
615            // replaced rather than kept. Keeping the first would address every reply to a peer
616            // that has gone, which the CHIP SDK drops as belonging to no session of its own.
617            //
618            // One context at a time is the simplification here; the specification allows
619            // several. What makes it safe is that the *contents* are two header fields and a
620            // replay window, and admitting a second handshake at all is refused a layer up by
621            // `PaseAdmission`.
622            self.unsecured_peer = Some(UnsecuredPeer {
623                ephemeral_initiator: source,
624                we_initiated: false,
625            });
626        }
627
628        let duplicate = matches!(verdict, Verdict::Duplicate);
629        let key = self.route(header.session_id, &protocol_header, duplicate, now)?;
630        let Some(exchange) = self.exchanges.find_mut(key) else {
631            bail!(NoExchange)
632        };
633        exchange.touch(now);
634        // Where the reply goes, and — §4.12.4 — whether MRP runs on this exchange. A peer
635        // that moved (a Thread node changing address, say) is followed here.
636        exchange.peer = Some(from);
637        exchange.mrp.note_peer_activity(now);
638
639        // §4.12.1: an acknowledgement may ride on any message, so it is taken before the
640        // message's own kind is considered.
641        if let Some(acknowledged) = protocol_header.acknowledged_counter {
642            exchange.mrp.on_ack(acknowledged, now);
643        }
644
645        if protocol_header.reliability {
646            exchange
647                .mrp
648                .on_reliable_received(header.message_counter, now, duplicate);
649        }
650        let needs_ack = protocol_header.reliability;
651
652        if duplicate {
653            return Ok(Received::Duplicate {
654                exchange: key,
655                needs_ack,
656            });
657        }
658        if protocol_header.protocol == ProtocolId::SECURE_CHANNEL
659            && protocol_header.opcode == crate::sc::opcode::MRP_STANDALONE_ACK
660        {
661            // A standalone acknowledgement carries nothing above the reliability layer.
662            return Ok(Received::Acknowledged { exchange: key });
663        }
664
665        // §4.11.1.4: "If a Node has either sent or received a CloseSession StatusReport, that
666        // Node SHALL remove all state associated with the session." Both halves are the
667        // message layer's, and this is the half a node is most likely to leave out — sending
668        // one is a decision it makes, receiving one is something that happens to it.
669        //
670        // Handled here rather than handed upward because the rule is about *this* layer's
671        // state: the session, its keys, its counters and its exchanges, including the exchange
672        // this message arrived on. A node that passed it up would answer on a session the
673        // specification says is already gone.
674        if !header.is_unsecured()
675            && protocol_header.protocol == ProtocolId::SECURE_CHANNEL
676            && protocol_header.opcode == crate::sc::opcode::STATUS_REPORT
677            && matches!(
678                crate::sc::status::StatusReport::decode(body),
679                Ok(report)
680                    if report.protocol == ProtocolId::SECURE_CHANNEL
681                        && report.protocol_code
682                            == crate::sc::status::SecureChannelCode::CloseSession as u16
683            )
684        {
685            let session = header.session_id;
686            self.close_session(session);
687            return Ok(Received::SessionClosed { session });
688        }
689
690        Ok(Received::Message {
691            exchange: key,
692            header: protocol_header,
693            needs_ack,
694            payload: body,
695        })
696    }
697
698    /// Finds or opens the exchange a message belongs to (§4.10.5.2).
699    ///
700    /// The three rules are in order, and the order is what bounds the table:
701    ///
702    /// 1. "If the unsolicited message is not marked as having a duplicate message counter,
703    ///    **has a registered Protocol ID**, and the I Flag is set: create a new exchange."
704    /// 2. "Otherwise, if the message has the R Flag set: create an *ephemeral* exchange … and
705    ///    send an immediate standalone acknowledgement. The message SHALL NOT be forwarded to
706    ///    the upper layer."
707    /// 3. "Otherwise, processing of the message SHALL stop."
708    ///
709    /// Rule 3 is the one that matters most and is the easiest to leave out: a message this
710    /// node will never act on, and which is not even asking for an acknowledgement, must not
711    /// cost a table entry. Without it every datagram that reaches the port allocates.
712    fn route(
713        &mut self,
714        session: SessionId,
715        header: &ProtocolHeader,
716        duplicate: bool,
717        now: Instant,
718    ) -> Result<ExchangeKey> {
719        if let Some(exchange) =
720            self.exchanges
721                .find_for_message(session, header.exchange_id, header.initiator)
722        {
723            return Ok(exchange.key);
724        }
725        // Only a message *from* an initiator may open an exchange. One claiming to be from a
726        // responder with no exchange to respond to is answering a question nobody asked.
727        if !header.initiator {
728            bail!(NoExchange)
729        }
730        let params = self.mrp_params(session);
731        if !duplicate && self.protocols.contains(header.protocol) {
732            return self.exchanges.open_responder(
733                session,
734                header.exchange_id,
735                header.protocol,
736                params,
737                now,
738            );
739        }
740        if header.reliability {
741            // Rule 2. The sender is owed an acknowledgement even though nothing here will
742            // read its message — withholding it costs five retransmissions — but the entry
743            // that carries it is closed as soon as it has been sent.
744            return self.exchanges.open_ephemeral(
745                session,
746                header.exchange_id,
747                header.protocol,
748                params,
749                now,
750            );
751        }
752        // Rule 3.
753        bail!(NoExchange)
754    }
755
756    /// Builds an outgoing message on an exchange (§4.7.1).
757    ///
758    /// `reliable` sets the MRP **R** flag; a reliable message is remembered for
759    /// retransmission until it is acknowledged, and [`Messaging::poll`] is what resends it.
760    /// `randomness` is the jitter draw of §4.12.2.1 and should come from
761    /// [`Rng`](crate::platform::Rng).
762    ///
763    /// Returns how many octets of `out` the datagram occupies, and the counter it was sent
764    /// with — which is what a retransmission is identified by.
765    #[expect(
766        clippy::too_many_arguments,
767        reason = "every one is a distinct fact about the message; bundling them into a \
768                  struct would only move the same list one line up"
769    )]
770    pub fn send(
771        &mut self,
772        exchange: ExchangeKey,
773        opcode: u8,
774        reliable: bool,
775        payload: &[u8],
776        now: Instant,
777        randomness: u32,
778        scratch: &mut [u8],
779        out: &mut [u8],
780    ) -> Result<(usize, u32)> {
781        let Some(open) = self.exchanges.find(exchange) else {
782            bail!(NoExchange)
783        };
784        let protocol = open.protocol;
785        // §4.12.4: "Reliable messages sent over TCP, PAFTP, or BTP SHALL utilize the
786        // underlying reliability mechanisms of those transports and SHOULD NOT set the R
787        // Flag." Running MRP on top of BTP would retransmit a message BTP has already
788        // guaranteed, and BTP would carry the duplicate faithfully.
789        let reliable = reliable && !open.is_transport_reliable();
790        let piggyback = self
791            .exchanges
792            .find_mut(exchange)
793            .and_then(|e| e.mrp.take_piggyback());
794
795        let protocol_header = ProtocolHeader {
796            initiator: exchange.role.is_initiator(),
797            acknowledged_counter: piggyback,
798            reliability: reliable,
799            exchange_id: exchange.id,
800            protocol,
801            opcode,
802        };
803
804        let counter = self.next_counter(exchange.session, now)?;
805        let written = self.frame(
806            exchange.session,
807            counter,
808            &protocol_header,
809            payload,
810            scratch,
811            out,
812        )?;
813
814        if reliable && let Some(open) = self.exchanges.find_mut(exchange) {
815            open.mrp.on_send(counter, now, randomness)?;
816        }
817        Ok((written, counter))
818    }
819
820    /// Sends the standalone acknowledgement a [`Received`] said was owed (§4.12.1).
821    ///
822    /// A standalone ack is *not* reliable — acknowledging an acknowledgement would never
823    /// terminate — and carries no payload.
824    pub fn acknowledge(
825        &mut self,
826        exchange: ExchangeKey,
827        now: Instant,
828        out: &mut [u8],
829    ) -> Result<usize> {
830        let Some(open) = self.exchanges.find_mut(exchange) else {
831            bail!(NoExchange)
832        };
833        let ephemeral = open.ephemeral;
834        let Some(acknowledged) = open.mrp.take_piggyback() else {
835            // Nothing owed: the acknowledgement was already carried by an earlier message.
836            if ephemeral {
837                self.exchanges.close(exchange);
838            }
839            return Ok(0);
840        };
841        let protocol_header = ProtocolHeader {
842            initiator: exchange.role.is_initiator(),
843            acknowledged_counter: Some(acknowledged),
844            reliability: false,
845            exchange_id: exchange.id,
846            // §4.12.7.1: "The Protocol ID SHALL be set to PROTOCOL_ID_SECURE_CHANNEL."
847            //
848            // Not the exchange's protocol, which is the natural thing to write and what this
849            // did: the opcode is Secure Channel's, so sending it under the exchange's protocol
850            // id produces a message that decodes as, say, Interaction Model opcode 0x10 — an
851            // opcode the Interaction Model does not define. The CHIP SDK prints it as
852            // `IM:----` and answers `Invalid message type`, which ends the interaction the
853            // acknowledgement was supposed to keep alive.
854            //
855            // MRP is a property of the *exchange layer*, below the protocol running on it, and
856            // this is where that shows on the wire.
857            protocol: ProtocolId::SECURE_CHANNEL,
858            opcode: crate::sc::opcode::MRP_STANDALONE_ACK,
859        };
860        let counter = self.next_counter(exchange.session, now)?;
861        // A standalone acknowledgement carries no payload, so the body being joined is the
862        // protocol header alone and the scratch never needs to be larger than one.
863        let mut scratch = [0u8; PROTOCOL_HEADER_MAX];
864        let written = self.frame(
865            exchange.session,
866            counter,
867            &protocol_header,
868            &[],
869            &mut scratch,
870            out,
871        )?;
872        // §4.12.5.2.2: "If the Exchange is marked as an ephemeral exchange the Exchange SHALL
873        // be closed." It existed only to carry this acknowledgement, and holding it open is
874        // what would make answering a stranger politely cost a table entry.
875        if ephemeral {
876            self.exchanges.close(exchange);
877        }
878        Ok(written)
879    }
880
881    /// Takes the next message counter for a session (§4.6.1).
882    fn next_counter(&mut self, session: SessionId, now: Instant) -> Result<u32> {
883        if session == SessionId::UNSECURED {
884            self.unsecured_counter.take()
885        } else {
886            self.sessions
887                .find_mut(session)
888                .ok_or(Error::new(ErrorCode::NoSession))?
889                .next_counter(now)
890        }
891    }
892
893    /// Frames, and encrypts when the session is secure.
894    fn frame(
895        &self,
896        session: SessionId,
897        counter: u32,
898        protocol_header: &ProtocolHeader,
899        payload: &[u8],
900        scratch: &mut [u8],
901        out: &mut [u8],
902    ) -> Result<usize> {
903        // §4.8's AEAD needs the protocol header and the payload contiguous before it can
904        // encrypt them, and this is where they are joined. The buffer is the caller's
905        // because its size is the *transport's*: a datagram node needs
906        // [`MAX_UDP_MESSAGE`](crate::config::MAX_UDP_MESSAGE) and nothing more, and a node on
907        // TCP needs [`Config::MAX_TCP_MSG`](crate::Config::MAX_TCP_MSG) — which is the whole
908        // reason §4.15 exists and is far too much to put on the stack of every node that
909        // never opens a connection.
910        let header_len = protocol_header.encode(scratch)?;
911        let end = header_len
912            .checked_add(payload.len())
913            .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
914        let Some(slot) = scratch.get_mut(header_len..end) else {
915            bail!(BufferTooSmall)
916        };
917        slot.copy_from_slice(payload);
918        let Some(body) = scratch.get(..end) else {
919            bail!(BufferTooSmall)
920        };
921
922        if session == SessionId::UNSECURED {
923            // §4.13.2.1: the Ephemeral Initiator Node ID is "enclosed by initiator as Source
924            // Node ID and responder as Destination Node ID". Which field it goes in is decided
925            // by which end of the context this node is, and a message carrying neither is one
926            // the peer cannot associate with any session — the CHIP SDK drops it outright.
927            let (source, destination) = match self.unsecured_peer {
928                Some(peer) if peer.we_initiated => {
929                    (Some(peer.ephemeral_initiator), Destination::None)
930                }
931                Some(peer) => (None, Destination::Node(peer.ephemeral_initiator)),
932                None => (None, Destination::None),
933            };
934            let header = MessageHeader {
935                session_id: SessionId::UNSECURED,
936                message_counter: counter,
937                source,
938                destination,
939                ..MessageHeader::default()
940            };
941            let header_len = header.encode(out)?;
942            let total = header_len
943                .checked_add(body.len())
944                .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
945            let Some(slot) = out.get_mut(header_len..total) else {
946                bail!(BufferTooSmall)
947            };
948            slot.copy_from_slice(body);
949            return Ok(total);
950        }
951
952        let found = self
953            .sessions
954            .find(session)
955            .ok_or(Error::new(ErrorCode::NoSession))?;
956        let header = MessageHeader {
957            session_id: found.peer_session_id,
958            message_counter: counter,
959            // §4.4.1.5: the Source Node ID is elided on a secure unicast session, where the
960            // session itself already says who is speaking.
961            source: None,
962            destination: Destination::None,
963            // §4.9 is the sender's choice on a unicast session; see
964            // [`Messaging::set_privacy`]. A PASE session is never private: it has no
965            // operational identity to correlate, so there would be nothing to hide.
966            privacy: self.privacy && matches!(found.kind, SessionKind::Case),
967            ..MessageHeader::default()
968        };
969        let nonce_source = match found.kind {
970            SessionKind::Pase => NonceSource::Pase,
971            SessionKind::Case => NonceSource::Case(found.local_node_id),
972        };
973        let keys = found.keys.sending(found.role);
974        protect(&header, nonce_source, body, keys, out)
975    }
976
977    /// When [`Messaging::poll`] next needs to be called.
978    ///
979    /// The earlier of a reliability deadline and the next moment an abandoned exchange could
980    /// be reclaimed, so a node that honours this wake-up gets §4.10.5.3's cleanup without
981    /// scheduling anything of its own.
982    #[must_use]
983    pub fn wake_at(&self) -> Option<Instant> {
984        let reap = self.exchanges.reap_deadline(EXCHANGE_IDLE_TIMEOUT);
985        match (self.exchanges.poll_deadline(), reap) {
986            (Some(a), Some(b)) => Some(if a <= b { a } else { b }),
987            (Some(a), None) => Some(a),
988            (None, b) => b,
989        }
990    }
991
992    /// Drives the reliability timers (§4.12.2.1) and reclaims abandoned exchanges (§4.10.5.3).
993    ///
994    /// Returns one action at a time; call until it returns `None`.
995    ///
996    /// Reaping happens here rather than in a method a node has to remember to call, because an
997    /// exchange table reclaimed only on request is one an attacker fills at leisure: every
998    /// unsecured datagram with the **I** flag opens an entry (§4.10.5.2), and `X` of them
999    /// would otherwise deny every later session establishment for the node's whole uptime.
1000    pub fn poll(&mut self, now: Instant, randomness: u32) -> Option<Due> {
1001        self.exchanges.reap(now, EXCHANGE_IDLE_TIMEOUT);
1002        let expired = self
1003            .exchanges
1004            .iter()
1005            .find(|e| e.mrp.poll_deadline().is_some_and(|at| at <= now))
1006            .map(|e| e.key)?;
1007        let open = self.exchanges.find_mut(expired)?;
1008        match open.mrp.on_timeout(now, randomness) {
1009            OnTimeout::Retransmit { counter, .. } => Some(Due::Retransmit {
1010                exchange: expired,
1011                counter,
1012            }),
1013            // §4.12.5.2.2: nothing to piggyback on, so the acknowledgement goes on its own.
1014            OnTimeout::SendStandaloneAck { .. } => Some(Due::Acknowledge { exchange: expired }),
1015            OnTimeout::GiveUp { .. } => {
1016                self.exchanges.close(expired);
1017                Some(Due::Abandoned { exchange: expired })
1018            }
1019            OnTimeout::Nothing => None,
1020        }
1021    }
1022}
1023
1024#[cfg(test)]
1025mod tests {
1026    use super::*;
1027    use crate::config::DefaultConfig;
1028    use crate::exchange::Role;
1029
1030    type Node = Messaging<DefaultConfig, 4, 8>;
1031
1032    fn at(ms: u64) -> Instant {
1033        Instant::from_micros(ms.saturating_mul(1000))
1034    }
1035
1036    const PEER: Peer = Peer::Udp(crate::platform::PeerAddr::new([
1037        0xFE, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1038    ]));
1039
1040    fn keys() -> crate::session::EstablishedKeys {
1041        crate::session::EstablishedKeys::derive(b"shared secret", &[]).expect("derive")
1042    }
1043
1044    fn session_on(id: u16, fabric: u8, now: Instant) -> SecureSession {
1045        let mut s = SecureSession::new(
1046            SessionId(id),
1047            SessionId(id.wrapping_add(100)),
1048            SessionKind::Case,
1049            crate::session::Role::Responder,
1050            keys(),
1051            1,
1052            now,
1053        );
1054        s.fabric_index = crate::msg::FabricIndex(fabric);
1055        s.peer = Some(PEER);
1056        s
1057    }
1058
1059    /// §4.11.1.4: "The CloseSession StatusReport SHALL only be sent encrypted within an
1060    /// exchange associated with a PASE or CASE session." So one that arrives on the *unsecured*
1061    /// session closes nothing — otherwise anybody who can reach the port could end a
1062    /// commissioned node's sessions with a datagram costing them nothing to send.
1063    #[test]
1064    fn an_unsecured_close_session_report_closes_nothing() {
1065        let mut node = Node::new(1, 100, 7);
1066        let mut scratch = [0u8; 512];
1067        let mut wire = [0u8; 512];
1068        node.install_session(session_on(1, 1, at(0)), at(0), 0, &mut scratch, &mut wire)
1069            .expect("install");
1070
1071        // A stranger's unsecured datagram carrying exactly the report a peer would send.
1072        let mut attacker = Node::new(2, 200, 9);
1073        let report = crate::sc::status::StatusReport {
1074            general: crate::sc::status::GeneralCode::Success,
1075            protocol: ProtocolId::SECURE_CHANNEL,
1076            protocol_code: crate::sc::status::SecureChannelCode::CloseSession as u16,
1077            data: &[],
1078        };
1079        let mut body = [0u8; 16];
1080        let len = report.encode(&mut body).expect("encode");
1081        let exchange = attacker
1082            .open(SessionId::UNSECURED, ProtocolId::SECURE_CHANNEL, at(0))
1083            .expect("open");
1084        let (sent, _) = attacker
1085            .send(
1086                exchange,
1087                crate::sc::opcode::STATUS_REPORT,
1088                false,
1089                body.get(..len).expect("body"),
1090                at(0),
1091                0,
1092                &mut scratch,
1093                &mut wire,
1094            )
1095            .expect("send");
1096
1097        let received = node.receive(wire.get_mut(..sent).expect("wire"), PEER, at(1));
1098        assert!(
1099            matches!(received, Ok(Received::Message { .. })),
1100            "an unsecured status report is an ordinary message, got {received:?}"
1101        );
1102        assert!(
1103            node.sessions().find(SessionId(1)).is_some(),
1104            "no unauthenticated datagram may close a session"
1105        );
1106    }
1107
1108    /// §4.16: a group datagram belongs to the group key store, and this layer says so rather
1109    /// than refusing it. Refusing made a node that holds group keys look like a node that
1110    /// cannot receive groupcast at all.
1111    #[test]
1112    fn a_group_datagram_is_handed_back_rather_than_refused() {
1113        let mut node = Node::new(1, 100, 7);
1114        // §4.4.1.2's session type bits: a group message names its Group Session Id and carries
1115        // the session type in the low bits of the security flags.
1116        let mut datagram = [0u8; 32];
1117        datagram[0] = 0b0000_0000; // message flags: no source, no destination
1118        datagram[1..3].copy_from_slice(&0x1234u16.to_le_bytes()); // group session id
1119        datagram[3] = 0b0000_0001; // security flags: session type = group
1120        datagram[4..8].copy_from_slice(&7u32.to_le_bytes()); // message counter
1121
1122        let received = node.receive(&mut datagram, PEER, at(0));
1123        assert!(
1124            matches!(
1125                received,
1126                Ok(Received::Group { session_id, from })
1127                    if session_id == SessionId(0x1234) && from == PEER
1128            ),
1129            "expected a group hand-off, got {received:?}"
1130        );
1131        assert_eq!(
1132            node.exchanges().len(),
1133            0,
1134            "a group message opens nothing: §4.16.2 step 2c sets only the P flag"
1135        );
1136    }
1137
1138    /// §4.11.1.4: "If a Node has either sent or received a CloseSession StatusReport, that
1139    /// Node SHALL remove all state associated with the session." The receiving half is the
1140    /// one a node leaves out, because sending one is a decision and receiving one is not.
1141    #[test]
1142    fn a_close_session_report_from_the_peer_closes_the_session_here_too() {
1143        let mut a = Node::new(1, 100, 7);
1144        let mut b = Node::new(2, 200, 9);
1145        let mut scratch = [0u8; 512];
1146        let mut wire = [0u8; 512];
1147
1148        // The same keys at both ends, with opposite roles, is a session the two share.
1149        let mut left = SecureSession::new(
1150            SessionId(1),
1151            SessionId(2),
1152            SessionKind::Case,
1153            crate::session::Role::Initiator,
1154            keys(),
1155            1,
1156            at(0),
1157        );
1158        left.peer = Some(PEER);
1159        let mut right = SecureSession::new(
1160            SessionId(2),
1161            SessionId(1),
1162            SessionKind::Case,
1163            crate::session::Role::Responder,
1164            keys(),
1165            1,
1166            at(0),
1167        );
1168        right.peer = Some(PEER);
1169        a.install_session(left, at(0), 0, &mut scratch, &mut wire)
1170            .expect("install");
1171        b.install_session(right, at(0), 0, &mut scratch, &mut wire)
1172            .expect("install");
1173        b.open(SessionId(2), ProtocolId::INTERACTION_MODEL, at(0))
1174            .expect("an exchange that the close has to take with it");
1175
1176        // A closes its end, which frames the report §4.11.1.4 owes the peer: a new exchange,
1177        // and no R flag.
1178        let report = crate::sc::status::StatusReport {
1179            general: crate::sc::status::GeneralCode::Success,
1180            protocol: ProtocolId::SECURE_CHANNEL,
1181            protocol_code: crate::sc::status::SecureChannelCode::CloseSession as u16,
1182            data: &[],
1183        };
1184        let mut body = [0u8; 16];
1185        let len = report.encode(&mut body).expect("encode");
1186        let exchange = a
1187            .open(SessionId(1), ProtocolId::SECURE_CHANNEL, at(0))
1188            .expect("open");
1189        let (sent, _) = a
1190            .send(
1191                exchange,
1192                crate::sc::opcode::STATUS_REPORT,
1193                false,
1194                body.get(..len).expect("body"),
1195                at(0),
1196                0,
1197                &mut scratch,
1198                &mut wire,
1199            )
1200            .expect("send");
1201
1202        let received = b.receive(wire.get_mut(..sent).expect("wire"), PEER, at(1));
1203        assert!(
1204            matches!(received, Ok(Received::SessionClosed { session }) if session == SessionId(2)),
1205            "expected the session to be closed, got {received:?}"
1206        );
1207        assert!(b.sessions().find(SessionId(2)).is_none());
1208        assert_eq!(
1209            b.exchanges().len(),
1210            0,
1211            "§4.13.3.1: all state associated with the session"
1212        );
1213    }
1214
1215    /// §4.11.1.1: a full session table evicts the least recently used session rather than
1216    /// refusing the handshake. Refusing it is a node that can be commissioned
1217    /// `Config::SESSIONS` times and never again.
1218    #[test]
1219    fn a_full_session_table_evicts_the_least_recently_used_session() {
1220        // `S` is 4 for this alias, so the fifth session has to displace one.
1221        let mut node = Node::new(1, 100, 7);
1222        let mut scratch = [0u8; 512];
1223        let mut out = [0u8; 512];
1224        for i in 0..4u16 {
1225            let evicted = node
1226                .install_session(
1227                    session_on(i + 1, 1, at(u64::from(i))),
1228                    at(u64::from(i)),
1229                    0,
1230                    &mut scratch,
1231                    &mut out,
1232                )
1233                .expect("install");
1234            assert!(evicted.is_none(), "there was room for session {i}");
1235        }
1236        assert_eq!(node.sessions().len(), 4);
1237
1238        let evicted = node
1239            .install_session(session_on(9, 1, at(10)), at(10), 0, &mut scratch, &mut out)
1240            .expect("install")
1241            .expect("the table was full, so one had to go");
1242
1243        // Step 1: the least recently used, which is the one installed first.
1244        assert_eq!(evicted.session, SessionId(1));
1245        // Step 2a: a datagram for its peer, framed before the session went away.
1246        assert_eq!(evicted.peer, Some(PEER));
1247        assert!(evicted.len > 0, "the CloseSession report was framed");
1248        // Step 2b: and the session itself is gone, with the new one in its place.
1249        assert!(node.sessions().find(SessionId(1)).is_none());
1250        assert!(node.sessions().find(SessionId(9)).is_some());
1251        assert_eq!(node.sessions().len(), 4);
1252    }
1253
1254    /// §4.13.3.1: closing a session removes "all state associated with" it, which includes
1255    /// the exchanges on it. An exchange that outlives its session can never be answered on,
1256    /// and holds a slot in a fixed-capacity table until it times out.
1257    #[test]
1258    fn closing_a_session_closes_its_exchanges() {
1259        let mut node = Node::new(1, 100, 7);
1260        let mut scratch = [0u8; 512];
1261        let mut out = [0u8; 512];
1262        node.install_session(session_on(1, 1, at(0)), at(0), 0, &mut scratch, &mut out)
1263            .expect("install");
1264        node.open(SessionId(1), ProtocolId::INTERACTION_MODEL, at(0))
1265            .expect("open");
1266        node.open(SessionId(1), ProtocolId::INTERACTION_MODEL, at(0))
1267            .expect("open");
1268        assert_eq!(node.exchanges().len(), 2);
1269
1270        assert!(node.close_session(SessionId(1)));
1271        assert_eq!(node.exchanges().len(), 0, "the exchanges went with it");
1272        assert!(node.sessions().find(SessionId(1)).is_none());
1273    }
1274
1275    /// §11.18.6.12: `RemoveFabric` takes the fabric's sessions — and their exchanges — while
1276    /// leaving every other fabric's alone.
1277    #[test]
1278    fn removing_a_fabric_takes_its_sessions_and_their_exchanges() {
1279        let mut node = Node::new(1, 100, 7);
1280        let mut scratch = [0u8; 512];
1281        let mut out = [0u8; 512];
1282        node.install_session(session_on(1, 1, at(0)), at(0), 0, &mut scratch, &mut out)
1283            .expect("install");
1284        node.install_session(session_on(2, 2, at(1)), at(1), 0, &mut scratch, &mut out)
1285            .expect("install");
1286        node.open(SessionId(1), ProtocolId::INTERACTION_MODEL, at(0))
1287            .expect("open");
1288        node.open(SessionId(2), ProtocolId::INTERACTION_MODEL, at(0))
1289            .expect("open");
1290
1291        assert_eq!(node.remove_fabric(crate::msg::FabricIndex(1)), 1);
1292        assert!(node.sessions().find(SessionId(1)).is_none());
1293        assert!(node.sessions().find(SessionId(2)).is_some());
1294        assert_eq!(
1295            node.exchanges().len(),
1296            1,
1297            "only the removed fabric's exchange went"
1298        );
1299    }
1300
1301    /// The unsecured session is what PASE runs over before any key exists.
1302    #[test]
1303    fn an_unsecured_message_round_trips_through_a_new_exchange() {
1304        let mut initiator = Node::new(1, 100, 7);
1305        let mut responder = Node::new(2, 200, 9);
1306
1307        let key = initiator
1308            .open(SessionId::UNSECURED, ProtocolId::SECURE_CHANNEL, at(0))
1309            .expect("open");
1310        let mut wire = [0u8; 512];
1311        let mut scratch = [0u8; 512];
1312        let (len, counter) = initiator
1313            .send(
1314                key,
1315                0x20,
1316                true,
1317                b"pbkdf-param-request",
1318                at(0),
1319                0,
1320                &mut scratch,
1321                &mut wire,
1322            )
1323            .expect("send");
1324
1325        let received = responder
1326            .receive(&mut wire[..len], PEER, at(1))
1327            .expect("receive");
1328        let Received::Message {
1329            exchange,
1330            header,
1331            needs_ack,
1332            payload,
1333        } = received
1334        else {
1335            panic!("expected a message, got {received:?}");
1336        };
1337        assert_eq!(payload, b"pbkdf-param-request");
1338        assert_eq!(header.opcode, 0x20);
1339        assert!(needs_ack, "a reliable message owes an acknowledgement");
1340        // The responder opened its own half of the exchange, with the peer's id.
1341        assert_eq!(exchange.role, Role::Responder);
1342        assert_eq!(exchange.id, key.id);
1343
1344        // ...and the acknowledgement it sends clears the initiator's retransmission.
1345        let mut ack = [0u8; 512];
1346        let ack_len = responder
1347            .acknowledge(exchange, at(1), &mut ack)
1348            .expect("ack");
1349        assert!(ack_len > 0);
1350        assert!(initiator.wake_at().is_some(), "waiting for the ack");
1351        let back = initiator
1352            .receive(&mut ack[..ack_len], PEER, at(2))
1353            .expect("receive ack");
1354        assert!(matches!(back, Received::Acknowledged { .. }));
1355        assert!(
1356            !initiator
1357                .exchanges()
1358                .find(key)
1359                .expect("still open")
1360                .mrp
1361                .is_awaiting_ack(),
1362            "acknowledged, so no retransmission is outstanding"
1363        );
1364        let _ = counter;
1365    }
1366
1367    /// Builds one unsecured datagram from a stranger, with the exchange id and protocol of
1368    /// its choosing — which is everything an off-path attacker controls before any key exists.
1369    fn stranger_datagram(
1370        exchange_id: u16,
1371        protocol: ProtocolId,
1372        reliable: bool,
1373        counter: u32,
1374        out: &mut [u8],
1375    ) -> usize {
1376        let mut sender = Node::new(1, exchange_id, counter);
1377        sender.register(Protocols::SECURE_CHANNEL.with(Protocols::INTERACTION_MODEL));
1378        let key = sender
1379            .open(SessionId::UNSECURED, protocol, at(0))
1380            .expect("open");
1381        let mut scratch = [0u8; 512];
1382        let (len, _) = sender
1383            .send(key, 0x20, reliable, b"x", at(0), 0, &mut scratch, out)
1384            .expect("send");
1385        len
1386    }
1387
1388    /// The exhaustion attack, and the shape CVE-2024-3297 had: every unsecured message with
1389    /// the **I** flag opens an exchange (§4.10.5.2), so a stranger who varies the exchange id
1390    /// fills the table. Without reclamation the node can never open another exchange — which
1391    /// means it can never establish another session, PASE or CASE, for the rest of its uptime.
1392    #[test]
1393    fn a_stranger_cannot_fill_the_exchange_table_for_good() {
1394        let mut node = Node::new(2, 200, 9);
1395        let mut wire = [0u8; 512];
1396
1397        // Eight is this node's whole table.
1398        for id in 0..8u16 {
1399            let len = stranger_datagram(
1400                id,
1401                ProtocolId::SECURE_CHANNEL,
1402                true,
1403                u32::from(id) + 1,
1404                &mut wire,
1405            );
1406            let _ = node.receive(&mut wire[..len], PEER, at(0));
1407        }
1408        assert_eq!(node.exchanges().len(), 8, "the table is full");
1409
1410        // A legitimate peer arrives while the attacker's entries are still fresh, and is
1411        // refused — which is correct, and is why the entries must not be permanent.
1412        let len = stranger_datagram(900, ProtocolId::SECURE_CHANNEL, true, 900, &mut wire);
1413        assert!(node.receive(&mut wire[..len], PEER, at(1)).is_err());
1414
1415        // A minute later nothing has happened on any of them, so they go.
1416        assert!(
1417            node.wake_at().is_some(),
1418            "the node knows it has something to reclaim"
1419        );
1420        node.poll(at(61_000), 0);
1421        assert_eq!(node.exchanges().len(), 0, "every abandoned entry reclaimed");
1422
1423        // ...and the node answers again.
1424        let len = stranger_datagram(901, ProtocolId::SECURE_CHANNEL, true, 901, &mut wire);
1425        assert!(
1426            node.receive(&mut wire[..len], PEER, at(62_000)).is_ok(),
1427            "a node that cannot open an exchange can never establish a session again"
1428        );
1429    }
1430
1431    /// Reclaiming on the timer is not enough on its own: a node whose timers are slow, or
1432    /// which is simply busy, must still not be refusing legitimate peers on behalf of entries
1433    /// that expired long ago.
1434    #[test]
1435    fn a_full_table_reclaims_before_refusing() {
1436        let mut node = Node::new(2, 200, 9);
1437        let mut wire = [0u8; 512];
1438        for id in 0..8u16 {
1439            let len = stranger_datagram(
1440                id,
1441                ProtocolId::SECURE_CHANNEL,
1442                true,
1443                u32::from(id) + 1,
1444                &mut wire,
1445            );
1446            let _ = node.receive(&mut wire[..len], PEER, at(0));
1447        }
1448        assert_eq!(node.exchanges().len(), 8);
1449
1450        // No `poll` in between — the pressure itself is the trigger.
1451        let len = stranger_datagram(900, ProtocolId::SECURE_CHANNEL, true, 900, &mut wire);
1452        assert!(
1453            node.receive(&mut wire[..len], PEER, at(61_000)).is_ok(),
1454            "the entry that would have refused this one had been idle for a minute"
1455        );
1456    }
1457
1458    /// §4.10.5.2 rule 1: "has a registered Protocol ID". An unregistered protocol is not
1459    /// something this node will ever act on, so it must not cost a table entry.
1460    #[test]
1461    fn an_unregistered_protocol_opens_no_exchange() {
1462        let mut node = Node::new(2, 200, 9);
1463        node.register(Protocols::SECURE_CHANNEL);
1464        let mut wire = [0u8; 512];
1465
1466        // The Interaction Model is not registered on this node.
1467        let len = stranger_datagram(5, ProtocolId::INTERACTION_MODEL, false, 5, &mut wire);
1468        assert!(node.receive(&mut wire[..len], PEER, at(0)).is_err());
1469        assert_eq!(node.exchanges().len(), 0, "rule 3: processing SHALL stop");
1470
1471        // Secure Channel is, so that one is answered.
1472        let len = stranger_datagram(6, ProtocolId::SECURE_CHANNEL, false, 6, &mut wire);
1473        assert!(node.receive(&mut wire[..len], PEER, at(0)).is_ok());
1474        assert_eq!(node.exchanges().len(), 1);
1475    }
1476
1477    /// §4.10.5.2 rule 2: an unregistered protocol that *asks* for an acknowledgement still
1478    /// gets one — withholding it costs the sender five retransmissions — but on an ephemeral
1479    /// exchange that §4.12.5.2.2 closes as soon as the acknowledgement is sent.
1480    #[test]
1481    fn an_unregistered_reliable_message_is_acknowledged_on_an_ephemeral_exchange() {
1482        let mut node = Node::new(2, 200, 9);
1483        node.register(Protocols::SECURE_CHANNEL);
1484        let mut wire = [0u8; 512];
1485        let len = stranger_datagram(7, ProtocolId::BDX, true, 7, &mut wire);
1486
1487        let received = node.receive(&mut wire[..len], PEER, at(0)).expect("routed");
1488        let Received::Message { exchange, .. } = received else {
1489            panic!("expected the ephemeral exchange, got {received:?}")
1490        };
1491        assert_eq!(node.exchanges().len(), 1);
1492        assert!(
1493            node.exchanges().find(exchange).is_some_and(|e| e.ephemeral),
1494            "it is ephemeral"
1495        );
1496
1497        let mut ack = [0u8; 512];
1498        assert!(node.acknowledge(exchange, at(0), &mut ack).expect("ack") > 0);
1499        assert_eq!(
1500            node.exchanges().len(),
1501            0,
1502            "§4.12.5.2.2: the ephemeral exchange SHALL be closed once it has acknowledged"
1503        );
1504    }
1505
1506    /// An exchange that is still trying to deliver something is not abandoned, however quiet
1507    /// the peer has been — §4.10.5.3 step 2b.
1508    #[test]
1509    fn an_exchange_with_a_pending_retransmission_is_never_reaped() {
1510        let mut node = Node::new(1, 100, 7);
1511        let key = node
1512            .open(SessionId::UNSECURED, ProtocolId::SECURE_CHANNEL, at(0))
1513            .expect("open");
1514        let mut wire = [0u8; 512];
1515        let mut scratch = [0u8; 512];
1516        let _ = node
1517            .send(key, 0x20, true, b"x", at(0), 0, &mut scratch, &mut wire)
1518            .expect("send");
1519
1520        // Far past the idle timeout, and never acknowledged.
1521        node.exchanges_mut()
1522            .reap(at(600_000), EXCHANGE_IDLE_TIMEOUT);
1523        assert_eq!(
1524            node.exchanges().len(),
1525            1,
1526            "a retransmission still pending keeps the exchange open"
1527        );
1528    }
1529
1530    /// §4.13.2.1's Unsecured Session Context, and the rule that no test of this crate against
1531    /// itself could catch.
1532    ///
1533    /// > Ephemeral Initiator Node ID: Randomly selected for each session by the initiator from
1534    /// > the Operational Node ID range and **enclosed by initiator as Source Node ID and
1535    /// > responder as Destination Node ID.**
1536    ///
1537    /// Both halves have to hold, and a stack that encloses *neither* is self-consistent: two
1538    /// nodes built from it commission each other perfectly. The CHIP SDK drops such a message
1539    /// before it reaches any protocol — "Received malformed unsecure packet with source 0x0
1540    /// destination 0x0" — so the symptom is a device no certified controller can pair with,
1541    /// while every test passes.
1542    #[test]
1543    fn an_unsecured_response_carries_the_initiators_ephemeral_node_id() {
1544        const EPHEMERAL: crate::msg::NodeId = crate::msg::NodeId(0x0102_0304_0506_0708);
1545
1546        let mut initiator = Node::new(1, 100, 7);
1547        initiator
1548            .open_unsecured_as_initiator(EPHEMERAL)
1549            .expect("an operational node id");
1550        let mut responder = Node::new(2, 200, 9);
1551
1552        let key = initiator
1553            .open(SessionId::UNSECURED, ProtocolId::SECURE_CHANNEL, at(0))
1554            .expect("open");
1555        let mut wire = [0u8; 512];
1556        let mut scratch = [0u8; 512];
1557        let (len, _) = initiator
1558            .send(
1559                key,
1560                0x20,
1561                true,
1562                b"request",
1563                at(0),
1564                0,
1565                &mut scratch,
1566                &mut wire,
1567            )
1568            .expect("send");
1569
1570        // The initiator encloses it as the Source Node ID: flag bit 2 of octet 0, then eight
1571        // octets little-endian after the four-octet counter.
1572        assert_eq!(wire[0] & 0x04, 0x04, "S flag set");
1573        assert_eq!(
1574            u64::from_le_bytes(wire[8..16].try_into().expect("eight octets")),
1575            EPHEMERAL.0,
1576            "and it is the ephemeral id"
1577        );
1578
1579        let received = responder
1580            .receive(&mut wire[..len], PEER, at(1))
1581            .expect("receive");
1582        let Received::Message { exchange, .. } = received else {
1583            panic!("expected a message, got {received:?}")
1584        };
1585        assert_eq!(
1586            responder.unsecured_ephemeral_id(),
1587            Some(EPHEMERAL),
1588            "the responder recorded it as the context's ephemeral initiator id"
1589        );
1590
1591        // ...and encloses it as the *Destination* Node ID on the way back.
1592        let mut back = [0u8; 512];
1593        let (len, _) = responder
1594            .send(
1595                exchange,
1596                0x21,
1597                true,
1598                b"response",
1599                at(1),
1600                0,
1601                &mut scratch,
1602                &mut back,
1603            )
1604            .expect("send");
1605        assert_eq!(back[0] & 0x04, 0, "no S flag on the responder's message");
1606        assert_eq!(back[0] & 0x03, 0x01, "DSIZ = 1, a 64-bit Node ID");
1607        assert_eq!(
1608            u64::from_le_bytes(back[8..16].try_into().expect("eight octets")),
1609            EPHEMERAL.0,
1610            "the destination is the initiator's ephemeral id"
1611        );
1612
1613        // The initiator accepts what comes back.
1614        let round = initiator
1615            .receive(&mut back[..len], PEER, at(2))
1616            .expect("the initiator accepts its own ephemeral id as the destination");
1617        assert!(matches!(round, Received::Message { .. }));
1618    }
1619
1620    /// §4.13.2.1 matches a context by Ephemeral Initiator Node ID and creates a new one when
1621    /// none matches. A node that kept the first would answer a second initiator — the same
1622    /// commissioner coming back for CASE after PASE, most of the time — with replies addressed
1623    /// to a peer that has gone, which the CHIP SDK drops before any protocol sees them.
1624    #[test]
1625    fn a_second_initiator_replaces_the_unsecured_context() {
1626        const FIRST: crate::msg::NodeId = crate::msg::NodeId(0x1111_1111_1111_1111);
1627        const SECOND: crate::msg::NodeId = crate::msg::NodeId(0x2222_2222_2222_2222);
1628
1629        let mut responder = Node::new(2, 200, 9);
1630        let mut wire = [0u8; 512];
1631        let mut scratch = [0u8; 512];
1632
1633        for (n, (ephemeral, counter)) in [(FIRST, 1u32), (SECOND, 2u32)].into_iter().enumerate() {
1634            let mut initiator = Node::new(1, 100 + u16::try_from(n).expect("fits"), counter);
1635            initiator
1636                .open_unsecured_as_initiator(ephemeral)
1637                .expect("operational");
1638            let key = initiator
1639                .open(SessionId::UNSECURED, ProtocolId::SECURE_CHANNEL, at(0))
1640                .expect("open");
1641            let (len, _) = initiator
1642                .send(key, 0x20, true, b"x", at(0), 0, &mut scratch, &mut wire)
1643                .expect("send");
1644            let received = responder
1645                .receive(&mut wire[..len], PEER, at(1))
1646                .expect("receive");
1647            let Received::Message { exchange, .. } = received else {
1648                panic!("expected a message")
1649            };
1650            assert_eq!(
1651                responder.unsecured_ephemeral_id(),
1652                Some(ephemeral),
1653                "the newest initiator owns the context"
1654            );
1655
1656            let mut back = [0u8; 512];
1657            let _ = responder
1658                .send(
1659                    exchange,
1660                    0x21,
1661                    true,
1662                    b"y",
1663                    at(1),
1664                    0,
1665                    &mut scratch,
1666                    &mut back,
1667                )
1668                .expect("send");
1669            assert_eq!(
1670                u64::from_le_bytes(back[8..16].try_into().expect("eight octets")),
1671                ephemeral.0,
1672                "and the reply is addressed to it"
1673            );
1674        }
1675    }
1676
1677    /// §4.13.2.1 constrains the ephemeral id to the Operational Node ID range, because it is
1678    /// what the responder will put in a Destination Node ID field.
1679    #[test]
1680    fn an_ephemeral_id_outside_the_operational_range_is_refused() {
1681        let mut node = Node::new(1, 100, 7);
1682        assert!(
1683            node.open_unsecured_as_initiator(crate::msg::NodeId::UNSPECIFIED)
1684                .is_err()
1685        );
1686        assert!(
1687            node.open_unsecured_as_initiator(crate::msg::NodeId(1))
1688                .is_ok()
1689        );
1690    }
1691
1692    /// §4.12.2.2: a duplicate is acknowledged and not delivered.
1693    #[test]
1694    fn a_duplicate_is_acknowledged_and_not_delivered_twice() {
1695        let mut initiator = Node::new(1, 100, 7);
1696        let mut responder = Node::new(2, 200, 9);
1697        let key = initiator
1698            .open(SessionId::UNSECURED, ProtocolId::SECURE_CHANNEL, at(0))
1699            .expect("open");
1700
1701        let mut wire = [0u8; 512];
1702        let mut scratch = [0u8; 512];
1703        let (len, _) = initiator
1704            .send(key, 0x20, true, b"once", at(0), 0, &mut scratch, &mut wire)
1705            .expect("send");
1706        let copy = wire;
1707
1708        let first = responder
1709            .receive(&mut wire[..len], PEER, at(1))
1710            .expect("first");
1711        assert!(matches!(first, Received::Message { .. }));
1712
1713        let mut again = copy;
1714        let second = responder
1715            .receive(&mut again[..len], PEER, at(2))
1716            .expect("second");
1717        match second {
1718            Received::Duplicate { needs_ack, .. } => {
1719                assert!(needs_ack, "still acknowledged — the sender's ack was lost");
1720            }
1721            other => panic!("a repeat must not reach the application: {other:?}"),
1722        }
1723    }
1724
1725    /// A message for a session this node does not have is refused, not guessed at.
1726    #[test]
1727    fn a_message_for_an_unknown_session_is_refused() {
1728        let mut node = Node::new(1, 100, 7);
1729        let mut wire = [0u8; 64];
1730        // Flags: version 0, no source/destination. Session id 0x1234, unicast.
1731        wire[0] = 0x00;
1732        wire[1] = 0x34;
1733        wire[2] = 0x12;
1734        wire[3] = 0x00;
1735        let err = node
1736            .receive(&mut wire, PEER, at(0))
1737            .expect_err("no session");
1738        assert_eq!(err.code(), ErrorCode::NoSession);
1739    }
1740
1741    /// A response to an exchange that was never opened is refused (§4.4.3.1).
1742    #[test]
1743    fn a_message_from_a_responder_cannot_open_an_exchange() {
1744        let mut initiator = Node::new(1, 100, 7);
1745        let mut responder = Node::new(2, 200, 9);
1746        let key = initiator
1747            .open(SessionId::UNSECURED, ProtocolId::SECURE_CHANNEL, at(0))
1748            .expect("open");
1749        let mut wire = [0u8; 512];
1750        let mut scratch = [0u8; 512];
1751        let (len, _) = initiator
1752            .send(
1753                key,
1754                0x20,
1755                false,
1756                b"hello",
1757                at(0),
1758                0,
1759                &mut scratch,
1760                &mut wire,
1761            )
1762            .expect("send");
1763        // Clear the I flag in the protocol header: now it claims to be a *response*.
1764        let header_len = MessageHeader::default().encoded_len();
1765        wire[header_len] &= !0x01;
1766
1767        let err = responder
1768            .receive(&mut wire[..len], PEER, at(1))
1769            .expect_err("a response answers a question nobody asked");
1770        assert_eq!(err.code(), ErrorCode::NoExchange);
1771    }
1772
1773    /// The retransmission timer fires, and names the counter to resend (§4.12.2.1).
1774    #[test]
1775    fn an_unacknowledged_message_is_retransmitted_with_its_own_counter() {
1776        let mut initiator = Node::new(1, 100, 7);
1777        let key = initiator
1778            .open(SessionId::UNSECURED, ProtocolId::SECURE_CHANNEL, at(0))
1779            .expect("open");
1780        let mut wire = [0u8; 512];
1781        let mut scratch = [0u8; 512];
1782        let (_, counter) = initiator
1783            .send(key, 0x20, true, b"lost", at(0), 0, &mut scratch, &mut wire)
1784            .expect("send");
1785
1786        let deadline = initiator.wake_at().expect("a reliable send arms a timer");
1787        match initiator.poll(deadline, 0) {
1788            Some(Due::Retransmit {
1789                exchange,
1790                counter: again,
1791            }) => {
1792                assert_eq!(exchange, key);
1793                assert_eq!(
1794                    again, counter,
1795                    "the same counter: a new one would be a new message and a reused nonce"
1796                );
1797            }
1798            other => panic!("expected a retransmission, got {other:?}"),
1799        }
1800    }
1801}