1use crate::Error;
9use std::fmt;
10use std::str::FromStr;
11
12#[derive(Clone, Copy, PartialEq, Eq, Hash)]
14pub struct Dsk(pub [u8; 16]);
15
16impl Dsk {
17 pub fn from_public_key(key: &[u8; 32]) -> Self {
19 let mut d = [0u8; 16];
20 d.copy_from_slice(&key[..16]);
21 Dsk(d)
22 }
23
24 pub fn pin(&self) -> u16 {
26 u16::from_be_bytes([self.0[0], self.0[1]])
27 }
28
29 pub fn without_pin(&self) -> Self {
31 let mut d = *self;
32 d.0[0] = 0;
33 d.0[1] = 0;
34 d
35 }
36
37 pub fn nwi_home_id(&self) -> [u8; 4] {
39 let mut h = [self.0[8], self.0[9], self.0[10], self.0[11]];
40 h[0] |= 0b1100_0000;
41 h[3] &= 0b1111_1110;
42 h
43 }
44
45 pub fn auth_home_id(&self) -> [u8; 4] {
47 let mut h = [self.0[12], self.0[13], self.0[14], self.0[15]];
48 h[0] &= 0b0011_1111;
49 h[3] |= 0b0000_0001;
50 h
51 }
52
53 pub fn masked(&self) -> String {
55 let s = self.to_string();
56 format!("xxxxx{}", &s[5..])
57 }
58}
59
60pub fn parse_pin(s: &str) -> Result<u16, Error> {
62 let s = s.trim();
63 if s.len() != 5 || !s.bytes().all(|b| b.is_ascii_digit()) {
64 return Err(Error::Invalid("PIN"));
65 }
66 s.parse::<u32>()
67 .ok()
68 .and_then(|v| u16::try_from(v).ok())
69 .ok_or(Error::Invalid("PIN"))
70}
71
72pub fn apply_pin(public_key: &mut [u8; 32], pin: u16) {
74 public_key[..2].copy_from_slice(&pin.to_be_bytes());
75}
76
77impl fmt::Display for Dsk {
78 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 for (i, pair) in self.0.chunks(2).enumerate() {
80 if i > 0 {
81 f.write_str("-")?;
82 }
83 write!(f, "{:05}", u16::from_be_bytes([pair[0], pair[1]]))?;
84 }
85 Ok(())
86 }
87}
88
89impl fmt::Debug for Dsk {
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 write!(f, "Dsk({self})")
92 }
93}
94
95impl FromStr for Dsk {
96 type Err = Error;
97 fn from_str(s: &str) -> Result<Self, Error> {
98 let groups: Vec<&str> = s.trim().split('-').collect();
99 if groups.len() != 8 {
100 return Err(Error::Invalid("DSK"));
101 }
102 let mut d = [0u8; 16];
103 for (i, g) in groups.iter().enumerate() {
104 let v = parse_pin(g).map_err(|_| Error::Invalid("DSK"))?;
105 d[i * 2..i * 2 + 2].copy_from_slice(&v.to_be_bytes());
106 }
107 Ok(Dsk(d))
108 }
109}
110
111#[cfg(feature = "serde")]
112impl serde::Serialize for Dsk {
113 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
114 s.collect_str(self)
115 }
116}
117
118#[cfg(feature = "serde")]
119impl<'de> serde::Deserialize<'de> for Dsk {
120 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
121 let s = String::deserialize(d)?;
122 s.parse().map_err(serde::de::Error::custom)
123 }
124}
125
126#[cfg(test)]
127mod tests {
128 use super::*;
129
130 #[test]
131 fn text_roundtrip() {
132 let s = "34028-23669-20938-46346-33746-07431-56821-14553";
133 let d: Dsk = s.parse().unwrap();
134 assert_eq!(d.to_string(), s);
135 assert_eq!(d.pin(), 34028);
136 assert_eq!(
137 d.masked(),
138 "xxxxx-23669-20938-46346-33746-07431-56821-14553"
139 );
140 assert!("34028-23669".parse::<Dsk>().is_err());
141 assert!("70000-23669-20938-46346-33746-07431-56821-14553"
142 .parse::<Dsk>()
143 .is_err());
144 assert_eq!(parse_pin(" 00042 ").unwrap(), 42);
145 assert!(parse_pin("1234").is_err());
146 }
147
148 #[test]
149 fn smartstart_home_ids() {
150 let d = Dsk([0xff; 16]);
151 assert_eq!(d.nwi_home_id(), [0xff, 0xff, 0xff, 0xfe]);
152 assert_eq!(d.auth_home_id(), [0x3f, 0xff, 0xff, 0xff]);
153 let d = Dsk([0; 16]);
154 assert_eq!(d.nwi_home_id(), [0xc0, 0, 0, 0]);
155 assert_eq!(d.auth_home_id(), [0, 0, 0, 1]);
156 }
157}