Skip to main content

matter_kit/commissioning/
payload.rs

1//! The onboarding payload — the QR code and the manual pairing code (Core §5.1).
2//!
3//! Everything PASE needs before it can start has to reach the commissioner somehow, and
4//! this is how: a string printed on the device or its box. Two forms, from the same data.
5//!
6//! ```text
7//! MT:-24J0AFN00KA0648G00        a QR code: 11 octets, base-38
8//! 3497011266                5   a manual code: 11 digits, the last one a checksum
9//! ```
10//!
11//! The QR form carries everything — vendor, product, how to discover the device, the
12//! 12-bit discriminator, the 27-bit passcode, and optional TLV. The manual form carries
13//! what a person can reasonably type: the passcode, the *top four bits* of the
14//! discriminator, and optionally vendor and product. A commissioner given only a manual
15//! code therefore has to search harder when it goes looking for the device.
16//!
17//! # The passcode is 27 bits and not all of them count
18//!
19//! "A Passcode SHALL be included as a 27-bit unsigned integer … SHALL be restricted to the
20//! values 0x0000001 to 0x5F5E0FE" — 1 to 99 999 998 — and twelve further values are
21//! forbidden outright for being guessable (§5.1.7.1). [`Passcode`] enforces both, because
22//! a device shipped with `12345678` is a device anyone can commission.
23
24use crate::error::{Error, ErrorCode, Result, bail};
25use crate::msg::VendorId;
26
27/// The base-38 alphabet of Core Table 61.
28///
29/// "a subset of the 45 available characters (A-Z0-9$%*+./ :-) in the QR code for
30/// alphanumeric encoding … with characters `$`, `%`, `*`, `+`, `/`, space and `:`
31/// removed" — so every character survives QR alphanumeric mode, which is what keeps the
32/// code small.
33const ALPHABET: &[u8; 38] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-.";
34
35/// The three-character prefix every Matter QR payload starts with (§5.1.3.1).
36pub const QR_PREFIX: &str = "MT:";
37
38/// The packed binary structure is 88 bits — 11 octets — before any TLV (§5.1.3.1.3).
39pub const PACKED_LEN: usize = 11;
40
41/// A base-38 QR payload for the packed structure alone, plus the prefix.
42pub const QR_LEN_NO_TLV: usize = 3 + 19;
43
44/// The longest manual pairing code: 21 digits, with vendor and product.
45pub const MANUAL_CODE_MAX_DIGITS: usize = 21;
46
47/// A validated setup passcode (§5.1.1.6, §5.1.7.1).
48///
49/// There is no way to build one that a device may not ship with, which is the point: the
50/// check belongs at the type, not at each of the several places a passcode enters the
51/// stack.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53pub struct Passcode(u32);
54
55impl Passcode {
56    /// The smallest legal value.
57    pub const MIN: u32 = 0x0000_0001;
58    /// The largest legal value — 99 999 998.
59    pub const MAX: u32 = 0x05F5_E0FE;
60
61    /// "The following Passcodes SHALL NOT be used for the PASE protocol due to their
62    /// trivial, insecure nature" (§5.1.7.1).
63    pub const INVALID: [u32; 12] = [
64        0, 11_111_111, 22_222_222, 33_333_333, 44_444_444, 55_555_555, 66_666_666, 77_777_777,
65        88_888_888, 99_999_999, 12_345_678, 87_654_321,
66    ];
67
68    /// Checks a value against both rules.
69    pub const fn new(value: u32) -> Result<Self> {
70        if value < Self::MIN || value > Self::MAX {
71            return Err(Error::new(ErrorCode::InvalidArgument));
72        }
73        // A `while let` over `split_first` keeps this both `const` and index-free.
74        let mut rest: &[u32] = &Self::INVALID;
75        while let [first, tail @ ..] = rest {
76            if *first == value {
77                return Err(Error::new(ErrorCode::InvalidArgument));
78            }
79            rest = tail;
80        }
81        Ok(Self(value))
82    }
83
84    /// The value.
85    #[must_use]
86    pub const fn value(self) -> u32 {
87        self.0
88    }
89}
90
91/// The Device Commissioning Flow (§5.1.1.3).
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
93#[repr(u8)]
94pub enum CustomFlow {
95    /// "Standard commissioning flow: such a device, when uncommissioned, always enters
96    /// commissioning mode upon power-up."
97    #[default]
98    Standard = 0,
99    /// "User-intent commissioning flow: user action required to enter commissioning mode."
100    UserIntent = 1,
101    /// "Custom commissioning flow: interaction with a vendor-specified means is needed
102    /// before commissioning."
103    Custom = 2,
104}
105
106impl CustomFlow {
107    const fn from_bits(bits: u8) -> Result<Self> {
108        Ok(match bits {
109            0 => Self::Standard,
110            1 => Self::UserIntent,
111            2 => Self::Custom,
112            // "3: Reserved".
113            _ => return Err(Error::new(ErrorCode::MessageReserved)),
114        })
115    }
116}
117
118bitflags::bitflags! {
119    /// How a device can be discovered (Core Table 60).
120    ///
121    /// Every bit means "supports this **when not commissioned**": a device already on a
122    /// fabric advertises none of them.
123    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
124    pub struct DiscoveryCapabilities: u8 {
125        /// Bit 1 — "Device supports BLE for discovery when not commissioned."
126        const BLE = 1 << 1;
127        /// Bit 2 — "Device is already on the IP network."
128        const ON_IP_NETWORK = 1 << 2;
129        /// Bit 3 — Wi-Fi Public Action Frame.
130        const WIFI_PAF = 1 << 3;
131        /// Bit 4 — the NFC Transport Layer.
132        const NFC = 1 << 4;
133        /// Bit 5 — the Thread Commissioning Protocol. Provisional: "Until it becomes
134        /// certifiable, Bit 5 should be treated as reserved."
135        const THREAD_COMMISSIONING = 1 << 5;
136    }
137}
138
139/// Everything printed on a device's label (§5.1.1).
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub struct OnboardingPayload {
142    /// Who made it.
143    pub vendor_id: VendorId,
144    /// What it is.
145    pub product_id: u16,
146    /// Whether the user has to do something before commissioning can start.
147    pub custom_flow: CustomFlow,
148    /// How to find it.
149    pub discovery: DiscoveryCapabilities,
150    /// A 12-bit value the device also advertises, so a commissioner can tell two
151    /// otherwise identical devices apart (§5.1.1.5).
152    pub discriminator: u16,
153    /// The shared secret PASE proves possession of.
154    pub passcode: Passcode,
155}
156
157/// The 12-bit discriminator's mask.
158const DISCRIMINATOR_MASK: u16 = 0x0FFF;
159
160impl OnboardingPayload {
161    /// Builds a payload, checking the discriminator fits 12 bits.
162    pub fn new(
163        vendor_id: VendorId,
164        product_id: u16,
165        discriminator: u16,
166        passcode: Passcode,
167        discovery: DiscoveryCapabilities,
168        custom_flow: CustomFlow,
169    ) -> Result<Self> {
170        if discriminator > DISCRIMINATOR_MASK {
171            bail!(InvalidArgument)
172        }
173        Ok(Self {
174            vendor_id,
175            product_id,
176            custom_flow,
177            discovery,
178            discriminator,
179            passcode,
180        })
181    }
182
183    /// The top four bits of the discriminator — all a manual pairing code carries
184    /// (§5.1.1.5).
185    #[must_use]
186    pub const fn short_discriminator(&self) -> u8 {
187        (self.discriminator >> 8) as u8
188    }
189
190    /// Packs the structure of Core Table 59 into 11 octets.
191    ///
192    /// "The bits of each fixed-size value are placed in the packed binary data structure
193    /// in order from least significant to most significant", and the whole is "padded with
194    /// '0' bits at the end of the structure to the nearest byte boundary".
195    pub fn pack(&self) -> [u8; PACKED_LEN] {
196        let mut bits = BitWriter::new();
197        // Version: "SHALL be 000".
198        bits.push(0, 3);
199        bits.push(u64::from(self.vendor_id.0), 16);
200        bits.push(u64::from(self.product_id), 16);
201        bits.push(self.custom_flow as u64, 2);
202        bits.push(u64::from(self.discovery.bits()), 8);
203        bits.push(u64::from(self.discriminator & DISCRIMINATOR_MASK), 12);
204        bits.push(u64::from(self.passcode.value()), 27);
205        // The four padding bits are already zero.
206        bits.finish()
207    }
208
209    /// Reads the packed structure back.
210    pub fn unpack(bytes: &[u8]) -> Result<Self> {
211        let Some(packed) = bytes.get(..PACKED_LEN) else {
212            bail!(MessageTruncated)
213        };
214        let mut bits = BitReader::new(packed);
215        let version = bits.take(3)?;
216        if version != 0 {
217            // §5.1.1.1: the version "SHALL be 000"; anything else is a payload this
218            // revision does not know how to read, and guessing would be worse than saying so.
219            bail!(UnsupportedVersion)
220        }
221        let vendor_id = VendorId(bits.take(16)? as u16);
222        let product_id = bits.take(16)? as u16;
223        let custom_flow = CustomFlow::from_bits(bits.take(2)? as u8)?;
224        let discovery = DiscoveryCapabilities::from_bits_retain(bits.take(8)? as u8);
225        let discriminator = bits.take(12)? as u16;
226        let passcode = Passcode::new(bits.take(27)? as u32)?;
227
228        Ok(Self {
229            vendor_id,
230            product_id,
231            custom_flow,
232            discovery,
233            discriminator,
234            passcode,
235        })
236    }
237
238    /// Renders the QR payload: `MT:` followed by the base-38 encoding.
239    pub fn to_qr(&self) -> Result<heapless::String<QR_LEN_NO_TLV>> {
240        let mut out = heapless::String::new();
241        out.push_str(QR_PREFIX)
242            .map_err(|_| Error::new(ErrorCode::NoSpace))?;
243        base38_encode(&self.pack(), &mut out)?;
244        Ok(out)
245    }
246
247    /// Parses a QR payload.
248    ///
249    /// Accepts the string with or without its `MT:` prefix; a camera app that strips it is
250    /// common enough that refusing would be unhelpful.
251    pub fn from_qr(text: &str) -> Result<Self> {
252        let body = text.strip_prefix(QR_PREFIX).unwrap_or(text);
253        let mut packed = [0u8; PACKED_LEN];
254        let n = base38_decode(body, &mut packed)?;
255        if n < PACKED_LEN {
256            bail!(MessageTruncated)
257        }
258        Self::unpack(&packed)
259    }
260
261    /// Renders the manual pairing code (§5.1.4).
262    ///
263    /// `include_vid_pid` produces the 21-digit form. §5.1.4.1.2 ties this to the
264    /// commissioning flow: a standard-flow device uses the short form, and a user-intent
265    /// or custom-flow device "SHALL" use the long one — so this refuses the combination
266    /// the specification forbids rather than producing a code a commissioner will
267    /// misread as standard flow.
268    pub fn to_manual_code(
269        &self,
270        include_vid_pid: bool,
271    ) -> Result<heapless::String<MANUAL_CODE_MAX_DIGITS>> {
272        if !include_vid_pid && self.custom_flow != CustomFlow::Standard {
273            bail!(InvalidArgument)
274        }
275
276        let passcode = self.passcode.value();
277        let discriminator = u32::from(self.discriminator & DISCRIMINATOR_MASK);
278
279        // DIGIT[1] := (VID_PID_PRESENT << 2) | (DISCRIMINATOR >> 10)
280        let first = (u32::from(include_vid_pid) << 2) | (discriminator >> 10);
281        // DIGIT[2..6] := ((DISCRIMINATOR & 0x300) << 6) | (PASSCODE & 0x3FFF)
282        let group2 = ((discriminator & 0x300) << 6) | (passcode & 0x3FFF);
283        // DIGIT[7..10] := (PASSCODE >> 14)
284        let group3 = passcode >> 14;
285
286        let mut out = heapless::String::<MANUAL_CODE_MAX_DIGITS>::new();
287        push_digits(&mut out, first, 1)?;
288        push_digits(&mut out, group2, 5)?;
289        push_digits(&mut out, group3, 4)?;
290        if include_vid_pid {
291            push_digits(&mut out, u32::from(self.vendor_id.0), 5)?;
292            push_digits(&mut out, u32::from(self.product_id), 5)?;
293        }
294        let check = verhoeff_check_digit(out.as_bytes())?;
295        push_digits(&mut out, u32::from(check), 1)?;
296        Ok(out)
297    }
298
299    /// Parses a manual pairing code.
300    ///
301    /// "The receiving application SHALL be robust against characters like dashes and
302    /// spaces that may be included in the string" (§5.1.4.2), so those are stripped before
303    /// anything else — a user who types `3497-011-2665` has typed a valid code.
304    ///
305    /// The discriminator that comes back has only its top four bits set; the rest are
306    /// zero, because a manual code does not carry them.
307    pub fn from_manual_code(text: &str) -> Result<Self> {
308        let mut digits = heapless::Vec::<u8, MANUAL_CODE_MAX_DIGITS>::new();
309        for c in text.chars() {
310            match c {
311                '0'..='9' => digits
312                    .push((c as u8).wrapping_sub(b'0'))
313                    .map_err(|_| Error::new(ErrorCode::InvalidArgument))?,
314                '-' | ' ' => {}
315                _ => bail!(InvalidArgument),
316            }
317        }
318
319        let expect_vid_pid = match digits.len() {
320            11 => false,
321            21 => true,
322            _ => bail!(InvalidArgument),
323        };
324        if !verhoeff_is_valid(&digits) {
325            // A single mistyped digit is caught here rather than by a failed PASE
326            // exchange several seconds later.
327            bail!(IntegrityCheckFailed)
328        }
329
330        let first = u32::from(digits.first().copied().unwrap_or(0));
331        // §5.1.4.1.4: "First digit of '8' or '9' would be invalid for v1".
332        if first > 7 {
333            bail!(UnsupportedVersion)
334        }
335        let vid_pid_present = (first & 0b100) != 0;
336        if vid_pid_present != expect_vid_pid {
337            // The flag and the length must agree, or one of them is a lie.
338            bail!(InvalidArgument)
339        }
340
341        let group2 = digits_value(&digits, 1, 5)?;
342        let group3 = digits_value(&digits, 6, 4)?;
343
344        let discriminator = (((first & 0b011) << 10) | ((group2 & 0xC000) >> 6)) as u16;
345        let passcode = Passcode::new((group2 & 0x3FFF) | (group3 << 14))?;
346
347        let (vendor_id, product_id) = if vid_pid_present {
348            (
349                VendorId(digits_value(&digits, 10, 5)? as u16),
350                digits_value(&digits, 15, 5)? as u16,
351            )
352        } else {
353            (VendorId(0), 0)
354        };
355
356        Ok(Self {
357            vendor_id,
358            product_id,
359            // §5.1.4.1.2: a short code means standard flow; a long one needs the
360            // Distributed Compliance Ledger to say which of the other two it is, so the
361            // most this parser can honestly report is "not standard".
362            custom_flow: if vid_pid_present {
363                CustomFlow::UserIntent
364            } else {
365                CustomFlow::Standard
366            },
367            discovery: DiscoveryCapabilities::empty(),
368            discriminator,
369            passcode,
370        })
371    }
372}
373
374fn push_digits<const N: usize>(
375    out: &mut heapless::String<N>,
376    value: u32,
377    width: usize,
378) -> Result<()> {
379    let mut scratch = [0u8; 10];
380    let mut v = value;
381    for i in (0..width).rev() {
382        let Some(slot) = scratch.get_mut(i) else {
383            bail!(InvalidArgument)
384        };
385        *slot = b'0'.saturating_add((v % 10) as u8);
386        v /= 10;
387    }
388    if v != 0 {
389        // The value did not fit the width it was promised, which would silently shift
390        // every later digit.
391        bail!(InvalidArgument)
392    }
393    let Some(text) = scratch
394        .get(..width)
395        .and_then(|b| core::str::from_utf8(b).ok())
396    else {
397        bail!(InvalidArgument)
398    };
399    out.push_str(text)
400        .map_err(|_| Error::new(ErrorCode::NoSpace))
401}
402
403fn digits_value(digits: &[u8], start: usize, width: usize) -> Result<u32> {
404    let end = start
405        .checked_add(width)
406        .ok_or(Error::new(ErrorCode::InvalidArgument))?;
407    let Some(slice) = digits.get(start..end) else {
408        bail!(InvalidArgument)
409    };
410    let mut value = 0u32;
411    for d in slice {
412        value = value
413            .checked_mul(10)
414            .and_then(|v| v.checked_add(u32::from(*d)))
415            .ok_or(Error::new(ErrorCode::InvalidArgument))?;
416    }
417    Ok(value)
418}
419
420// --- Base 38 (§5.1.3.1.5) ---------------------------------------------------------------
421
422/// "every 3 bytes (24 bits) of binary source data are encoded to 5 characters", with two
423/// bytes going to four characters and one byte to two.
424fn base38_encode<const N: usize>(data: &[u8], out: &mut heapless::String<N>) -> Result<()> {
425    for chunk in data.chunks(3) {
426        let (value, width) = match chunk {
427            // "UINT24 = (BYTE[N+2] << 16) | (BYTE[N+1] << 8) | (BYTE[N] << 0)" — the
428            // chunk is little-endian.
429            [a, b, c] => (
430                u32::from(*a) | (u32::from(*b) << 8) | (u32::from(*c) << 16),
431                5,
432            ),
433            [a, b] => (u32::from(*a) | (u32::from(*b) << 8), 4),
434            [a] => (u32::from(*a), 2),
435            _ => bail!(InvalidArgument),
436        };
437        let mut v = value;
438        for _ in 0..width {
439            let Some(&c) = ALPHABET.get((v % 38) as usize) else {
440                bail!(InvalidArgument)
441            };
442            // "with the least-significant character appearing first (little-endian)".
443            out.push(char::from(c))
444                .map_err(|_| Error::new(ErrorCode::NoSpace))?;
445            v /= 38;
446        }
447    }
448    Ok(())
449}
450
451/// Decodes base-38 into `out`, returning how many octets it produced.
452fn base38_decode(text: &str, out: &mut [u8]) -> Result<usize> {
453    let bytes = text.as_bytes();
454    let mut written = 0usize;
455
456    for chunk in bytes.chunks(5) {
457        let width = match chunk.len() {
458            5 => 3usize,
459            4 => 2,
460            2 => 1,
461            // 1 or 3 characters cannot be a whole number of octets.
462            _ => bail!(InvalidArgument),
463        };
464        let mut value = 0u32;
465        // Least-significant character first, so fold from the end.
466        for c in chunk.iter().rev() {
467            let Some(digit) = ALPHABET.iter().position(|a| a == c) else {
468                bail!(InvalidArgument)
469            };
470            value = value
471                .checked_mul(38)
472                .and_then(|v| v.checked_add(digit as u32))
473                .ok_or(Error::new(ErrorCode::InvalidArgument))?;
474        }
475        // A 5-character group must fit 24 bits, a 4-character group 16, a 2-character
476        // group 8 — a larger value means the encoding is not one this alphabet produced.
477        let limit = 1u32
478            .checked_shl((width as u32).saturating_mul(8))
479            .unwrap_or(u32::MAX);
480        if width < 4 && value >= limit {
481            bail!(InvalidArgument)
482        }
483        for i in 0..width {
484            let Some(slot) = out.get_mut(written) else {
485                bail!(BufferTooSmall)
486            };
487            *slot = (value >> (i.saturating_mul(8))) as u8;
488            written = written.saturating_add(1);
489        }
490    }
491    Ok(written)
492}
493
494// --- Verhoeff (§5.1.4.1.5) ----------------------------------------------------------------
495
496/// The dihedral group D₅ multiplication table.
497const VERHOEFF_D: [[u8; 10]; 10] = [
498    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
499    [1, 2, 3, 4, 0, 6, 7, 8, 9, 5],
500    [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],
501    [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],
502    [4, 0, 1, 2, 3, 9, 5, 6, 7, 8],
503    [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],
504    [6, 5, 9, 8, 7, 1, 0, 4, 3, 2],
505    [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],
506    [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],
507    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0],
508];
509
510/// The permutation table, applied by position.
511const VERHOEFF_P: [[u8; 10]; 8] = [
512    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
513    [1, 5, 7, 6, 2, 8, 3, 0, 9, 4],
514    [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],
515    [8, 9, 1, 6, 0, 4, 3, 5, 2, 7],
516    [9, 4, 5, 3, 1, 2, 6, 8, 7, 0],
517    [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],
518    [2, 7, 9, 3, 8, 0, 6, 4, 1, 5],
519    [7, 0, 4, 6, 9, 1, 3, 2, 5, 8],
520];
521
522/// The inverse table.
523const VERHOEFF_INV: [u8; 10] = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9];
524
525/// The check digit for a string of ASCII digits.
526///
527/// Verhoeff catches every single-digit error and every adjacent transposition, which are
528/// the two mistakes a person typing a number actually makes — a plain modulo-10 checksum
529/// catches the first and misses the second.
530fn verhoeff_check_digit(ascii_digits: &[u8]) -> Result<u8> {
531    let mut c = 0u8;
532    for (i, ascii) in ascii_digits.iter().rev().enumerate() {
533        let digit = ascii.checked_sub(b'0').filter(|d| *d < 10);
534        let Some(digit) = digit else {
535            bail!(InvalidArgument)
536        };
537        // Generating the check digit permutes by `i + 1`, because the digit being
538        // generated will occupy position 0 once it is appended.
539        let Some(row) = VERHOEFF_P.get(i.saturating_add(1) % 8) else {
540            bail!(InvalidArgument)
541        };
542        let Some(&permuted) = row.get(usize::from(digit)) else {
543            bail!(InvalidArgument)
544        };
545        let Some(&next) = VERHOEFF_D
546            .get(usize::from(c))
547            .and_then(|r| r.get(usize::from(permuted)))
548        else {
549            bail!(InvalidArgument)
550        };
551        c = next;
552    }
553    VERHOEFF_INV
554        .get(usize::from(c))
555        .copied()
556        .ok_or(Error::new(ErrorCode::InvalidArgument))
557}
558
559/// Whether a string of digits, check digit included, is self-consistent.
560fn verhoeff_is_valid(digits: &[u8]) -> bool {
561    let mut c = 0u8;
562    for (i, digit) in digits.iter().rev().enumerate() {
563        if *digit > 9 {
564            return false;
565        }
566        let (Some(row), Some(table)) = (VERHOEFF_P.get(i % 8), VERHOEFF_D.get(usize::from(c)))
567        else {
568            return false;
569        };
570        let Some(&permuted) = row.get(usize::from(*digit)) else {
571            return false;
572        };
573        let Some(&next) = table.get(usize::from(permuted)) else {
574            return false;
575        };
576        c = next;
577    }
578    c == 0
579}
580
581// --- Bit packing ---------------------------------------------------------------------------
582
583/// Writes fields least-significant-bit first, as Core Table 58 pictures.
584struct BitWriter {
585    bytes: [u8; PACKED_LEN],
586    bit: usize,
587}
588
589impl BitWriter {
590    const fn new() -> Self {
591        Self {
592            bytes: [0; PACKED_LEN],
593            bit: 0,
594        }
595    }
596
597    fn push(&mut self, value: u64, width: usize) {
598        for i in 0..width {
599            if (value >> i) & 1 == 1 {
600                let index = self.bit.saturating_add(i);
601                if let Some(slot) = self.bytes.get_mut(index / 8) {
602                    *slot |= 1u8 << (index % 8);
603                }
604            }
605        }
606        self.bit = self.bit.saturating_add(width);
607    }
608
609    const fn finish(self) -> [u8; PACKED_LEN] {
610        self.bytes
611    }
612}
613
614/// Reads fields the same way.
615struct BitReader<'a> {
616    bytes: &'a [u8],
617    bit: usize,
618}
619
620impl<'a> BitReader<'a> {
621    const fn new(bytes: &'a [u8]) -> Self {
622        Self { bytes, bit: 0 }
623    }
624
625    fn take(&mut self, width: usize) -> Result<u64> {
626        let mut value = 0u64;
627        for i in 0..width {
628            let index = self.bit.saturating_add(i);
629            let Some(&byte) = self.bytes.get(index / 8) else {
630                bail!(MessageTruncated)
631            };
632            if (byte >> (index % 8)) & 1 == 1 {
633                value |= 1u64 << i;
634            }
635        }
636        self.bit = self.bit.saturating_add(width);
637        Ok(value)
638    }
639}
640
641#[cfg(test)]
642mod tests {
643    use super::*;
644
645    /// The onboarding payload CHIP's test devices carry.
646    fn test_payload() -> OnboardingPayload {
647        OnboardingPayload::new(
648            VendorId(0xFFF1),
649            0x8001,
650            3840,
651            Passcode::new(20_202_021).expect("passcode"),
652            DiscoveryCapabilities::ON_IP_NETWORK,
653            CustomFlow::Standard,
654        )
655        .expect("payload")
656    }
657
658    #[test]
659    fn the_passcode_rules_of_5_1_7_1_are_enforced() {
660        assert!(Passcode::new(20_202_021).is_ok());
661        assert!(Passcode::new(1).is_ok());
662        assert!(Passcode::new(99_999_998).is_ok());
663        // Out of range.
664        assert!(Passcode::new(0).is_err());
665        assert!(Passcode::new(99_999_999).is_err());
666        assert!(Passcode::new(u32::MAX).is_err());
667        // Every one of the twelve trivial values.
668        for invalid in Passcode::INVALID {
669            assert!(Passcode::new(invalid).is_err(), "{invalid} must be refused");
670        }
671    }
672
673    #[test]
674    fn the_packed_structure_is_88_bits() {
675        // 3 + 16 + 16 + 2 + 8 + 12 + 27 = 84, padded to 88 = 11 octets.
676        assert_eq!(test_payload().pack().len(), PACKED_LEN);
677    }
678
679    #[test]
680    fn the_packed_structure_round_trips() {
681        let payload = test_payload();
682        assert_eq!(
683            OnboardingPayload::unpack(&payload.pack()).expect("unpack"),
684            payload
685        );
686    }
687
688    #[test]
689    fn version_zero_is_the_only_one_readable() {
690        // §5.1.1.1: "SHALL be 000".
691        let mut packed = test_payload().pack();
692        packed[0] |= 0b001;
693        assert_eq!(
694            OnboardingPayload::unpack(&packed).unwrap_err().code(),
695            ErrorCode::UnsupportedVersion
696        );
697    }
698
699    #[test]
700    fn the_qr_payload_round_trips() {
701        let payload = test_payload();
702        let qr = payload.to_qr().expect("qr");
703        assert!(qr.starts_with("MT:"), "{qr}");
704        // The packed structure alone is 11 octets: three 3-octet groups and one 2-octet
705        // group, so 5 + 5 + 5 + 4 = 19 characters after the prefix.
706        assert_eq!(qr.len(), 22, "{qr}");
707        assert_eq!(OnboardingPayload::from_qr(&qr).expect("parse"), payload);
708    }
709
710    #[test]
711    fn a_qr_payload_parses_with_or_without_its_prefix() {
712        let qr = test_payload().to_qr().expect("qr");
713        let bare = qr.strip_prefix("MT:").expect("prefix");
714        assert_eq!(
715            OnboardingPayload::from_qr(bare).expect("bare"),
716            OnboardingPayload::from_qr(&qr).expect("prefixed")
717        );
718    }
719
720    #[test]
721    fn base38_uses_the_alphabet_of_table_61() {
722        // Every character the encoder can produce must be in the QR alphanumeric set.
723        const QR_ALPHANUMERIC: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
724        for c in ALPHABET {
725            assert!(QR_ALPHANUMERIC.contains(c), "{}", char::from(*c));
726        }
727        assert_eq!(ALPHABET.len(), 38);
728        // And the removed ones are genuinely absent.
729        for removed in b"$%*+/ :" {
730            assert!(!ALPHABET.contains(removed), "{}", char::from(*removed));
731        }
732    }
733
734    #[test]
735    fn base38_group_sizes_follow_the_specification() {
736        // 3 octets → 5 characters, 2 → 4, 1 → 2.
737        for (octets, chars) in [(3usize, 5usize), (2, 4), (1, 2), (6, 10), (11, 19)] {
738            let mut out = heapless::String::<64>::new();
739            base38_encode(&vec_of(octets), &mut out).expect("encode");
740            assert_eq!(out.len(), chars, "{octets} octets");
741        }
742    }
743
744    fn vec_of(n: usize) -> heapless::Vec<u8, 16> {
745        let mut v = heapless::Vec::new();
746        for i in 0..n {
747            let _ = v.push(i as u8);
748        }
749        v
750    }
751
752    #[test]
753    fn base38_round_trips_every_length() {
754        for len in 1..=11usize {
755            let data = vec_of(len);
756            let mut text = heapless::String::<64>::new();
757            base38_encode(&data, &mut text).expect("encode");
758            let mut back = [0u8; 16];
759            let n = base38_decode(&text, &mut back).expect("decode");
760            assert_eq!(n, len);
761            assert_eq!(&back[..n], &data[..], "length {len}");
762        }
763    }
764
765    #[test]
766    fn base38_refuses_characters_outside_the_alphabet() {
767        let mut out = [0u8; 16];
768        assert!(base38_decode("ABC$E", &mut out).is_err());
769        assert!(base38_decode("abcde", &mut out).is_err(), "lower case");
770        // A group of 1 or 3 characters is not a whole number of octets.
771        assert!(base38_decode("A", &mut out).is_err());
772        assert!(base38_decode("ABC", &mut out).is_err());
773    }
774
775    #[test]
776    fn the_manual_code_round_trips() {
777        let payload = test_payload();
778        let code = payload.to_manual_code(false).expect("code");
779        assert_eq!(code.len(), 11, "{code}");
780
781        let parsed = OnboardingPayload::from_manual_code(&code).expect("parse");
782        assert_eq!(parsed.passcode, payload.passcode);
783        // A manual code carries only the top four bits of the discriminator.
784        assert_eq!(
785            parsed.discriminator >> 8,
786            payload.discriminator >> 8,
787            "{code}"
788        );
789        assert_eq!(parsed.discriminator & 0xFF, 0, "the rest are unknown");
790    }
791
792    #[test]
793    fn the_long_manual_code_carries_vendor_and_product() {
794        let mut payload = test_payload();
795        payload.custom_flow = CustomFlow::UserIntent;
796        let code = payload.to_manual_code(true).expect("code");
797        assert_eq!(code.len(), 21, "{code}");
798
799        let parsed = OnboardingPayload::from_manual_code(&code).expect("parse");
800        assert_eq!(parsed.vendor_id, payload.vendor_id);
801        assert_eq!(parsed.product_id, payload.product_id);
802        assert_eq!(parsed.passcode, payload.passcode);
803    }
804
805    #[test]
806    fn a_non_standard_flow_may_not_use_the_short_code() {
807        // §5.1.4.1.2: a commissioner reading a short code "SHALL assume it is a 'standard
808        // flow' device", so emitting one for a device that needs user action would make
809        // commissioning fail in a way nobody can diagnose.
810        let mut payload = test_payload();
811        payload.custom_flow = CustomFlow::UserIntent;
812        assert!(payload.to_manual_code(false).is_err());
813        assert!(payload.to_manual_code(true).is_ok());
814    }
815
816    #[test]
817    fn the_check_digit_catches_a_single_wrong_digit() {
818        // This is what Verhoeff is for: a person typing eleven digits gets one wrong.
819        let code = test_payload().to_manual_code(false).expect("code");
820        let bytes = code.as_bytes();
821        for position in 0..bytes.len() {
822            for replacement in b'0'..=b'9' {
823                if bytes[position] == replacement {
824                    continue;
825                }
826                let mut broken = heapless::String::<32>::new();
827                for (i, b) in bytes.iter().enumerate() {
828                    let c = if i == position { replacement } else { *b };
829                    let _ = broken.push(char::from(c));
830                }
831                assert!(
832                    OnboardingPayload::from_manual_code(&broken).is_err(),
833                    "a wrong digit at {position} was accepted: {broken}"
834                );
835            }
836        }
837    }
838
839    #[test]
840    fn the_check_digit_catches_a_transposition() {
841        // The other mistake people make, and the one a modulo-10 checksum misses.
842        let code = test_payload().to_manual_code(false).expect("code");
843        let bytes = code.as_bytes();
844        for i in 0..bytes.len().saturating_sub(1) {
845            if bytes[i] == bytes[i + 1] {
846                continue;
847            }
848            let mut swapped = heapless::String::<32>::new();
849            for (j, b) in bytes.iter().enumerate() {
850                let c = if j == i {
851                    bytes[i + 1]
852                } else if j == i + 1 {
853                    bytes[i]
854                } else {
855                    *b
856                };
857                let _ = swapped.push(char::from(c));
858            }
859            assert!(
860                OnboardingPayload::from_manual_code(&swapped).is_err(),
861                "a transposition at {i} was accepted: {swapped}"
862            );
863        }
864    }
865
866    #[test]
867    fn dashes_and_spaces_are_tolerated() {
868        // §5.1.4.2: "a receiving application seeing the code '1234-567-8910' would need to
869        // interpret it as '12345678910'".
870        let code = test_payload().to_manual_code(false).expect("code");
871        let mut spaced = heapless::String::<32>::new();
872        for (i, c) in code.chars().enumerate() {
873            if i == 4 || i == 7 {
874                let _ = spaced.push('-');
875            }
876            let _ = spaced.push(c);
877        }
878        assert_eq!(
879            OnboardingPayload::from_manual_code(&spaced).expect("spaced"),
880            OnboardingPayload::from_manual_code(&code).expect("plain")
881        );
882    }
883
884    #[test]
885    fn a_manual_code_of_the_wrong_length_is_refused() {
886        for text in [
887            "",
888            "1",
889            "1234567890",
890            "123456789012",
891            "1".repeat(22).as_str(),
892        ] {
893            assert!(
894                OnboardingPayload::from_manual_code(text).is_err(),
895                "{text:?} has {} digits",
896                text.len()
897            );
898        }
899    }
900
901    #[test]
902    fn a_first_digit_of_eight_or_nine_is_a_future_version() {
903        // §5.1.4.1.4: "First digit of '8' or '9' would be invalid for v1 and would
904        // indicate new format".
905        for first in ['8', '9'] {
906            let mut code = heapless::String::<32>::new();
907            let _ = code.push(first);
908            for _ in 0..10 {
909                let _ = code.push('0');
910            }
911            // Whatever the check digit says, the version is what is refused first — so
912            // build one with a valid checksum.
913            let digits: heapless::Vec<u8, 21> = code.bytes().take(10).map(|b| b - b'0').collect();
914            let mut ascii = heapless::String::<32>::new();
915            for d in &digits {
916                let _ = ascii.push(char::from(b'0' + d));
917            }
918            let check = verhoeff_check_digit(ascii.as_bytes()).expect("check");
919            let _ = ascii.push(char::from(b'0' + check));
920            assert_eq!(
921                OnboardingPayload::from_manual_code(&ascii)
922                    .unwrap_err()
923                    .code(),
924                ErrorCode::UnsupportedVersion,
925                "{ascii}"
926            );
927        }
928    }
929
930    #[test]
931    fn the_discriminator_must_fit_twelve_bits() {
932        assert!(
933            OnboardingPayload::new(
934                VendorId(1),
935                1,
936                0x1000,
937                Passcode::new(1).expect("p"),
938                DiscoveryCapabilities::empty(),
939                CustomFlow::Standard,
940            )
941            .is_err()
942        );
943        assert!(
944            OnboardingPayload::new(
945                VendorId(1),
946                1,
947                0x0FFF,
948                Passcode::new(1).expect("p"),
949                DiscoveryCapabilities::empty(),
950                CustomFlow::Standard,
951            )
952            .is_ok()
953        );
954    }
955
956    #[test]
957    fn a_reserved_custom_flow_is_refused() {
958        // "3: Reserved". Custom Flow is two bits at offset 35 (3 + 16 + 16), so setting
959        // both means bit 35 and bit 36 — byte 4, bits 3 and 4.
960        assert_eq!(
961            CustomFlow::from_bits(3).unwrap_err().code(),
962            ErrorCode::MessageReserved
963        );
964        let mut packed = test_payload().pack();
965        packed[4] |= 0b0001_1000;
966        assert_eq!(
967            OnboardingPayload::unpack(&packed).unwrap_err().code(),
968            ErrorCode::MessageReserved,
969            "a payload with the reserved flow must not decode"
970        );
971    }
972
973    #[test]
974    fn every_field_survives_the_round_trip_independently() {
975        // A bit-packing bug usually shows as one field bleeding into the next, which a
976        // single fixture would miss.
977        for discriminator in [0u16, 1, 0x0FF, 0x800, 0x0FFF] {
978            for passcode in [1u32, 20_202_021, 99_999_998] {
979                for flow in [
980                    CustomFlow::Standard,
981                    CustomFlow::UserIntent,
982                    CustomFlow::Custom,
983                ] {
984                    let payload = OnboardingPayload::new(
985                        VendorId(0xFFF1),
986                        0x8001,
987                        discriminator,
988                        Passcode::new(passcode).expect("passcode"),
989                        DiscoveryCapabilities::BLE | DiscoveryCapabilities::ON_IP_NETWORK,
990                        flow,
991                    )
992                    .expect("payload");
993                    let qr = payload.to_qr().expect("qr");
994                    assert_eq!(
995                        OnboardingPayload::from_qr(&qr).expect("parse"),
996                        payload,
997                        "{discriminator:#x} {passcode} {flow:?}"
998                    );
999                }
1000            }
1001        }
1002    }
1003}