1use core::fmt;
2use core::str::FromStr;
3
4use data_encoding::{BASE32_NOPAD, HEXLOWER, HEXLOWER_PERMISSIVE};
5use sha2::{Digest as _, Sha256, Sha384, Sha512};
6use subtle::ConstantTimeEq;
7
8use crate::error::Error;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
17#[non_exhaustive]
18pub enum Digest {
19 Sha256,
21 Sha384,
23 Sha512,
25 Sha1,
27}
28
29impl Digest {
30 pub const fn name(self) -> &'static str {
32 match self {
33 Self::Sha256 => "sha256",
34 Self::Sha384 => "sha384",
35 Self::Sha512 => "sha512",
36 Self::Sha1 => "sha1",
37 }
38 }
39
40 pub const fn size(self) -> usize {
42 match self {
43 Self::Sha256 => 32,
44 Self::Sha384 => 48,
45 Self::Sha512 => 64,
46 Self::Sha1 => 20,
47 }
48 }
49
50 pub fn of(self, data: &[u8]) -> PeerId {
53 let mut bytes = [0u8; 64];
54 let out = &mut bytes[..self.size()];
55 match self {
56 Self::Sha256 => out.copy_from_slice(&Sha256::digest(data)),
57 Self::Sha384 => out.copy_from_slice(&Sha384::digest(data)),
58 Self::Sha512 => out.copy_from_slice(&Sha512::digest(data)),
59 Self::Sha1 => out.copy_from_slice(&sha1::Sha1::digest(data)),
60 }
61 PeerId {
62 digest: self,
63 bytes,
64 }
65 }
66
67 fn of_length(len: usize) -> Option<Self> {
68 [Self::Sha256, Self::Sha384, Self::Sha512, Self::Sha1]
69 .into_iter()
70 .find(|digest| digest.size() == len)
71 }
72}
73
74#[cfg(feature = "serde")]
75impl serde::Serialize for Digest {
76 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
77 serializer.serialize_str(self.name())
78 }
79}
80
81#[cfg(feature = "serde")]
82impl<'de> serde::Deserialize<'de> for Digest {
83 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
84 let text = <alloc::borrow::Cow<'de, str>>::deserialize(deserializer)?;
85 text.parse().map_err(serde::de::Error::custom)
86 }
87}
88
89#[cfg(feature = "serde")]
90impl serde::Serialize for PeerId {
91 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
92 serializer.collect_str(self)
93 }
94}
95
96#[cfg(feature = "serde")]
97impl<'de> serde::Deserialize<'de> for PeerId {
98 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
99 let text = <alloc::borrow::Cow<'de, str>>::deserialize(deserializer)?;
100 text.parse().map_err(serde::de::Error::custom)
101 }
102}
103
104impl fmt::Display for Digest {
105 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
106 formatter.write_str(self.name())
107 }
108}
109
110impl FromStr for Digest {
111 type Err = Error;
112
113 fn from_str(value: &str) -> Result<Self, Self::Err> {
114 match value.trim().to_ascii_lowercase().as_str() {
115 "sha256" => Ok(Self::Sha256),
116 "sha384" => Ok(Self::Sha384),
117 "sha512" => Ok(Self::Sha512),
118 "sha1" => Ok(Self::Sha1),
119 "md5" => Err(Error::WeakDigest),
120 other => Err(Error::UnknownDigest(other.to_owned())),
121 }
122 }
123}
124
125#[derive(Clone, Copy, Eq, PartialOrd, Ord)]
141pub struct PeerId {
142 digest: Digest,
143 bytes: [u8; 64],
144}
145
146impl core::hash::Hash for PeerId {
147 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
148 self.digest.hash(state);
149 self.as_bytes().hash(state);
150 }
151}
152
153impl PartialEq for PeerId {
154 fn eq(&self, other: &Self) -> bool {
155 bool::from(self.bytes.ct_eq(&other.bytes)) & (self.digest == other.digest)
157 }
158}
159
160impl PeerId {
161 pub fn of(data: &[u8]) -> Self {
163 Digest::Sha256.of(data)
164 }
165
166 pub fn from_bytes(bytes: [u8; 32]) -> Self {
168 let mut padded = [0u8; 64];
169 padded[..32].copy_from_slice(&bytes);
170 Self {
171 digest: Digest::Sha256,
172 bytes: padded,
173 }
174 }
175
176 pub const fn digest(&self) -> Digest {
178 self.digest
179 }
180
181 pub fn as_bytes(&self) -> &[u8] {
183 &self.bytes[..self.digest.size()]
184 }
185
186 pub fn hex(&self) -> String {
188 HEXLOWER.encode(self.as_bytes())
189 }
190
191 pub fn canonical(&self) -> String {
193 format!("{}:{}", self.digest, self.hex())
194 }
195
196 pub fn to_base32_grouped(&self) -> String {
200 if self.digest != Digest::Sha256 {
201 return self.canonical();
202 }
203 BASE32_NOPAD
204 .encode(self.as_bytes())
205 .as_bytes()
206 .chunks(4)
207 .map(|chunk| core::str::from_utf8(chunk).unwrap_or_default())
208 .collect::<Vec<_>>()
209 .join("-")
210 }
211}
212
213impl fmt::Display for PeerId {
214 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
215 formatter.write_str(&self.canonical())
216 }
217}
218
219impl fmt::Debug for PeerId {
220 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
221 write!(formatter, "PeerId({})", self.canonical())
222 }
223}
224
225impl FromStr for PeerId {
226 type Err = Error;
227
228 fn from_str(value: &str) -> Result<Self, Self::Err> {
229 let value = value.trim();
230 let lower = value.to_ascii_lowercase();
231 let (named, body) = match lower.split_once(':') {
232 Some((name, rest))
233 if !name.is_empty()
234 && name.bytes().all(|b| b.is_ascii_alphanumeric())
235 && name.len() > 2 =>
236 {
237 (Some(name.parse::<Digest>()?), rest)
238 }
239 _ => (None, lower.as_str()),
240 };
241 let hex: String = if body.contains(':') {
243 let pairs: Vec<&str> = body.split(':').collect();
244 if !pairs
245 .iter()
246 .all(|pair| pair.len() == 2 && pair.bytes().all(|b| b.is_ascii_hexdigit()))
247 {
248 return Err(Error::InvalidId);
249 }
250 pairs.concat()
251 } else {
252 body.to_owned()
253 };
254 let is_hex = hex.bytes().all(|byte| byte.is_ascii_hexdigit());
255 if let Some(digest) = named {
256 return from_hex(&hex, Some(digest));
257 }
258 if is_hex && matches!(hex.len(), 32 | 40 | 64 | 96 | 128) {
259 return from_hex(&hex, None);
260 }
261 from_base32(value)
262 }
263}
264
265fn from_hex(hex: &str, named: Option<Digest>) -> Result<PeerId, Error> {
266 if hex.len() == 32 && named.is_none() {
267 return Err(Error::WeakDigest);
268 }
269 let digest = Digest::of_length(hex.len() / 2).ok_or(Error::InvalidId)?;
270 if !hex.len().is_multiple_of(2) || named.is_some_and(|named| named != digest) {
271 return Err(Error::InvalidId);
272 }
273 let mut bytes = [0u8; 64];
274 HEXLOWER_PERMISSIVE
275 .decode_mut(hex.as_bytes(), &mut bytes[..digest.size()])
276 .map_err(|_| Error::InvalidId)?;
277 Ok(PeerId { digest, bytes })
278}
279
280fn from_base32(value: &str) -> Result<PeerId, Error> {
281 let letters: String = value
282 .chars()
283 .filter(|character| !matches!(character, '-' | ' ' | '\t' | '\n' | '\r'))
284 .map(|character| character.to_ascii_uppercase())
285 .collect();
286 if letters.len() != 52 {
289 return Err(Error::InvalidId);
290 }
291 let mut digest = [0u8; 32];
292 BASE32_NOPAD
293 .decode_mut(letters.as_bytes(), &mut digest)
294 .map_err(|_| Error::InvalidId)?;
295 Ok(PeerId::from_bytes(digest))
296}
297
298#[cfg(test)]
299mod tests {
300 use super::*;
301
302 fn colons(id: &PeerId) -> String {
303 id.hex()
304 .as_bytes()
305 .chunks(2)
306 .map(|pair| core::str::from_utf8(pair).unwrap().to_uppercase())
307 .collect::<Vec<_>>()
308 .join(":")
309 }
310
311 #[test]
312 fn spellings_round_trip() {
313 let id = PeerId::of(b"certificate");
314 for spelling in [
315 id.canonical(),
316 id.hex(),
317 id.hex().to_uppercase(),
318 colons(&id),
319 format!("sha256:{}", colons(&id)),
320 id.to_base32_grouped(),
321 id.to_base32_grouped().replace('-', "").to_lowercase(),
322 ] {
323 assert_eq!(spelling.parse::<PeerId>().unwrap(), id, "{spelling}");
324 }
325 assert_eq!(id.to_base32_grouped().len(), 52 + 12);
326 assert_eq!(id.to_string(), id.canonical());
327 assert!(id.to_string().starts_with("sha256:"));
328 }
329
330 #[test]
331 fn other_digests_are_named_and_distinct() {
332 for digest in [Digest::Sha384, Digest::Sha512, Digest::Sha1] {
333 let id = digest.of(b"certificate");
334 assert_eq!(id.digest(), digest);
335 assert_eq!(id.as_bytes().len(), digest.size());
336 assert!(id.to_string().starts_with(&format!("{digest}:")));
337 for spelling in [id.canonical(), id.hex(), colons(&id)] {
338 assert_eq!(spelling.parse::<PeerId>().unwrap(), id, "{spelling}");
339 }
340 }
341 assert_ne!(Digest::Sha256.of(b"x"), Digest::Sha512.of(b"x"));
342 let sha1 = Digest::Sha1.of(b"x").hex();
344 assert!(format!("sha256:{sha1}").parse::<PeerId>().is_err());
345 }
346
347 #[test]
348 fn malformed_and_md5_ids_are_refused() {
349 let id = PeerId::of(b"certificate");
350 for bad in ["", "not-a-id", "sha256:abcd", "AA:BB:C", "sha256:zz"] {
351 assert!(
352 matches!(bad.parse::<PeerId>(), Err(Error::InvalidId)),
353 "{bad}"
354 );
355 }
356 let md5 = "b".repeat(32);
357 for weak in [md5.clone(), format!("md5:{md5}"), vec!["AB"; 16].join(":")] {
358 assert!(
359 matches!(weak.parse::<PeerId>(), Err(Error::WeakDigest)),
360 "{weak}"
361 );
362 }
363 let mut noncanonical = id.to_base32_grouped().replace('-', "");
364 let last = noncanonical.pop().unwrap();
365 noncanonical.push(if last == 'A' { 'B' } else { 'R' });
366 assert!(noncanonical.parse::<PeerId>().is_err());
367 }
368}