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 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 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 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 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 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 let first = (u32::from(include_vid_pid) << 2) | (discriminator >> 10);
281 let group2 = ((discriminator & 0x300) << 6) | (passcode & 0x3FFF);
283 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 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 bail!(IntegrityCheckFailed)
328 }
329
330 let first = u32::from(digits.first().copied().unwrap_or(0));
331 if first > 7 {
333 bail!(UnsupportedVersion)
334 }
335 let vid_pid_present = (first & 0b100) != 0;
336 if vid_pid_present != expect_vid_pid {
337 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 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 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
420fn 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 [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 out.push(char::from(c))
444 .map_err(|_| Error::new(ErrorCode::NoSpace))?;
445 v /= 38;
446 }
447 }
448 Ok(())
449}
450
451fn 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 _ => bail!(InvalidArgument),
463 };
464 let mut value = 0u32;
465 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 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
494const 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
510const 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
522const VERHOEFF_INV: [u8; 10] = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9];
524
525fn 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 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
559fn 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
581struct 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
614struct 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 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 assert!(Passcode::new(0).is_err());
665 assert!(Passcode::new(99_999_999).is_err());
666 assert!(Passcode::new(u32::MAX).is_err());
667 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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}