Skip to main content

weirdnet_contacts/
id.rs

1//! The identity type.
2use serde::{Deserialize, Serialize};
3use std::fmt;
4use weirdnet_net::{Keypair, PeerId, PublicKey};
5
6/// An identity: a Weirdnet peer id, as text. It is the key for contacts, blocks and bans.
7#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
8#[serde(transparent)]
9pub struct UserId(String);
10
11/// A string that is not a peer id.
12#[derive(Debug, thiserror::Error)]
13#[error("not a peer id: {0}")]
14pub struct IdError(pub String);
15
16impl UserId {
17    /// Checks that `s` is a peer id.
18    pub fn parse(s: &str) -> Result<UserId, IdError> {
19        s.parse::<PeerId>().map(|p| UserId(p.to_string())).map_err(|_| IdError(s.to_string()))
20    }
21
22    /// The identity of a public key.
23    pub fn of_key(pk: &PublicKey) -> UserId {
24        UserId(pk.to_peer_id().to_string())
25    }
26
27    /// The identity of a keypair.
28    pub fn of_keypair(kp: &Keypair) -> UserId {
29        Self::of_key(&kp.public())
30    }
31
32    /// The identity of a protobuf-encoded public key, if it decodes.
33    pub fn of_key_bytes(b: &[u8]) -> Option<UserId> {
34        PublicKey::try_decode_protobuf(b).ok().map(|pk| Self::of_key(&pk))
35    }
36
37    /// The peer id text.
38    pub fn as_str(&self) -> &str {
39        &self.0
40    }
41
42    /// The first characters, for a label when there is no name.
43    pub fn short(&self) -> &str {
44        let n = self.0.len();
45        &self.0[n.saturating_sub(8)..]
46    }
47}
48
49impl fmt::Display for UserId {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        f.write_str(&self.0)
52    }
53}