Skip to main content

tower_defense/crypto/
peer_id.rs

1use std::str::FromStr;
2
3use quick_protobuf::Writer;
4use serde::{Deserialize, Serialize};
5use sha2::Digest as _;
6
7use super::PublicKey;
8
9const MAX_INLINE_KEY_LENGTH: usize = 42;
10
11const MULTIHASH_IDENTITY_CODE: u64 = 0;
12const MULTIHASH_SHA256_CODE: u64 = 0x12;
13
14type Multihash = multihash::Multihash<64>;
15
16#[derive(Clone, PartialEq, Eq, Hash)]
17pub struct PeerId(Multihash);
18
19impl PeerId {
20    #[must_use]
21    pub fn to_bytes(&self) -> Vec<u8> {
22        self.0.to_bytes()
23    }
24
25    #[must_use]
26    pub fn to_base58(&self) -> String {
27        bs58::encode(self.0.to_bytes()).into_string()
28    }
29
30    /// Create a `PeerId` from bytes.
31    ///
32    /// # Errors
33    ///
34    /// This function will return an error if the bytes do not represent a valid `PeerId`.
35    pub fn from_bytes(data: &[u8]) -> Result<Self, ParseError> {
36        Self::from_multihash(Multihash::from_bytes(data)?)
37            .map_err(|mh| ParseError::UnsupportedCode(mh.code()))
38    }
39
40    /// Create a `PeerId` from a multihash.
41    ///
42    /// # Errors
43    ///
44    /// This function will return an error if the multihash code is not supported.
45    pub fn from_multihash(multihash: Multihash) -> Result<Self, Multihash> {
46        match multihash.code() {
47            MULTIHASH_SHA256_CODE => Ok(Self(multihash)),
48            MULTIHASH_IDENTITY_CODE if multihash.digest().len() <= MAX_INLINE_KEY_LENGTH => {
49                Ok(Self(multihash))
50            }
51            _ => Err(multihash),
52        }
53    }
54}
55
56impl From<PublicKey> for PeerId {
57    fn from(key: PublicKey) -> Self {
58        let encided = encode_ed25519(key.0.as_bytes());
59
60        let multihash = if encided.len() <= MAX_INLINE_KEY_LENGTH {
61            Multihash::wrap(MULTIHASH_IDENTITY_CODE, &encided)
62                .expect("64 byte multihash provides sufficient space")
63        } else {
64            Multihash::wrap(MULTIHASH_SHA256_CODE, &sha2::Sha256::digest(encided))
65                .expect("64 byte multihash provides sufficient space")
66        };
67
68        Self(multihash)
69    }
70}
71
72impl std::fmt::Debug for PeerId {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        f.debug_tuple("PeerId").field(&self.to_base58()).finish()
75    }
76}
77
78impl std::fmt::Display for PeerId {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        self.to_base58().fmt(f)
81    }
82}
83
84#[derive(Debug, thiserror::Error)]
85pub enum ParseError {
86    #[error("base-58 decode error: {0}")]
87    B58(#[from] bs58::decode::Error),
88    #[error("unsupported multihash code '{0}'")]
89    UnsupportedCode(u64),
90    #[error("invalid multihash")]
91    InvalidMultihash(#[from] multihash::Error),
92}
93
94impl FromStr for PeerId {
95    type Err = ParseError;
96
97    fn from_str(s: &str) -> Result<Self, Self::Err> {
98        let bytes = bs58::decode(s).into_vec()?;
99        let peer_id = PeerId::from_bytes(&bytes)?;
100
101        Ok(peer_id)
102    }
103}
104
105impl Serialize for PeerId {
106    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
107    where
108        S: serde::Serializer,
109    {
110        if serializer.is_human_readable() {
111            serializer.serialize_str(&self.to_base58())
112        } else {
113            serializer.serialize_bytes(&self.to_bytes()[..])
114        }
115    }
116}
117
118impl<'de> Deserialize<'de> for PeerId {
119    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
120    where
121        D: serde::Deserializer<'de>,
122    {
123        use serde::de::{Error, Unexpected, Visitor};
124
125        struct PeerIdVisitor;
126
127        impl Visitor<'_> for PeerIdVisitor {
128            type Value = PeerId;
129
130            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
131                write!(f, "valid peer id")
132            }
133
134            fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
135            where
136                E: Error,
137            {
138                PeerId::from_bytes(v).map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))
139            }
140
141            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
142            where
143                E: Error,
144            {
145                PeerId::from_str(v).map_err(|_| Error::invalid_value(Unexpected::Str(v), &self))
146            }
147        }
148
149        if deserializer.is_human_readable() {
150            deserializer.deserialize_str(PeerIdVisitor)
151        } else {
152            deserializer.deserialize_bytes(PeerIdVisitor)
153        }
154    }
155}
156
157fn encode_ed25519(pubkey_bytes: &[u8; 32]) -> Vec<u8> {
158    let mut buf = Vec::new();
159    {
160        let mut writer = Writer::new(&mut buf);
161        // Write field 1: Tag = (1 << 3) | 0 = 8. Write the enum wariant 1 for ed25519.
162        writer
163            .write_with_tag(8, |w| w.write_enum(1))
164            .expect("could write enum variant");
165        // Write field 2: Tag = (2 << 3) | 2 = 18. Write the 32 bytes.
166        writer
167            .write_with_tag(18, |w| w.write_bytes(&pubkey_bytes[..]))
168            .expect("could write all 32 bytes of public key");
169    }
170    buf
171}
172
173#[cfg(test)]
174mod test {
175    use super::*;
176    use crate::crypto::Keypair;
177
178    #[test]
179    fn example_1() {
180        let mut signing_key_raw = [0u8; 32];
181        hex::decode_to_slice(
182            "87ad5ca4be14d1a97c49b915bc6a33849425469921649f4ec970cad30c0d9a94",
183            &mut signing_key_raw,
184        )
185        .unwrap();
186        let keypair = Keypair::from_secret_bytes(&signing_key_raw);
187        let peer_id = PeerId::from(keypair.public());
188
189        assert_eq!(
190            peer_id.to_base58(),
191            "12D3KooWDZy8EabSzFCSSNZFRvUpkhLAb1WCTv3KVEYJuryW9H1N"
192        );
193    }
194}