Skip to main content

sedsnet/
wire_format.rs

1//! Wire-format packing and unpacking of telemetry packets.
2//!
3//! This module defines the compact v2 wire format used to send and receive
4//! [`Packet`]s, along with:
5//! - [`pack_packet`] / [`unpack_packet`] for full packets.
6//! - [`peek_envelope`] for header-only inspection without touching the payload.
7//! - Size helpers like [`header_size_bytes`] and [`packet_wire_size`].
8//!
9//! The core public type here is [`TelemetryEnvelope`], a lightweight view of
10//! the header fields used by `peek_envelope`.
11
12use crate::MessageElement;
13use crate::{
14    DataEndpoint, TelemetryError, TelemetryResult, config::DataType, is_reliable_type,
15    message_meta, packet::Packet,
16};
17
18use crate::config::StandardSmallPayload;
19use crate::packet::{hash_bytes_u64, sender_address_u32};
20#[cfg(feature = "std")]
21use alloc::collections::BTreeMap;
22#[cfg(feature = "cryptography")]
23use alloc::vec;
24use alloc::{sync::Arc, vec::Vec};
25use crc32fast::Hasher as Crc32Hasher;
26#[cfg(feature = "std")]
27use std::sync::{Mutex, OnceLock};
28
29/// Lightweight header-only view of a packed [`Packet`].
30///
31/// Produced by [`peek_envelope`] without allocating or copying the payload.
32#[derive(Clone, Debug, PartialEq, Eq)]
33pub struct TelemetryEnvelope {
34    /// Telemetry [`DataType`] discriminant.
35    pub ty: DataType,
36    /// All endpoints this packet is destined for (set bits in the bitmap).
37    pub endpoints: Arc<[DataEndpoint]>,
38    /// Sender identity resolved from discovery/config address state.
39    pub sender: Arc<str>,
40    /// Compact source address carried by the packet header.
41    pub source_address: u32,
42    /// Timestamp in milliseconds (as stored on the wire).
43    pub timestamp_ms: u64,
44    /// Inline wire-format payload shape, if present.
45    pub wire_shape: Option<MessageElement>,
46    /// Frozen destination sender hashes, if present.
47    pub target_senders: Arc<[u64]>,
48}
49
50/// Reliable header included for data types marked `reliable` in the schema.
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub struct ReliableHeader {
53    pub flags: u8,
54    pub seq: u32,
55    pub ack: u32,
56}
57
58/// Reliable header flag: frame is ACK-only control (no payload).
59pub const RELIABLE_FLAG_ACK_ONLY: u8 = 0x01;
60
61/// Reliable header flag: frame is reliable but unordered (ACK/retransmit without ordering).
62pub const RELIABLE_FLAG_UNORDERED: u8 = 0x02;
63
64/// Reliable header flag: frame is unsequenced best-effort (no ordering/ack).
65pub const RELIABLE_FLAG_UNSEQUENCED: u8 = 0x80;
66
67/// Fixed size of the reliable header on the wire.
68pub const RELIABLE_HEADER_BYTES: usize = 1 + 4 + 4;
69/// Fixed size of the CRC32 trailer on the wire.
70pub const CRC32_BYTES: usize = 4;
71
72// packet Layout:
73//
74//   [FLAGS: u8]
75//       Bit 0: payload compressed flag (1 = compressed)
76//       Bit 1: reliable header present
77//       Bit 7: explicit endpoint ID list present (mutually exclusive with bit5)
78//       Bit 5: endpoint bitmap present (0 = derive endpoints from data type metadata)
79//       Bit 6: compact reliable header present (if a reliable header exists)
80//
81//   [NEP: u8]
82//       Number of selected endpoints.
83//
84//   VARINT(ty: u32 as u64)           -- ULEB128
85//   VARINT(data_size: u64)           -- ULEB128   (LOGICAL payload size, uncompressed)
86//   VARINT(timestamp: u64)           -- ULEB128
87//   [VARINT(nonce: u16 as u64)]      -- ULEB128   (ONLY if bit3 set)
88//   VARINT(src_addr: u32 as u64)     -- ULEB128
89//
90//   [ENDPOINTS_BITMAP]               -- ONLY if bit5 set; 1 bit per possible endpoint
91//   [ENDPOINT_ID_LIST]               -- NEP sorted unique ULEB128 IDs if bit7 set
92//   [RELIABLE HEADER]                -- declared by bit1 or the wire contract
93//       [REL_FLAGS: u8]
94//       [SEQ: u32 LE]
95//       [ACK: u32 LE]
96//   PAYLOAD BYTES                    -- raw or compressed payload bytes
97//   [CRC32: u32 LE]                  -- checksum of all prior bytes
98
99// ===========================================================================
100// ULEB128 (varint) encoding helpers
101// ===========================================================================
102const FLAG_COMPRESSED_PAYLOAD: u8 = 0x01;
103const FLAG_RELIABLE_HEADER_PRESENT: u8 = 0x02;
104const FLAG_WIRE_CONTRACT: u8 = 0x04;
105const FLAG_PACKET_NONCE: u8 = 0x08;
106#[cfg(feature = "cryptography")]
107const FLAG_E2E_ENCRYPTED_PAYLOAD: u8 = 0x10;
108const FLAG_ENDPOINT_BITMAP_PRESENT: u8 = 0x20;
109const FLAG_ENDPOINT_LIST_PRESENT: u8 = 0x80;
110const FLAG_COMPACT_RELIABLE_HEADER: u8 = 0x40;
111const CONTRACT_FLAG_TARGETS: u8 = 0x01;
112const CONTRACT_FLAG_SHAPE: u8 = 0x02;
113const CONTRACT_FLAG_RELIABLE_HEADER: u8 = 0x04;
114const RELIABLE_WIRE_FLAG_SEQ_PRESENT: u8 = 0x04;
115const RELIABLE_WIRE_FLAG_ACK_PRESENT: u8 = 0x08;
116const RELIABLE_PUBLIC_FLAGS_MASK: u8 =
117    RELIABLE_FLAG_ACK_ONLY | RELIABLE_FLAG_UNORDERED | RELIABLE_FLAG_UNSEQUENCED;
118#[cfg(feature = "cryptography")]
119const E2E_NONCE_LEN: usize = 12;
120#[cfg(feature = "cryptography")]
121const E2E_TAG_CAP: usize = 32;
122
123#[derive(Clone, Debug, PartialEq, Eq)]
124struct WireContract {
125    shape: Option<MessageElement>,
126    target_senders: Option<Arc<[u64]>>,
127    has_reliable_header: bool,
128}
129
130/// Encode a `u64` as ULEB128 and append it to `out`.
131#[inline]
132fn write_uleb128<T>(mut v: u64, out: &mut Vec<T>)
133where
134    T: From<u8>,
135{
136    loop {
137        let mut byte = (v & 0x7F) as u8;
138        v >>= 7;
139        if v != 0 {
140            byte |= 0x80;
141        }
142        out.push(T::from(byte));
143        if v == 0 {
144            break;
145        }
146    }
147}
148
149/// Decode a ULEB128-encoded `u64` from the given reader.
150#[inline]
151fn read_uleb128(r: &mut ByteReader) -> Result<u64, TelemetryError> {
152    crate::varint::read_u64(r.buf, &mut r.off)
153}
154
155/// Compute the encoded length (in bytes) of a ULEB128-encoded `u64`.
156#[inline]
157fn uleb128_size(mut v: u64) -> usize {
158    let mut n = 1;
159    while v >= 0x80 {
160        v >>= 7;
161        n += 1;
162    }
163    n
164}
165
166/// Count the total number of bits set across all bytes of the bitmap.
167#[inline]
168fn bitmap_popcount(bm: &[u8]) -> usize {
169    bm.iter().map(|b| b.count_ones() as usize).sum()
170}
171
172// ===========================================================================
173// ByteReader: tiny cursor over a byte slice
174// ===========================================================================
175
176#[derive(Clone, Copy)]
177struct ByteReader<'a> {
178    buf: &'a [u8],
179    off: usize,
180}
181
182impl<'a> ByteReader<'a> {
183    /// Create a new reader over the given buffer starting at offset 0.
184    fn new(buf: &'a [u8]) -> Self {
185        Self { buf, off: 0 }
186    }
187
188    /// Remaining bytes that can still be read.
189    fn remaining(&self) -> usize {
190        self.buf.len().saturating_sub(self.off)
191    }
192
193    /// Read exactly `n` bytes, advancing the internal offset.
194    #[inline(always)]
195    fn read_bytes(&mut self, n: usize) -> Result<&'a [u8], TelemetryError> {
196        if self.remaining() < n {
197            return Err(TelemetryError::Unpack("short read"));
198        }
199        let s = &self.buf[self.off..self.off + n];
200        self.off += n;
201        Ok(s)
202    }
203}
204
205#[inline]
206fn write_u32_le(v: u32, out: &mut Vec<u8>) {
207    out.extend_from_slice(&v.to_le_bytes());
208}
209
210#[inline]
211fn read_u32_le(r: &mut ByteReader) -> Result<u32, TelemetryError> {
212    let b = r.read_bytes(4)?;
213    Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
214}
215
216#[inline]
217fn write_wire_shape(shape: MessageElement, out: &mut Vec<u8>) -> Result<(), TelemetryError> {
218    let dt = crate::config::message_data_type_code(shape.data_type());
219    let class = crate::config::message_class_code(shape.message_type());
220    let mut packed = dt | (class << 4);
221    if matches!(shape, MessageElement::Static(_, _, _)) {
222        packed |= 1 << 6;
223    }
224    out.push(packed);
225    if let MessageElement::Static(count, _, _) = shape {
226        let count = u64::try_from(count).map_err(|_| TelemetryError::Pack("wire shape count"))?;
227        write_uleb128(count, out);
228    }
229    Ok(())
230}
231
232#[inline]
233fn decode_wire_shape(r: &mut ByteReader) -> Result<MessageElement, TelemetryError> {
234    let packed = r.read_bytes(1)?[0];
235    let dt = crate::config::message_data_type_from_code(packed & 0x0F)
236        .ok_or(TelemetryError::Unpack("wire shape type"))?;
237    let class = crate::config::message_class_from_code((packed >> 4) & 0x03)
238        .ok_or(TelemetryError::Unpack("wire shape class"))?;
239    if (packed & (1 << 6)) != 0 {
240        let count = usize::try_from(read_uleb128(r)?)
241            .map_err(|_| TelemetryError::Unpack("wire shape count"))?;
242        Ok(MessageElement::Static(count, dt, class))
243    } else {
244        Ok(MessageElement::Dynamic(dt, class))
245    }
246}
247
248#[inline]
249fn write_wire_contract(
250    shape: Option<MessageElement>,
251    target_senders: &[u64],
252    has_reliable_header: bool,
253    out: &mut Vec<u8>,
254) -> Result<(), TelemetryError> {
255    // Keep the contract self-contained and compact. It exists only to preserve
256    // delivery/decode intent for packets that are already in flight while
257    // schema or topology updates are still converging.
258    let mut flags = 0u8;
259    if !target_senders.is_empty() {
260        flags |= CONTRACT_FLAG_TARGETS;
261    }
262    if shape.is_some() {
263        flags |= CONTRACT_FLAG_SHAPE;
264    }
265    if has_reliable_header {
266        flags |= CONTRACT_FLAG_RELIABLE_HEADER;
267    }
268    out.push(flags);
269    if let Some(shape) = shape {
270        write_wire_shape(shape, out)?;
271    }
272    if !target_senders.is_empty() {
273        write_uleb128(target_senders.len() as u64, out);
274        for hash in target_senders {
275            out.extend_from_slice(&hash.to_le_bytes());
276        }
277    }
278    Ok(())
279}
280
281/// Size the frozen contract without constructing temporary shape/target buffers.
282fn wire_contract_size(shape: Option<MessageElement>, target_senders: &[u64]) -> usize {
283    1 + shape.map_or(0, |shape| match shape {
284        MessageElement::Static(count, _, _) => 1 + uleb128_size(count as u64),
285        _ => 1,
286    }) + if target_senders.is_empty() {
287        0
288    } else {
289        uleb128_size(target_senders.len() as u64) + target_senders.len() * 8
290    }
291}
292
293#[inline]
294fn decode_wire_contract(
295    r: &mut ByteReader,
296    has_contract: bool,
297) -> Result<WireContract, TelemetryError> {
298    if !has_contract {
299        return Ok(WireContract {
300            shape: None,
301            target_senders: None,
302            has_reliable_header: false,
303        });
304    }
305    let contract_len = usize::try_from(read_uleb128(r)?)
306        .map_err(|_| TelemetryError::Unpack("wire contract length"))?;
307    let contract_bytes = r.read_bytes(contract_len)?;
308    let mut cr = ByteReader::new(contract_bytes);
309    // Parsing through a bounded sub-reader lets us reject trailing garbage in
310    // the contract cleanly instead of accidentally treating it as payload or
311    // reliable-header bytes.
312    let flags = cr.read_bytes(1)?[0];
313    let shape = if (flags & CONTRACT_FLAG_SHAPE) != 0 {
314        Some(decode_wire_shape(&mut cr)?)
315    } else {
316        None
317    };
318    let target_senders: Option<Arc<[u64]>> = if (flags & CONTRACT_FLAG_TARGETS) != 0 {
319        let count = usize::try_from(read_uleb128(&mut cr)?)
320            .map_err(|_| TelemetryError::Unpack("wire contract target count"))?;
321        if count > cr.remaining() / 8 {
322            return Err(TelemetryError::Unpack("wire contract target count"));
323        }
324        if count == 0 {
325            None
326        } else {
327            let mut targets = Arc::<[u64]>::new_uninit_slice(count);
328            for slot in Arc::get_mut(&mut targets).expect("new target storage is unique") {
329                let bytes = cr.read_bytes(8)?;
330                slot.write(u64::from_le_bytes([
331                    bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
332                ]));
333            }
334            // The bounded target count guarantees every slot was initialized.
335            Some(unsafe { targets.assume_init() })
336        }
337    } else {
338        None
339    };
340    if cr.remaining() != 0 {
341        return Err(TelemetryError::Unpack("wire contract trailing bytes"));
342    }
343    Ok(WireContract {
344        shape,
345        target_senders,
346        has_reliable_header: (flags & CONTRACT_FLAG_RELIABLE_HEADER) != 0,
347    })
348}
349
350#[inline]
351fn crc32_bytes(data: &[u8]) -> u32 {
352    let mut hasher = Crc32Hasher::new();
353    hasher.update(data);
354    hasher.finalize()
355}
356
357#[inline]
358fn append_crc32(out: &mut Vec<u8>) {
359    let crc = crc32_bytes(out);
360    out.extend_from_slice(&crc.to_le_bytes());
361}
362
363// Initialize every byte before publishing the shared frame. Keeping the
364// payload separate avoids a second full-size allocation during Arc creation.
365fn join_frame_with_crc(header: &[u8], payload: &[u8]) -> Arc<[u8]> {
366    let mut hasher = Crc32Hasher::new();
367    hasher.update(header);
368    hasher.update(payload);
369    let crc = hasher.finalize().to_le_bytes();
370    let mut frame = Arc::<[u8]>::new_uninit_slice(header.len() + payload.len() + crc.len());
371    let bytes = Arc::get_mut(&mut frame).unwrap();
372    for (slot, value) in bytes
373        .iter_mut()
374        .zip(header.iter().chain(payload).chain(&crc))
375    {
376        slot.write(*value);
377    }
378    // SAFETY: the iterator above writes exactly header + payload + CRC bytes,
379    // which is the full allocation length. No uninitialized byte escapes.
380    unsafe { frame.assume_init() }
381}
382
383#[inline]
384fn split_crc32(buf: &[u8]) -> Result<(&[u8], u32), TelemetryError> {
385    if buf.len() < CRC32_BYTES {
386        return Err(TelemetryError::Unpack("short buffer"));
387    }
388    let data_len = buf.len() - CRC32_BYTES;
389    let crc = u32::from_le_bytes([
390        buf[data_len],
391        buf[data_len + 1],
392        buf[data_len + 2],
393        buf[data_len + 3],
394    ]);
395    Ok((&buf[..data_len], crc))
396}
397
398#[inline]
399fn verify_crc32(buf: &[u8]) -> Result<&[u8], TelemetryError> {
400    let (data, expected) = split_crc32(buf)?;
401    let actual = crc32_bytes(data);
402    if actual != expected {
403        return Err(TelemetryError::Unpack("crc32 mismatch"));
404    }
405    Ok(data)
406}
407
408#[cfg(feature = "cryptography")]
409#[inline]
410fn e2e_nonce_for_packet(pkt: &Packet) -> [u8; E2E_NONCE_LEN] {
411    let mut nonce = [0u8; E2E_NONCE_LEN];
412    nonce[..4].copy_from_slice(&pkt.data_type().as_u32().to_le_bytes());
413    nonce[4..10].copy_from_slice(&(pkt.timestamp() & 0x0000_FFFF_FFFF_FFFF).to_le_bytes()[..6]);
414    nonce[10..].copy_from_slice(&pkt.nonce().to_le_bytes());
415    nonce
416}
417
418#[cfg(feature = "cryptography")]
419fn write_encrypted_payload(
420    pkt: &Packet,
421    key_id: u32,
422    plaintext_wire_payload: &[u8],
423    out: &mut Vec<u8>,
424) -> TelemetryResult<()> {
425    let aad_end = out.len();
426    let nonce = e2e_nonce_for_packet(pkt);
427    let mut ciphertext = vec![0u8; plaintext_wire_payload.len()];
428    let mut tag = [0u8; E2E_TAG_CAP];
429    let (ciphertext_len, tag_len) = crate::crypto::seal_with_registered_crypto(
430        key_id,
431        &nonce,
432        &out[..aad_end],
433        plaintext_wire_payload,
434        &mut ciphertext,
435        &mut tag,
436    )?;
437    if ciphertext_len > ciphertext.len() || tag_len > tag.len() {
438        return Err(TelemetryError::SizeMismatchError);
439    }
440    write_uleb128(u64::from(key_id), out);
441    write_uleb128(plaintext_wire_payload.len() as u64, out);
442    write_uleb128(nonce.len() as u64, out);
443    out.extend_from_slice(&nonce);
444    write_uleb128(tag_len as u64, out);
445    out.extend_from_slice(&tag[..tag_len]);
446    out.extend_from_slice(&ciphertext[..ciphertext_len]);
447    Ok(())
448}
449
450#[cfg(feature = "cryptography")]
451fn read_encrypted_payload(
452    r: &mut ByteReader,
453    aad: &[u8],
454    plaintext_len: usize,
455) -> TelemetryResult<Vec<u8>> {
456    let key_id = u32::try_from(read_uleb128(r)?)
457        .map_err(|_| TelemetryError::Unpack("e2e key id too large"))?;
458    let wire_payload_len = usize::try_from(read_uleb128(r)?)
459        .map_err(|_| TelemetryError::Unpack("e2e payload length"))?;
460    if wire_payload_len > plaintext_len {
461        return Err(TelemetryError::Unpack("bad e2e payload length"));
462    }
463    let nonce_len = usize::try_from(read_uleb128(r)?)
464        .map_err(|_| TelemetryError::Unpack("e2e nonce length"))?;
465    if nonce_len == 0 || nonce_len > 64 {
466        return Err(TelemetryError::Unpack("bad e2e nonce length"));
467    }
468    let nonce = r.read_bytes(nonce_len)?;
469    let tag_len =
470        usize::try_from(read_uleb128(r)?).map_err(|_| TelemetryError::Unpack("e2e tag length"))?;
471    if tag_len == 0 || tag_len > E2E_TAG_CAP {
472        return Err(TelemetryError::Unpack("bad e2e tag length"));
473    }
474    let tag = r.read_bytes(tag_len)?;
475    let ciphertext_len = r.remaining();
476    let ciphertext = r.read_bytes(ciphertext_len)?;
477    let mut plaintext = vec![0u8; wire_payload_len];
478    let opened_len = crate::crypto::open_with_registered_crypto(
479        key_id,
480        nonce,
481        aad,
482        ciphertext,
483        tag,
484        &mut plaintext,
485    )?;
486    if opened_len != wire_payload_len {
487        return Err(TelemetryError::SizeMismatchError);
488    }
489    Ok(plaintext)
490}
491
492#[inline]
493fn write_reliable_header(h: ReliableHeader, out: &mut Vec<u8>) {
494    out.push(h.flags);
495    write_u32_le(h.seq, out);
496    write_u32_le(h.ack, out);
497}
498
499#[inline]
500fn reliable_compact_size(h: ReliableHeader) -> usize {
501    let seq_present = (h.flags & RELIABLE_FLAG_ACK_ONLY) == 0 || h.seq != 0;
502    let ack_present = h.ack != 0 || (h.flags & RELIABLE_FLAG_ACK_ONLY) != 0;
503    1 + if seq_present {
504        uleb128_size(h.seq as u64)
505    } else {
506        0
507    } + if ack_present {
508        uleb128_size(h.ack as u64)
509    } else {
510        0
511    }
512}
513
514#[inline]
515fn should_compact_reliable_header(h: ReliableHeader) -> bool {
516    reliable_compact_size(h) < RELIABLE_HEADER_BYTES
517}
518
519#[inline]
520fn reliable_wire_size(h: ReliableHeader, compact: bool) -> usize {
521    if compact {
522        reliable_compact_size(h)
523    } else {
524        RELIABLE_HEADER_BYTES
525    }
526}
527
528pub(crate) fn write_reliable_header_encoded(h: ReliableHeader, compact: bool, out: &mut Vec<u8>) {
529    if !compact {
530        write_reliable_header(h, out);
531        return;
532    }
533
534    let seq_present = (h.flags & RELIABLE_FLAG_ACK_ONLY) == 0 || h.seq != 0;
535    let ack_present = h.ack != 0 || (h.flags & RELIABLE_FLAG_ACK_ONLY) != 0;
536    let mut wire_flags = h.flags & RELIABLE_PUBLIC_FLAGS_MASK;
537    if seq_present {
538        wire_flags |= RELIABLE_WIRE_FLAG_SEQ_PRESENT;
539    }
540    if ack_present {
541        wire_flags |= RELIABLE_WIRE_FLAG_ACK_PRESENT;
542    }
543    out.push(wire_flags);
544    if seq_present {
545        write_uleb128(h.seq as u64, out);
546    }
547    if ack_present {
548        write_uleb128(h.ack as u64, out);
549    }
550}
551
552#[inline]
553fn read_reliable_header(r: &mut ByteReader) -> Result<ReliableHeader, TelemetryError> {
554    let flags = r.read_bytes(1)?[0];
555    let seq = read_u32_le(r)?;
556    let ack = read_u32_le(r)?;
557    Ok(ReliableHeader { flags, seq, ack })
558}
559
560fn read_reliable_header_compact(r: &mut ByteReader) -> Result<ReliableHeader, TelemetryError> {
561    let wire_flags = r.read_bytes(1)?[0];
562    let seq = if (wire_flags & RELIABLE_WIRE_FLAG_SEQ_PRESENT) != 0 {
563        u32::try_from(read_uleb128(r)?)
564            .map_err(|_| TelemetryError::Unpack("reliable seq too large"))?
565    } else {
566        0
567    };
568    let ack = if (wire_flags & RELIABLE_WIRE_FLAG_ACK_PRESENT) != 0 {
569        u32::try_from(read_uleb128(r)?)
570            .map_err(|_| TelemetryError::Unpack("reliable ack too large"))?
571    } else {
572        0
573    };
574    Ok(ReliableHeader {
575        flags: wire_flags & RELIABLE_PUBLIC_FLAGS_MASK,
576        seq,
577        ack,
578    })
579}
580
581#[inline]
582fn read_reliable_header_encoded(
583    r: &mut ByteReader,
584    compact: bool,
585) -> Result<ReliableHeader, TelemetryError> {
586    if compact {
587        read_reliable_header_compact(r)
588    } else {
589        read_reliable_header(r)
590    }
591}
592
593#[cfg(feature = "std")]
594static ADDRESS_BOOK: OnceLock<Mutex<BTreeMap<u32, Arc<str>>>> = OnceLock::new();
595
596#[cfg(feature = "std")]
597fn address_book() -> &'static Mutex<BTreeMap<u32, Arc<str>>> {
598    ADDRESS_BOOK.get_or_init(|| Mutex::new(BTreeMap::new()))
599}
600
601#[inline]
602pub(crate) fn source_address_for_sender(sender: &str) -> u32 {
603    let addr = sender_address_u32(sender);
604    remember_source_address(addr, sender);
605    addr
606}
607
608#[cfg(feature = "std")]
609pub(crate) fn remember_source_address(addr: u32, sender: &str) {
610    address_book()
611        .lock()
612        .expect("wire address book poisoned")
613        .entry(addr)
614        .or_insert_with(|| Arc::<str>::from(sender));
615}
616
617#[cfg(not(feature = "std"))]
618pub(crate) fn remember_source_address(_addr: u32, _sender: &str) {}
619
620#[cfg(feature = "std")]
621fn sender_name_for_address(addr: u32) -> Arc<str> {
622    address_book()
623        .lock()
624        .expect("wire address book poisoned")
625        .get(&addr)
626        .cloned()
627        .unwrap_or_else(|| format_sender_address(addr))
628}
629
630#[cfg(not(feature = "std"))]
631fn sender_name_for_address(addr: u32) -> Arc<str> {
632    format_sender_address(addr)
633}
634
635fn format_sender_address(addr: u32) -> Arc<str> {
636    // Format the numeric alias on the stack; only the retained Arc allocates.
637    let mut bytes = [0u8; 16];
638    let mut start = bytes.len();
639    let mut remaining = addr;
640    loop {
641        start -= 1;
642        bytes[start] = b'0' + (remaining % 10) as u8;
643        remaining /= 10;
644        if remaining == 0 {
645            break;
646        }
647    }
648    start -= 6;
649    bytes[start..start + 6].copy_from_slice(b"@addr:");
650    Arc::from(core::str::from_utf8(&bytes[start..]).expect("numeric alias is ASCII"))
651}
652
653// ===========================================================================
654// Endpoint bitmap constants and helpers
655// ===========================================================================
656
657/// Number of bits needed to cover all possible `DataEndpoint` discriminants.
658const EP_BITMAP_BITS: usize = 256;
659#[cfg(test)]
660use crate::MAX_VALUE_DATA_ENDPOINT;
661
662/// Number of bytes required to store [`EP_BITMAP_BITS`] bits.
663const EP_BITMAP_BYTES: usize = EP_BITMAP_BITS.div_ceil(8);
664
665/// Build a compact endpoint bitmap from the provided list of endpoints.
666///
667/// Each endpoint `ep` sets the bit at position `ep.as_u32()` in the bitmap.
668/// Bits are packed LSB-first within each byte.
669#[inline]
670fn build_endpoint_bitmap(eps: &[DataEndpoint]) -> [u8; EP_BITMAP_BYTES] {
671    let mut bm = [0u8; EP_BITMAP_BYTES];
672    for &ep in eps {
673        let idx = ep.as_u32() as usize;
674        debug_assert!(idx < EP_BITMAP_BITS, "endpoint discriminant out of range");
675        if idx < EP_BITMAP_BITS {
676            let byte = idx / 8;
677            let bit = idx % 8;
678            bm[byte] |= 1u8 << bit;
679        }
680    }
681    bm
682}
683
684/// Expand a bitmap into registered endpoints in ascending discriminant order.
685fn expand_endpoint_bitmap(bm: &[u8]) -> TelemetryResult<Arc<[DataEndpoint]>> {
686    if bm.len() != EP_BITMAP_BYTES {
687        return Err(TelemetryError::Unpack("bad endpoint bitmap size"));
688    }
689    // Only visit set bits. Sparse telemetry destinations should not initialize
690    // and copy a 256-element endpoint array on every header inspection.
691    let count = bitmap_popcount(bm);
692    let mut endpoints = Arc::<[DataEndpoint]>::new_uninit_slice(count);
693    let slots = Arc::get_mut(&mut endpoints).expect("new endpoint storage is unique");
694    let mut written = 0;
695    for (byte_index, &byte) in bm.iter().enumerate() {
696        let mut bits = byte;
697        while bits != 0 {
698            let idx = byte_index * 8 + bits.trailing_zeros() as usize;
699            slots[written].write(
700                DataEndpoint::try_from_u32(idx as u32)
701                    .ok_or(TelemetryError::Unpack("bad endpoint bit set"))?,
702            );
703            written += 1;
704            bits &= bits - 1;
705        }
706    }
707    // Every set bit initializes exactly one slot; errors drop uninitialized storage.
708    debug_assert_eq!(written, count);
709    Ok(unsafe { endpoints.assume_init() })
710}
711
712pub(crate) fn unique_sorted_endpoints(
713    endpoints: &[DataEndpoint],
714) -> impl Iterator<Item = DataEndpoint> + '_ {
715    let mut previous = None;
716    core::iter::from_fn(move || {
717        let next = endpoints
718            .iter()
719            .copied()
720            .filter(|endpoint| previous.is_none_or(|previous| *endpoint > previous))
721            .min();
722        // Retain the last maximum after exhaustion; subsequent calls remain
723        // exhausted without a separate state field or restarting the sequence.
724        previous = next.or(previous);
725        next
726    })
727}
728
729fn endpoint_arc_from_iter(
730    count: usize,
731    endpoints: impl Iterator<Item = DataEndpoint>,
732) -> TelemetryResult<Arc<[DataEndpoint]>> {
733    let mut output = Arc::<[DataEndpoint]>::new_uninit_slice(count);
734    let slots = Arc::get_mut(&mut output).unwrap();
735    let mut written = 0;
736    for endpoint in endpoints {
737        if written == count {
738            return Err(TelemetryError::Unpack("endpoint count mismatch"));
739        }
740        slots[written].write(endpoint);
741        written += 1;
742    }
743    if written != count {
744        return Err(TelemetryError::Unpack("endpoint count mismatch"));
745    }
746    // SAFETY: every slot was initialized exactly once above.
747    Ok(unsafe { output.assume_init() })
748}
749fn endpoint_list_size(eps: &[DataEndpoint]) -> usize {
750    unique_sorted_endpoints(eps)
751        .map(|ep| uleb128_size(u64::from(ep.0)))
752        .sum()
753}
754fn explicit_endpoint_list(eps: &[DataEndpoint]) -> bool {
755    eps.iter().any(|ep| ep.0 >= EP_BITMAP_BITS as u32) || endpoint_list_size(eps) < EP_BITMAP_BYTES
756}
757fn endpoints_match_schema(ty: DataType, eps: &[DataEndpoint]) -> bool {
758    let meta = message_meta(ty);
759    unique_sorted_endpoints(eps).eq(unique_sorted_endpoints(meta.endpoints_ref()))
760}
761fn read_endpoint_list<'a>(r: &mut ByteReader<'a>, count: usize) -> TelemetryResult<&'a [u8]> {
762    let start = r.off;
763    let mut previous = None;
764    for _ in 0..count {
765        let id = u32::try_from(read_uleb128(r)?)
766            .map_err(|_| TelemetryError::Unpack("endpoint too large"))?;
767        if previous.is_some_and(|previous| id <= previous) {
768            return Err(TelemetryError::Unpack(
769                "endpoint list is not unique and sorted",
770            ));
771        }
772        previous = Some(id);
773    }
774    Ok(&r.buf[start..r.off])
775}
776fn endpoint_list_iter(bytes: &[u8]) -> impl Iterator<Item = DataEndpoint> + '_ {
777    let mut r = ByteReader::new(bytes);
778    core::iter::from_fn(move || {
779        if r.remaining() == 0 {
780            return None;
781        }
782        read_uleb128(&mut r)
783            .ok()
784            .and_then(|id| u32::try_from(id).ok())
785            .map(DataEndpoint)
786    })
787}
788
789#[inline]
790fn schema_endpoints_from_type(ty: DataType, nep: usize) -> TelemetryResult<Arc<[DataEndpoint]>> {
791    // Match bitmap ordering and duplicate removal without expanding all 256
792    // possible destinations for the usual one-endpoint schema.
793    let meta = message_meta(ty);
794    let schema = meta.endpoints_ref();
795    if schema.len() == nep
796        && schema
797            .windows(2)
798            .all(|pair| pair[0].as_u32() < pair[1].as_u32())
799        && schema
800            .iter()
801            .all(|ep| DataEndpoint::try_from_u32(ep.as_u32()).is_some())
802    {
803        // Compiled/registered metadata already owns sorted endpoints on hosts;
804        // embedded metadata is static. Avoid a temporary Vec in either case.
805        #[cfg(feature = "std")]
806        return Ok(meta.endpoints);
807        #[cfg(not(feature = "std"))]
808        return Ok(Arc::from(schema));
809    }
810    endpoint_arc_from_iter(nep, unique_sorted_endpoints(schema))
811}
812
813#[inline]
814fn endpoints_from_wire_or_schema(
815    r: &mut ByteReader<'_>,
816    bitmap_present: bool,
817    list_present: bool,
818    ty: Option<DataType>,
819    nep: usize,
820) -> TelemetryResult<Arc<[DataEndpoint]>> {
821    if list_present {
822        if bitmap_present {
823            return Err(TelemetryError::Unpack("ambiguous endpoint encoding"));
824        }
825        let bytes = read_endpoint_list(r, nep)?;
826        #[cfg(feature = "std")]
827        if let Some(meta) = ty.and_then(crate::config::try_get_message_meta)
828            && endpoint_list_iter(bytes).eq(meta.endpoints.iter().copied())
829        {
830            return Ok(meta.endpoints);
831        }
832        return endpoint_arc_from_iter(nep, endpoint_list_iter(bytes));
833    }
834    if bitmap_present {
835        let bm = r.read_bytes(EP_BITMAP_BYTES)?;
836        let endpoints = expand_endpoint_bitmap(bm)?;
837        if endpoints.len() != nep {
838            return Err(TelemetryError::Unpack("endpoint count mismatch"));
839        }
840        Ok(endpoints)
841    } else {
842        let ty = ty.ok_or(TelemetryError::InvalidType)?;
843        schema_endpoints_from_type(ty, nep)
844    }
845}
846
847#[inline]
848fn data_type_id_from_wire(ty_v: u64) -> TelemetryResult<u32> {
849    let ty_u32 = u32::try_from(ty_v).map_err(|_| TelemetryError::Unpack("type too large"))?;
850    Ok(ty_u32)
851}
852
853// ===========================================================================
854// Packing
855// ===========================================================================
856
857/// Pack a [`Packet`] into the compact v2 wire format.
858///
859/// The returned `Arc<[u8]>` owns the packed bytes and can be shared cheaply.
860/// # Arguments
861/// - `pkt`: Telemetry packet to pack.
862///
863/// # Returns
864/// - `Arc<[u8]>`: Packed packet in compact v2 wire format.
865pub fn pack_packet(pkt: &Packet) -> Arc<[u8]> {
866    if is_reliable_type(pkt.data_type()) {
867        // Default to an unsequenced reliable header to keep the wire format consistent.
868        // Use `pack_packet_with_reliable` for ordered/retransmitted delivery.
869        let hdr = ReliableHeader {
870            flags: RELIABLE_FLAG_UNSEQUENCED,
871            seq: 0,
872            ack: 0,
873        };
874        return pack_packet_with_reliable(pkt, hdr);
875    }
876    pack_packet_inner(pkt, None)
877}
878
879/// Pack a [`Packet`] with an explicit reliable header.
880///
881/// This should be used for data types configured as `reliable` in the schema.
882pub fn pack_packet_with_reliable(pkt: &Packet, header: ReliableHeader) -> Arc<[u8]> {
883    pack_packet_inner(pkt, Some(header))
884}
885
886/// Pack a reliable ACK-only control frame for the given data type.
887///
888/// The resulting bytes are not a valid `Packet` and should be handled
889/// by the router's reliable layer.
890pub fn pack_reliable_ack(sender: &str, ty: DataType, timestamp_ms: u64, ack: u32) -> Arc<[u8]> {
891    let source_address = source_address_for_sender(sender);
892
893    // No payload for ACK-only control frames.
894    let mut out = Vec::with_capacity(32 + EP_BITMAP_BYTES + CRC32_BYTES);
895
896    let flags: u8 = FLAG_ENDPOINT_LIST_PRESENT | FLAG_RELIABLE_HEADER_PRESENT;
897    out.push(flags);
898    out.push(0u8); // NEP = 0
899
900    write_uleb128(ty.as_u32() as u64, &mut out);
901    write_uleb128(0u64, &mut out); // payload size
902    write_uleb128(timestamp_ms, &mut out);
903    write_uleb128(source_address as u64, &mut out);
904
905    let reliable = ReliableHeader {
906        flags: RELIABLE_FLAG_ACK_ONLY,
907        seq: 0,
908        ack,
909    };
910    if should_compact_reliable_header(reliable) {
911        out[0] |= FLAG_COMPACT_RELIABLE_HEADER;
912        write_reliable_header_encoded(reliable, true, &mut out);
913    } else {
914        write_reliable_header_encoded(reliable, false, &mut out);
915    }
916    append_crc32(&mut out);
917
918    Arc::<[u8]>::from(out)
919}
920
921fn pack_packet_inner(pkt: &Packet, reliable: Option<ReliableHeader>) -> Arc<[u8]> {
922    pack_packet_inner_with_contract(
923        pkt,
924        reliable,
925        pkt.wire_shape(),
926        pkt.wire_target_senders(),
927        None,
928    )
929    .expect("plaintext packet packing failed")
930}
931
932/// Pack `pkt` while explicitly controlling the wire-contract metadata.
933///
934/// Router and relay forwarding paths use this helper when they need to attach
935/// or preserve a migration-safe contract instead of simply serializing the
936/// packet against the current runtime schema/topology view.
937///
938/// # Parameters
939/// - `pkt`: Logical packet to pack.
940/// - `reliable`: Optional hop-level reliable header to append after the
941///   contract.
942/// - `shape`: Optional inline payload shape to encode into the contract so
943///   downstream unpackers can validate/decode the payload against the
944///   original shape.
945/// - `target_senders`: Frozen destination-holder sender hashes that keep
946///   in-flight routing bound to the intended holders.
947///
948/// # Returns
949/// - `Ok(Arc<[u8]>)` containing the packed frame bytes.
950/// - `Err(TelemetryError)` if contract encoding fails.
951pub(crate) fn pack_packet_with_wire_contract(
952    pkt: &Packet,
953    reliable: Option<ReliableHeader>,
954    shape: Option<MessageElement>,
955    target_senders: &[u64],
956) -> TelemetryResult<Arc<[u8]>> {
957    pack_packet_inner_with_contract(pkt, reliable, shape, target_senders, None)
958}
959
960#[derive(Clone, Copy, Debug)]
961#[cfg_attr(not(feature = "cryptography"), allow(dead_code))]
962pub(crate) struct E2eSealConfig {
963    pub key_id: u32,
964}
965
966#[cfg(feature = "cryptography")]
967pub(crate) fn pack_packet_with_wire_contract_e2e(
968    pkt: &Packet,
969    reliable: Option<ReliableHeader>,
970    shape: Option<MessageElement>,
971    target_senders: &[u64],
972    e2e: E2eSealConfig,
973) -> TelemetryResult<Arc<[u8]>> {
974    pack_packet_inner_with_contract(pkt, reliable, shape, target_senders, Some(e2e))
975}
976
977fn pack_packet_inner_with_contract(
978    pkt: &Packet,
979    reliable: Option<ReliableHeader>,
980    shape: Option<MessageElement>,
981    target_senders: &[u64],
982    e2e: Option<E2eSealConfig>,
983) -> TelemetryResult<Arc<[u8]>> {
984    with_packet_frame_parts(
985        pkt,
986        reliable,
987        shape,
988        target_senders,
989        e2e,
990        |header, payload| Ok(join_frame_with_crc(header, payload)),
991    )
992}
993
994/// Serialize the normal plaintext header while retaining the existing payload.
995/// Used by chunked internal discovery to avoid a second schema-sized buffer.
996pub(crate) fn with_plain_packet_parts<T>(
997    pkt: &Packet,
998    consume: impl FnOnce(&[u8], &[u8]) -> TelemetryResult<T>,
999) -> TelemetryResult<T> {
1000    let reliable = is_reliable_type(pkt.data_type()).then_some(ReliableHeader {
1001        flags: RELIABLE_FLAG_UNSEQUENCED,
1002        seq: 0,
1003        ack: 0,
1004    });
1005    with_packet_frame_parts(
1006        pkt,
1007        reliable,
1008        pkt.wire_shape(),
1009        pkt.wire_target_senders(),
1010        None,
1011        consume,
1012    )
1013}
1014
1015fn packet_endpoint_bitmap_present(
1016    pkt: &Packet,
1017    shape: Option<MessageElement>,
1018    target_senders: &[u64],
1019) -> bool {
1020    let carries_wire_contract = shape.is_some() || !target_senders.is_empty();
1021    let endpoints_are_schema_default = endpoints_match_schema(pkt.data_type(), pkt.endpoints());
1022    // Reliability controls have a protocol-defined endpoint on every peer;
1023    // their receipt contract does not require a second, 32-byte copy of it.
1024    // Runtime application types retain explicit endpoints with a frozen
1025    // contract, since their schemas may differ during discovery/rejoin.
1026    let fixed_control_endpoints = matches!(
1027        pkt.data_type(),
1028        DataType::ReliableAck | DataType::ReliablePartialAck | DataType::ReliablePacketRequest
1029    );
1030    // Application catalogs may be complementary or still converging. A short
1031    // explicit list preserves this packet's actual destinations in that case.
1032    pkt.data_type().0 > DataType::P2pMessage.0
1033        || !endpoints_are_schema_default
1034        || (carries_wire_contract && !fixed_control_endpoints)
1035}
1036
1037fn with_packet_frame_parts<T>(
1038    pkt: &Packet,
1039    reliable: Option<ReliableHeader>,
1040    shape: Option<MessageElement>,
1041    target_senders: &[u64],
1042    #[cfg_attr(not(feature = "cryptography"), allow(unused_variables))] e2e: Option<E2eSealConfig>,
1043    consume: impl FnOnce(&[u8], &[u8]) -> TelemetryResult<T>,
1044) -> TelemetryResult<T> {
1045    let carries_wire_contract = shape.is_some() || !target_senders.is_empty();
1046    let endpoint_bitmap_present = packet_endpoint_bitmap_present(pkt, shape, target_senders);
1047    let endpoint_list_present = endpoint_bitmap_present && explicit_endpoint_list(pkt.endpoints());
1048    let nep_unique = unique_sorted_endpoints(pkt.endpoints()).count();
1049    let endpoint_bytes = if endpoint_list_present {
1050        endpoint_list_size(pkt.endpoints())
1051    } else if endpoint_bitmap_present {
1052        EP_BITMAP_BYTES
1053    } else {
1054        0
1055    };
1056
1057    let source_address = source_address_for_sender(pkt.sender());
1058
1059    // Decide whether to compress the payload.
1060    let payload = pkt.payload();
1061    let (payload_compressed, payload_wire) = payload_compression::compress_if_beneficial(payload);
1062
1063    // Size the variable-length prefix exactly. A 16-byte estimate can be
1064    // too small for real timestamps/nonces, doubling a multi-KiB schema
1065    // buffer while its payload and the old allocation are still retained.
1066    let reliable_is_compact = reliable.is_some_and(should_compact_reliable_header);
1067    let reliable_len = if let Some(hdr) = reliable {
1068        reliable_wire_size(hdr, reliable_is_compact)
1069    } else {
1070        0
1071    };
1072    let contract_bytes = wire_contract_size(shape, target_senders);
1073    let contract_len = if carries_wire_contract {
1074        uleb128_size(contract_bytes as u64) + contract_bytes
1075    } else {
1076        0
1077    };
1078    let capacity = header_size_bytes(pkt)
1079        + endpoint_bytes
1080        + contract_len
1081        + reliable_len
1082        + payload_wire.len()
1083        + CRC32_BYTES;
1084    #[cfg(feature = "cryptography")]
1085    let capacity = capacity
1086        + e2e.map_or(0, |seal| {
1087            uleb128_size(u64::from(seal.key_id))
1088                + uleb128_size(payload_wire.len() as u64)
1089                + uleb128_size(E2E_NONCE_LEN as u64)
1090                + E2E_NONCE_LEN
1091                + uleb128_size(E2E_TAG_CAP as u64)
1092                + E2E_TAG_CAP
1093        });
1094    // Plain frames need only a small header scratch buffer. Construct the
1095    // final Arc directly: Vec -> Arc otherwise retains two frame-sized
1096    // allocations alongside the schema payload on embedded routers.
1097    #[cfg(feature = "cryptography")]
1098    let encrypted = e2e.is_some();
1099    #[cfg(not(feature = "cryptography"))]
1100    let encrypted = false;
1101    let scratch_capacity = if encrypted {
1102        capacity
1103    } else {
1104        capacity - payload_wire.len() - CRC32_BYTES
1105    };
1106    let mut out = Vec::with_capacity(scratch_capacity);
1107    #[cfg(debug_assertions)]
1108    let initial_capacity = out.capacity();
1109
1110    // FLAGS byte
1111    let mut flags: u8 = 0;
1112    if payload_compressed {
1113        flags |= FLAG_COMPRESSED_PAYLOAD;
1114    }
1115    if carries_wire_contract {
1116        flags |= FLAG_WIRE_CONTRACT;
1117    }
1118    if pkt.nonce() != 0 {
1119        flags |= FLAG_PACKET_NONCE;
1120    }
1121    if endpoint_list_present {
1122        flags |= FLAG_ENDPOINT_LIST_PRESENT;
1123    } else if endpoint_bitmap_present {
1124        flags |= FLAG_ENDPOINT_BITMAP_PRESENT;
1125    }
1126    if reliable.is_some() {
1127        flags |= FLAG_RELIABLE_HEADER_PRESENT;
1128    }
1129    if reliable_is_compact {
1130        flags |= FLAG_COMPACT_RELIABLE_HEADER;
1131    }
1132    #[cfg(feature = "cryptography")]
1133    if e2e.is_some() {
1134        flags |= FLAG_E2E_ENCRYPTED_PAYLOAD;
1135    }
1136    out.push(flags);
1137
1138    assert!(
1139        nep_unique <= u8::MAX as usize,
1140        "too many endpoints selected to fit in NEP u8"
1141    );
1142    out.push(nep_unique as u8);
1143
1144    // NOTE: data_size is the *logical* (uncompressed) payload size.
1145    write_uleb128(pkt.data_type().as_u32() as u64, &mut out);
1146    write_uleb128(pkt.data_size() as u64, &mut out);
1147    write_uleb128(pkt.timestamp(), &mut out);
1148    if pkt.nonce() != 0 {
1149        write_uleb128(pkt.nonce() as u64, &mut out);
1150    }
1151
1152    write_uleb128(source_address as u64, &mut out);
1153
1154    if endpoint_list_present {
1155        for endpoint in unique_sorted_endpoints(pkt.endpoints()) {
1156            write_uleb128(u64::from(endpoint.0), &mut out);
1157        }
1158    } else if endpoint_bitmap_present {
1159        out.extend_from_slice(&build_endpoint_bitmap(pkt.endpoints()));
1160    }
1161    if (flags & FLAG_WIRE_CONTRACT) != 0 {
1162        // The contract must appear before the reliable header because it may
1163        // carry the "reliable header present" bit for packets whose current
1164        // runtime schema lookup no longer reflects the original wire semantics.
1165        write_uleb128(contract_bytes as u64, &mut out);
1166        write_wire_contract(shape, target_senders, reliable.is_some(), &mut out)?;
1167    }
1168    if let Some(hdr) = reliable {
1169        write_reliable_header_encoded(hdr, reliable_is_compact, &mut out);
1170    }
1171    #[cfg(feature = "cryptography")]
1172    if let Some(e2e) = e2e {
1173        write_encrypted_payload(pkt, e2e.key_id, &payload_wire, &mut out)?;
1174        return consume(&out, &[]);
1175    }
1176    #[cfg(debug_assertions)]
1177    debug_assert_eq!(
1178        out.capacity(),
1179        initial_capacity,
1180        "packet header grew its buffer"
1181    );
1182    consume(&out, &payload_wire)
1183}
1184
1185// ===========================================================================
1186// Unpacking (full packet)
1187// ===========================================================================
1188
1189/// Unpack a full [`Packet`] from a packed v2 wire frame.
1190///
1191/// This validates the frame CRC, resolves the endpoint set, decodes the
1192/// optional migration-safe wire contract, parses the optional reliable header,
1193/// and reconstructs the logical `Packet`. When the frame carries an inline wire
1194/// shape, the returned packet preserves that shape so payload validation and
1195/// formatting remain stable even if the local runtime schema has changed since
1196/// the packet was originally packed.
1197///
1198/// # Parameters
1199/// - `buf`: Complete packed frame bytes, including the CRC32 trailer.
1200///
1201/// # Returns
1202/// - `Ok(Packet)` when the frame is well-formed and contains a payload-bearing
1203///   telemetry packet.
1204///
1205/// # Errors
1206/// - [`TelemetryError::Unpack`] if the frame is malformed, truncated, or
1207///   fails CRC validation.
1208/// - [`TelemetryError::InvalidType`] if the type ID is not valid and the frame
1209///   does not carry enough inline shape information to keep decoding it.
1210pub fn unpack_packet(buf: &[u8]) -> Result<Packet, TelemetryError> {
1211    let data = verify_crc32(buf)?;
1212    if data.is_empty() {
1213        return Err(TelemetryError::Unpack("short prelude"));
1214    }
1215    let mut r = ByteReader::new(data);
1216
1217    let flags = r.read_bytes(1)?[0];
1218    let payload_is_compressed = (flags & FLAG_COMPRESSED_PAYLOAD) != 0;
1219    let endpoint_bitmap_present = (flags & FLAG_ENDPOINT_BITMAP_PRESENT) != 0;
1220    let compact_reliable_header = (flags & FLAG_COMPACT_RELIABLE_HEADER) != 0;
1221    #[cfg(feature = "cryptography")]
1222    let payload_is_encrypted = (flags & FLAG_E2E_ENCRYPTED_PAYLOAD) != 0;
1223    #[cfg(not(feature = "cryptography"))]
1224    if (flags & 0x10) != 0 {
1225        return Err(TelemetryError::Unpack("e2e crypto unsupported"));
1226    }
1227
1228    let nep = r.read_bytes(1)?[0] as usize;
1229
1230    let ty_v = read_uleb128(&mut r)?;
1231    let dsz = read_uleb128(&mut r)? as usize; // logical (uncompressed) payload size
1232    let ts_v = read_uleb128(&mut r)?;
1233    let nonce = if (flags & FLAG_PACKET_NONCE) != 0 {
1234        u16::try_from(read_uleb128(&mut r)?)
1235            .map_err(|_| TelemetryError::Unpack("packet nonce too large"))?
1236    } else {
1237        0
1238    };
1239    let source_address = u32::try_from(read_uleb128(&mut r)?)
1240        .map_err(|_| TelemetryError::Unpack("source address too large"))?;
1241    let sender_str = sender_name_for_address(source_address);
1242    let ty_u32 = data_type_id_from_wire(ty_v)?;
1243    let known_ty = DataType::try_from_u32(ty_u32);
1244    let endpoint_bytes = if endpoint_bitmap_present {
1245        EP_BITMAP_BYTES
1246    } else {
1247        0
1248    };
1249
1250    // For uncompressed payload: bitmap + [contract] + [reliable] + payload(dsz)
1251    // For compressed payload: bitmap + [contract] + [reliable] + at least 1 byte.
1252    if !payload_is_compressed {
1253        if r.remaining() < endpoint_bytes + dsz {
1254            return Err(TelemetryError::Unpack("short buffer"));
1255        }
1256    } else if r.remaining() < endpoint_bytes + 1 {
1257        return Err(TelemetryError::Unpack("short buffer"));
1258    }
1259
1260    let eps = endpoints_from_wire_or_schema(
1261        &mut r,
1262        endpoint_bitmap_present,
1263        flags & FLAG_ENDPOINT_LIST_PRESENT != 0,
1264        known_ty,
1265        nep,
1266    )?;
1267
1268    let contract = decode_wire_contract(&mut r, (flags & FLAG_WIRE_CONTRACT) != 0)?;
1269    let ty = known_ty
1270        .or_else(|| contract.shape.map(|_| DataType(ty_u32)))
1271        .ok_or(TelemetryError::InvalidType)?;
1272
1273    // ----- Reliable header (optional) -----
1274    let mut reliable_hdr: Option<ReliableHeader> = None;
1275    if flags & FLAG_RELIABLE_HEADER_PRESENT != 0 || contract.has_reliable_header {
1276        let hdr = read_reliable_header_encoded(&mut r, compact_reliable_header)?;
1277        if (hdr.flags & RELIABLE_FLAG_ACK_ONLY) != 0 {
1278            return Err(TelemetryError::Unpack("reliable control frame"));
1279        }
1280        reliable_hdr = Some(hdr);
1281    }
1282
1283    // Reassembled side frames bypass the small-fragment ingress estimate.
1284    // Check again immediately before allocating their logical payload, including
1285    // decompression/decryption scratch when enabled.
1286    let payload_copies = if payload_is_compressed { 3 } else { 1 };
1287    #[cfg(feature = "cryptography")]
1288    let payload_copies = payload_copies + usize::from(payload_is_encrypted);
1289    let small_ack = matches!(ty, DataType::ReliableAck | DataType::ReliablePartialAck)
1290        && dsz <= 32
1291        && payload_copies == 1;
1292    crate::memory_admission::check(
1293        if small_ack {
1294            512
1295        } else {
1296            dsz.saturating_mul(payload_copies).saturating_add(512)
1297        },
1298        dsz.saturating_add(32),
1299    )?;
1300    // ----- Payload handling -----
1301    let payload: StandardSmallPayload = {
1302        #[cfg(feature = "cryptography")]
1303        let payload_wire_owned;
1304        #[cfg(feature = "cryptography")]
1305        let payload_wire: &[u8] = if payload_is_encrypted {
1306            let aad_end = r.off;
1307            payload_wire_owned = read_encrypted_payload(&mut r, &data[..aad_end], dsz)?;
1308            &payload_wire_owned
1309        } else if !payload_is_compressed {
1310            r.read_bytes(dsz)?
1311        } else {
1312            let comp_len = r.remaining();
1313            r.read_bytes(comp_len)?
1314        };
1315
1316        #[cfg(not(feature = "cryptography"))]
1317        let payload_wire: &[u8] = if !payload_is_compressed {
1318            r.read_bytes(dsz)?
1319        } else {
1320            let comp_len = r.remaining();
1321            r.read_bytes(comp_len)?
1322        };
1323
1324        if payload_is_compressed {
1325            let decompressed = payload_compression::decompress(payload_wire, dsz)?;
1326            crate::memory_admission::check(dsz.saturating_add(512), dsz.saturating_add(32))?;
1327            StandardSmallPayload::new(&decompressed)
1328        } else {
1329            if payload_wire.len() != dsz {
1330                return Err(TelemetryError::Unpack("payload length mismatch"));
1331            }
1332            StandardSmallPayload::new(payload_wire)
1333        }
1334    };
1335
1336    // `Packet` preserves logical payload data plus wire-contract metadata, but
1337    // not hop-level reliable transport state. The router/relay reliable layer
1338    // consumes that header before handing the logical packet onward.
1339    let _ = reliable_hdr;
1340    Packet::new_with_owned_wire_contract(
1341        ty,
1342        eps,
1343        sender_str,
1344        ts_v,
1345        nonce,
1346        payload,
1347        contract.shape,
1348        contract.target_senders,
1349    )
1350}
1351
1352// ===========================================================================
1353// Peek / envelope-only decode
1354// ===========================================================================
1355
1356/// Decode only the routing-relevant envelope of a packed packet.
1357///
1358/// This reads enough of the frame to expose type, endpoints, sender, timestamp,
1359/// and any migration-safe contract metadata without touching payload bytes.
1360/// That makes it the fast path for routing and other header-only inspection.
1361///
1362/// # Parameters
1363/// - `buf`: Complete packed frame bytes, including the CRC32 trailer.
1364///
1365/// # Returns
1366/// - `Ok(TelemetryEnvelope)` containing the logical packet envelope plus any
1367///   inline wire-shape and target-sender metadata.
1368///
1369/// # Errors
1370/// - [`TelemetryError::Unpack`] if the frame is malformed or fails CRC.
1371/// - [`TelemetryError::InvalidType`] if the type ID cannot be resolved.
1372pub fn peek_envelope(buf: &[u8]) -> TelemetryResult<TelemetryEnvelope> {
1373    Ok(peek_routing_envelope(buf)?.into_owned())
1374}
1375
1376/// Validated routing metadata without owned strings or heap-backed arrays.
1377/// The fixed bitmap is normalized against the current schema on every parse;
1378/// nothing is cached across schema updates or packet lifetimes.
1379#[derive(Clone, Debug)]
1380pub(crate) struct RoutingEnvelope<'a> {
1381    pub ty: DataType,
1382    bitmap: [u64; EP_BITMAP_BYTES / 8],
1383    endpoint_list: Option<&'a [u8]>,
1384    schema_endpoints: Option<crate::MessageMeta>,
1385    pub source_address: u32,
1386    pub timestamp_ms: u64,
1387    pub wire_shape: Option<MessageElement>,
1388    pub is_reliable: bool,
1389    targets: &'a [u8],
1390    has_reliable_header: bool,
1391}
1392pub(crate) struct RoutingEndpointIter<'a> {
1393    envelope: &'a RoutingEnvelope<'a>,
1394    word: usize,
1395    bits: u64,
1396    list_offset: usize,
1397    previous: Option<DataEndpoint>,
1398    finished: bool,
1399}
1400impl Iterator for RoutingEndpointIter<'_> {
1401    type Item = DataEndpoint;
1402    #[inline(never)]
1403    fn next(&mut self) -> Option<DataEndpoint> {
1404        if self.finished {
1405            return None;
1406        }
1407        if let Some(bytes) = self.envelope.endpoint_list {
1408            let mut reader = ByteReader {
1409                buf: bytes,
1410                off: self.list_offset,
1411            };
1412            if reader.remaining() == 0 {
1413                self.finished = true;
1414                return None;
1415            }
1416            let endpoint = read_uleb128(&mut reader)
1417                .ok()
1418                .and_then(|id| u32::try_from(id).ok())
1419                .map(DataEndpoint);
1420            self.list_offset = reader.off;
1421            return endpoint;
1422        }
1423        if let Some(meta) = &self.envelope.schema_endpoints {
1424            let next = meta
1425                .endpoints_ref()
1426                .iter()
1427                .copied()
1428                .filter(|ep| self.previous.is_none_or(|previous| *ep > previous))
1429                .min();
1430            self.previous = next;
1431            self.finished = next.is_none();
1432            return next;
1433        }
1434        while self.bits == 0 {
1435            self.word += 1;
1436            if self.word == self.envelope.bitmap.len() {
1437                self.finished = true;
1438                return None;
1439            }
1440            self.bits = self.envelope.bitmap[self.word];
1441        }
1442        let bit = self.bits.trailing_zeros();
1443        self.bits &= self.bits - 1;
1444        Some(DataEndpoint((self.word * 64 + bit as usize) as u32))
1445    }
1446}
1447
1448impl RoutingEnvelope<'_> {
1449    pub fn endpoints(&self) -> RoutingEndpointIter<'_> {
1450        RoutingEndpointIter {
1451            envelope: self,
1452            word: 0,
1453            bits: self.bitmap[0],
1454            list_offset: 0,
1455            previous: None,
1456            finished: false,
1457        }
1458    }
1459    pub fn target_senders(&self) -> impl ExactSizeIterator<Item = u64> + '_ {
1460        self.targets
1461            .as_chunks::<8>()
1462            .0
1463            .iter()
1464            .map(|bytes| u64::from_le_bytes(*bytes))
1465    }
1466    fn into_owned(self) -> TelemetryEnvelope {
1467        TelemetryEnvelope {
1468            ty: self.ty,
1469            endpoints: self.endpoints().collect::<Arc<[_]>>(),
1470            sender: sender_name_for_address(self.source_address),
1471            source_address: self.source_address,
1472            timestamp_ms: self.timestamp_ms,
1473            wire_shape: self.wire_shape,
1474            target_senders: self.target_senders().collect::<Arc<[_]>>(),
1475        }
1476    }
1477}
1478
1479fn read_routing_envelope<'a>(r: &mut ByteReader<'a>) -> TelemetryResult<RoutingEnvelope<'a>> {
1480    let flags = r.read_bytes(1)?[0];
1481    let nep = r.read_bytes(1)?[0] as usize;
1482    let ty_v = read_uleb128(r)?;
1483    let _data_size = read_uleb128(r)?;
1484    let timestamp_ms = read_uleb128(r)?;
1485    if flags & FLAG_PACKET_NONCE != 0 {
1486        let _ = read_uleb128(r)?;
1487    }
1488    let source_address = u32::try_from(read_uleb128(r)?)
1489        .map_err(|_| TelemetryError::Unpack("source address too large"))?;
1490    let ty_u32 = data_type_id_from_wire(ty_v)?;
1491    let metadata = crate::config::try_get_message_meta(DataType(ty_u32));
1492    let known_ty = metadata.as_ref().map(|_| DataType(ty_u32));
1493    let is_reliable = flags & FLAG_RELIABLE_HEADER_PRESENT != 0;
1494    // Word-sized bitmaps avoid repeatedly scanning 32 individual bytes for
1495    // the usual one-destination telemetry frame on size-optimized MCUs.
1496    let mut bitmap = [0u64; EP_BITMAP_BYTES / 8];
1497    let mut endpoint_list = None;
1498    let mut schema_endpoints = None;
1499    if flags & FLAG_ENDPOINT_LIST_PRESENT != 0 {
1500        if flags & FLAG_ENDPOINT_BITMAP_PRESENT != 0 {
1501            return Err(TelemetryError::Unpack("ambiguous endpoint encoding"));
1502        }
1503        let bytes = read_endpoint_list(r, nep)?;
1504        endpoint_list = Some(bytes);
1505    } else if flags & FLAG_ENDPOINT_BITMAP_PRESENT != 0 {
1506        let bytes = r.read_bytes(EP_BITMAP_BYTES)?;
1507        for (word, chunk) in bitmap.iter_mut().zip(bytes.as_chunks::<8>().0) {
1508            *word = u64::from_le_bytes(*chunk);
1509        }
1510        if bitmap
1511            .iter()
1512            .map(|word| word.count_ones() as usize)
1513            .sum::<usize>()
1514            != nep
1515        {
1516            return Err(TelemetryError::Unpack("endpoint count mismatch"));
1517        }
1518        for (index, &word) in bitmap.iter().enumerate() {
1519            let mut bits = word;
1520            while bits != 0 {
1521                let id = index * 64 + bits.trailing_zeros() as usize;
1522                if !crate::config::endpoint_exists(DataEndpoint(id as u32)) {
1523                    return Err(TelemetryError::Unpack("bad endpoint bit set"));
1524                }
1525                bits &= bits - 1;
1526            }
1527        }
1528    } else {
1529        let meta = metadata.ok_or(TelemetryError::InvalidType)?;
1530        if unique_sorted_endpoints(meta.endpoints_ref()).count() != nep {
1531            return Err(TelemetryError::Unpack("endpoint count mismatch"));
1532        }
1533        schema_endpoints = Some(meta);
1534    }
1535    let mut shape = None;
1536    let mut targets: &'a [u8] = &[];
1537    let mut has_reliable_header = false;
1538    if flags & FLAG_WIRE_CONTRACT != 0 {
1539        let len = usize::try_from(read_uleb128(r)?)
1540            .map_err(|_| TelemetryError::Unpack("wire contract length"))?;
1541        let mut cr = ByteReader::new(r.read_bytes(len)?);
1542        let contract_flags = cr.read_bytes(1)?[0];
1543        if contract_flags & CONTRACT_FLAG_SHAPE != 0 {
1544            shape = Some(decode_wire_shape(&mut cr)?);
1545        }
1546        if contract_flags & CONTRACT_FLAG_TARGETS != 0 {
1547            let count = usize::try_from(read_uleb128(&mut cr)?)
1548                .map_err(|_| TelemetryError::Unpack("wire contract target count"))?;
1549            let bytes = count
1550                .checked_mul(8)
1551                .ok_or(TelemetryError::Unpack("wire contract target count"))?;
1552            targets = cr.read_bytes(bytes)?;
1553        }
1554        if cr.remaining() != 0 {
1555            return Err(TelemetryError::Unpack("wire contract trailing bytes"));
1556        }
1557        has_reliable_header = contract_flags & CONTRACT_FLAG_RELIABLE_HEADER != 0;
1558    }
1559    if nep == 0 {
1560        if !is_reliable && !has_reliable_header {
1561            return Err(TelemetryError::EmptyEndpoints);
1562        }
1563        let mut header = ByteReader {
1564            buf: r.buf,
1565            off: r.off,
1566        };
1567        let reliable =
1568            read_reliable_header_encoded(&mut header, flags & FLAG_COMPACT_RELIABLE_HEADER != 0)?;
1569        if reliable.flags & RELIABLE_FLAG_ACK_ONLY == 0 {
1570            return Err(TelemetryError::EmptyEndpoints);
1571        }
1572    }
1573    let ty = known_ty.unwrap_or(DataType(ty_u32));
1574    Ok(RoutingEnvelope {
1575        ty,
1576        bitmap,
1577        endpoint_list,
1578        schema_endpoints,
1579        source_address,
1580        timestamp_ms,
1581        wire_shape: shape,
1582        is_reliable,
1583        targets,
1584        has_reliable_header,
1585    })
1586}
1587
1588/// Read only the bounded type prefix for queue scheduling. This is deliberately
1589/// not frame validation: dispatch must still verify CRC and the full envelope.
1590/// Scanning an RX queue must not checksum every retained payload on each pass.
1591pub(crate) fn scheduling_type(buf: &[u8]) -> Option<DataType> {
1592    let mut reader = ByteReader::new(buf.get(..buf.len().min(12))?);
1593    reader.read_bytes(2).ok()?;
1594    let id = data_type_id_from_wire(read_uleb128(&mut reader).ok()?).ok()?;
1595    DataType::try_from_u32(id)
1596}
1597
1598pub(crate) fn peek_routing_envelope(buf: &[u8]) -> TelemetryResult<RoutingEnvelope<'_>> {
1599    let data = verify_crc32(buf)?;
1600    read_routing_envelope(&mut ByteReader::new(data))
1601}
1602
1603/// Decode the header/envelope and optional reliable header without touching the payload.
1604pub struct TelemetryFrameInfo {
1605    pub envelope: TelemetryEnvelope,
1606    pub reliable: Option<ReliableHeader>,
1607}
1608
1609impl TelemetryFrameInfo {
1610    #[inline]
1611    /// Returns `true` when the frame carries only a reliable-delivery acknowledgment.
1612    pub fn ack_only(&self) -> bool {
1613        self.reliable
1614            .map(|h| (h.flags & RELIABLE_FLAG_ACK_ONLY) != 0)
1615            .unwrap_or(false)
1616    }
1617}
1618
1619pub(crate) struct RoutingFrameInfo<'a> {
1620    pub envelope: RoutingEnvelope<'a>,
1621    pub reliable: Option<ReliableHeader>,
1622}
1623impl RoutingFrameInfo<'_> {
1624    pub fn ack_only(&self) -> bool {
1625        self.reliable
1626            .is_some_and(|header| header.flags & RELIABLE_FLAG_ACK_ONLY != 0)
1627    }
1628}
1629/// Borrow a complete, uncompressed schema without allocating its envelope or payload.
1630/// Other packet kinds retain the ordinary decode and reliable-delivery path.
1631#[cfg(all(feature = "discovery", not(feature = "std")))]
1632pub(crate) fn peek_plain_schema_payload(buf: &[u8]) -> TelemetryResult<Option<(u32, &[u8])>> {
1633    // Avoid a second CRC pass for ordinary telemetry. Its existing receive
1634    // and decode path remains responsible for complete frame validation.
1635    let mut prelude = ByteReader::new(buf);
1636    prelude.read_bytes(2)?;
1637    if data_type_id_from_wire(read_uleb128(&mut prelude)?)? != DataType::DiscoverySchema.as_u32() {
1638        return Ok(None);
1639    }
1640    let data = verify_crc32(buf)?;
1641    let mut reader = ByteReader::new(data);
1642    let envelope = read_routing_envelope(&mut reader)?;
1643    if envelope.ty != DataType::DiscoverySchema
1644        || data[0] & (FLAG_COMPRESSED_PAYLOAD | 0x10) != 0
1645        || envelope.target_senders().len() != 0
1646        || envelope
1647            .wire_shape
1648            .is_some_and(|shape| shape != crate::message_meta(DataType::DiscoverySchema).element)
1649    {
1650        return Ok(None);
1651    }
1652    if envelope.is_reliable || envelope.has_reliable_header {
1653        let reliable =
1654            read_reliable_header_encoded(&mut reader, data[0] & FLAG_COMPACT_RELIABLE_HEADER != 0)?;
1655        // Only the normal unsequenced broadcast snapshot is a no-op. A
1656        // sequenced snapshot or piggyback ACK still needs reliable processing.
1657        if reliable.flags != RELIABLE_FLAG_UNSEQUENCED || reliable.seq != 0 || reliable.ack != 0 {
1658            return Ok(None);
1659        }
1660    }
1661    // The routing parser already validated endpoints and any inline contract.
1662    // Recover the logical size from the short prelude without owning arrays.
1663    let mut prelude = ByteReader::new(data);
1664    prelude.read_bytes(2)?;
1665    read_uleb128(&mut prelude)?;
1666    let size = usize::try_from(read_uleb128(&mut prelude)?)
1667        .map_err(|_| TelemetryError::Unpack("schema payload too large"))?;
1668    if reader.remaining() != size {
1669        return Err(TelemetryError::Unpack("schema payload length mismatch"));
1670    }
1671    Ok(Some((envelope.source_address, reader.read_bytes(size)?)))
1672}
1673
1674pub(crate) fn peek_routing_frame_info(buf: &[u8]) -> TelemetryResult<RoutingFrameInfo<'_>> {
1675    let data = verify_crc32(buf)?;
1676    let mut reader = ByteReader::new(data);
1677    let envelope = read_routing_envelope(&mut reader)?;
1678    let reliable = if envelope.is_reliable || envelope.has_reliable_header {
1679        Some(read_reliable_header_encoded(
1680            &mut reader,
1681            data[0] & FLAG_COMPACT_RELIABLE_HEADER != 0,
1682        )?)
1683    } else {
1684        None
1685    };
1686    Ok(RoutingFrameInfo { envelope, reliable })
1687}
1688
1689fn peek_frame_info_inner(buf: &[u8]) -> TelemetryResult<TelemetryFrameInfo> {
1690    let mut r = ByteReader::new(buf);
1691    let header = read_routing_envelope(&mut r)?;
1692    let reliable = if header.is_reliable || header.has_reliable_header {
1693        Some(read_reliable_header_encoded(
1694            &mut r,
1695            buf[0] & FLAG_COMPACT_RELIABLE_HEADER != 0,
1696        )?)
1697    } else {
1698        None
1699    };
1700    Ok(TelemetryFrameInfo {
1701        envelope: header.into_owned(),
1702        reliable,
1703    })
1704}
1705
1706/// Peek the envelope plus reliable header (if present) without decoding payload bytes.
1707///
1708/// This is the primary router/relay fast path for reliable-layer decisions on
1709/// packed traffic. It still validates the frame CRC before exposing any
1710/// information.
1711pub fn peek_frame_info(buf: &[u8]) -> TelemetryResult<TelemetryFrameInfo> {
1712    let data = verify_crc32(buf)?;
1713    peek_frame_info_inner(data)
1714}
1715
1716/// Peek the envelope plus reliable header (if present) without validating CRC32.
1717///
1718/// This is intended only for internal call sites that have already validated
1719/// frame integrity or intentionally want best-effort inspection of partially
1720/// trusted bytes.
1721pub fn peek_frame_info_unchecked(buf: &[u8]) -> TelemetryResult<TelemetryFrameInfo> {
1722    let (data, _crc) = split_crc32(buf)?;
1723    peek_frame_info_inner(data)
1724}
1725
1726/// Locate the reliable-header byte offset within a packed frame.
1727///
1728/// The offset is computed after walking the source address and optional wire
1729/// contract. This matters because the contract can explicitly state that a
1730/// reliable header is present even if the current runtime schema no longer
1731/// marks the type as reliable.
1732///
1733/// # Parameters
1734/// - `buf`: Packed frame bytes, including the CRC32 trailer.
1735///
1736/// # Returns
1737/// - `Ok(Some(offset))` when a reliable header is present.
1738/// - `Ok(None)` when the frame carries no reliable header.
1739/// - `Err(TelemetryError)` when the frame is malformed.
1740pub fn reliable_header_offset(buf: &[u8]) -> TelemetryResult<Option<usize>> {
1741    Ok(reliable_header_span(buf)?.map(|(off, _, _)| off))
1742}
1743
1744pub(crate) fn reliable_header_span(
1745    buf: &[u8],
1746) -> TelemetryResult<Option<(usize, usize, ReliableHeader)>> {
1747    if buf.len() < CRC32_BYTES + 1 {
1748        return Err(TelemetryError::Unpack("short prelude"));
1749    }
1750    let data_len = buf.len().saturating_sub(CRC32_BYTES);
1751    let mut r = ByteReader::new(&buf[..data_len]);
1752
1753    let flags = r.read_bytes(1)?[0];
1754    let endpoint_bitmap_present = (flags & FLAG_ENDPOINT_BITMAP_PRESENT) != 0;
1755    let compact_reliable_header = (flags & FLAG_COMPACT_RELIABLE_HEADER) != 0;
1756
1757    let nep = r.read_bytes(1)?[0] as usize;
1758
1759    let ty_v = read_uleb128(&mut r)?;
1760    let _dsz = read_uleb128(&mut r)? as usize;
1761    let _ts_v = read_uleb128(&mut r)?;
1762    if (flags & FLAG_PACKET_NONCE) != 0 {
1763        let _ = read_uleb128(&mut r)?;
1764    }
1765    let _source_address = u32::try_from(read_uleb128(&mut r)?)
1766        .map_err(|_| TelemetryError::Unpack("source address too large"))?;
1767    let endpoint_bytes = if endpoint_bitmap_present {
1768        EP_BITMAP_BYTES
1769    } else {
1770        0
1771    };
1772
1773    if r.remaining() < endpoint_bytes {
1774        return Err(TelemetryError::Unpack("short buffer"));
1775    }
1776
1777    if flags & FLAG_ENDPOINT_LIST_PRESENT != 0 {
1778        if endpoint_bitmap_present {
1779            return Err(TelemetryError::Unpack("ambiguous endpoint encoding"));
1780        }
1781        read_endpoint_list(&mut r, nep)?;
1782    } else if endpoint_bitmap_present {
1783        r.read_bytes(EP_BITMAP_BYTES)?;
1784    }
1785    let contract = decode_wire_contract(&mut r, (flags & FLAG_WIRE_CONTRACT) != 0)?;
1786    let ty_u32 = data_type_id_from_wire(ty_v)?;
1787    let _ty = DataType(ty_u32);
1788    if flags & FLAG_RELIABLE_HEADER_PRESENT == 0 && !contract.has_reliable_header {
1789        return Ok(None);
1790    }
1791
1792    let off = r.off;
1793    let hdr = read_reliable_header_encoded(&mut r, compact_reliable_header)?;
1794    Ok(Some((off, r.off - off, hdr)))
1795}
1796
1797/// Rewrite the reliable header in-place and refresh the frame CRC32.
1798///
1799/// This avoids reserializing the entire packet when reliable transport code
1800/// only needs to change sequence/ACK state in an already-built frame.
1801///
1802/// # Parameters
1803/// - `buf`: Mutable packed frame bytes.
1804/// - `flags`: Replacement reliable-header flags byte.
1805/// - `seq`: Replacement sequence number.
1806/// - `ack`: Replacement cumulative ACK value.
1807///
1808/// # Returns
1809/// - `Ok(true)` if the frame carried a reliable header and it was rewritten.
1810/// - `Ok(false)` if no reliable header is present.
1811/// - `Err(TelemetryError)` if the frame is malformed.
1812pub fn rewrite_reliable_header(
1813    buf: &mut [u8],
1814    flags: u8,
1815    seq: u32,
1816    ack: u32,
1817) -> TelemetryResult<bool> {
1818    let Some((off, old_len, _)) = reliable_header_span(buf)? else {
1819        return Ok(false);
1820    };
1821    let hdr = ReliableHeader { flags, seq, ack };
1822    let compact = should_compact_reliable_header(hdr);
1823    if reliable_wire_size(hdr, compact) != old_len {
1824        return Err(TelemetryError::Unpack(
1825            "reliable header rewrite changes wire size",
1826        ));
1827    }
1828    let data_len = buf.len().saturating_sub(CRC32_BYTES);
1829    if data_len.saturating_sub(off) < old_len {
1830        return Err(TelemetryError::Unpack("short buffer"));
1831    }
1832    if compact {
1833        buf[0] |= FLAG_COMPACT_RELIABLE_HEADER;
1834    } else {
1835        buf[0] &= !FLAG_COMPACT_RELIABLE_HEADER;
1836    }
1837    let mut encoded = Vec::with_capacity(old_len);
1838    write_reliable_header_encoded(hdr, compact, &mut encoded);
1839    buf[off..off + old_len].copy_from_slice(&encoded);
1840    if buf.len() < CRC32_BYTES {
1841        return Err(TelemetryError::Unpack("short buffer"));
1842    }
1843    let crc = crc32_bytes(&buf[..data_len]);
1844    buf[data_len..data_len + CRC32_BYTES].copy_from_slice(&crc.to_le_bytes());
1845    Ok(true)
1846}
1847
1848pub(crate) fn rewrite_reliable_header_owned(
1849    buf: &[u8],
1850    flags: u8,
1851    seq: u32,
1852    ack: u32,
1853) -> TelemetryResult<Option<Arc<[u8]>>> {
1854    let Some((off, old_len, _)) = reliable_header_span(buf)? else {
1855        return Ok(None);
1856    };
1857    let data_len = buf.len().saturating_sub(CRC32_BYTES);
1858    if data_len < off + old_len {
1859        return Err(TelemetryError::Unpack("short buffer"));
1860    }
1861    let hdr = ReliableHeader { flags, seq, ack };
1862    let compact = should_compact_reliable_header(hdr);
1863    let mut encoded = Vec::with_capacity(reliable_wire_size(hdr, compact));
1864    write_reliable_header_encoded(hdr, compact, &mut encoded);
1865
1866    let mut out = Vec::with_capacity(data_len - old_len + encoded.len() + CRC32_BYTES);
1867    out.extend_from_slice(&buf[..off]);
1868    if compact {
1869        out[0] |= FLAG_COMPACT_RELIABLE_HEADER;
1870    } else {
1871        out[0] &= !FLAG_COMPACT_RELIABLE_HEADER;
1872    }
1873    out.extend_from_slice(&encoded);
1874    out.extend_from_slice(&buf[off + old_len..data_len]);
1875    let crc = crc32_bytes(&out);
1876    out.extend_from_slice(&crc.to_le_bytes());
1877    Ok(Some(Arc::from(out)))
1878}
1879
1880// ===========================================================================
1881// Size helpers
1882// ===========================================================================
1883
1884/// Compute the encoded metadata-prefix size for `pkt`.
1885///
1886/// This includes the fixed prelude and top-level varints, but excludes the
1887/// optional endpoint bitmap, optional wire contract, optional reliable header,
1888/// payload bytes, and CRC32 trailer.
1889///
1890/// # Parameters
1891/// - `pkt`: Packet to size.
1892///
1893/// # Returns
1894/// - Byte count of the packed metadata prefix.
1895pub fn header_size_bytes(pkt: &Packet) -> usize {
1896    let prelude = 2; // FLAGS (u8) + NEP (u8)
1897
1898    let source_address = sender_address_u32(pkt.sender());
1899
1900    prelude
1901        + uleb128_size(pkt.data_type().as_u32() as u64)
1902        + uleb128_size(pkt.data_size() as u64)
1903        + uleb128_size(pkt.timestamp())
1904        + if pkt.nonce() != 0 {
1905            uleb128_size(pkt.nonce() as u64)
1906        } else {
1907            0
1908        }
1909        + uleb128_size(source_address as u64)
1910}
1911
1912/// Compute the full packed wire size for `pkt`.
1913///
1914/// This applies the same sender/payload compression heuristics as normal
1915/// packing, then sums the metadata prefix, optional endpoint bitmap and frozen
1916/// wire contract, payload bytes, and CRC32 trailer. It matches [`pack_packet`];
1917/// its default unsequenced reliable header is included.
1918///
1919/// # Parameters
1920/// - `pkt`: Packet to size.
1921///
1922/// # Returns
1923/// - Total encoded frame size in bytes.
1924pub fn packet_wire_size(pkt: &Packet) -> usize {
1925    let shape = pkt.wire_shape();
1926    let targets = pkt.wire_target_senders();
1927    let contract_bytes = wire_contract_size(shape, targets);
1928    let contract_len = if shape.is_some() || !targets.is_empty() {
1929        uleb128_size(contract_bytes as u64) + contract_bytes
1930    } else {
1931        0
1932    };
1933    let endpoint_len = if packet_endpoint_bitmap_present(pkt, shape, targets) {
1934        if explicit_endpoint_list(pkt.endpoints()) {
1935            endpoint_list_size(pkt.endpoints())
1936        } else {
1937            EP_BITMAP_BYTES
1938        }
1939    } else {
1940        0
1941    };
1942    let (_, payload_wire) = payload_compression::compress_if_beneficial(pkt.payload());
1943    let reliable_len = if is_reliable_type(pkt.data_type()) {
1944        let header = ReliableHeader {
1945            flags: RELIABLE_FLAG_UNSEQUENCED,
1946            seq: 0,
1947            ack: 0,
1948        };
1949        reliable_wire_size(header, should_compact_reliable_header(header))
1950    } else {
1951        0
1952    };
1953    // Match pack_packet, including its default unsequenced reliable header.
1954    // No frame/header allocation, payload copy or CRC scan is needed for sizing.
1955    header_size_bytes(pkt)
1956        + endpoint_len
1957        + contract_len
1958        + reliable_len
1959        + payload_wire.len()
1960        + CRC32_BYTES
1961}
1962
1963#[inline]
1964/// Computes the same packet ID as [`Packet::packet_id`] directly from a packed wire frame.
1965pub fn packet_id_from_wire(buf: &[u8]) -> Result<u64, TelemetryError> {
1966    let data = verify_crc32(buf)?;
1967    if data.len() < 2 {
1968        return Err(TelemetryError::Unpack("short prelude"));
1969    }
1970
1971    let mut r = ByteReader::new(data);
1972
1973    let flags = r.read_bytes(1)?[0];
1974    let payload_is_compressed = (flags & FLAG_COMPRESSED_PAYLOAD) != 0;
1975    let compact_reliable_header = (flags & FLAG_COMPACT_RELIABLE_HEADER) != 0;
1976    #[cfg(feature = "cryptography")]
1977    let payload_is_encrypted = (flags & FLAG_E2E_ENCRYPTED_PAYLOAD) != 0;
1978    #[cfg(not(feature = "cryptography"))]
1979    if (flags & 0x10) != 0 {
1980        return Err(TelemetryError::Unpack("e2e crypto unsupported"));
1981    }
1982
1983    let _nep = r.read_bytes(1)?[0] as usize;
1984
1985    let _ = read_uleb128(&mut r)?;
1986    let dsz = read_uleb128(&mut r)? as usize; // logical payload size (uncompressed)
1987    let ts_v = read_uleb128(&mut r)?;
1988    let nonce = if (flags & FLAG_PACKET_NONCE) != 0 {
1989        u16::try_from(read_uleb128(&mut r)?)
1990            .map_err(|_| TelemetryError::Unpack("packet nonce too large"))?
1991    } else {
1992        0
1993    };
1994    let source_address = u32::try_from(read_uleb128(&mut r)?)
1995        .map_err(|_| TelemetryError::Unpack("source address too large"))?;
1996    // Reuse the validated borrowed envelope. Computing an ID must not build
1997    // owned endpoint/target arrays merely to hash or inspect their contents.
1998    let mut envelope_reader = ByteReader::new(data);
1999    let envelope = read_routing_envelope(&mut envelope_reader)?;
2000    r = envelope_reader;
2001    let ty = envelope.ty;
2002
2003    // ---- reliable header (optional) ----
2004    if envelope.is_reliable || envelope.has_reliable_header {
2005        let hdr = read_reliable_header_encoded(&mut r, compact_reliable_header)?;
2006        if (hdr.flags & RELIABLE_FLAG_ACK_ONLY) != 0 {
2007            return Err(TelemetryError::Unpack("reliable control frame"));
2008        }
2009    }
2010
2011    // ---- payload bytes (must hash *logical* payload bytes) ----
2012    #[cfg(feature = "cryptography")]
2013    let payload_wire_owned;
2014    #[cfg(feature = "cryptography")]
2015    let payload_wire: &[u8] = if payload_is_encrypted {
2016        let aad_end = r.off;
2017        payload_wire_owned =
2018            read_encrypted_payload(&mut r, data.get(..aad_end).unwrap_or(&[]), dsz)?;
2019        &payload_wire_owned
2020    } else if !payload_is_compressed {
2021        if r.remaining() < dsz {
2022            return Err(TelemetryError::Unpack("short buffer"));
2023        }
2024        r.read_bytes(dsz)?
2025    } else {
2026        let comp_len = r.remaining();
2027        if comp_len < 1 {
2028            return Err(TelemetryError::Unpack("short buffer"));
2029        }
2030        r.read_bytes(comp_len)?
2031    };
2032    #[cfg(not(feature = "cryptography"))]
2033    let payload_wire: &[u8] = if !payload_is_compressed {
2034        if r.remaining() < dsz {
2035            return Err(TelemetryError::Unpack("short buffer"));
2036        }
2037        r.read_bytes(dsz)?
2038    } else {
2039        let comp_len = r.remaining();
2040        if comp_len < 1 {
2041            return Err(TelemetryError::Unpack("short buffer"));
2042        }
2043        r.read_bytes(comp_len)?
2044    };
2045    let payload_decompressed;
2046    let payload_bytes: &[u8] = if payload_is_compressed {
2047        payload_decompressed = payload_compression::decompress(payload_wire, dsz)?;
2048        &payload_decompressed
2049    } else {
2050        if payload_wire.len() != dsz {
2051            return Err(TelemetryError::Unpack("payload length mismatch"));
2052        }
2053        payload_wire
2054    };
2055
2056    // ---- hash exactly like Packet::packet_id() ----
2057    let mut h: u64 = 0x9E37_79B9_7F4A_7C15;
2058
2059    // Compact source address.
2060    h = hash_bytes_u64(h, &source_address.to_le_bytes());
2061
2062    // Stable numeric identity is independent of when schema names are learned.
2063    h = hash_bytes_u64(h, &ty.0.to_le_bytes());
2064
2065    // Endpoints as string bytes, in ascending discriminant order.
2066    for ep in envelope.endpoints() {
2067        h = hash_bytes_u64(h, &ep.0.to_le_bytes());
2068    }
2069
2070    // Timestamp + data_size as bytes
2071    h = hash_bytes_u64(h, &ts_v.to_le_bytes());
2072    h = hash_bytes_u64(h, &nonce.to_le_bytes());
2073    h = hash_bytes_u64(h, &(dsz as u64).to_le_bytes());
2074
2075    // Payload bytes (logical payload)
2076    h = hash_bytes_u64(h, payload_bytes);
2077    Ok(h)
2078}
2079
2080mod payload_compression {
2081    use crate::TelemetryError;
2082    use alloc::borrow::Cow;
2083    #[cfg(feature = "compression")]
2084    use alloc::vec;
2085    use alloc::vec::Vec;
2086
2087    #[cfg(feature = "compression")]
2088    use crate::config::runtime_payload_compress_threshold;
2089    #[cfg(feature = "compression")]
2090    use zstd_safe::CompressionLevel;
2091
2092    /// Compress the given payload if it is beneficial to do so.
2093    /// # Arguments
2094    /// - `payload`: Original uncompressed payload bytes.
2095    /// # Returns
2096    /// - `(bool, Cow<[u8]>)`: Tuple where the first element indicates whether
2097    ///   compression was applied, and the second element is the resulting
2098    ///   payload bytes (compressed or original).
2099    #[cfg(feature = "compression")]
2100    pub fn compress_if_beneficial(payload: &'_ [u8]) -> (bool, Cow<'_, [u8]>) {
2101        if payload.len() < runtime_payload_compress_threshold() {
2102            return (false, Cow::Borrowed(payload));
2103        }
2104
2105        // Bound output and avoid growth beyond useful threshold.
2106        let Some(compressed) = compress_to_vec_bounded(payload, payload.len().saturating_sub(2))
2107        else {
2108            return (false, Cow::Borrowed(payload));
2109        };
2110
2111        // Only use compressed form if it actually saves space.
2112        if compressed.len() + 1 >= payload.len() {
2113            (false, Cow::Borrowed(payload))
2114        } else {
2115            (true, Cow::Owned(compressed))
2116        }
2117    }
2118
2119    #[cfg(feature = "compression")]
2120    fn compress_to_vec_bounded(input: &[u8], max_output: usize) -> Option<Vec<u8>> {
2121        if input.is_empty() || max_output == 0 {
2122            return None;
2123        }
2124
2125        let mut out = vec![0u8; max_output];
2126        // Use default-level behavior for better compression ratio on typical telemetry payloads.
2127        let level: CompressionLevel = 1;
2128        let written = zstd_safe::compress(&mut out[..], input, level).ok()?;
2129        out.truncate(written);
2130        Some(out)
2131    }
2132
2133    /// Decompress the given compressed payload.
2134    /// # Arguments
2135    /// - `compressed`: Compressed payload bytes.
2136    /// - `expected_len`: Expected length of the decompressed payload.
2137    /// # Returns
2138    /// - `Vec<u8>`: Decompressed payload bytes.
2139    /// # Errors
2140    /// - `TelemetryError::Unpack` if decompression fails or the size
2141    ///   does not match `expected_len`.
2142    #[cfg(feature = "compression")]
2143    pub fn decompress(compressed: &[u8], expected_len: usize) -> Result<Vec<u8>, TelemetryError> {
2144        let mut out = vec![0u8; expected_len];
2145        let written = zstd_safe::decompress(&mut out[..], compressed)
2146            .map_err(|_| TelemetryError::Unpack("decompression failed"))?;
2147        if written != expected_len {
2148            return Err(TelemetryError::Unpack("decompressed size mismatch"));
2149        }
2150        Ok(out)
2151    }
2152
2153    // Stub when compression is disabled (never actually produces compressed payloads).
2154    #[cfg(not(feature = "compression"))]
2155    /// Returns the original payload unchanged when compression support is disabled.
2156    pub fn compress_if_beneficial<'a>(payload: &'a [u8]) -> (bool, Cow<'a, [u8]>) {
2157        (false, Cow::Borrowed(payload))
2158    }
2159
2160    #[cfg(not(feature = "compression"))]
2161    /// Reports that compressed payloads cannot be decoded when compression support is disabled.
2162    pub fn decompress(_compressed: &[u8], _expected_len: usize) -> Result<Vec<u8>, TelemetryError> {
2163        Err(TelemetryError::Unpack(
2164            "compressed payloads not supported (compression feature disabled)",
2165        ))
2166    }
2167}
2168
2169#[cfg(test)]
2170mod endpoint_decode_tests {
2171    use super::*;
2172
2173    #[test]
2174    fn numeric_sender_alias_keeps_packet_wire_and_receipt_identity() {
2175        let ty = DataType::ReliableAck;
2176        let make = |sender: &str| {
2177            Packet::new_with_wire_contract(
2178                ty,
2179                message_meta(ty).endpoints_ref(),
2180                sender,
2181                200,
2182                9,
2183                Arc::from(42u64.to_le_bytes()),
2184                Some(MessageElement::Static(
2185                    2,
2186                    crate::MessageDataType::UInt32,
2187                    crate::MessageClass::Data,
2188                )),
2189                Arc::from([123u64]),
2190            )
2191            .unwrap()
2192        };
2193        let named = make("FC");
2194        let alias = alloc::format!("@addr:{}", sender_address_u32("FC"));
2195        let unresolved = make(&alias);
2196        assert_eq!(unresolved.packet_id(), named.packet_id());
2197        let named_wire = pack_packet(&named);
2198        let alias_wire = pack_packet(&unresolved);
2199        assert_eq!(alias_wire, named_wire);
2200        assert_eq!(packet_id_from_wire(&alias_wire).unwrap(), named.packet_id());
2201        assert_eq!(
2202            unpack_packet(&alias_wire).unwrap().packet_id(),
2203            named.packet_id()
2204        );
2205    }
2206
2207    #[test]
2208    fn scheduling_type_is_bounded_and_never_replaces_frame_validation() {
2209        let pkt = Packet::new_with_wire_contract(
2210            DataType::ReliableAck,
2211            message_meta(DataType::ReliableAck).endpoints_ref(),
2212            "E2EACK:GS",
2213            100,
2214            1,
2215            Arc::from(42u64.to_le_bytes()),
2216            Some(MessageElement::Static(
2217                2,
2218                crate::MessageDataType::UInt32,
2219                crate::MessageClass::Data,
2220            )),
2221            Arc::from([123u64]),
2222        )
2223        .unwrap();
2224        let mut bytes = pack_packet(&pkt).to_vec();
2225        assert_eq!(scheduling_type(&bytes), Some(DataType::ReliableAck));
2226        let last = bytes.len() - 1;
2227        bytes[last] ^= 1;
2228        assert_eq!(scheduling_type(&bytes), Some(DataType::ReliableAck));
2229        assert!(peek_routing_envelope(&bytes).is_err());
2230        assert!(unpack_packet(&bytes).is_err());
2231        assert_eq!(scheduling_type(&[0, 0, 0x80]), None);
2232        assert_eq!(scheduling_type(&[0xff; 1024]), None);
2233        assert_eq!(scheduling_type(&[]), None);
2234    }
2235
2236    #[test]
2237    fn receipt_contract_omits_redundant_builtin_endpoint_bitmap() {
2238        for ty in [
2239            DataType::ReliableAck,
2240            DataType::ReliablePartialAck,
2241            DataType::ReliablePacketRequest,
2242        ] {
2243            let shape = Some(MessageElement::Static(
2244                2,
2245                crate::MessageDataType::UInt32,
2246                crate::MessageClass::Data,
2247            ));
2248            let targets: Arc<[u64]> = Arc::from([0xa7fcbb129e92435f, 0x41426f62de53eb28]);
2249            let payload: Arc<[u8]> = Arc::from(0x9c2a63d6d7d44100u64.to_le_bytes());
2250            let make = |eps: &[DataEndpoint]| {
2251                Packet::new_with_wire_contract(
2252                    ty,
2253                    eps,
2254                    "E2EACK:GS",
2255                    1791737696510,
2256                    1234,
2257                    payload.clone(),
2258                    shape,
2259                    targets.clone(),
2260                )
2261                .unwrap()
2262            };
2263            let packet = make(message_meta(ty).endpoints_ref());
2264            let packed = pack_packet(&packet);
2265            assert_eq!(packed[0] & FLAG_ENDPOINT_BITMAP_PRESENT, 0);
2266            assert_ne!(packed[0] & FLAG_WIRE_CONTRACT, 0);
2267            let routing = peek_routing_envelope(&packed).unwrap();
2268            assert_eq!(routing.endpoints().collect::<Vec<_>>(), packet.endpoints());
2269            assert_eq!(
2270                routing.target_senders().collect::<Vec<_>>(),
2271                targets.as_ref()
2272            );
2273            let decoded = unpack_packet(&packed).unwrap();
2274            assert_eq!(decoded.packet_id(), packet.packet_id());
2275            assert_eq!(decoded.payload(), packet.payload());
2276            assert_eq!(decoded.wire_target_senders(), targets.as_ref());
2277            // Sparse explicit endpoints use a short sorted list.
2278            let explicit = pack_packet(&make(&[DataEndpoint::Discovery]));
2279            assert_ne!(explicit[0] & FLAG_ENDPOINT_LIST_PRESENT, 0);
2280            assert_eq!(
2281                explicit.len(),
2282                packed.len() + uleb128_size(u64::from(DataEndpoint::Discovery.0))
2283            );
2284            assert_eq!(
2285                unpack_packet(&explicit).unwrap().endpoints(),
2286                &[DataEndpoint::Discovery]
2287            );
2288        }
2289    }
2290
2291    #[test]
2292    fn borrowed_routing_header_preserves_targets_and_validates_truncated_contracts() {
2293        let targets: Arc<[u64]> = Arc::from([1, u64::MAX, 42]);
2294        let packet = Packet::new_with_wire_contract(
2295            DataType::DiscoverySchema,
2296            &[DataEndpoint::Discovery],
2297            "PEER",
2298            1234,
2299            7,
2300            Arc::from([1u8, 2, 3]),
2301            Some(MessageElement::Dynamic(
2302                crate::MessageDataType::Binary,
2303                crate::MessageClass::Data,
2304            )),
2305            targets.clone(),
2306        )
2307        .unwrap();
2308        let packed = pack_packet(&packet);
2309        let routing = peek_routing_envelope(&packed).unwrap();
2310        let full = unpack_packet(&packed).unwrap();
2311        assert_eq!(routing.ty, full.data_type());
2312        assert_eq!(routing.endpoints().collect::<Vec<_>>(), full.endpoints());
2313        assert_eq!(
2314            routing.target_senders().collect::<Vec<_>>(),
2315            targets.as_ref()
2316        );
2317        assert_eq!(routing.timestamp_ms, full.timestamp());
2318        // Cut through the header, recomputing CRC so truncation validation runs.
2319        let data = verify_crc32(&packed).unwrap();
2320        let mut reader = ByteReader::new(data);
2321        read_routing_envelope(&mut reader).unwrap();
2322        for end in 0..reader.off {
2323            let mut truncated = data[..end].to_vec();
2324            append_crc32(&mut truncated);
2325            assert!(
2326                peek_routing_envelope(&truncated).is_err(),
2327                "accepted cut at {end}"
2328            );
2329        }
2330    }
2331
2332    #[test]
2333    fn large_packet_with_long_prefix_does_not_grow_packing_buffer() {
2334        let payload: Vec<u8> = (0..3500)
2335            .map(|i| ((i * 73 + i / 251) % 256) as u8)
2336            .collect();
2337        let packet = Packet::new(
2338            DataType::DiscoverySchema,
2339            &[DataEndpoint::Discovery],
2340            "LONG_PREFIX_SENDER",
2341            u64::MAX,
2342            payload.into(),
2343        )
2344        .unwrap()
2345        .with_nonce(u16::MAX);
2346        assert!(header_size_bytes(&packet) > 16);
2347        let packed = pack_packet(&packet);
2348        let unpacked = unpack_packet(&packed).unwrap();
2349        assert_eq!(unpacked.payload(), packet.payload());
2350        assert_eq!(unpacked.timestamp(), u64::MAX);
2351        assert_eq!(unpacked.nonce(), u16::MAX);
2352    }
2353
2354    #[test]
2355    fn bitmap_decode_preserves_sorted_unique_destinations() {
2356        let input = [
2357            DataEndpoint::TelemetryError,
2358            DataEndpoint::TimeSync,
2359            DataEndpoint::Discovery,
2360            DataEndpoint::TimeSync,
2361        ];
2362        let decoded = expand_endpoint_bitmap(&build_endpoint_bitmap(&input)).unwrap();
2363        assert_eq!(
2364            &*decoded,
2365            &[
2366                DataEndpoint::TimeSync,
2367                DataEndpoint::Discovery,
2368                DataEndpoint::TelemetryError
2369            ]
2370        );
2371        assert!(
2372            expand_endpoint_bitmap(&[0; EP_BITMAP_BYTES])
2373                .unwrap()
2374                .is_empty()
2375        );
2376        assert!(expand_endpoint_bitmap(&[0; EP_BITMAP_BYTES - 1]).is_err());
2377    }
2378
2379    #[test]
2380    fn bitmap_decode_rejects_unregistered_endpoint_bits() {
2381        if let Some(id) =
2382            (0..=MAX_VALUE_DATA_ENDPOINT).find(|id| DataEndpoint::try_from_u32(*id).is_none())
2383        {
2384            let mut bitmap = [0; EP_BITMAP_BYTES];
2385            bitmap[id as usize / 8] = 1 << (id % 8);
2386            assert!(expand_endpoint_bitmap(&bitmap).is_err());
2387        }
2388    }
2389}