Skip to main content

rs_matter_pairing/
code.rs

1/*
2 *
3 *    Copyright (c) 2023-2026 Project CHIP Authors
4 *
5 *    Licensed under the Apache License, Version 2.0 (the "License");
6 *    you may not use this file except in compliance with the License.
7 *    You may obtain a copy of the License at
8 *
9 *        http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *    Unless required by applicable law or agreed to in writing, software
12 *    distributed under the License is distributed on an "AS IS" BASIS,
13 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *    See the License for the specific language governing permissions and
15 *    limitations under the License.
16 */
17
18use core::fmt::Write;
19
20use verhoeff::Verhoeff;
21
22use crate::utils::storage::String;
23use crate::BasicCommData;
24
25impl BasicCommData {
26    /// Compute the 11-digit manual pairing code (no vendor/product IDs)
27    ///
28    /// Implies the standard commissioning flow; other flows need
29    /// [`Self::compute_pairing_code_long`].
30    pub fn compute_pairing_code(&self) -> String<11> {
31        let mut digits = String::new();
32
33        self.write_pairing_code_digits(&mut digits, None);
34
35        digits
36    }
37
38    /// Compute the 21-digit manual pairing code, which carries the vendor and
39    /// product IDs; required for non-standard commissioning flows
40    pub fn compute_pairing_code_long(&self, vid: u16, pid: u16) -> String<21> {
41        let mut digits = String::new();
42
43        self.write_pairing_code_digits(&mut digits, Some((vid, pid)));
44
45        digits
46    }
47
48    /// The 11-digit manual pairing code grouped for display: `XXXX-XXX-XXXX`
49    pub fn compute_pretty_pairing_code(&self) -> String<13> {
50        let pairing_code = self.compute_pairing_code();
51
52        let mut pretty = String::new();
53        Self::write_groups(&mut pretty, &pairing_code, &[4, 3, 4]);
54
55        pretty
56    }
57
58    /// The 21-digit manual pairing code grouped for display:
59    /// `XXXX-XXX-XXXX-XXXXX-XXXXX` (the spec prescribes no grouping)
60    pub fn compute_pretty_pairing_code_long(&self, vid: u16, pid: u16) -> String<25> {
61        let pairing_code = self.compute_pairing_code_long(vid, pid);
62
63        let mut pretty = String::new();
64        Self::write_groups(&mut pretty, &pairing_code, &[4, 3, 4, 5, 5]);
65
66        pretty
67    }
68
69    /// Write the pairing code digits, check digit included; the 21-digit
70    /// variant if `vid_pid` is present.
71    fn write_pairing_code_digits<const N: usize>(
72        &self,
73        digits: &mut String<N>,
74        vid_pid: Option<(u16, u16)>,
75    ) {
76        let BasicCommData {
77            password,
78            discriminator,
79            ..
80        } = self;
81
82        let password = u32::from_le_bytes(*password.access());
83        let vid_pid_present: u8 = vid_pid.is_some().into();
84
85        // DIGIT[1]      := (VID_PID_PRESENT << 2) | (DISCRIMINATOR >> 10)
86        // DIGIT[2..6]   := ((DISCRIMINATOR & 0x300) << 6) | (PASSCODE & 0x3FFF)
87        // DIGIT[7..10]  := PASSCODE >> 14
88        // DIGIT[11..15] := VID and DIGIT[16..20] := PID (21-digit variant only)
89        // Last digit    := Verhoeff check digit over all of the above
90        write_unwrap!(
91            digits,
92            "{}{:0>5}{:0>4}",
93            (vid_pid_present << 2) | (discriminator >> 10) as u8,
94            ((discriminator & 0x300) << 6) | (password & 0x3FFF) as u16,
95            password >> 14
96        );
97
98        if let Some((vid, pid)) = vid_pid {
99            write_unwrap!(digits, "{vid:0>5}{pid:0>5}");
100        }
101
102        let check_digit = digits.calculate_verhoeff_check_digit();
103        write_unwrap!(digits, "{check_digit}");
104    }
105
106    /// Write `digits` into `pretty` in dash-separated groups of the given sizes.
107    fn write_groups<const N: usize>(pretty: &mut String<N>, digits: &str, groups: &[usize]) {
108        let mut offset = 0;
109
110        for (index, group) in groups.iter().enumerate() {
111            if index > 0 {
112                unwrap!(pretty.push('-'));
113            }
114
115            unwrap!(pretty.push_str(&digits[offset..offset + group]));
116            offset += group;
117        }
118    }
119}
120
121#[cfg(test)]
122#[cfg_attr(coverage_nightly, coverage(off))]
123mod tests {
124    use super::*;
125
126    use crate::qr::QrPayload;
127
128    #[test]
129    fn can_compute_pairing_code() {
130        let comm_data = BasicCommData {
131            password: 123456_u32.to_le_bytes().into(),
132            discriminator: 250,
133        };
134        let pairing_code = comm_data.compute_pairing_code();
135        assert_eq!(pairing_code, "00876800071");
136
137        let comm_data = BasicCommData {
138            password: 34567890_u32.to_le_bytes().into(),
139            discriminator: 2976,
140        };
141        let pairing_code = comm_data.compute_pairing_code();
142        assert_eq!(pairing_code, "26318621095");
143        assert_eq!(comm_data.compute_pretty_pairing_code(), "2631-862-1095");
144    }
145
146    /// Vectors from the CHIP SDK's `TestManualCode` suite (given there without
147    /// the check digit).
148    #[test]
149    fn can_compute_pairing_code_long() {
150        let comm_data = BasicCommData {
151            password: 12345679_u32.to_le_bytes().into(),
152            discriminator: 2560,
153        };
154
155        let short = comm_data.compute_pairing_code();
156        assert_eq!(&short[..10], "2412950753");
157        assert!(short.validate_verhoeff_check_digit());
158
159        let long = comm_data.compute_pairing_code_long(0, 0);
160        assert_eq!(&long[..20], "64129507530000000000");
161        assert!(long.validate_verhoeff_check_digit());
162
163        let long = comm_data.compute_pairing_code_long(1, 1);
164        assert_eq!(&long[..20], "64129507530000100001");
165        assert!(long.validate_verhoeff_check_digit());
166
167        let long = comm_data.compute_pairing_code_long(45367, 14526);
168        assert_eq!(&long[..20], "64129507534536714526");
169        assert!(long.validate_verhoeff_check_digit());
170
171        let pretty = comm_data.compute_pretty_pairing_code_long(45367, 14526);
172        assert_eq!(&pretty[..24], "6412-950-7534-53671-4526");
173        assert_eq!(pretty.len(), 25);
174
175        // Round-trip through the parser, dashes and all
176        let parsed = QrPayload::parse_pairing_code(&pretty).unwrap();
177        assert_eq!(parsed.passcode(), 12345679);
178        assert_eq!(parsed.short_discriminator(), (2560 >> 8) as u8);
179        assert_eq!(parsed.vid_pid(), Some((45367, 14526)));
180
181        // The all-ones vector: every field at its maximum
182        let comm_data = BasicCommData {
183            password: 0x7FF_FFFF_u32.to_le_bytes().into(),
184            discriminator: 0xFFF,
185        };
186        let long = comm_data.compute_pairing_code_long(65535, 65535);
187        assert_eq!(&long[..20], "76553581916553565535");
188        assert!(long.validate_verhoeff_check_digit());
189    }
190}