1use core::fmt;
2
3use subtle::ConstantTimeEq;
4
5use crate::error::Error;
6use crate::random::Random;
7
8#[derive(Debug, Clone, PartialEq, Eq, coqui_builder::Describe)]
16#[map(deny_unknown_fields)]
17#[non_exhaustive]
18pub struct CodeAlphabet {
19 pub chars: String,
21 pub len: usize,
23}
24
25impl CodeAlphabet {
26 pub fn new(chars: impl Into<String>, len: usize) -> Self {
28 Self {
29 chars: chars.into(),
30 len,
31 }
32 }
33
34 pub fn pin() -> Self {
36 Self {
37 chars: "0123456789".to_owned(),
38 len: 6,
39 }
40 }
41
42 pub fn user_code() -> Self {
45 Self {
46 chars: "BCDFGHJKLMNPQRSTVWXZ".to_owned(),
47 len: 8,
48 }
49 }
50
51 pub fn combinations(&self) -> u128 {
53 let base = self.chars.chars().count() as u128;
54 u32::try_from(self.len)
55 .ok()
56 .and_then(|len| base.checked_pow(len))
57 .unwrap_or(u128::MAX)
58 }
59
60 pub fn check(&self) -> Result<(), Error> {
67 let chars: Vec<char> = self.chars.chars().collect();
68 let repeated = chars
69 .iter()
70 .enumerate()
71 .any(|(index, c)| chars[..index].contains(c));
72 if chars.is_empty() || repeated || chars.iter().any(|c| c.is_control()) || self.len == 0 {
73 return Err(Error::InvalidOptions);
74 }
75 Ok(())
76 }
77
78 pub(crate) fn generate(&self, random: &Random) -> Result<String, Error> {
85 self.check()?;
86 let chars: Vec<char> = self.chars.chars().collect();
87 let mut code = String::with_capacity(self.len);
88 for _ in 0..self.len {
89 code.push(chars[below(random, chars.len())?]);
90 }
91 Ok(code)
92 }
93
94 pub(crate) fn parse(&self, text: &str) -> Result<String, Error> {
101 self.check()?;
102 if text.chars().count() != self.len || !text.chars().all(|c| self.chars.contains(c)) {
103 return Err(Error::InvalidCode);
104 }
105 Ok(text.to_owned())
106 }
107}
108
109pub(crate) fn below(random: &Random, bound: usize) -> Result<usize, Error> {
111 let bound = u64::try_from(bound.max(1)).unwrap_or(u64::MAX);
112 let span = 1u64 << 32;
113 let limit = span - span % bound;
114 loop {
115 let mut bytes = [0u8; 4];
116 random.fill(&mut bytes)?;
117 let value = u64::from(u32::from_be_bytes(bytes));
118 if value < limit {
119 return Ok(usize::try_from(value % bound).unwrap_or(0));
120 }
121 }
122}
123
124pub(crate) fn same(left: &str, right: &str) -> bool {
126 left.len() == right.len() && bool::from(left.as_bytes().ct_eq(right.as_bytes()))
127}
128
129#[derive(Clone, PartialEq, Eq)]
132pub struct Pin(String);
133
134impl Pin {
135 pub fn generate(alphabet: &CodeAlphabet, random: &Random) -> Result<Self, Error> {
141 alphabet.generate(random).map(Self)
142 }
143
144 pub fn parse(alphabet: &CodeAlphabet, text: &str) -> Result<Self, Error> {
150 alphabet.parse(text).map(Self)
151 }
152
153 pub fn as_str(&self) -> &str {
155 &self.0
156 }
157}
158
159impl Drop for Pin {
160 fn drop(&mut self) {
161 zeroize::Zeroize::zeroize(&mut self.0);
162 }
163}
164
165impl fmt::Debug for Pin {
166 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
167 formatter.write_str("Pin(..)")
168 }
169}
170
171#[derive(Debug, Clone, PartialEq, Eq)]
175pub struct PairingCode {
176 pub slot: Option<u8>,
179 pub pin: Pin,
181}
182
183#[derive(Clone, PartialEq, Eq)]
186pub struct UserCode(String);
187
188impl UserCode {
189 pub(crate) fn issued(text: String) -> Self {
191 Self(text)
192 }
193
194 pub fn generate(alphabet: &CodeAlphabet, random: &Random) -> Result<Self, Error> {
200 alphabet.generate(random).map(Self)
201 }
202
203 pub fn parse(alphabet: &CodeAlphabet, text: &str) -> Result<Self, Error> {
209 alphabet.parse(text).map(Self)
210 }
211
212 pub fn as_str(&self) -> &str {
214 &self.0
215 }
216}
217
218impl fmt::Debug for UserCode {
219 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
220 formatter.write_str("UserCode(..)")
221 }
222}
223
224#[cfg(test)]
225mod tests {
226 use super::*;
227
228 #[test]
229 fn codes_match_exactly_over_their_alphabet() {
230 let alphabet = CodeAlphabet::user_code();
231 assert!(UserCode::parse(&alphabet, "WDJBMJHT").is_ok());
232 for bad in [
233 "wdjbmjht",
234 "WDJB-MJHT",
235 "WDJB MJHT",
236 "WDJBMJH",
237 "WDJBMJHTA",
238 "AAAAAAAA",
239 ] {
240 assert!(matches!(
241 UserCode::parse(&alphabet, bad),
242 Err(Error::InvalidCode)
243 ));
244 }
245 assert!(Pin::parse(&CodeAlphabet::pin(), "482913").is_ok());
246 assert!(Pin::parse(&CodeAlphabet::pin(), "48291a").is_err());
247 }
248
249 #[test]
250 fn combinations_are_reported_not_refused() {
251 assert_eq!(CodeAlphabet::pin().combinations(), 1_000_000);
252 assert_eq!(CodeAlphabet::user_code().combinations(), 20u128.pow(8));
253 let tiny = CodeAlphabet::new("01", 1);
254 assert!(tiny.check().is_ok());
255 assert_eq!(tiny.combinations(), 2);
256 let huge = CodeAlphabet::new("01", 1000);
257 assert_eq!(huge.combinations(), u128::MAX);
258 }
259
260 #[test]
261 fn meaningless_alphabets_are_errors() {
262 for (chars, len) in [("", 6), ("0123", 0), ("0012", 4), ("01\n", 4)] {
263 let alphabet = CodeAlphabet {
264 chars: chars.to_owned(),
265 len,
266 };
267 assert!(matches!(alphabet.check(), Err(Error::InvalidOptions)));
268 }
269 }
270
271 #[test]
272 fn generated_codes_use_the_whole_alphabet() {
273 let counter = core::sync::atomic::AtomicU32::new(0);
274 let random = Random::from_fn(move |out| {
275 let value = counter.fetch_add(1, core::sync::atomic::Ordering::SeqCst);
276 out.copy_from_slice(&value.to_be_bytes()[..out.len()]);
277 Ok(())
278 });
279 let alphabet = CodeAlphabet::pin();
280 let code = Pin::generate(&alphabet, &random).unwrap();
281 assert_eq!(code.as_str(), "012345");
282 assert!(Pin::parse(&alphabet, code.as_str()).is_ok());
283 }
284}