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