Skip to main content

fedimint_core/
invite_code.rs

1use core::fmt;
2use std::borrow::Cow;
3use std::collections::BTreeMap;
4use std::fmt::{Display, Formatter};
5use std::io::Read;
6use std::str::FromStr;
7
8use anyhow::ensure;
9use bech32::{Bech32m, Hrp};
10use serde::{Deserialize, Serialize};
11
12use crate::base32::FEDIMINT_PREFIX;
13use crate::config::FederationId;
14use crate::encoding::{Decodable, DecodeError, Encodable};
15use crate::module::registry::{ModuleDecoderRegistry, ModuleRegistry};
16use crate::util::SafeUrl;
17use crate::{NumPeersExt, PeerId};
18
19/// Information required for client to join Federation
20///
21/// Can be used to download the configs and bootstrap a client.
22///
23/// ## Invariants
24/// Constructors have to guarantee that:
25///   * At least one Api entry is present
26///   * At least one Federation ID is present
27#[derive(Clone, Debug, Eq, PartialEq, Encodable, Hash, Ord, PartialOrd)]
28pub struct InviteCode(Vec<InviteCodePart>);
29
30#[cfg(feature = "uniffi")]
31uniffi::custom_type!(InviteCode, String, {
32    lower: |i| i.to_string(),
33    try_lift: |s| s.parse().map_err(|e: anyhow::Error| e),
34});
35
36impl Decodable for InviteCode {
37    fn consensus_decode_partial<R: Read>(
38        r: &mut R,
39        modules: &ModuleDecoderRegistry,
40    ) -> Result<Self, DecodeError> {
41        let inner: Vec<InviteCodePart> = Decodable::consensus_decode_partial(r, modules)?;
42
43        if !inner
44            .iter()
45            .any(|data| matches!(data, InviteCodePart::Api { .. }))
46        {
47            return Err(DecodeError::from_str(
48                "No API was provided in the invite code",
49            ));
50        }
51
52        if !inner
53            .iter()
54            .any(|data| matches!(data, InviteCodePart::FederationId(_)))
55        {
56            return Err(DecodeError::from_str(
57                "No Federation ID provided in invite code",
58            ));
59        }
60
61        Ok(Self(inner))
62    }
63}
64
65impl InviteCode {
66    pub fn new(
67        url: SafeUrl,
68        peer: PeerId,
69        federation_id: FederationId,
70        api_secret: Option<String>,
71    ) -> Self {
72        let mut s = Self(vec![
73            InviteCodePart::Api { url, peer },
74            InviteCodePart::FederationId(federation_id),
75        ]);
76
77        if let Some(api_secret) = api_secret {
78            s.0.push(InviteCodePart::ApiSecret(api_secret));
79        }
80
81        s
82    }
83
84    pub fn from_map(
85        peer_to_url_map: &BTreeMap<PeerId, SafeUrl>,
86        federation_id: FederationId,
87        api_secret: Option<String>,
88    ) -> Self {
89        let max_size = peer_to_url_map.to_num_peers().max_evil() + 1;
90        let mut code_vec: Vec<InviteCodePart> = peer_to_url_map
91            .iter()
92            .take(max_size)
93            .map(|(peer, url)| InviteCodePart::Api {
94                url: url.clone(),
95                peer: *peer,
96            })
97            .collect();
98
99        code_vec.push(InviteCodePart::FederationId(federation_id));
100
101        if let Some(api_secret) = api_secret {
102            code_vec.push(InviteCodePart::ApiSecret(api_secret));
103        }
104
105        Self(code_vec)
106    }
107
108    /// Constructs an [`InviteCode`] which contains as many guardian URLs as
109    /// needed to always be able to join a working federation
110    pub fn new_with_essential_num_guardians(
111        peer_to_url_map: &BTreeMap<PeerId, SafeUrl>,
112        federation_id: FederationId,
113    ) -> Self {
114        let max_size = peer_to_url_map.to_num_peers().max_evil() + 1;
115        let mut code_vec: Vec<InviteCodePart> = peer_to_url_map
116            .iter()
117            .take(max_size)
118            .map(|(peer, url)| InviteCodePart::Api {
119                url: url.clone(),
120                peer: *peer,
121            })
122            .collect();
123        code_vec.push(InviteCodePart::FederationId(federation_id));
124
125        Self(code_vec)
126    }
127
128    /// Returns the API URL of one of the guardians.
129    pub fn url(&self) -> SafeUrl {
130        self.0
131            .iter()
132            .find_map(|data| match data {
133                InviteCodePart::Api { url, .. } => Some(url.clone()),
134                _ => None,
135            })
136            .expect("Ensured by constructor")
137    }
138
139    /// Api secret, if needed, to use when communicating with the federation
140    pub fn api_secret(&self) -> Option<String> {
141        self.0.iter().find_map(|data| match data {
142            InviteCodePart::ApiSecret(api_secret) => Some(api_secret.clone()),
143            _ => None,
144        })
145    }
146    /// Returns the id of the guardian from which we got the API URL, see
147    /// [`InviteCode::url`].
148    pub fn peer(&self) -> PeerId {
149        self.0
150            .iter()
151            .find_map(|data| match data {
152                InviteCodePart::Api { peer, .. } => Some(*peer),
153                _ => None,
154            })
155            .expect("Ensured by constructor")
156    }
157
158    /// Get all peer URLs in the [`InviteCode`]
159    pub fn peers(&self) -> BTreeMap<PeerId, SafeUrl> {
160        self.0
161            .iter()
162            .filter_map(|entry| match entry {
163                InviteCodePart::Api { url, peer } => Some((*peer, url.clone())),
164                _ => None,
165            })
166            .collect()
167    }
168
169    /// Returns the federation's ID that can be used to authenticate the config
170    /// downloaded from the API.
171    pub fn federation_id(&self) -> FederationId {
172        self.0
173            .iter()
174            .find_map(|data| match data {
175                InviteCodePart::FederationId(federation_id) => Some(*federation_id),
176                _ => None,
177            })
178            .expect("Ensured by constructor")
179    }
180}
181
182/// For extendability [`InviteCode`] consists of parts, where client can ignore
183/// ones they don't understand.
184///
185/// ones they don't understand Data that can be encoded in the invite code.
186/// Currently we always just use one `Api` and one `FederationId` variant in an
187/// invite code, but more can be added in the future while still keeping the
188/// invite code readable for older clients, which will just ignore the new
189/// fields.
190#[derive(Clone, Debug, Eq, PartialEq, Encodable, Decodable, Hash, Ord, PartialOrd)]
191enum InviteCodePart {
192    /// API endpoint of one of the guardians
193    Api {
194        /// URL to reach an API that we can download configs from
195        url: SafeUrl,
196        /// Peer id of the host from the Url
197        peer: PeerId,
198    },
199
200    /// Authentication id for the federation
201    FederationId(FederationId),
202
203    /// Api secret to use
204    ApiSecret(String),
205
206    /// Unknown invite code fields to be defined in the future
207    #[encodable_default]
208    Default { variant: u64, bytes: Vec<u8> },
209}
210
211/// We can represent client invite code as a bech32 string for compactness and
212/// error-checking
213///
214/// Human readable part (HRP) includes the version
215/// ```txt
216/// [ hrp (4 bytes) ] [ id (48 bytes) ] ([ url len (2 bytes) ] [ url bytes (url len bytes) ])+
217/// ```
218const BECH32_HRP: Hrp = Hrp::parse_unchecked("fed1");
219
220impl FromStr for InviteCode {
221    type Err = anyhow::Error;
222
223    fn from_str(encoded: &str) -> Result<Self, Self::Err> {
224        if let Ok(invite_code) = crate::base32::decode_prefixed(FEDIMINT_PREFIX, encoded) {
225            return Ok(invite_code);
226        }
227
228        let (hrp, data) = bech32::decode(encoded)?;
229
230        ensure!(hrp == BECH32_HRP, "Invalid HRP in bech32 encoding");
231
232        let invite = Self::consensus_decode_whole(&data, &ModuleRegistry::default())?;
233
234        Ok(invite)
235    }
236}
237
238/// Parses the invite code from a bech32 string
239impl Display for InviteCode {
240    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
241        let data = self.consensus_encode_to_vec();
242        let encode = bech32::encode::<Bech32m>(BECH32_HRP, &data).map_err(|_| fmt::Error)?;
243        formatter.write_str(&encode)
244    }
245}
246
247impl Serialize for InviteCode {
248    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
249    where
250        S: serde::Serializer,
251    {
252        String::serialize(&self.to_string(), serializer)
253    }
254}
255
256impl<'de> Deserialize<'de> for InviteCode {
257    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
258    where
259        D: serde::Deserializer<'de>,
260    {
261        let string = Cow::<str>::deserialize(deserializer)?;
262        Self::from_str(&string).map_err(serde::de::Error::custom)
263    }
264}
265
266#[cfg(test)]
267mod tests {
268    use std::str::FromStr;
269
270    use fedimint_core::PeerId;
271    use fedimint_core::base32::FEDIMINT_PREFIX;
272
273    use crate::config::FederationId;
274    use crate::invite_code::InviteCode;
275
276    #[test]
277    fn test_invite_code_to_from_string() {
278        let invite_code_str = "fed11qgqpu8rhwden5te0vejkg6tdd9h8gepwd4cxcumxv4jzuen0duhsqqfqh6nl7sgk72caxfx8khtfnn8y436q3nhyrkev3qp8ugdhdllnh86qmp42pm";
279        let invite_code = InviteCode::from_str(invite_code_str).expect("valid invite code");
280
281        InviteCode::from_str(&crate::base32::encode_prefixed(
282            FEDIMINT_PREFIX,
283            &invite_code,
284        ))
285        .expect("Failed to parse base 32 invite code");
286
287        assert_eq!(invite_code.to_string(), invite_code_str);
288        assert_eq!(
289            invite_code.0,
290            [
291                crate::invite_code::InviteCodePart::Api {
292                    url: "wss://fedimintd.mplsfed.foo/".parse().expect("valid url"),
293                    peer: PeerId::new(0),
294                },
295                crate::invite_code::InviteCodePart::FederationId(FederationId(
296                    bitcoin::hashes::sha256::Hash::from_str(
297                        "bea7ff4116f2b1d324c7b5d699cce4ac7408cee41db2c88027e21b76fff3b9f4"
298                    )
299                    .expect("valid hash")
300                ))
301            ]
302        );
303    }
304}