Skip to main content

rostra_core/
id.rs

1use core::fmt;
2use std::str::FromStr;
3
4use data_encoding::Specification;
5use snafu::{OptionExt as _, Snafu};
6
7use crate::{EventId, ShortEventId, array_type_define_public, array_type_impl_serde};
8
9#[cfg(test)]
10mod tests;
11
12#[cfg(feature = "ed25519-dalek")]
13mod ed25519;
14
15#[cfg(feature = "pkarr")]
16mod pkarr;
17
18#[cfg(feature = "serde")]
19mod serde;
20
21pub fn z32_encoding() -> data_encoding::Encoding {
22    let mut spec = Specification::new();
23    spec.symbols.push_str("ybndrfg8ejkmcpqxot1uwisza345h769");
24    spec.encoding().unwrap()
25}
26
27array_type_define_public!(struct RostraId, 32);
28array_type_impl_serde!(struct RostraId, 32);
29impl RostraId {
30    // Obsolete
31    pub const BECH32_HRP: bech32::Hrp = bech32::Hrp::parse_unchecked("rstr");
32}
33
34impl fmt::Display for RostraId {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        f.write_str("rs")?;
37        let str = z32::encode(self.0.as_slice());
38        f.write_str(&str)?;
39        let str_data_encoding = z32_encoding().encode(self.as_slice());
40        assert_eq!(str, str_data_encoding);
41        Ok(())
42    }
43}
44
45#[derive(Debug, Snafu, Clone)]
46pub enum RostraIdParseError {
47    #[snafu(transparent)]
48    DecodingBech32 {
49        source: bech32::DecodeError,
50    },
51    DecodingZ32,
52    InvalidHrp,
53    InvalidLength,
54    InvalidPrefix,
55}
56
57impl RostraId {
58    fn from_rs_z32_str(s: &str) -> Result<Self, RostraIdParseError> {
59        if !s.starts_with("rs") {
60            return Err(InvalidPrefixSnafu.build());
61        }
62
63        let bytes = z32::decode(&s.as_bytes()[2..])
64            .ok()
65            .context(DecodingZ32Snafu)?;
66
67        if bytes.len() != 32 {
68            return Err(InvalidLengthSnafu.build());
69        }
70        Ok(Self(bytes.try_into().expect("Just checked length")))
71    }
72    fn from_bech32m_str(s: &str) -> Result<Self, RostraIdParseError> {
73        let (hrp, bytes) = bech32::decode(s)?;
74        if hrp != Self::BECH32_HRP {
75            return Err(InvalidHrpSnafu.build());
76        }
77        if bytes.len() != 32 {
78            return Err(InvalidLengthSnafu.build());
79        }
80        Ok(Self(bytes.try_into().expect("Just checked length")))
81    }
82
83    pub fn from_unprefixed_z32_str(s: &str) -> Result<Self, RostraIdParseError> {
84        // Fallback attempting decoding with unprefixed-older z32 (pkarr) encoding
85        let bytes = z32::decode(s.as_bytes()).ok().context(DecodingZ32Snafu)?;
86        if bytes.len() != 32 {
87            return Err(InvalidLengthSnafu.build());
88        }
89        Ok(Self(bytes.try_into().expect("Just checked length")))
90    }
91
92    pub fn to_unprefixed_z32_string(&self) -> String {
93        z32::encode(&self.0)
94    }
95
96    pub fn to_bech32_string(&self) -> String {
97        match bech32::encode::<bech32::Bech32m>(RostraId::BECH32_HRP, &self.0) {
98            Ok(s) => s,
99            Err(e) => match e {
100                bech32::EncodeError::TooLong(_) => unreachable!("Fixed size"),
101                e => panic!("Unexpected error: {e:#}"),
102            },
103        }
104    }
105}
106
107impl FromStr for RostraId {
108    type Err = RostraIdParseError;
109
110    fn from_str(s: &str) -> Result<Self, Self::Err> {
111        match Self::from_rs_z32_str(s) {
112            Ok(o) => Ok(o),
113            Err(err) => {
114                if let Ok(o) = Self::from_bech32m_str(s) {
115                    return Ok(o);
116                }
117                if let Ok(o) = Self::from_unprefixed_z32_str(s) {
118                    return Ok(o);
119                }
120
121                Err(err)
122            }
123        }
124    }
125}
126
127impl From<RostraId> for ShortRostraId {
128    fn from(id: RostraId) -> Self {
129        id.split().0
130    }
131}
132
133array_type_define_public!(struct ShortRostraId, 16);
134
135array_type_define_public!(struct RestRostraId, 16);
136
137impl fmt::Display for RestRostraId {
138    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139        data_encoding::BASE64URL_NOPAD.encode_write(&self.0, f)
140    }
141}
142impl fmt::Display for ShortRostraId {
143    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144        f.write_str("rs")?;
145        let str = z32::encode(self.0.as_slice());
146        f.write_str(&str)?;
147
148        let str_data_encoding = z32_encoding().encode(self.as_slice());
149
150        assert_eq!(str, str_data_encoding);
151
152        Ok(())
153    }
154}
155
156impl FromStr for ShortRostraId {
157    type Err = RostraIdParseError;
158
159    fn from_str(s: &str) -> Result<Self, Self::Err> {
160        if !s.starts_with("rs") {
161            return Err(InvalidPrefixSnafu.build());
162        }
163
164        let bytes = z32::decode(&s.as_bytes()[2..])
165            .ok()
166            .context(DecodingZ32Snafu)?;
167        if bytes.len() != 16 {
168            return Err(InvalidLengthSnafu.build());
169        }
170
171        Ok(Self(bytes.try_into().expect("Just checked length")))
172    }
173}
174
175pub struct FmtShortRostraId(RostraId);
176
177impl fmt::Display for FmtShortRostraId {
178    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179        f.write_str("rs")?;
180        f.write_str(&z32::encode(&self.0.as_slice()[..5]))
181    }
182}
183
184impl RostraId {
185    pub fn fmt_short(self) -> FmtShortRostraId {
186        FmtShortRostraId(self)
187    }
188}
189
190impl RostraId {
191    pub fn split(self) -> (ShortRostraId, RestRostraId) {
192        (
193            ShortRostraId(self.0[0..16].try_into().expect("Can't fail")),
194            RestRostraId(self.0[16..32].try_into().expect("Can't fail")),
195        )
196    }
197
198    pub fn assemble(short: ShortRostraId, rest: RestRostraId) -> Self {
199        Self([short.0, rest.0].concat().try_into().expect("Can't fail"))
200    }
201}
202
203array_type_define_public!(struct RostraIdSecretKey, 32);
204array_type_impl_serde!(struct RostraIdSecretKey, 32);
205
206#[cfg(feature = "serde")]
207impl fmt::Display for RostraIdSecretKey {
208    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209        f.write_str(
210            &bip39::Mnemonic::from_entropy(self.0.as_slice())
211                .expect("Fixed len, can't fail")
212                .to_string(),
213        )
214    }
215}
216
217#[cfg(not(feature = "serde"))]
218impl fmt::Display for RostraIdSecretKey {
219    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220        // Fallback to hex when bip39 is not available
221        for byte in &self.0 {
222            write!(f, "{byte:02x}")?;
223        }
224        Ok(())
225    }
226}
227
228#[derive(Debug, Snafu)]
229#[snafu(display("SecretKey error: {msg}"))]
230pub struct RostraIdSecretKeyError {
231    msg: String,
232}
233
234impl AsRef<str> for RostraIdSecretKeyError {
235    fn as_ref(&self) -> &str {
236        self.msg.as_str()
237    }
238}
239
240impl From<String> for RostraIdSecretKeyError {
241    fn from(msg: String) -> Self {
242        Self { msg }
243    }
244}
245
246pub trait ToShort {
247    type ShortId;
248    fn to_short(self) -> Self::ShortId;
249}
250
251impl ToShort for ShortRostraId {
252    type ShortId = Self;
253
254    fn to_short(self) -> Self::ShortId {
255        self
256    }
257}
258
259impl ToShort for RostraId {
260    type ShortId = ShortRostraId;
261
262    fn to_short(self) -> Self::ShortId {
263        self.into()
264    }
265}
266impl ToShort for ShortEventId {
267    type ShortId = Self;
268
269    fn to_short(self) -> Self::ShortId {
270        self
271    }
272}
273
274impl ToShort for EventId {
275    type ShortId = ShortEventId;
276
277    fn to_short(self) -> Self::ShortId {
278        self.into()
279    }
280}
281
282/// Full, external event id
283///
284/// Combination of [`RostraId`] of the author and [`ShortEventId`]
285/// of the [`crate::Event`] that makes it possible to possibly fetch the event
286/// by anyone.
287///
288/// Encoded as a concatenation/tuple of the two.
289#[cfg_attr(feature = "bincode", derive(::bincode::Encode, ::bincode::Decode))]
290#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
291pub struct ExternalEventId((RostraId, ShortEventId));
292
293impl ExternalEventId {
294    pub fn new(rostra_id: RostraId, event_id: impl Into<ShortEventId>) -> Self {
295        Self((rostra_id, event_id.into()))
296    }
297    pub fn rostra_id(self) -> RostraId {
298        self.0.0
299    }
300
301    pub fn event_id(self) -> ShortEventId {
302        self.0.1
303    }
304}
305#[derive(Debug, Snafu)]
306pub enum ExternalEventIdParseError {
307    InvalidParts,
308    RostraId,
309    EventId,
310}
311
312impl FromStr for ExternalEventId {
313    type Err = ExternalEventIdParseError;
314
315    fn from_str(s: &str) -> Result<Self, Self::Err> {
316        let Some((author, event)) = s.split_once('-') else {
317            return InvalidPartsSnafu.fail();
318        };
319
320        Ok(ExternalEventId::new(
321            RostraId::from_str(author).map_err(|_| RostraIdSnafu.build())?,
322            ShortEventId::from_str(event).map_err(|_| EventIdSnafu.build())?,
323        ))
324    }
325}
326
327impl fmt::Display for ExternalEventId {
328    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329        // Dash was picked because it well uurlencodes and such
330        f.write_fmt(format_args!("{}-{}", self.0.0, self.0.1))
331    }
332}