Skip to main content

coqui_peer/
id.rs

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/// The algorithm a [`PeerId`] is made with: the `<alg>` of its `<alg>:<hash>` text.
11///
12/// [`Sha256`](Digest::Sha256) is the id of a peer by default. The others exist so a pin written
13/// elsewhere can be read; whether a method accepts them is its own allow-list (a list of
14/// `Digest` values). MD5 is not supported at all. Methods whose keys are named by another
15/// algorithm add variants here, which is why the enum is non-exhaustive.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, coqui_builder::Leaf)]
17#[map(rename_all = "lowercase")]
18#[non_exhaustive]
19pub enum Digest {
20    /// SHA-256, 32 bytes. The default and the only digest of an identity.
21    Sha256,
22    /// SHA-384, 48 bytes.
23    Sha384,
24    /// SHA-512, 64 bytes.
25    Sha512,
26    /// SHA-1, 20 bytes. Legacy interoperability only.
27    Sha1,
28}
29
30impl Digest {
31    /// The lowercase name used in text: `sha256`, `sha384`, `sha512`, `sha1`.
32    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    /// The digest length in bytes.
42    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    /// The id of `data` under this algorithm: what a method hashes is its public key, or the
52    /// encoding of its certificate.
53    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/// Who a peer is: the hash of its public key or certificate, the whole of what one peer is
127/// told of another.
128///
129/// The canonical text form, and the [`Display`](fmt::Display) form, is `<alg>:<hash>`: the
130/// algorithm name, a colon and lowercase hexadecimal, `sha256:3f15...`. For an X.509
131/// certificate `openssl x509 -outform DER | sha256sum` reproduces the hex. [`FromStr`] also
132/// accepts:
133///
134/// - bare hexadecimal of a supported digest's length (64 characters is SHA-256);
135/// - hexadecimal pairs separated by colons (`AA:BB:...`), as most tools print it;
136/// - for SHA-256 only, 52 base32 characters, grouped in fours by `-` or not
137///   ([`to_base32_grouped`](PeerId::to_base32_grouped)), meant to be read aloud.
138///
139/// Text that is the length of an MD5 digest, or names `md5`, is [`Error::WeakDigest`].
140/// Equality is constant time.
141#[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        // Both are compared whatever differs, so equality does not leak where it ends.
157        bool::from(self.bytes.ct_eq(&other.bytes)) & (self.digest == other.digest)
158    }
159}
160
161impl PeerId {
162    /// The SHA-256 id of `data`.
163    pub fn of(data: &[u8]) -> Self {
164        Digest::Sha256.of(data)
165    }
166
167    /// A SHA-256 id from its 32 digest bytes.
168    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    /// The hash this id is made with.
178    pub const fn digest(&self) -> Digest {
179        self.digest
180    }
181
182    /// The digest bytes: 32 for SHA-256.
183    pub fn as_bytes(&self) -> &[u8] {
184        &self.bytes[..self.digest.size()]
185    }
186
187    /// Lowercase hexadecimal of the digest, without the name.
188    pub fn hex(&self) -> String {
189        HEXLOWER.encode(self.as_bytes())
190    }
191
192    /// The canonical form: the digest name, a colon and [`hex`](PeerId::hex).
193    pub fn canonical(&self) -> String {
194        format!("{}:{}", self.digest, self.hex())
195    }
196
197    /// SHA-256 only: 52 uppercase base32 characters in 13 groups of four separated by `-`,
198    /// for screens that show it and for reading aloud. Any other digest gives its
199    /// [`canonical`](PeerId::canonical) form.
200    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        // Colon-separated pairs: `AA:BB:...`.
243        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    // 52 symbols carry 260 bits: the 256 of a SHA-256 digest and four padding bits, which the
288    // decoder refuses unless they are zero.
289    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        // A name must agree with the length.
344        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}