Skip to main content

volans_core/
identity.rs

1use std::{fmt, str::FromStr};
2
3pub use ed25519_dalek::{
4    SecretKey, SignatureError, SigningKey as KeyPair, VerifyingKey as PublicKey,
5};
6use serde::{Deserialize, Serialize};
7
8#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
9pub struct PeerId([u8; 32]);
10
11impl PeerId {
12    pub fn from_public_key(key: &PublicKey) -> Self {
13        Self(key.to_bytes())
14    }
15
16    pub fn random() -> Self {
17        Self(rand::random())
18    }
19
20    pub fn from_bytes(bytes: [u8; 32]) -> Self {
21        Self(bytes)
22    }
23
24    pub fn try_from_slice(bytes: &[u8]) -> Result<Self, Error> {
25        if bytes.len() == 32 {
26            let mut array = [0u8; 32];
27            array.copy_from_slice(bytes);
28            Ok(Self(array))
29        } else {
30            Err(Error::LengthInvalid)
31        }
32    }
33
34    pub fn try_from_base58(s: &str) -> Result<Self, Error> {
35        let bytes = bs58::decode(s).into_vec()?;
36        Self::try_from_slice(&bytes)
37    }
38
39    pub fn into_bytes(&self) -> [u8; 32] {
40        self.0
41    }
42
43    pub fn as_bytes(&self) -> &[u8; 32] {
44        &self.0
45    }
46
47    pub fn into_base58(self) -> String {
48        bs58::encode(self.into_bytes()).into_string()
49    }
50}
51
52impl fmt::Debug for PeerId {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        f.debug_tuple("PeerId").field(&self.into_base58()).finish()
55    }
56}
57
58impl fmt::Display for PeerId {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        self.into_base58().fmt(f)
61    }
62}
63
64impl Serialize for PeerId {
65    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
66    where
67        S: serde::Serializer,
68    {
69        if serializer.is_human_readable() {
70            serializer.serialize_str(&self.into_base58())
71        } else {
72            serializer.serialize_bytes(&self.into_bytes()[..])
73        }
74    }
75}
76
77impl<'de> Deserialize<'de> for PeerId {
78    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
79    where
80        D: serde::Deserializer<'de>,
81    {
82        use serde::de::*;
83
84        struct PeerIdVisitor;
85
86        impl Visitor<'_> for PeerIdVisitor {
87            type Value = PeerId;
88
89            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
90                write!(f, "valid peer id")
91            }
92
93            fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
94            where
95                E: Error,
96            {
97                PeerId::try_from_slice(v)
98                    .map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))
99            }
100
101            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
102            where
103                E: Error,
104            {
105                PeerId::from_str(v).map_err(|_| Error::invalid_value(Unexpected::Str(v), &self))
106            }
107        }
108
109        if deserializer.is_human_readable() {
110            deserializer.deserialize_str(PeerIdVisitor)
111        } else {
112            deserializer.deserialize_bytes(PeerIdVisitor)
113        }
114    }
115}
116
117#[derive(Debug, thiserror::Error)]
118pub enum Error {
119    #[error("base-58 decode error: {0}")]
120    Bs58(#[from] bs58::decode::Error),
121    #[error("PeerId length invalid, expected 32 bytes")]
122    LengthInvalid,
123}
124
125impl FromStr for PeerId {
126    type Err = Error;
127
128    #[inline]
129    fn from_str(s: &str) -> Result<Self, Self::Err> {
130        let bytes = bs58::decode(s).into_vec()?;
131        let peer_id = PeerId::try_from_slice(&bytes)?;
132        Ok(peer_id)
133    }
134}