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    #[expect(
211        clippy::cast_possible_truncation,
212        reason = "every `take` here is width-exact: §5.1.3.1.3's fields are 27, 16, 12, 8 and 2 bits"
213    )]
214    pub fn unpack(bytes: &[u8]) -> Result<Self> {
215        let Some(packed) = bytes.get(..PACKED_LEN) else {
216            bail!(MessageTruncated)
217        };
218        let mut bits = BitReader::new(packed);
219        let version = bits.take(3)?;
220        if version != 0 {
221            // §5.1.1.1: the version "SHALL be 000"; anything else is a payload this
222            // revision does not know how to read, and guessing would be worse than saying so.
223            bail!(UnsupportedVersion)
224        }
225        let vendor_id = VendorId(bits.take(16)? as u16);
226        let product_id = bits.take(16)? as u16;
227        let custom_flow = CustomFlow::from_bits(bits.take(2)? as u8)?;
228        let discovery = DiscoveryCapabilities::from_bits_retain(bits.take(8)? as u8);
229        let discriminator = bits.take(12)? as u16;
230        let passcode = Passcode::new(bits.take(27)? as u32)?;
231
232        Ok(Self {
233            vendor_id,
234            product_id,
235            custom_flow,
236            discovery,
237            discriminator,
238            passcode,
239        })
240    }
241
242    /// Renders the QR payload: `MT:` followed by the base-38 encoding.
243    pub fn to_qr(&self) -> Result<heapless::String<QR_LEN_NO_TLV>> {
244        let mut out = heapless::String::new();
245        out.push_str(QR_PREFIX)
246            .map_err(|_| Error::new(ErrorCode::NoSpace))?;
247        base38_encode(&self.pack(), &mut out)?;
248        Ok(out)
249    }
250
251    /// Parses a QR payload.
252    ///
253    /// Accepts the string with or without its `MT:` prefix; a camera app that strips it is
254    /// common enough that refusing would be unhelpful.
255    pub fn from_qr(text: &str) -> Result<Self> {
256        let body = text.strip_prefix(QR_PREFIX).unwrap_or(text);
257        let mut packed = [0u8; PACKED_LEN];
258        let n = base38_decode(body, &mut packed)?;
259        if n < PACKED_LEN {
260            bail!(MessageTruncated)
261        }
262        Self::unpack(&packed)
263    }
264
265    /// Renders the manual pairing code (§5.1.4).
266    ///
267    /// `include_vid_pid` produces the 21-digit form. §5.1.4.1.2 ties this to the
268    /// commissioning flow: a standard-flow device uses the short form, and a user-intent
269    /// or custom-flow device "SHALL" use the long one — so this refuses the combination
270    /// the specification forbids rather than producing a code a commissioner will
271    /// misread as standard flow.
272    pub fn to_manual_code(
273        &self,
274        include_vid_pid: bool,
275    ) -> Result<heapless::String<MANUAL_CODE_MAX_DIGITS>> {
276        if !include_vid_pid && self.custom_flow != CustomFlow::Standard {
277            bail!(InvalidArgument)
278        }
279
280        let passcode = self.passcode.value();
281        let discriminator = u32::from(self.discriminator & DISCRIMINATOR_MASK);
282
283        // DIGIT[1] := (VID_PID_PRESENT << 2) | (DISCRIMINATOR >> 10)
284        let first = (u32::from(include_vid_pid) << 2) | (discriminator >> 10);
285        // DIGIT[2..6] := ((DISCRIMINATOR & 0x300) << 6) | (PASSCODE & 0x3FFF)
286        let group2 = ((discriminator & 0x300) << 6) | (passcode & 0x3FFF);
287        // DIGIT[7..10] := (PASSCODE >> 14)
288        let group3 = passcode >> 14;
289
290        let mut out = heapless::String::<MANUAL_CODE_MAX_DIGITS>::new();
291        push_digits(&mut out, first, 1)?;
292        push_digits(&mut out, group2, 5)?;
293        push_digits(&mut out, group3, 4)?;
294        if include_vid_pid {
295            push_digits(&mut out, u32::from(self.vendor_id.0), 5)?;
296            push_digits(&mut out, u32::from(self.product_id), 5)?;
297        }
298        let check = verhoeff_check_digit(out.as_bytes())?;
299        push_digits(&mut out, u32::from(check), 1)?;
300        Ok(out)
301    }
302
303    /// Parses a manual pairing code.
304    ///
305    /// "The receiving application SHALL be robust against characters like dashes and
306    /// spaces that may be included in the string" (§5.1.4.2), so those are stripped before
307    /// anything else — a user who types `3497-011-2665` has typed a valid code.
308    ///
309    /// The discriminator that comes back has only its top four bits set; the rest are
310    /// zero, because a manual code does not carry them.
311    #[expect(
312        clippy::cast_possible_truncation,
313        reason = "`bounded` holds each group to the width §5.1.4.1.4's tables give it, before any cast"
314    )]
315    pub fn from_manual_code(text: &str) -> Result<Self> {
316        let mut digits = heapless::Vec::<u8, MANUAL_CODE_MAX_DIGITS>::new();
317        for c in text.chars() {
318            match c {
319                '0'..='9' => digits
320                    .push((c as u8).wrapping_sub(b'0'))
321                    .map_err(|_| Error::new(ErrorCode::InvalidArgument))?,
322                '-' | ' ' => {}
323                _ => bail!(InvalidArgument),
324            }
325        }
326
327        let expect_vid_pid = match digits.len() {
328            11 => false,
329            21 => true,
330            _ => bail!(InvalidArgument),
331        };
332        if !verhoeff_is_valid(&digits) {
333            // A single mistyped digit is caught here rather than by a failed PASE
334            // exchange several seconds later.
335            bail!(IntegrityCheckFailed)
336        }
337
338        let first = u32::from(digits.first().copied().unwrap_or(0));
339        // §5.1.4.1.4: "First digit of '8' or '9' would be invalid for v1".
340        if first > 7 {
341            bail!(UnsupportedVersion)
342        }
343        let vid_pid_present = (first & 0b100) != 0;
344        if vid_pid_present != expect_vid_pid {
345            // The flag and the length must agree, or one of them is a lie.
346            bail!(InvalidArgument)
347        }
348
349        // §5.1.4.1.4's Tables 63 and 64 state the range of every group, and a group outside it
350        // is not a code this encoding produced. Reading one anyway is worse than refusing it:
351        // the surplus bits fall off a mask or an `as`, so an invalid code decodes — silently —
352        // to a *different* device's discriminator, passcode or vendor. `push_digits` has always
353        // refused to write a value too wide for its group; this is the reading half of that.
354        let group2 = bounded(digits_value(&digits, 1, 5)?, 0xFFFF)?;
355        let group3 = bounded(digits_value(&digits, 6, 4)?, 0x1FFF)?;
356
357        let discriminator = (((first & 0b011) << 10) | ((group2 & 0xC000) >> 6)) as u16;
358        let passcode = Passcode::new((group2 & 0x3FFF) | (group3 << 14))?;
359
360        let (vendor_id, product_id) = if vid_pid_present {
361            (
362                VendorId(bounded(digits_value(&digits, 10, 5)?, 0xFFFF)? as u16),
363                bounded(digits_value(&digits, 15, 5)?, 0xFFFF)? as u16,
364            )
365        } else {
366            (VendorId(0), 0)
367        };
368
369        Ok(Self {
370            vendor_id,
371            product_id,
372            // §5.1.4.1.2: a short code means standard flow; a long one needs the
373            // Distributed Compliance Ledger to say which of the other two it is, so the
374            // most this parser can honestly report is "not standard".
375            custom_flow: if vid_pid_present {
376                CustomFlow::UserIntent
377            } else {
378                CustomFlow::Standard
379            },
380            discovery: DiscoveryCapabilities::empty(),
381            discriminator,
382            passcode,
383        })
384    }
385}
386
387fn push_digits<const N: usize>(
388    out: &mut heapless::String<N>,
389    value: u32,
390    width: usize,
391) -> Result<()> {
392    let mut scratch = [0u8; 10];
393    let mut v = value;
394    for i in (0..width).rev() {
395        let Some(slot) = scratch.get_mut(i) else {
396            bail!(InvalidArgument)
397        };
398        *slot = b'0'.saturating_add((v % 10) as u8);
399        v /= 10;
400    }
401    if v != 0 {
402        // The value did not fit the width it was promised, which would silently shift
403        // every later digit.
404        bail!(InvalidArgument)
405    }
406    let Some(text) = scratch
407        .get(..width)
408        .and_then(|b| core::str::from_utf8(b).ok())
409    else {
410        bail!(InvalidArgument)
411    };
412    out.push_str(text)
413        .map_err(|_| Error::new(ErrorCode::NoSpace))
414}
415
416/// A digit group's value, refused if it is wider than the field it encodes.
417///
418/// §5.1.4.1.4's tables give each group a range — 00000..=65535 for the two 16-bit groups,
419/// 0000..=8191 for the 13-bit one — and a five-digit group can hold 99999. The difference is
420/// exactly the space in which an invalid code would otherwise decode to a valid-looking one.
421const fn bounded(value: u32, max: u32) -> Result<u32> {
422    if value > max {
423        return Err(Error::new(ErrorCode::InvalidArgument));
424    }
425    Ok(value)
426}
427
428fn digits_value(digits: &[u8], start: usize, width: usize) -> Result<u32> {
429    let end = start
430        .checked_add(width)
431        .ok_or(Error::new(ErrorCode::InvalidArgument))?;
432    let Some(slice) = digits.get(start..end) else {
433        bail!(InvalidArgument)
434    };
435    let mut value = 0u32;
436    for d in slice {
437        value = value
438            .checked_mul(10)
439            .and_then(|v| v.checked_add(u32::from(*d)))
440            .ok_or(Error::new(ErrorCode::InvalidArgument))?;
441    }
442    Ok(value)
443}
444
445// --- Base 38 (§5.1.3.1.5) ---------------------------------------------------------------
446
447/// "every 3 bytes (24 bits) of binary source data are encoded to 5 characters", with two
448/// bytes going to four characters and one byte to two.
449fn base38_encode<const N: usize>(data: &[u8], out: &mut heapless::String<N>) -> Result<()> {
450    for chunk in data.chunks(3) {
451        let (value, width) = match chunk {
452            // "UINT24 = (BYTE[N+2] << 16) | (BYTE[N+1] << 8) | (BYTE[N] << 0)" — the
453            // chunk is little-endian.
454            [a, b, c] => (
455                u32::from(*a) | (u32::from(*b) << 8) | (u32::from(*c) << 16),
456                5,
457            ),
458            [a, b] => (u32::from(*a) | (u32::from(*b) << 8), 4),
459            [a] => (u32::from(*a), 2),
460            _ => bail!(InvalidArgument),
461        };
462        let mut v = value;
463        for _ in 0..width {
464            let Some(&c) = ALPHABET.get((v % 38) as usize) else {
465                bail!(InvalidArgument)
466            };
467            // "with the least-significant character appearing first (little-endian)".
468            out.push(char::from(c))
469                .map_err(|_| Error::new(ErrorCode::NoSpace))?;
470            v /= 38;
471        }
472    }
473    Ok(())
474}
475
476/// Decodes base-38 into `out`, returning how many octets it produced.
477#[expect(
478    clippy::cast_possible_truncation,
479    reason = "a base-38 group is checked against its own byte width before its octets are taken"
480)]
481fn base38_decode(text: &str, out: &mut [u8]) -> Result<usize> {
482    let bytes = text.as_bytes();
483    let mut written = 0usize;
484
485    for chunk in bytes.chunks(5) {
486        let width = match chunk.len() {
487            5 => 3usize,
488            4 => 2,
489            2 => 1,
490            // 1 or 3 characters cannot be a whole number of octets.
491            _ => bail!(InvalidArgument),
492        };
493        let mut value = 0u32;
494        // Least-significant character first, so fold from the end.
495        for c in chunk.iter().rev() {
496            let Some(digit) = ALPHABET.iter().position(|a| a == c) else {
497                bail!(InvalidArgument)
498            };
499            value = value
500                .checked_mul(38)
501                .and_then(|v| v.checked_add(digit as u32))
502                .ok_or(Error::new(ErrorCode::InvalidArgument))?;
503        }
504        // A 5-character group must fit 24 bits, a 4-character group 16, a 2-character
505        // group 8 — a larger value means the encoding is not one this alphabet produced.
506        let limit = 1u32
507            .checked_shl((width as u32).saturating_mul(8))
508            .unwrap_or(u32::MAX);
509        if width < 4 && value >= limit {
510            bail!(InvalidArgument)
511        }
512        for i in 0..width {
513            let Some(slot) = out.get_mut(written) else {
514                bail!(BufferTooSmall)
515            };
516            *slot = (value >> (i.saturating_mul(8))) as u8;
517            written = written.saturating_add(1);
518        }
519    }
520    Ok(written)
521}
522
523// --- Verhoeff (§5.1.4.1.5) ----------------------------------------------------------------
524
525/// The dihedral group D₅ multiplication table.
526const VERHOEFF_D: [[u8; 10]; 10] = [
527    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
528    [1, 2, 3, 4, 0, 6, 7, 8, 9, 5],
529    [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],
530    [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],
531    [4, 0, 1, 2, 3, 9, 5, 6, 7, 8],
532    [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],
533    [6, 5, 9, 8, 7, 1, 0, 4, 3, 2],
534    [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],
535    [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],
536    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0],
537];
538
539/// The permutation table, applied by position.
540const VERHOEFF_P: [[u8; 10]; 8] = [
541    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
542    [1, 5, 7, 6, 2, 8, 3, 0, 9, 4],
543    [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],
544    [8, 9, 1, 6, 0, 4, 3, 5, 2, 7],
545    [9, 4, 5, 3, 1, 2, 6, 8, 7, 0],
546    [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],
547    [2, 7, 9, 3, 8, 0, 6, 4, 1, 5],
548    [7, 0, 4, 6, 9, 1, 3, 2, 5, 8],
549];
550
551/// The inverse table.
552const VERHOEFF_INV: [u8; 10] = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9];
553
554/// The check digit for a string of ASCII digits.
555///
556/// Verhoeff catches every single-digit error and every adjacent transposition, which are
557/// the two mistakes a person typing a number actually makes — a plain modulo-10 checksum
558/// catches the first and misses the second.
559fn verhoeff_check_digit(ascii_digits: &[u8]) -> Result<u8> {
560    let mut c = 0u8;
561    for (i, ascii) in ascii_digits.iter().rev().enumerate() {
562        let digit = ascii.checked_sub(b'0').filter(|d| *d < 10);
563        let Some(digit) = digit else {
564            bail!(InvalidArgument)
565        };
566        // Generating the check digit permutes by `i + 1`, because the digit being
567        // generated will occupy position 0 once it is appended.
568        let Some(row) = VERHOEFF_P.get(i.saturating_add(1) % 8) else {
569            bail!(InvalidArgument)
570        };
571        let Some(&permuted) = row.get(usize::from(digit)) else {
572            bail!(InvalidArgument)
573        };
574        let Some(&next) = VERHOEFF_D
575            .get(usize::from(c))
576            .and_then(|r| r.get(usize::from(permuted)))
577        else {
578            bail!(InvalidArgument)
579        };
580        c = next;
581    }
582    VERHOEFF_INV
583        .get(usize::from(c))
584        .copied()
585        .ok_or(Error::new(ErrorCode::InvalidArgument))
586}
587
588/// Whether a string of digits, check digit included, is self-consistent.
589fn verhoeff_is_valid(digits: &[u8]) -> bool {
590    let mut c = 0u8;
591    for (i, digit) in digits.iter().rev().enumerate() {
592        if *digit > 9 {
593            return false;
594        }
595        let (Some(row), Some(table)) = (VERHOEFF_P.get(i % 8), VERHOEFF_D.get(usize::from(c)))
596        else {
597            return false;
598        };
599        let Some(&permuted) = row.get(usize::from(*digit)) else {
600            return false;
601        };
602        let Some(&next) = table.get(usize::from(permuted)) else {
603            return false;
604        };
605        c = next;
606    }
607    c == 0
608}
609
610// --- Bit packing ---------------------------------------------------------------------------
611
612/// Writes fields least-significant-bit first, as Core Table 58 pictures.
613struct BitWriter {
614    bytes: [u8; PACKED_LEN],
615    bit: usize,
616}
617
618impl BitWriter {
619    const fn new() -> Self {
620        Self {
621            bytes: [0; PACKED_LEN],
622            bit: 0,
623        }
624    }
625
626    fn push(&mut self, value: u64, width: usize) {
627        for i in 0..width {
628            if (value >> i) & 1 == 1 {
629                let index = self.bit.saturating_add(i);
630                if let Some(slot) = self.bytes.get_mut(index / 8) {
631                    *slot |= 1u8 << (index % 8);
632                }
633            }
634        }
635        self.bit = self.bit.saturating_add(width);
636    }
637
638    const fn finish(self) -> [u8; PACKED_LEN] {
639        self.bytes
640    }
641}
642
643/// Reads fields the same way.
644struct BitReader<'a> {
645    bytes: &'a [u8],
646    bit: usize,
647}
648
649impl<'a> BitReader<'a> {
650    const fn new(bytes: &'a [u8]) -> Self {
651        Self { bytes, bit: 0 }
652    }
653
654    fn take(&mut self, width: usize) -> Result<u64> {
655        let mut value = 0u64;
656        for i in 0..width {
657            let index = self.bit.saturating_add(i);
658            let Some(&byte) = self.bytes.get(index / 8) else {
659                bail!(MessageTruncated)
660            };
661            if (byte >> (index % 8)) & 1 == 1 {
662                value |= 1u64 << i;
663            }
664        }
665        self.bit = self.bit.saturating_add(width);
666        Ok(value)
667    }
668}
669
670#[cfg(test)]
671mod tests {
672    use super::*;
673
674    /// The onboarding payload CHIP's test devices carry.
675    fn test_payload() -> OnboardingPayload {
676        OnboardingPayload::new(
677            VendorId(0xFFF1),
678            0x8001,
679            3840,
680            Passcode::new(20_202_021).expect("passcode"),
681            DiscoveryCapabilities::ON_IP_NETWORK,
682            CustomFlow::Standard,
683        )
684        .expect("payload")
685    }
686
687    #[test]
688    fn the_passcode_rules_of_5_1_7_1_are_enforced() {
689        assert!(Passcode::new(20_202_021).is_ok());
690        assert!(Passcode::new(1).is_ok());
691        assert!(Passcode::new(99_999_998).is_ok());
692        // Out of range.
693        assert!(Passcode::new(0).is_err());
694        assert!(Passcode::new(99_999_999).is_err());
695        assert!(Passcode::new(u32::MAX).is_err());
696        // Every one of the twelve trivial values.
697        for invalid in Passcode::INVALID {
698            assert!(Passcode::new(invalid).is_err(), "{invalid} must be refused");
699        }
700    }
701
702    #[test]
703    fn the_packed_structure_is_88_bits() {
704        // 3 + 16 + 16 + 2 + 8 + 12 + 27 = 84, padded to 88 = 11 octets.
705        assert_eq!(test_payload().pack().len(), PACKED_LEN);
706    }
707
708    #[test]
709    fn the_packed_structure_round_trips() {
710        let payload = test_payload();
711        assert_eq!(
712            OnboardingPayload::unpack(&payload.pack()).expect("unpack"),
713            payload
714        );
715    }
716
717    #[test]
718    fn version_zero_is_the_only_one_readable() {
719        // §5.1.1.1: "SHALL be 000".
720        let mut packed = test_payload().pack();
721        packed[0] |= 0b001;
722        assert_eq!(
723            OnboardingPayload::unpack(&packed).unwrap_err().code(),
724            ErrorCode::UnsupportedVersion
725        );
726    }
727
728    #[test]
729    fn the_qr_payload_round_trips() {
730        let payload = test_payload();
731        let qr = payload.to_qr().expect("qr");
732        assert!(qr.starts_with("MT:"), "{qr}");
733        // The packed structure alone is 11 octets: three 3-octet groups and one 2-octet
734        // group, so 5 + 5 + 5 + 4 = 19 characters after the prefix.
735        assert_eq!(qr.len(), 22, "{qr}");
736        assert_eq!(OnboardingPayload::from_qr(&qr).expect("parse"), payload);
737    }
738
739    #[test]
740    fn a_qr_payload_parses_with_or_without_its_prefix() {
741        let qr = test_payload().to_qr().expect("qr");
742        let bare = qr.strip_prefix("MT:").expect("prefix");
743        assert_eq!(
744            OnboardingPayload::from_qr(bare).expect("bare"),
745            OnboardingPayload::from_qr(&qr).expect("prefixed")
746        );
747    }
748
749    #[test]
750    fn base38_uses_the_alphabet_of_table_61() {
751        // Every character the encoder can produce must be in the QR alphanumeric set.
752        const QR_ALPHANUMERIC: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
753        for c in ALPHABET {
754            assert!(QR_ALPHANUMERIC.contains(c), "{}", char::from(*c));
755        }
756        assert_eq!(ALPHABET.len(), 38);
757        // And the removed ones are genuinely absent.
758        for removed in b"$%*+/ :" {
759            assert!(!ALPHABET.contains(removed), "{}", char::from(*removed));
760        }
761    }
762
763    #[test]
764    fn base38_group_sizes_follow_the_specification() {
765        // 3 octets → 5 characters, 2 → 4, 1 → 2.
766        for (octets, chars) in [(3usize, 5usize), (2, 4), (1, 2), (6, 10), (11, 19)] {
767            let mut out = heapless::String::<64>::new();
768            base38_encode(&vec_of(octets), &mut out).expect("encode");
769            assert_eq!(out.len(), chars, "{octets} octets");
770        }
771    }
772
773    fn vec_of(n: usize) -> heapless::Vec<u8, 16> {
774        let mut v = heapless::Vec::new();
775        for i in 0..n {
776            let _ = v.push(i as u8);
777        }
778        v
779    }
780
781    #[test]
782    fn base38_round_trips_every_length() {
783        for len in 1..=11usize {
784            let data = vec_of(len);
785            let mut text = heapless::String::<64>::new();
786            base38_encode(&data, &mut text).expect("encode");
787            let mut back = [0u8; 16];
788            let n = base38_decode(&text, &mut back).expect("decode");
789            assert_eq!(n, len);
790            assert_eq!(&back[..n], &data[..], "length {len}");
791        }
792    }
793
794    #[test]
795    fn base38_refuses_characters_outside_the_alphabet() {
796        let mut out = [0u8; 16];
797        assert!(base38_decode("ABC$E", &mut out).is_err());
798        assert!(base38_decode("abcde", &mut out).is_err(), "lower case");
799        // A group of 1 or 3 characters is not a whole number of octets.
800        assert!(base38_decode("A", &mut out).is_err());
801        assert!(base38_decode("ABC", &mut out).is_err());
802    }
803
804    #[test]
805    fn the_manual_code_round_trips() {
806        let payload = test_payload();
807        let code = payload.to_manual_code(false).expect("code");
808        assert_eq!(code.len(), 11, "{code}");
809
810        let parsed = OnboardingPayload::from_manual_code(&code).expect("parse");
811        assert_eq!(parsed.passcode, payload.passcode);
812        // A manual code carries only the top four bits of the discriminator.
813        assert_eq!(
814            parsed.discriminator >> 8,
815            payload.discriminator >> 8,
816            "{code}"
817        );
818        assert_eq!(parsed.discriminator & 0xFF, 0, "the rest are unknown");
819    }
820
821    #[test]
822    fn the_long_manual_code_carries_vendor_and_product() {
823        let mut payload = test_payload();
824        payload.custom_flow = CustomFlow::UserIntent;
825        let code = payload.to_manual_code(true).expect("code");
826        assert_eq!(code.len(), 21, "{code}");
827
828        let parsed = OnboardingPayload::from_manual_code(&code).expect("parse");
829        assert_eq!(parsed.vendor_id, payload.vendor_id);
830        assert_eq!(parsed.product_id, payload.product_id);
831        assert_eq!(parsed.passcode, payload.passcode);
832    }
833
834    #[test]
835    fn a_non_standard_flow_may_not_use_the_short_code() {
836        // §5.1.4.1.2: a commissioner reading a short code "SHALL assume it is a 'standard
837        // flow' device", so emitting one for a device that needs user action would make
838        // commissioning fail in a way nobody can diagnose.
839        let mut payload = test_payload();
840        payload.custom_flow = CustomFlow::UserIntent;
841        assert!(payload.to_manual_code(false).is_err());
842        assert!(payload.to_manual_code(true).is_ok());
843    }
844
845    #[test]
846    fn the_check_digit_catches_a_single_wrong_digit() {
847        // This is what Verhoeff is for: a person typing eleven digits gets one wrong.
848        let code = test_payload().to_manual_code(false).expect("code");
849        let bytes = code.as_bytes();
850        for position in 0..bytes.len() {
851            for replacement in b'0'..=b'9' {
852                if bytes[position] == replacement {
853                    continue;
854                }
855                let mut broken = heapless::String::<32>::new();
856                for (i, b) in bytes.iter().enumerate() {
857                    let c = if i == position { replacement } else { *b };
858                    let _ = broken.push(char::from(c));
859                }
860                assert!(
861                    OnboardingPayload::from_manual_code(&broken).is_err(),
862                    "a wrong digit at {position} was accepted: {broken}"
863                );
864            }
865        }
866    }
867
868    #[test]
869    fn the_check_digit_catches_a_transposition() {
870        // The other mistake people make, and the one a modulo-10 checksum misses.
871        let code = test_payload().to_manual_code(false).expect("code");
872        let bytes = code.as_bytes();
873        for i in 0..bytes.len().saturating_sub(1) {
874            if bytes[i] == bytes[i + 1] {
875                continue;
876            }
877            let mut swapped = heapless::String::<32>::new();
878            for (j, b) in bytes.iter().enumerate() {
879                let c = if j == i {
880                    bytes[i + 1]
881                } else if j == i + 1 {
882                    bytes[i]
883                } else {
884                    *b
885                };
886                let _ = swapped.push(char::from(c));
887            }
888            assert!(
889                OnboardingPayload::from_manual_code(&swapped).is_err(),
890                "a transposition at {i} was accepted: {swapped}"
891            );
892        }
893    }
894
895    #[test]
896    fn dashes_and_spaces_are_tolerated() {
897        // §5.1.4.2: "a receiving application seeing the code '1234-567-8910' would need to
898        // interpret it as '12345678910'".
899        let code = test_payload().to_manual_code(false).expect("code");
900        let mut spaced = heapless::String::<32>::new();
901        for (i, c) in code.chars().enumerate() {
902            if i == 4 || i == 7 {
903                let _ = spaced.push('-');
904            }
905            let _ = spaced.push(c);
906        }
907        assert_eq!(
908            OnboardingPayload::from_manual_code(&spaced).expect("spaced"),
909            OnboardingPayload::from_manual_code(&code).expect("plain")
910        );
911    }
912
913    #[test]
914    fn a_manual_code_of_the_wrong_length_is_refused() {
915        for text in [
916            "",
917            "1",
918            "1234567890",
919            "123456789012",
920            "1".repeat(22).as_str(),
921        ] {
922            assert!(
923                OnboardingPayload::from_manual_code(text).is_err(),
924                "{text:?} has {} digits",
925                text.len()
926            );
927        }
928    }
929
930    #[test]
931    fn a_first_digit_of_eight_or_nine_is_a_future_version() {
932        // §5.1.4.1.4: "First digit of '8' or '9' would be invalid for v1 and would
933        // indicate new format".
934        for first in ['8', '9'] {
935            let mut code = heapless::String::<32>::new();
936            let _ = code.push(first);
937            for _ in 0..10 {
938                let _ = code.push('0');
939            }
940            // Whatever the check digit says, the version is what is refused first — so
941            // build one with a valid checksum.
942            let digits: heapless::Vec<u8, 21> = code.bytes().take(10).map(|b| b - b'0').collect();
943            let mut ascii = heapless::String::<32>::new();
944            for d in &digits {
945                let _ = ascii.push(char::from(b'0' + d));
946            }
947            let check = verhoeff_check_digit(ascii.as_bytes()).expect("check");
948            let _ = ascii.push(char::from(b'0' + check));
949            assert_eq!(
950                OnboardingPayload::from_manual_code(&ascii)
951                    .unwrap_err()
952                    .code(),
953                ErrorCode::UnsupportedVersion,
954                "{ascii}"
955            );
956        }
957    }
958
959    #[test]
960    fn the_discriminator_must_fit_twelve_bits() {
961        assert!(
962            OnboardingPayload::new(
963                VendorId(1),
964                1,
965                0x1000,
966                Passcode::new(1).expect("p"),
967                DiscoveryCapabilities::empty(),
968                CustomFlow::Standard,
969            )
970            .is_err()
971        );
972        assert!(
973            OnboardingPayload::new(
974                VendorId(1),
975                1,
976                0x0FFF,
977                Passcode::new(1).expect("p"),
978                DiscoveryCapabilities::empty(),
979                CustomFlow::Standard,
980            )
981            .is_ok()
982        );
983    }
984
985    #[test]
986    fn a_reserved_custom_flow_is_refused() {
987        // "3: Reserved". Custom Flow is two bits at offset 35 (3 + 16 + 16), so setting
988        // both means bit 35 and bit 36 — byte 4, bits 3 and 4.
989        assert_eq!(
990            CustomFlow::from_bits(3).unwrap_err().code(),
991            ErrorCode::MessageReserved
992        );
993        let mut packed = test_payload().pack();
994        packed[4] |= 0b0001_1000;
995        assert_eq!(
996            OnboardingPayload::unpack(&packed).unwrap_err().code(),
997            ErrorCode::MessageReserved,
998            "a payload with the reserved flow must not decode"
999        );
1000    }
1001
1002    #[test]
1003    fn every_field_survives_the_round_trip_independently() {
1004        // A bit-packing bug usually shows as one field bleeding into the next, which a
1005        // single fixture would miss.
1006        for discriminator in [0u16, 1, 0x0FF, 0x800, 0x0FFF] {
1007            for passcode in [1u32, 20_202_021, 99_999_998] {
1008                for flow in [
1009                    CustomFlow::Standard,
1010                    CustomFlow::UserIntent,
1011                    CustomFlow::Custom,
1012                ] {
1013                    let payload = OnboardingPayload::new(
1014                        VendorId(0xFFF1),
1015                        0x8001,
1016                        discriminator,
1017                        Passcode::new(passcode).expect("passcode"),
1018                        DiscoveryCapabilities::BLE | DiscoveryCapabilities::ON_IP_NETWORK,
1019                        flow,
1020                    )
1021                    .expect("payload");
1022                    let qr = payload.to_qr().expect("qr");
1023                    assert_eq!(
1024                        OnboardingPayload::from_qr(&qr).expect("parse"),
1025                        payload,
1026                        "{discriminator:#x} {passcode} {flow:?}"
1027                    );
1028                }
1029            }
1030        }
1031    }
1032}