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::{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)]
56pub enum Received<'a> {
57    /// A protocol message for the layer above.
58    Message {
59        /// The exchange it belongs to.
60        exchange: ExchangeKey,
61        /// The protocol header it carried.
62        header: ProtocolHeader,
63        /// Whether an acknowledgement is owed, which [`Messaging::acknowledge`] sends.
64        needs_ack: bool,
65        /// The application payload, decrypted in place.
66        payload: &'a [u8],
67    },
68    /// An authenticated message this node has already seen (§4.12.2.2).
69    ///
70    /// Not delivered upward. Still acknowledged, because the sender's retransmission means
71    /// its last acknowledgement was lost, not that its message was.
72    Duplicate {
73        /// The exchange it belongs to.
74        exchange: ExchangeKey,
75        /// Whether an acknowledgement is owed.
76        needs_ack: bool,
77    },
78    /// A standalone acknowledgement, consumed entirely by the reliability layer.
79    Acknowledged {
80        /// The exchange it acknowledged.
81        exchange: ExchangeKey,
82    },
83}
84
85/// What a timer expiry asks the caller to do.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum Due {
88    /// Retransmit the message with this counter on this exchange (§4.12.2.1).
89    ///
90    /// "Logical retransmission is of a given message as identified by its message counter",
91    /// so the caller resends the *same bytes*, not a re-encoding: a new counter would be a
92    /// new message and would reuse a nonce.
93    Retransmit {
94        /// Which exchange.
95        exchange: ExchangeKey,
96        /// The counter of the message to resend.
97        counter: u32,
98    },
99    /// An acknowledgement has waited long enough for a message to ride on (§4.12.5.2.2).
100    ///
101    /// [`Messaging::acknowledge`] writes it.
102    Acknowledge {
103        /// Which exchange owes it.
104        exchange: ExchangeKey,
105    },
106    /// `MRP_MAX_TRANSMISSIONS` passed with no acknowledgement; the exchange is closed.
107    Abandoned {
108        /// Which exchange was given up on.
109        exchange: ExchangeKey,
110    },
111}
112
113/// Which protocols the upper layer will accept (§4.10.3.1).
114///
115/// "The Interaction Model layer indicates to the Exchange Layer which Protocols it will accept.
116/// Any message for a Protocol ID that is not registered with the Exchange Layer SHALL be
117/// dropped."
118///
119/// This is not bookkeeping. §4.10.5.2 opens an exchange for any unsolicited message with the
120/// **I** flag, and on the unsecured session that is any datagram at all — so the set of
121/// protocols a node answers is also the set an attacker can make it allocate for. A node that
122/// registers only what it serves refuses the rest before the exchange table is touched.
123#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
124pub struct Protocols(u8);
125
126impl Protocols {
127    const fn bit(protocol: ProtocolId) -> Option<u8> {
128        if protocol.vendor.0 != crate::msg::VendorId::COMMON.0 {
129            return None;
130        }
131        match protocol.id {
132            0x0000..=0x0004 => Some(1u8 << protocol.id),
133            _ => None,
134        }
135    }
136
137    /// Nothing registered — every unsolicited message is dropped.
138    pub const NONE: Self = Self(0);
139
140    /// Secure Channel (§4.11). Every node needs it: it is how sessions are established.
141    pub const SECURE_CHANNEL: Self = Self(1 << 0);
142    /// The Interaction Model (ch. 8) — what a node that serves clusters registers.
143    pub const INTERACTION_MODEL: Self = Self(1 << 1);
144    /// BDX (§11.22), for a node that transfers files.
145    pub const BDX: Self = Self(1 << 2);
146    /// User Directed Commissioning (§5.3).
147    pub const USER_DIRECTED_COMMISSIONING: Self = Self(1 << 3);
148    /// The range reserved for testing.
149    pub const FOR_TESTING: Self = Self(1 << 4);
150
151    /// What an ordinary device registers: Secure Channel and the Interaction Model.
152    pub const DEVICE: Self = Self(Self::SECURE_CHANNEL.0 | Self::INTERACTION_MODEL.0);
153
154    /// Both of these, registered.
155    #[must_use]
156    pub const fn with(self, other: Self) -> Self {
157        Self(self.0 | other.0)
158    }
159
160    /// Whether `protocol` is registered.
161    ///
162    /// A vendor-specific protocol id is never registered: §4.10.3.1's registration is by
163    /// identity, and this node serves none.
164    #[must_use]
165    pub const fn contains(self, protocol: ProtocolId) -> bool {
166        match Self::bit(protocol) {
167            Some(bit) => self.0 & bit != 0,
168            None => false,
169        }
170    }
171}
172
173/// §4.13.2.1's Unsecured Session Context, reduced to what framing needs.
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175struct UnsecuredPeer {
176    /// The Ephemeral Initiator Node ID, whichever end chose it.
177    ephemeral_initiator: crate::msg::NodeId,
178    /// Whether *this* node is the initiator, which decides which header field carries it.
179    we_initiated: bool,
180}
181
182/// A node's message processing: sessions, exchanges, and the framing between them.
183///
184/// `S` is [`Config::SESSIONS`] and `X` is `SESSIONS * EXCHANGES_PER_SESSION`.
185#[derive(Debug)]
186pub struct Messaging<C: Config, const S: usize, const X: usize> {
187    sessions: SessionTable<C, S>,
188    exchanges: ExchangeTable<C, X>,
189    /// The counter for messages sent on the unsecured session (§4.6.1.2).
190    unsecured_counter: MessageCounter,
191    /// Duplicate detection for the unsecured session.
192    ///
193    /// §4.6.5 applies to unencrypted messages too, and this is the window that makes a PASE
194    /// handshake replay-resistant before any key exists.
195    unsecured_window: CounterWindow,
196    /// §4.13.2.1's Unsecured Session Context: the **Ephemeral Initiator Node ID**, and which
197    /// end of it this node is.
198    ///
199    /// "Randomly selected for each session by the initiator from the Operational Node ID range
200    /// and enclosed by initiator as Source Node ID and responder as Destination Node ID."
201    ///
202    /// One context, not a table. §4.13.2.1 allows several, keyed by ephemeral id, but a device
203    /// answers one session establishment at a time — which
204    /// [`PaseAdmission`](crate::commissioning::PaseAdmission) now enforces — and a controller
205    /// commissions one device at a time.
206    unsecured_peer: Option<UnsecuredPeer>,
207    /// Whether to apply §4.9's privacy processing to outgoing secure unicast messages.
208    privacy: bool,
209    /// §4.10.3.1's registered protocols.
210    protocols: Protocols,
211}
212
213impl<C: Config, const S: usize, const X: usize> Messaging<C, S, X> {
214    /// A node with no sessions and no exchanges.
215    ///
216    /// `first_session_id`, `first_exchange_id` and `initial_counter` should all come from
217    /// [`Rng`](crate::platform::Rng). §4.6.1.1 requires the counter to start at random: one
218    /// that always starts at zero leaks how many times a device has rebooted and makes nonce
219    /// reuse across a factory reset far too easy. A full-width random number is what to pass —
220    /// [`MessageCounter::new`](crate::msg::MessageCounter::new) narrows it to the twenty-eight
221    /// bits §4.6.1.1 allows, so the caller does not have to know that it must.
222    #[must_use]
223    pub fn new(first_session_id: u16, first_exchange_id: u16, initial_counter: u32) -> Self {
224        Self {
225            sessions: SessionTable::new(first_session_id),
226            exchanges: ExchangeTable::new(first_exchange_id),
227            unsecured_counter: MessageCounter::new(initial_counter),
228            unsecured_window: CounterWindow::new(CounterKind::Rollover),
229            unsecured_peer: None,
230            privacy: false,
231            protocols: Protocols::DEVICE,
232        }
233    }
234
235    /// Registers the protocols this node's upper layer will accept (§4.10.3.1).
236    ///
237    /// Defaults to [`Protocols::DEVICE`] — Secure Channel and the Interaction Model — which is
238    /// what a node that serves clusters needs. A node that also transfers files registers
239    /// [`Protocols::BDX`] on top; one that does neither registers less.
240    pub const fn register(&mut self, protocols: Protocols) {
241        self.protocols = protocols;
242    }
243
244    /// Which protocols are registered.
245    #[must_use]
246    pub const fn protocols(&self) -> Protocols {
247        self.protocols
248    }
249
250    /// Applies §4.9's privacy processing to outgoing secure unicast messages.
251    ///
252    /// Off by default, and deliberately. The **P** flag is only *required* on group messages
253    /// (§4.16.4, §4.18): on a secure unicast session it is the sender's choice, and what it
254    /// buys is hiding the message counter from a passive observer on the link — the counter
255    /// is already authenticated, and anyone with the key can read it either way. What it
256    /// costs is depending on every peer having exercised its deobfuscation path, which is
257    /// not a bet worth making by default for a property this small.
258    ///
259    /// Receiving a private message never needs this: the flag is in the message, and
260    /// [`Messaging::receive`] honours it whatever this is set to.
261    pub const fn set_privacy(&mut self, privacy: bool) {
262        self.privacy = privacy;
263    }
264
265    /// Opens §4.13.2.1's Unsecured Session Context as the **initiator**.
266    ///
267    /// `ephemeral` is the Ephemeral Initiator Node ID this node encloses as the Source Node ID
268    /// of every unsecured message it sends, and which the responder will echo back as the
269    /// Destination Node ID. §4.13.2.1: "Initiators SHALL select a new random ephemeral node ID
270    /// for each unsecured session", from the Operational Node ID range — so it comes from
271    /// [`Rng`](crate::platform::Rng) and is *not* the node's operational identity. A node that
272    /// reused one identity across sessions would let a passive observer link them.
273    ///
274    /// # Errors
275    ///
276    /// [`ErrorCode::InvalidArgument`] unless `ephemeral` is in the Operational Node ID range.
277    pub fn open_unsecured_as_initiator(&mut self, ephemeral: crate::msg::NodeId) -> Result<()> {
278        if !ephemeral.is_operational() {
279            bail!(InvalidArgument)
280        }
281        self.unsecured_peer = Some(UnsecuredPeer {
282            ephemeral_initiator: ephemeral,
283            we_initiated: true,
284        });
285        Ok(())
286    }
287
288    /// Forgets the Unsecured Session Context, so the next handshake starts a new one.
289    pub const fn close_unsecured(&mut self) {
290        self.unsecured_peer = None;
291    }
292
293    /// The Ephemeral Initiator Node ID of the current Unsecured Session Context, if there is one.
294    #[must_use]
295    pub const fn unsecured_ephemeral_id(&self) -> Option<crate::msg::NodeId> {
296        match self.unsecured_peer {
297            Some(peer) => Some(peer.ephemeral_initiator),
298            None => None,
299        }
300    }
301
302    /// The session table.
303    pub const fn sessions(&self) -> &SessionTable<C, S> {
304        &self.sessions
305    }
306
307    /// The session table, mutably — how a completed PASE or CASE installs its keys.
308    pub const fn sessions_mut(&mut self) -> &mut SessionTable<C, S> {
309        &mut self.sessions
310    }
311
312    /// The exchange table.
313    pub const fn exchanges(&self) -> &ExchangeTable<C, X> {
314        &self.exchanges
315    }
316
317    /// The exchange table, mutably.
318    pub const fn exchanges_mut(&mut self) -> &mut ExchangeTable<C, X> {
319        &mut self.exchanges
320    }
321
322    /// Opens an exchange this node initiates, to a peer it has not named yet.
323    ///
324    /// The peer is learned from the first message that comes back. Prefer
325    /// [`Messaging::open_to`] where it is already known: until it is, this node assumes UDP
326    /// and runs MRP, which is right for UDP and one wasted round trip on BTP.
327    pub fn open(
328        &mut self,
329        session: SessionId,
330        protocol: ProtocolId,
331        now: Instant,
332    ) -> Result<ExchangeKey> {
333        let params = self.mrp_params(session);
334        // Where the peer last was, which is the only answer available and the right one: a
335        // session exists because that peer authenticated itself from there. Opening with no
336        // peer produces an exchange that cannot send — [`Stack::send`] builds the message and
337        // [`Stack::peer`] then has no address to give the caller, so the message is built,
338        // counted, and dropped, with no error anywhere. Use [`Stack::open_to`] to name a
339        // different address, for a peer just rediscovered at a new one.
340        let peer = self.sessions.find(session).and_then(|s| s.peer);
341        self.exchanges
342            .open_initiator(session, protocol, params, peer, now)
343    }
344
345    /// Opens an exchange to a peer this node has already found.
346    ///
347    /// Naming the transport is what lets §4.12.4 be honoured: a BLE peer's exchange never
348    /// sets the **R** flag, because BTP has already delivered the message or closed the
349    /// session trying.
350    pub fn open_to(
351        &mut self,
352        session: SessionId,
353        protocol: ProtocolId,
354        peer: Peer,
355        now: Instant,
356    ) -> Result<ExchangeKey> {
357        let params = self.mrp_params(session);
358        self.exchanges
359            .open_initiator(session, protocol, params, Some(peer), now)
360    }
361
362    /// Where an exchange's peer is, once it is known.
363    #[must_use]
364    pub fn peer(&self, exchange: ExchangeKey) -> Option<Peer> {
365        self.exchanges.find(exchange).and_then(|e| e.peer)
366    }
367
368    fn mrp_params(&self, session: SessionId) -> MrpParams {
369        self.sessions
370            .find(session)
371            .map_or_else(MrpParams::default, |s| s.mrp)
372    }
373
374    /// Closes an exchange.
375    pub fn close(&mut self, exchange: ExchangeKey) -> bool {
376        self.exchanges.close(exchange)
377    }
378
379    /// Processes one arriving datagram, in place (§4.7.2).
380    ///
381    /// `buf` is decrypted in place, so the returned payload borrows it. On any failure the
382    /// contents of `buf` are unspecified — §3.6.2 says a failed tag check leaves the payload
383    /// undefined — and nothing in this node's state has moved.
384    pub fn receive<'b>(
385        &mut self,
386        buf: &'b mut [u8],
387        from: Peer,
388        now: Instant,
389    ) -> Result<Received<'b>> {
390        let head = preview(buf)?;
391        if matches!(head.session_type, SessionType::Group) {
392            // Group messages are keyed by an operational group key rather than by a session,
393            // and this node has no group key store yet.
394            bail!(Unsupported)
395        }
396
397        let (header, range) = if head.session_id == SessionId::UNSECURED {
398            let (header, rest) = MessageHeader::decode(buf)?;
399            if !header.is_unsecured() {
400                bail!(MessageReserved)
401            }
402            let start = buf.len().saturating_sub(rest.len());
403            (header, start..buf.len())
404        } else {
405            let session = self
406                .sessions
407                .find(head.session_id)
408                .ok_or(Error::new(ErrorCode::NoSession))?;
409            // §4.8.1.1's nonce depends on how the session was established, and getting it
410            // wrong fails the tag rather than silently mis-decrypting — but naming it here
411            // keeps the two readings from ever being confused.
412            let nonce_source = match session.kind {
413                SessionKind::Pase => NonceSource::Pase,
414                SessionKind::Case => NonceSource::Case(session.peer_node_id),
415            };
416            let keys = session.keys.receiving(session.role).clone();
417            unprotect(buf, &keys, nonce_source)?
418        };
419
420        // Authenticated. Only now may any counter move.
421        let verdict = if header.is_unsecured() {
422            self.unsecured_window.accept(header.message_counter)
423        } else {
424            let session = self
425                .sessions
426                .find_mut(head.session_id)
427                .ok_or(Error::new(ErrorCode::NoSession))?;
428            // Authenticated, so it is the peer and this is where it is. A node that opens an
429            // exchange of its own — §8.5.3's subscription reports above all — has no other way
430            // to learn the address, and an exchange with no peer sends nothing.
431            session.peer = Some(from);
432            session.accept_counter(header.message_counter, now)
433        };
434
435        let Some(payload) = buf.get(range) else {
436            bail!(MessageTruncated)
437        };
438        let (protocol_header, body) = ProtocolHeader::decode(payload)?;
439
440        // §4.13.2.1's context matching: "Else if the message carries a Source Node ID … Set
441        // Session Role to responder … Record the incoming message's Source Node ID as Ephemeral
442        // Initiator Node ID." Recorded here, before the exchange is routed, so that the very
443        // first reply carries it back as the Destination Node ID.
444        if header.is_unsecured()
445            && let Some(source) = header.source
446            && self
447                .unsecured_peer
448                .is_none_or(|peer| peer.ephemeral_initiator != source)
449        {
450            // §4.13.2.1 matches a context by Ephemeral Initiator Node ID and creates a *new*
451            // one when no context matches. A different id is a different session — a second
452            // commissioner, or the same one returning for CASE after PASE — so the context is
453            // replaced rather than kept. Keeping the first would address every reply to a peer
454            // that has gone, which the CHIP SDK drops as belonging to no session of its own.
455            //
456            // One context at a time is the simplification here; the specification allows
457            // several. What makes it safe is that the *contents* are two header fields and a
458            // replay window, and admitting a second handshake at all is refused a layer up by
459            // `PaseAdmission`.
460            self.unsecured_peer = Some(UnsecuredPeer {
461                ephemeral_initiator: source,
462                we_initiated: false,
463            });
464        }
465
466        let duplicate = matches!(verdict, Verdict::Duplicate);
467        let key = self.route(header.session_id, &protocol_header, duplicate, now)?;
468        let Some(exchange) = self.exchanges.find_mut(key) else {
469            bail!(NoExchange)
470        };
471        exchange.touch(now);
472        // Where the reply goes, and — §4.12.4 — whether MRP runs on this exchange. A peer
473        // that moved (a Thread node changing address, say) is followed here.
474        exchange.peer = Some(from);
475        exchange.mrp.note_peer_activity(now);
476
477        // §4.12.1: an acknowledgement may ride on any message, so it is taken before the
478        // message's own kind is considered.
479        if let Some(acknowledged) = protocol_header.acknowledged_counter {
480            exchange.mrp.on_ack(acknowledged, now);
481        }
482
483        if protocol_header.reliability {
484            exchange
485                .mrp
486                .on_reliable_received(header.message_counter, now, duplicate);
487        }
488        let needs_ack = protocol_header.reliability;
489
490        if duplicate {
491            return Ok(Received::Duplicate {
492                exchange: key,
493                needs_ack,
494            });
495        }
496        if protocol_header.protocol == ProtocolId::SECURE_CHANNEL
497            && protocol_header.opcode == crate::sc::opcode::MRP_STANDALONE_ACK
498        {
499            // A standalone acknowledgement carries nothing above the reliability layer.
500            return Ok(Received::Acknowledged { exchange: key });
501        }
502
503        Ok(Received::Message {
504            exchange: key,
505            header: protocol_header,
506            needs_ack,
507            payload: body,
508        })
509    }
510
511    /// Finds or opens the exchange a message belongs to (§4.10.5.2).
512    ///
513    /// The three rules are in order, and the order is what bounds the table:
514    ///
515    /// 1. "If the unsolicited message is not marked as having a duplicate message counter,
516    ///    **has a registered Protocol ID**, and the I Flag is set: create a new exchange."
517    /// 2. "Otherwise, if the message has the R Flag set: create an *ephemeral* exchange … and
518    ///    send an immediate standalone acknowledgement. The message SHALL NOT be forwarded to
519    ///    the upper layer."
520    /// 3. "Otherwise, processing of the message SHALL stop."
521    ///
522    /// Rule 3 is the one that matters most and is the easiest to leave out: a message this
523    /// node will never act on, and which is not even asking for an acknowledgement, must not
524    /// cost a table entry. Without it every datagram that reaches the port allocates.
525    fn route(
526        &mut self,
527        session: SessionId,
528        header: &ProtocolHeader,
529        duplicate: bool,
530        now: Instant,
531    ) -> Result<ExchangeKey> {
532        if let Some(exchange) =
533            self.exchanges
534                .find_for_message(session, header.exchange_id, header.initiator)
535        {
536            return Ok(exchange.key);
537        }
538        // Only a message *from* an initiator may open an exchange. One claiming to be from a
539        // responder with no exchange to respond to is answering a question nobody asked.
540        if !header.initiator {
541            bail!(NoExchange)
542        }
543        let params = self.mrp_params(session);
544        if !duplicate && self.protocols.contains(header.protocol) {
545            return self.exchanges.open_responder(
546                session,
547                header.exchange_id,
548                header.protocol,
549                params,
550                now,
551            );
552        }
553        if header.reliability {
554            // Rule 2. The sender is owed an acknowledgement even though nothing here will
555            // read its message — withholding it costs five retransmissions — but the entry
556            // that carries it is closed as soon as it has been sent.
557            return self.exchanges.open_ephemeral(
558                session,
559                header.exchange_id,
560                header.protocol,
561                params,
562                now,
563            );
564        }
565        // Rule 3.
566        bail!(NoExchange)
567    }
568
569    /// Builds an outgoing message on an exchange (§4.7.1).
570    ///
571    /// `reliable` sets the MRP **R** flag; a reliable message is remembered for
572    /// retransmission until it is acknowledged, and [`Messaging::poll`] is what resends it.
573    /// `randomness` is the jitter draw of §4.12.2.1 and should come from
574    /// [`Rng`](crate::platform::Rng).
575    ///
576    /// Returns how many octets of `out` the datagram occupies, and the counter it was sent
577    /// with — which is what a retransmission is identified by.
578    #[expect(
579        clippy::too_many_arguments,
580        reason = "every one is a distinct fact about the message; bundling them into a \
581                  struct would only move the same list one line up"
582    )]
583    pub fn send(
584        &mut self,
585        exchange: ExchangeKey,
586        opcode: u8,
587        reliable: bool,
588        payload: &[u8],
589        now: Instant,
590        randomness: u32,
591        scratch: &mut [u8],
592        out: &mut [u8],
593    ) -> Result<(usize, u32)> {
594        let Some(open) = self.exchanges.find(exchange) else {
595            bail!(NoExchange)
596        };
597        let protocol = open.protocol;
598        // §4.12.4: "Reliable messages sent over TCP, PAFTP, or BTP SHALL utilize the
599        // underlying reliability mechanisms of those transports and SHOULD NOT set the R
600        // Flag." Running MRP on top of BTP would retransmit a message BTP has already
601        // guaranteed, and BTP would carry the duplicate faithfully.
602        let reliable = reliable && !open.is_transport_reliable();
603        let piggyback = self
604            .exchanges
605            .find_mut(exchange)
606            .and_then(|e| e.mrp.take_piggyback());
607
608        let protocol_header = ProtocolHeader {
609            initiator: exchange.role.is_initiator(),
610            acknowledged_counter: piggyback,
611            reliability: reliable,
612            exchange_id: exchange.id,
613            protocol,
614            opcode,
615        };
616
617        let counter = self.next_counter(exchange.session, now)?;
618        let written = self.frame(
619            exchange.session,
620            counter,
621            &protocol_header,
622            payload,
623            scratch,
624            out,
625        )?;
626
627        if reliable && let Some(open) = self.exchanges.find_mut(exchange) {
628            open.mrp.on_send(counter, now, randomness)?;
629        }
630        Ok((written, counter))
631    }
632
633    /// Sends the standalone acknowledgement a [`Received`] said was owed (§4.12.1).
634    ///
635    /// A standalone ack is *not* reliable — acknowledging an acknowledgement would never
636    /// terminate — and carries no payload.
637    pub fn acknowledge(
638        &mut self,
639        exchange: ExchangeKey,
640        now: Instant,
641        out: &mut [u8],
642    ) -> Result<usize> {
643        let Some(open) = self.exchanges.find_mut(exchange) else {
644            bail!(NoExchange)
645        };
646        let ephemeral = open.ephemeral;
647        let Some(acknowledged) = open.mrp.take_piggyback() else {
648            // Nothing owed: the acknowledgement was already carried by an earlier message.
649            if ephemeral {
650                self.exchanges.close(exchange);
651            }
652            return Ok(0);
653        };
654        let protocol_header = ProtocolHeader {
655            initiator: exchange.role.is_initiator(),
656            acknowledged_counter: Some(acknowledged),
657            reliability: false,
658            exchange_id: exchange.id,
659            // §4.12.7.1: "The Protocol ID SHALL be set to PROTOCOL_ID_SECURE_CHANNEL."
660            //
661            // Not the exchange's protocol, which is the natural thing to write and what this
662            // did: the opcode is Secure Channel's, so sending it under the exchange's protocol
663            // id produces a message that decodes as, say, Interaction Model opcode 0x10 — an
664            // opcode the Interaction Model does not define. The CHIP SDK prints it as
665            // `IM:----` and answers `Invalid message type`, which ends the interaction the
666            // acknowledgement was supposed to keep alive.
667            //
668            // MRP is a property of the *exchange layer*, below the protocol running on it, and
669            // this is where that shows on the wire.
670            protocol: ProtocolId::SECURE_CHANNEL,
671            opcode: crate::sc::opcode::MRP_STANDALONE_ACK,
672        };
673        let counter = self.next_counter(exchange.session, now)?;
674        // A standalone acknowledgement carries no payload, so the body being joined is the
675        // protocol header alone and the scratch never needs to be larger than one.
676        let mut scratch = [0u8; PROTOCOL_HEADER_MAX];
677        let written = self.frame(
678            exchange.session,
679            counter,
680            &protocol_header,
681            &[],
682            &mut scratch,
683            out,
684        )?;
685        // §4.12.5.2.2: "If the Exchange is marked as an ephemeral exchange the Exchange SHALL
686        // be closed." It existed only to carry this acknowledgement, and holding it open is
687        // what would make answering a stranger politely cost a table entry.
688        if ephemeral {
689            self.exchanges.close(exchange);
690        }
691        Ok(written)
692    }
693
694    /// Takes the next message counter for a session (§4.6.1).
695    fn next_counter(&mut self, session: SessionId, now: Instant) -> Result<u32> {
696        if session == SessionId::UNSECURED {
697            self.unsecured_counter.take()
698        } else {
699            self.sessions
700                .find_mut(session)
701                .ok_or(Error::new(ErrorCode::NoSession))?
702                .next_counter(now)
703        }
704    }
705
706    /// Frames, and encrypts when the session is secure.
707    fn frame(
708        &self,
709        session: SessionId,
710        counter: u32,
711        protocol_header: &ProtocolHeader,
712        payload: &[u8],
713        scratch: &mut [u8],
714        out: &mut [u8],
715    ) -> Result<usize> {
716        // §4.8's AEAD needs the protocol header and the payload contiguous before it can
717        // encrypt them, and this is where they are joined. The buffer is the caller's
718        // because its size is the *transport's*: a datagram node needs
719        // [`MAX_UDP_MESSAGE`](crate::config::MAX_UDP_MESSAGE) and nothing more, and a node on
720        // TCP needs [`Config::MAX_TCP_MSG`](crate::Config::MAX_TCP_MSG) — which is the whole
721        // reason §4.15 exists and is far too much to put on the stack of every node that
722        // never opens a connection.
723        let header_len = protocol_header.encode(scratch)?;
724        let end = header_len
725            .checked_add(payload.len())
726            .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
727        let Some(slot) = scratch.get_mut(header_len..end) else {
728            bail!(BufferTooSmall)
729        };
730        slot.copy_from_slice(payload);
731        let Some(body) = scratch.get(..end) else {
732            bail!(BufferTooSmall)
733        };
734
735        if session == SessionId::UNSECURED {
736            // §4.13.2.1: the Ephemeral Initiator Node ID is "enclosed by initiator as Source
737            // Node ID and responder as Destination Node ID". Which field it goes in is decided
738            // by which end of the context this node is, and a message carrying neither is one
739            // the peer cannot associate with any session — the CHIP SDK drops it outright.
740            let (source, destination) = match self.unsecured_peer {
741                Some(peer) if peer.we_initiated => {
742                    (Some(peer.ephemeral_initiator), Destination::None)
743                }
744                Some(peer) => (None, Destination::Node(peer.ephemeral_initiator)),
745                None => (None, Destination::None),
746            };
747            let header = MessageHeader {
748                session_id: SessionId::UNSECURED,
749                message_counter: counter,
750                source,
751                destination,
752                ..MessageHeader::default()
753            };
754            let header_len = header.encode(out)?;
755            let total = header_len
756                .checked_add(body.len())
757                .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
758            let Some(slot) = out.get_mut(header_len..total) else {
759                bail!(BufferTooSmall)
760            };
761            slot.copy_from_slice(body);
762            return Ok(total);
763        }
764
765        let found = self
766            .sessions
767            .find(session)
768            .ok_or(Error::new(ErrorCode::NoSession))?;
769        let header = MessageHeader {
770            session_id: found.peer_session_id,
771            message_counter: counter,
772            // §4.4.1.5: the Source Node ID is elided on a secure unicast session, where the
773            // session itself already says who is speaking.
774            source: None,
775            destination: Destination::None,
776            // §4.9 is the sender's choice on a unicast session; see
777            // [`Messaging::set_privacy`]. A PASE session is never private: it has no
778            // operational identity to correlate, so there would be nothing to hide.
779            privacy: self.privacy && matches!(found.kind, SessionKind::Case),
780            ..MessageHeader::default()
781        };
782        let nonce_source = match found.kind {
783            SessionKind::Pase => NonceSource::Pase,
784            SessionKind::Case => NonceSource::Case(found.local_node_id),
785        };
786        let keys = found.keys.sending(found.role);
787        protect(&header, nonce_source, body, keys, out)
788    }
789
790    /// When [`Messaging::poll`] next needs to be called.
791    ///
792    /// The earlier of a reliability deadline and the next moment an abandoned exchange could
793    /// be reclaimed, so a node that honours this wake-up gets §4.10.5.3's cleanup without
794    /// scheduling anything of its own.
795    #[must_use]
796    pub fn wake_at(&self) -> Option<Instant> {
797        let reap = self.exchanges.reap_deadline(EXCHANGE_IDLE_TIMEOUT);
798        match (self.exchanges.poll_deadline(), reap) {
799            (Some(a), Some(b)) => Some(if a <= b { a } else { b }),
800            (Some(a), None) => Some(a),
801            (None, b) => b,
802        }
803    }
804
805    /// Drives the reliability timers (§4.12.2.1) and reclaims abandoned exchanges (§4.10.5.3).
806    ///
807    /// Returns one action at a time; call until it returns `None`.
808    ///
809    /// Reaping happens here rather than in a method a node has to remember to call, because an
810    /// exchange table reclaimed only on request is one an attacker fills at leisure: every
811    /// unsecured datagram with the **I** flag opens an entry (§4.10.5.2), and `X` of them
812    /// would otherwise deny every later session establishment for the node's whole uptime.
813    pub fn poll(&mut self, now: Instant, randomness: u32) -> Option<Due> {
814        self.exchanges.reap(now, EXCHANGE_IDLE_TIMEOUT);
815        let expired = self
816            .exchanges
817            .iter()
818            .find(|e| e.mrp.poll_deadline().is_some_and(|at| at <= now))
819            .map(|e| e.key)?;
820        let open = self.exchanges.find_mut(expired)?;
821        match open.mrp.on_timeout(now, randomness) {
822            OnTimeout::Retransmit { counter, .. } => Some(Due::Retransmit {
823                exchange: expired,
824                counter,
825            }),
826            // §4.12.5.2.2: nothing to piggyback on, so the acknowledgement goes on its own.
827            OnTimeout::SendStandaloneAck { .. } => Some(Due::Acknowledge { exchange: expired }),
828            OnTimeout::GiveUp { .. } => {
829                self.exchanges.close(expired);
830                Some(Due::Abandoned { exchange: expired })
831            }
832            OnTimeout::Nothing => None,
833        }
834    }
835}
836
837#[cfg(test)]
838mod tests {
839    use super::*;
840    use crate::config::DefaultConfig;
841    use crate::exchange::Role;
842
843    type Node = Messaging<DefaultConfig, 4, 8>;
844
845    fn at(ms: u64) -> Instant {
846        Instant::from_micros(ms.saturating_mul(1000))
847    }
848
849    const PEER: Peer = Peer::Udp(crate::platform::PeerAddr::new([
850        0xFE, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
851    ]));
852
853    /// The unsecured session is what PASE runs over before any key exists.
854    #[test]
855    fn an_unsecured_message_round_trips_through_a_new_exchange() {
856        let mut initiator = Node::new(1, 100, 7);
857        let mut responder = Node::new(2, 200, 9);
858
859        let key = initiator
860            .open(SessionId::UNSECURED, ProtocolId::SECURE_CHANNEL, at(0))
861            .expect("open");
862        let mut wire = [0u8; 512];
863        let mut scratch = [0u8; 512];
864        let (len, counter) = initiator
865            .send(
866                key,
867                0x20,
868                true,
869                b"pbkdf-param-request",
870                at(0),
871                0,
872                &mut scratch,
873                &mut wire,
874            )
875            .expect("send");
876
877        let received = responder
878            .receive(&mut wire[..len], PEER, at(1))
879            .expect("receive");
880        let Received::Message {
881            exchange,
882            header,
883            needs_ack,
884            payload,
885        } = received
886        else {
887            panic!("expected a message, got {received:?}");
888        };
889        assert_eq!(payload, b"pbkdf-param-request");
890        assert_eq!(header.opcode, 0x20);
891        assert!(needs_ack, "a reliable message owes an acknowledgement");
892        // The responder opened its own half of the exchange, with the peer's id.
893        assert_eq!(exchange.role, Role::Responder);
894        assert_eq!(exchange.id, key.id);
895
896        // ...and the acknowledgement it sends clears the initiator's retransmission.
897        let mut ack = [0u8; 512];
898        let ack_len = responder
899            .acknowledge(exchange, at(1), &mut ack)
900            .expect("ack");
901        assert!(ack_len > 0);
902        assert!(initiator.wake_at().is_some(), "waiting for the ack");
903        let back = initiator
904            .receive(&mut ack[..ack_len], PEER, at(2))
905            .expect("receive ack");
906        assert!(matches!(back, Received::Acknowledged { .. }));
907        assert!(
908            !initiator
909                .exchanges()
910                .find(key)
911                .expect("still open")
912                .mrp
913                .is_awaiting_ack(),
914            "acknowledged, so no retransmission is outstanding"
915        );
916        let _ = counter;
917    }
918
919    /// Builds one unsecured datagram from a stranger, with the exchange id and protocol of
920    /// its choosing — which is everything an off-path attacker controls before any key exists.
921    fn stranger_datagram(
922        exchange_id: u16,
923        protocol: ProtocolId,
924        reliable: bool,
925        counter: u32,
926        out: &mut [u8],
927    ) -> usize {
928        let mut sender = Node::new(1, exchange_id, counter);
929        sender.register(Protocols::SECURE_CHANNEL.with(Protocols::INTERACTION_MODEL));
930        let key = sender
931            .open(SessionId::UNSECURED, protocol, at(0))
932            .expect("open");
933        let mut scratch = [0u8; 512];
934        let (len, _) = sender
935            .send(key, 0x20, reliable, b"x", at(0), 0, &mut scratch, out)
936            .expect("send");
937        len
938    }
939
940    /// The exhaustion attack, and the shape CVE-2024-3297 had: every unsecured message with
941    /// the **I** flag opens an exchange (§4.10.5.2), so a stranger who varies the exchange id
942    /// fills the table. Without reclamation the node can never open another exchange — which
943    /// means it can never establish another session, PASE or CASE, for the rest of its uptime.
944    #[test]
945    fn a_stranger_cannot_fill_the_exchange_table_for_good() {
946        let mut node = Node::new(2, 200, 9);
947        let mut wire = [0u8; 512];
948
949        // Eight is this node's whole table.
950        for id in 0..8u16 {
951            let len = stranger_datagram(
952                id,
953                ProtocolId::SECURE_CHANNEL,
954                true,
955                u32::from(id) + 1,
956                &mut wire,
957            );
958            let _ = node.receive(&mut wire[..len], PEER, at(0));
959        }
960        assert_eq!(node.exchanges().len(), 8, "the table is full");
961
962        // A legitimate peer arrives while the attacker's entries are still fresh, and is
963        // refused — which is correct, and is why the entries must not be permanent.
964        let len = stranger_datagram(900, ProtocolId::SECURE_CHANNEL, true, 900, &mut wire);
965        assert!(node.receive(&mut wire[..len], PEER, at(1)).is_err());
966
967        // A minute later nothing has happened on any of them, so they go.
968        assert!(
969            node.wake_at().is_some(),
970            "the node knows it has something to reclaim"
971        );
972        node.poll(at(61_000), 0);
973        assert_eq!(node.exchanges().len(), 0, "every abandoned entry reclaimed");
974
975        // ...and the node answers again.
976        let len = stranger_datagram(901, ProtocolId::SECURE_CHANNEL, true, 901, &mut wire);
977        assert!(
978            node.receive(&mut wire[..len], PEER, at(62_000)).is_ok(),
979            "a node that cannot open an exchange can never establish a session again"
980        );
981    }
982
983    /// Reclaiming on the timer is not enough on its own: a node whose timers are slow, or
984    /// which is simply busy, must still not be refusing legitimate peers on behalf of entries
985    /// that expired long ago.
986    #[test]
987    fn a_full_table_reclaims_before_refusing() {
988        let mut node = Node::new(2, 200, 9);
989        let mut wire = [0u8; 512];
990        for id in 0..8u16 {
991            let len = stranger_datagram(
992                id,
993                ProtocolId::SECURE_CHANNEL,
994                true,
995                u32::from(id) + 1,
996                &mut wire,
997            );
998            let _ = node.receive(&mut wire[..len], PEER, at(0));
999        }
1000        assert_eq!(node.exchanges().len(), 8);
1001
1002        // No `poll` in between — the pressure itself is the trigger.
1003        let len = stranger_datagram(900, ProtocolId::SECURE_CHANNEL, true, 900, &mut wire);
1004        assert!(
1005            node.receive(&mut wire[..len], PEER, at(61_000)).is_ok(),
1006            "the entry that would have refused this one had been idle for a minute"
1007        );
1008    }
1009
1010    /// §4.10.5.2 rule 1: "has a registered Protocol ID". An unregistered protocol is not
1011    /// something this node will ever act on, so it must not cost a table entry.
1012    #[test]
1013    fn an_unregistered_protocol_opens_no_exchange() {
1014        let mut node = Node::new(2, 200, 9);
1015        node.register(Protocols::SECURE_CHANNEL);
1016        let mut wire = [0u8; 512];
1017
1018        // The Interaction Model is not registered on this node.
1019        let len = stranger_datagram(5, ProtocolId::INTERACTION_MODEL, false, 5, &mut wire);
1020        assert!(node.receive(&mut wire[..len], PEER, at(0)).is_err());
1021        assert_eq!(node.exchanges().len(), 0, "rule 3: processing SHALL stop");
1022
1023        // Secure Channel is, so that one is answered.
1024        let len = stranger_datagram(6, ProtocolId::SECURE_CHANNEL, false, 6, &mut wire);
1025        assert!(node.receive(&mut wire[..len], PEER, at(0)).is_ok());
1026        assert_eq!(node.exchanges().len(), 1);
1027    }
1028
1029    /// §4.10.5.2 rule 2: an unregistered protocol that *asks* for an acknowledgement still
1030    /// gets one — withholding it costs the sender five retransmissions — but on an ephemeral
1031    /// exchange that §4.12.5.2.2 closes as soon as the acknowledgement is sent.
1032    #[test]
1033    fn an_unregistered_reliable_message_is_acknowledged_on_an_ephemeral_exchange() {
1034        let mut node = Node::new(2, 200, 9);
1035        node.register(Protocols::SECURE_CHANNEL);
1036        let mut wire = [0u8; 512];
1037        let len = stranger_datagram(7, ProtocolId::BDX, true, 7, &mut wire);
1038
1039        let received = node.receive(&mut wire[..len], PEER, at(0)).expect("routed");
1040        let Received::Message { exchange, .. } = received else {
1041            panic!("expected the ephemeral exchange, got {received:?}")
1042        };
1043        assert_eq!(node.exchanges().len(), 1);
1044        assert!(
1045            node.exchanges().find(exchange).is_some_and(|e| e.ephemeral),
1046            "it is ephemeral"
1047        );
1048
1049        let mut ack = [0u8; 512];
1050        assert!(node.acknowledge(exchange, at(0), &mut ack).expect("ack") > 0);
1051        assert_eq!(
1052            node.exchanges().len(),
1053            0,
1054            "§4.12.5.2.2: the ephemeral exchange SHALL be closed once it has acknowledged"
1055        );
1056    }
1057
1058    /// An exchange that is still trying to deliver something is not abandoned, however quiet
1059    /// the peer has been — §4.10.5.3 step 2b.
1060    #[test]
1061    fn an_exchange_with_a_pending_retransmission_is_never_reaped() {
1062        let mut node = Node::new(1, 100, 7);
1063        let key = node
1064            .open(SessionId::UNSECURED, ProtocolId::SECURE_CHANNEL, at(0))
1065            .expect("open");
1066        let mut wire = [0u8; 512];
1067        let mut scratch = [0u8; 512];
1068        let _ = node
1069            .send(key, 0x20, true, b"x", at(0), 0, &mut scratch, &mut wire)
1070            .expect("send");
1071
1072        // Far past the idle timeout, and never acknowledged.
1073        node.exchanges_mut()
1074            .reap(at(600_000), EXCHANGE_IDLE_TIMEOUT);
1075        assert_eq!(
1076            node.exchanges().len(),
1077            1,
1078            "a retransmission still pending keeps the exchange open"
1079        );
1080    }
1081
1082    /// §4.13.2.1's Unsecured Session Context, and the rule that no test of this crate against
1083    /// itself could catch.
1084    ///
1085    /// > Ephemeral Initiator Node ID: Randomly selected for each session by the initiator from
1086    /// > the Operational Node ID range and **enclosed by initiator as Source Node ID and
1087    /// > responder as Destination Node ID.**
1088    ///
1089    /// Both halves have to hold, and a stack that encloses *neither* is self-consistent: two
1090    /// nodes built from it commission each other perfectly. The CHIP SDK drops such a message
1091    /// before it reaches any protocol — "Received malformed unsecure packet with source 0x0
1092    /// destination 0x0" — so the symptom is a device no certified controller can pair with,
1093    /// while every test passes.
1094    #[test]
1095    fn an_unsecured_response_carries_the_initiators_ephemeral_node_id() {
1096        const EPHEMERAL: crate::msg::NodeId = crate::msg::NodeId(0x0102_0304_0506_0708);
1097
1098        let mut initiator = Node::new(1, 100, 7);
1099        initiator
1100            .open_unsecured_as_initiator(EPHEMERAL)
1101            .expect("an operational node id");
1102        let mut responder = Node::new(2, 200, 9);
1103
1104        let key = initiator
1105            .open(SessionId::UNSECURED, ProtocolId::SECURE_CHANNEL, at(0))
1106            .expect("open");
1107        let mut wire = [0u8; 512];
1108        let mut scratch = [0u8; 512];
1109        let (len, _) = initiator
1110            .send(
1111                key,
1112                0x20,
1113                true,
1114                b"request",
1115                at(0),
1116                0,
1117                &mut scratch,
1118                &mut wire,
1119            )
1120            .expect("send");
1121
1122        // The initiator encloses it as the Source Node ID: flag bit 2 of octet 0, then eight
1123        // octets little-endian after the four-octet counter.
1124        assert_eq!(wire[0] & 0x04, 0x04, "S flag set");
1125        assert_eq!(
1126            u64::from_le_bytes(wire[8..16].try_into().expect("eight octets")),
1127            EPHEMERAL.0,
1128            "and it is the ephemeral id"
1129        );
1130
1131        let received = responder
1132            .receive(&mut wire[..len], PEER, at(1))
1133            .expect("receive");
1134        let Received::Message { exchange, .. } = received else {
1135            panic!("expected a message, got {received:?}")
1136        };
1137        assert_eq!(
1138            responder.unsecured_ephemeral_id(),
1139            Some(EPHEMERAL),
1140            "the responder recorded it as the context's ephemeral initiator id"
1141        );
1142
1143        // ...and encloses it as the *Destination* Node ID on the way back.
1144        let mut back = [0u8; 512];
1145        let (len, _) = responder
1146            .send(
1147                exchange,
1148                0x21,
1149                true,
1150                b"response",
1151                at(1),
1152                0,
1153                &mut scratch,
1154                &mut back,
1155            )
1156            .expect("send");
1157        assert_eq!(back[0] & 0x04, 0, "no S flag on the responder's message");
1158        assert_eq!(back[0] & 0x03, 0x01, "DSIZ = 1, a 64-bit Node ID");
1159        assert_eq!(
1160            u64::from_le_bytes(back[8..16].try_into().expect("eight octets")),
1161            EPHEMERAL.0,
1162            "the destination is the initiator's ephemeral id"
1163        );
1164
1165        // The initiator accepts what comes back.
1166        let round = initiator
1167            .receive(&mut back[..len], PEER, at(2))
1168            .expect("the initiator accepts its own ephemeral id as the destination");
1169        assert!(matches!(round, Received::Message { .. }));
1170    }
1171
1172    /// §4.13.2.1 matches a context by Ephemeral Initiator Node ID and creates a new one when
1173    /// none matches. A node that kept the first would answer a second initiator — the same
1174    /// commissioner coming back for CASE after PASE, most of the time — with replies addressed
1175    /// to a peer that has gone, which the CHIP SDK drops before any protocol sees them.
1176    #[test]
1177    fn a_second_initiator_replaces_the_unsecured_context() {
1178        const FIRST: crate::msg::NodeId = crate::msg::NodeId(0x1111_1111_1111_1111);
1179        const SECOND: crate::msg::NodeId = crate::msg::NodeId(0x2222_2222_2222_2222);
1180
1181        let mut responder = Node::new(2, 200, 9);
1182        let mut wire = [0u8; 512];
1183        let mut scratch = [0u8; 512];
1184
1185        for (n, (ephemeral, counter)) in [(FIRST, 1u32), (SECOND, 2u32)].into_iter().enumerate() {
1186            let mut initiator = Node::new(1, 100 + u16::try_from(n).expect("fits"), counter);
1187            initiator
1188                .open_unsecured_as_initiator(ephemeral)
1189                .expect("operational");
1190            let key = initiator
1191                .open(SessionId::UNSECURED, ProtocolId::SECURE_CHANNEL, at(0))
1192                .expect("open");
1193            let (len, _) = initiator
1194                .send(key, 0x20, true, b"x", at(0), 0, &mut scratch, &mut wire)
1195                .expect("send");
1196            let received = responder
1197                .receive(&mut wire[..len], PEER, at(1))
1198                .expect("receive");
1199            let Received::Message { exchange, .. } = received else {
1200                panic!("expected a message")
1201            };
1202            assert_eq!(
1203                responder.unsecured_ephemeral_id(),
1204                Some(ephemeral),
1205                "the newest initiator owns the context"
1206            );
1207
1208            let mut back = [0u8; 512];
1209            let _ = responder
1210                .send(
1211                    exchange,
1212                    0x21,
1213                    true,
1214                    b"y",
1215                    at(1),
1216                    0,
1217                    &mut scratch,
1218                    &mut back,
1219                )
1220                .expect("send");
1221            assert_eq!(
1222                u64::from_le_bytes(back[8..16].try_into().expect("eight octets")),
1223                ephemeral.0,
1224                "and the reply is addressed to it"
1225            );
1226        }
1227    }
1228
1229    /// §4.13.2.1 constrains the ephemeral id to the Operational Node ID range, because it is
1230    /// what the responder will put in a Destination Node ID field.
1231    #[test]
1232    fn an_ephemeral_id_outside_the_operational_range_is_refused() {
1233        let mut node = Node::new(1, 100, 7);
1234        assert!(
1235            node.open_unsecured_as_initiator(crate::msg::NodeId::UNSPECIFIED)
1236                .is_err()
1237        );
1238        assert!(
1239            node.open_unsecured_as_initiator(crate::msg::NodeId(1))
1240                .is_ok()
1241        );
1242    }
1243
1244    /// §4.12.2.2: a duplicate is acknowledged and not delivered.
1245    #[test]
1246    fn a_duplicate_is_acknowledged_and_not_delivered_twice() {
1247        let mut initiator = Node::new(1, 100, 7);
1248        let mut responder = Node::new(2, 200, 9);
1249        let key = initiator
1250            .open(SessionId::UNSECURED, ProtocolId::SECURE_CHANNEL, at(0))
1251            .expect("open");
1252
1253        let mut wire = [0u8; 512];
1254        let mut scratch = [0u8; 512];
1255        let (len, _) = initiator
1256            .send(key, 0x20, true, b"once", at(0), 0, &mut scratch, &mut wire)
1257            .expect("send");
1258        let copy = wire;
1259
1260        let first = responder
1261            .receive(&mut wire[..len], PEER, at(1))
1262            .expect("first");
1263        assert!(matches!(first, Received::Message { .. }));
1264
1265        let mut again = copy;
1266        let second = responder
1267            .receive(&mut again[..len], PEER, at(2))
1268            .expect("second");
1269        match second {
1270            Received::Duplicate { needs_ack, .. } => {
1271                assert!(needs_ack, "still acknowledged — the sender's ack was lost");
1272            }
1273            other => panic!("a repeat must not reach the application: {other:?}"),
1274        }
1275    }
1276
1277    /// A message for a session this node does not have is refused, not guessed at.
1278    #[test]
1279    fn a_message_for_an_unknown_session_is_refused() {
1280        let mut node = Node::new(1, 100, 7);
1281        let mut wire = [0u8; 64];
1282        // Flags: version 0, no source/destination. Session id 0x1234, unicast.
1283        wire[0] = 0x00;
1284        wire[1] = 0x34;
1285        wire[2] = 0x12;
1286        wire[3] = 0x00;
1287        let err = node
1288            .receive(&mut wire, PEER, at(0))
1289            .expect_err("no session");
1290        assert_eq!(err.code(), ErrorCode::NoSession);
1291    }
1292
1293    /// A response to an exchange that was never opened is refused (§4.4.3.1).
1294    #[test]
1295    fn a_message_from_a_responder_cannot_open_an_exchange() {
1296        let mut initiator = Node::new(1, 100, 7);
1297        let mut responder = Node::new(2, 200, 9);
1298        let key = initiator
1299            .open(SessionId::UNSECURED, ProtocolId::SECURE_CHANNEL, at(0))
1300            .expect("open");
1301        let mut wire = [0u8; 512];
1302        let mut scratch = [0u8; 512];
1303        let (len, _) = initiator
1304            .send(
1305                key,
1306                0x20,
1307                false,
1308                b"hello",
1309                at(0),
1310                0,
1311                &mut scratch,
1312                &mut wire,
1313            )
1314            .expect("send");
1315        // Clear the I flag in the protocol header: now it claims to be a *response*.
1316        let header_len = MessageHeader::default().encoded_len();
1317        wire[header_len] &= !0x01;
1318
1319        let err = responder
1320            .receive(&mut wire[..len], PEER, at(1))
1321            .expect_err("a response answers a question nobody asked");
1322        assert_eq!(err.code(), ErrorCode::NoExchange);
1323    }
1324
1325    /// The retransmission timer fires, and names the counter to resend (§4.12.2.1).
1326    #[test]
1327    fn an_unacknowledged_message_is_retransmitted_with_its_own_counter() {
1328        let mut initiator = Node::new(1, 100, 7);
1329        let key = initiator
1330            .open(SessionId::UNSECURED, ProtocolId::SECURE_CHANNEL, at(0))
1331            .expect("open");
1332        let mut wire = [0u8; 512];
1333        let mut scratch = [0u8; 512];
1334        let (_, counter) = initiator
1335            .send(key, 0x20, true, b"lost", at(0), 0, &mut scratch, &mut wire)
1336            .expect("send");
1337
1338        let deadline = initiator.wake_at().expect("a reliable send arms a timer");
1339        match initiator.poll(deadline, 0) {
1340            Some(Due::Retransmit {
1341                exchange,
1342                counter: again,
1343            }) => {
1344                assert_eq!(exchange, key);
1345                assert_eq!(
1346                    again, counter,
1347                    "the same counter: a new one would be a new message and a reused nonce"
1348                );
1349            }
1350            other => panic!("expected a retransmission, got {other:?}"),
1351        }
1352    }
1353}