Skip to main content

fedimint_client/
api_announcements.rs

1use std::collections::BTreeMap;
2use std::sync::Arc;
3use std::time::Duration;
4
5use fedimint_api_client::api::{DynGlobalApi, ServerError};
6use fedimint_connectors::iroh_next_endpoint_url;
7use fedimint_core::config::ClientConfig;
8use fedimint_core::db::{Database, IDatabaseTransactionOpsCoreTyped};
9use fedimint_core::encoding::{Decodable, Encodable};
10use fedimint_core::envs::is_running_in_test_env;
11use fedimint_core::net::api_announcement::SignedApiAnnouncement;
12use fedimint_core::net::guardian_metadata::SignedGuardianMetadata;
13use fedimint_core::runtime::{self, sleep};
14use fedimint_core::secp256k1::SECP256K1;
15use fedimint_core::util::backoff_util::custom_backoff;
16use fedimint_core::util::{FmtCompact as _, SafeUrl};
17use fedimint_core::{NumPeersExt as _, PeerId, impl_db_lookup, impl_db_record};
18use fedimint_logging::LOG_CLIENT;
19use futures::stream::{FuturesUnordered, StreamExt as _};
20use tracing::{debug, warn};
21
22use crate::Client;
23use crate::db::DbKeyPrefix;
24use crate::guardian_metadata::GuardianMetadataPrefix;
25
26#[cfg(test)]
27mod tests;
28
29#[derive(Clone, Debug, Encodable, Decodable)]
30pub struct ApiAnnouncementKey(pub PeerId);
31
32#[derive(Clone, Debug, Encodable, Decodable)]
33pub struct ApiAnnouncementPrefix;
34
35impl_db_record!(
36    key = ApiAnnouncementKey,
37    value = SignedApiAnnouncement,
38    db_prefix = DbKeyPrefix::ApiUrlAnnouncement,
39    notify_on_modify = false,
40);
41impl_db_lookup!(
42    key = ApiAnnouncementKey,
43    query_prefix = ApiAnnouncementPrefix
44);
45
46/// Fetches API URL announcements from guardians, validates them and updates the
47/// DB if any new more upt to date ones are found.
48pub(crate) async fn run_api_announcement_refresh_task(client_inner: Arc<Client>) {
49    // Wait for the guardian keys to be available
50    let guardian_pub_keys = client_inner.get_guardian_public_keys_blocking().await;
51    loop {
52        let api: &DynGlobalApi = &client_inner.api;
53        let results = fetch_api_announcements_from_at_least_num_of_peers(
54            1,
55            api,
56            &guardian_pub_keys,
57            if is_running_in_test_env!() {
58                Duration::from_millis(1)
59            } else {
60                Duration::from_secs(30)
61            },
62        )
63        .await;
64        store_api_announcements_updates_from_peers(client_inner.db(), &results).await;
65
66        let duration = if is_running_in_test_env!() {
67            Duration::from_secs(1)
68        } else {
69            // Check once an hour if there are new announcements
70            Duration::from_secs(3600)
71        };
72        sleep(duration).await;
73    }
74}
75
76pub(crate) async fn store_api_announcements_updates_from_peers(
77    db: &Database,
78    updates: &[BTreeMap<PeerId, SignedApiAnnouncement>],
79) {
80    for announcements in updates {
81        store_api_announcement_updates(db, announcements).await;
82    }
83}
84
85pub(crate) type PeersSignedApiAnnouncements = BTreeMap<PeerId, SignedApiAnnouncement>;
86
87/// Fetch responses from at least `num_responses_required` of peers.
88///
89/// Will wait a little bit extra in hopes of collecting more than strictly
90/// needed responses.
91pub(crate) async fn fetch_api_announcements_from_at_least_num_of_peers(
92    num_responses_required: usize,
93    api: &DynGlobalApi,
94    guardian_pub_keys: &BTreeMap<PeerId, bitcoin::secp256k1::PublicKey>,
95    extra_response_wait: Duration,
96) -> Vec<PeersSignedApiAnnouncements> {
97    let Ok(num_peers) = guardian_pub_keys.try_num_peers() else {
98        // Older or malformed configs may contain Some(empty) broadcast keys.
99        // Preserve the empty result without terminating the refresh task.
100        return Vec::new();
101    };
102    // Keep trying, initially somewhat aggressively, but after a while retry very
103    // slowly, because chances for response are getting lower and lower.
104    let mut backoff = custom_backoff(Duration::from_millis(200), Duration::from_secs(600), None);
105
106    // Make a single request to a peer after a delay
107    async fn make_request(
108        delay: Duration,
109        peer_id: PeerId,
110        api: &DynGlobalApi,
111        guardian_pub_keys: &BTreeMap<PeerId, bitcoin::secp256k1::PublicKey>,
112    ) -> (
113        PeerId,
114        Result<PeersSignedApiAnnouncements, FetchApiAnnouncementsError>,
115    ) {
116        runtime::sleep(delay).await;
117
118        let result = async {
119            let announcements = api
120                .api_announcements(peer_id)
121                .await
122                .map_err(|source| FetchApiAnnouncementsError::Request { peer_id, source })?;
123
124            // If any of the announcements is invalid something is fishy with that
125            // guardian and we ignore all its responses
126            for (peer_id, announcement) in &announcements {
127                let Some(guardian_pub_key) = guardian_pub_keys.get(peer_id) else {
128                    return Err(FetchApiAnnouncementsError::UnknownGuardian { peer_id: *peer_id });
129                };
130
131                if !announcement.verify(SECP256K1, guardian_pub_key) {
132                    return Err(FetchApiAnnouncementsError::InvalidSignature { peer_id: *peer_id });
133                }
134            }
135            Ok(announcements)
136        }
137        .await;
138
139        (peer_id, result)
140    }
141
142    let mut requests = FuturesUnordered::new();
143
144    for peer_id in num_peers.peer_ids() {
145        requests.push(make_request(
146            Duration::ZERO,
147            peer_id,
148            api,
149            guardian_pub_keys,
150        ));
151    }
152
153    let mut responses = Vec::new();
154
155    loop {
156        let next_response = if responses.len() < num_responses_required {
157            // If we don't have enough responses yet, we wait
158            requests.next().await
159        } else {
160            // if we do have responses we need, we wait opportunistically just for a small
161            // duration if any other responses are ready anyway, just to not
162            // throw them away
163            fedimint_core::runtime::timeout(extra_response_wait, requests.next())
164                .await
165                .ok()
166                .flatten()
167        };
168
169        let Some((peer_id, response)) = next_response else {
170            break;
171        };
172
173        match response {
174            Err(err) => {
175                debug!(
176                    target: LOG_CLIENT,
177                    %peer_id,
178                    err = %err.fmt_compact(),
179                    "Failed to fetch API announcements from peer"
180                );
181                requests.push(make_request(
182                    backoff.next().expect("Keeps retrying"),
183                    peer_id,
184                    api,
185                    guardian_pub_keys,
186                ));
187            }
188            Ok(announcements) => {
189                responses.push(announcements);
190            }
191        }
192    }
193
194    responses
195}
196
197pub(crate) async fn store_api_announcement_updates(
198    db: &Database,
199    announcements: &BTreeMap<PeerId, SignedApiAnnouncement>,
200) {
201    db
202        .autocommit(
203            |dbtx, _|{
204                let announcements_inner = announcements.clone();
205            Box::pin(async move {
206                for (peer, new_announcement) in announcements_inner {
207                    let replace_current_announcement = dbtx
208                        .get_value(&ApiAnnouncementKey(peer))
209                        .await.is_none_or(|current_announcement| {
210                            current_announcement.api_announcement.nonce
211                                < new_announcement.api_announcement.nonce
212                        });
213                    if replace_current_announcement {
214                        debug!(target: LOG_CLIENT, ?peer, %new_announcement.api_announcement.api_url, "Updating API announcement");
215                        dbtx.insert_entry(&ApiAnnouncementKey(peer), &new_announcement)
216                            .await;
217                    }
218                }
219
220                Result::<(), ()>::Ok(())
221            })},
222            None,
223        )
224        .await
225        .expect("Will never return an error");
226}
227
228/// Returns a list of all peers and their respective API URLs taking into
229/// account guardian metadata and API announcements overwriting the URLs
230/// contained in the original configuration.
231///
232/// Priority order:
233/// 1. Guardian metadata (if available) - uses first URL from api_urls
234/// 2. API announcement (if available)
235/// 3. Configured URL (fallback)
236pub async fn get_api_urls(
237    db: &Database,
238    cfg: &ClientConfig,
239    client_iroh_next_enabled: bool,
240) -> BTreeMap<PeerId, SafeUrl> {
241    let mut dbtx = db.begin_transaction_nc().await;
242
243    // Load guardian metadata for all peers
244    let guardian_metadata: BTreeMap<PeerId, SignedGuardianMetadata> = dbtx
245        .find_by_prefix(&GuardianMetadataPrefix)
246        .await
247        .map(|(key, metadata)| (key.0, metadata))
248        .collect()
249        .await;
250
251    // Load API announcements for all peers
252    let api_announcements: BTreeMap<PeerId, SignedApiAnnouncement> = dbtx
253        .find_by_prefix(&ApiAnnouncementPrefix)
254        .await
255        .map(|(key, announcement)| (key.0, announcement))
256        .collect()
257        .await;
258
259    // For each peer: prefer guardian metadata, then API announcement, then config.
260    // When the client supports iroh-next and the guardian advertises an
261    // iroh-next endpoint, replace the original iroh:// identity with the
262    // advertised identity. The original identity is not retained as a fallback.
263    cfg.global
264        .api_endpoints
265        .iter()
266        .filter_map(|(peer_id, peer_url)| {
267            let metadata = guardian_metadata.get(peer_id);
268
269            let mut url = metadata
270                .and_then(|m| m.guardian_metadata().api_urls.first().cloned())
271                .or_else(|| {
272                    api_announcements
273                        .get(peer_id)
274                        .map(|a| a.api_announcement.api_url.clone())
275                })
276                .unwrap_or_else(|| peer_url.url.clone());
277
278            // If the resolved URL is iroh:// and iroh-next endpoint preference is
279            // enabled, swap in the advertised iroh-next endpoint.
280            if url.scheme() == "iroh"
281                && client_iroh_next_enabled
282                && let Some(m) = metadata
283            {
284                let gm = m.guardian_metadata();
285                if let Some(endpoint) = &gm.iroh_next_endpoint {
286                    match iroh_next_endpoint_url(endpoint) {
287                        Ok(next_url) => {
288                            debug!(
289                                target: LOG_CLIENT,
290                                %peer_id,
291                                %next_url,
292                                "Using iroh-next endpoint from guardian metadata",
293                            );
294                            url = next_url;
295                        }
296                        Err(err) => {
297                            warn!(
298                                target: LOG_CLIENT,
299                                %peer_id,
300                                err = %err.fmt_compact(),
301                                "Ignoring peer with invalid advertised iroh-next endpoint",
302                            );
303                            return None;
304                        }
305                    }
306                }
307            }
308
309            Some((*peer_id, url))
310        })
311        .collect()
312}
313
314/// Why a peer's API announcements were not accepted.
315#[derive(Debug, thiserror::Error)]
316enum FetchApiAnnouncementsError {
317    /// The peer could not be asked.
318    #[error("Fetching API announcements from peer {peer_id} failed")]
319    Request {
320        peer_id: PeerId,
321        #[source]
322        source: ServerError,
323    },
324
325    /// The peer sent an announcement of a guardian the client does not know.
326    #[error("Guardian public key not found for peer {peer_id}")]
327    UnknownGuardian { peer_id: PeerId },
328
329    /// The peer sent an announcement whose signature does not verify.
330    #[error("Failed to verify announcement for peer {peer_id}")]
331    InvalidSignature { peer_id: PeerId },
332}