1use crate::error::{Error, ErrorCode, Result, bail};
25use crate::msg::VendorId;
26
27const ALPHABET: &[u8; 38] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-.";
34
35pub const QR_PREFIX: &str = "MT:";
37
38pub const PACKED_LEN: usize = 11;
40
41pub const QR_LEN_NO_TLV: usize = 3 + 19;
43
44pub const MANUAL_CODE_MAX_DIGITS: usize = 21;
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53pub struct Passcode(u32);
54
55impl Passcode {
56 pub const MIN: u32 = 0x0000_0001;
58 pub const MAX: u32 = 0x05F5_E0FE;
60
61 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 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 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 #[must_use]
86 pub const fn value(self) -> u32 {
87 self.0
88 }
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
93#[repr(u8)]
94pub enum CustomFlow {
95 #[default]
98 Standard = 0,
99 UserIntent = 1,
101 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 _ => return Err(Error::new(ErrorCode::MessageReserved)),
114 })
115 }
116}
117
118bitflags::bitflags! {
119 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
124 pub struct DiscoveryCapabilities: u8 {
125 const BLE = 1 << 1;
127 const ON_IP_NETWORK = 1 << 2;
129 const WIFI_PAF = 1 << 3;
131 const NFC = 1 << 4;
133 const THREAD_COMMISSIONING = 1 << 5;
136 }
137}
138
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub struct OnboardingPayload {
142 pub vendor_id: VendorId,
144 pub product_id: u16,
146 pub custom_flow: CustomFlow,
148 pub discovery: DiscoveryCapabilities,
150 pub discriminator: u16,
153 pub passcode: Passcode,
155}
156
157const DISCRIMINATOR_MASK: u16 = 0x0FFF;
159
160impl OnboardingPayload {
161 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 #[must_use]
186 pub const fn short_discriminator(&self) -> u8 {
187 (self.discriminator >> 8) as u8
188 }
189
190 pub fn pack(&self) -> [u8; PACKED_LEN] {
196 let mut bits = BitWriter::new();
197 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 bits.finish()
207 }
208
209 #[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 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 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 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 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 let first = (u32::from(include_vid_pid) << 2) | (discriminator >> 10);
285 let group2 = ((discriminator & 0x300) << 6) | (passcode & 0x3FFF);
287 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 #[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 bail!(IntegrityCheckFailed)
336 }
337
338 let first = u32::from(digits.first().copied().unwrap_or(0));
339 if first > 7 {
341 bail!(UnsupportedVersion)
342 }
343 let vid_pid_present = (first & 0b100) != 0;
344 if vid_pid_present != expect_vid_pid {
345 bail!(InvalidArgument)
347 }
348
349 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 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 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
416const 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
445fn 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 [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 out.push(char::from(c))
469 .map_err(|_| Error::new(ErrorCode::NoSpace))?;
470 v /= 38;
471 }
472 }
473 Ok(())
474}
475
476#[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 _ => bail!(InvalidArgument),
492 };
493 let mut value = 0u32;
494 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 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
523const 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
539const 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
551const VERHOEFF_INV: [u8; 10] = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9];
553
554fn 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 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
588fn 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
610struct 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
643struct 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 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 assert!(Passcode::new(0).is_err());
694 assert!(Passcode::new(99_999_999).is_err());
695 assert!(Passcode::new(u32::MAX).is_err());
696 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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}