Skip to main content

fedimint_server/net/api/
announcement.rs

1use std::collections::BTreeMap;
2use std::time::Duration;
3
4use fedimint_api_client::api::DynGlobalApi;
5use fedimint_core::db::{Database, IDatabaseTransactionOpsCoreTyped};
6use fedimint_core::encoding::{Decodable, Encodable};
7use fedimint_core::envs::is_running_in_test_env;
8use fedimint_core::net::api_announcement::{ApiAnnouncement, SignedApiAnnouncement};
9use fedimint_core::net::guardian_metadata::SignedGuardianMetadata;
10use fedimint_core::task::{TaskGroup, sleep};
11use fedimint_core::util::{FmtCompact, SafeUrl};
12use fedimint_core::{PeerId, impl_db_lookup, impl_db_record, secp256k1};
13use fedimint_logging::LOG_NET_API;
14use futures::future::join_all;
15use futures::stream::StreamExt;
16use tokio::select;
17use tracing::debug;
18
19use super::guardian_metadata::GuardianMetadataPrefix;
20use crate::config::{ServerConfig, ServerConfigConsensus};
21use crate::db::DbKeyPrefix;
22use crate::net::iroh::guardian_connector_registry_builder;
23
24#[derive(Clone, Debug, Encodable, Decodable)]
25pub struct ApiAnnouncementKey(pub PeerId);
26
27#[derive(Clone, Debug, Encodable, Decodable)]
28pub struct ApiAnnouncementPrefix;
29
30impl_db_record!(
31    key = ApiAnnouncementKey,
32    value = SignedApiAnnouncement,
33    db_prefix = DbKeyPrefix::ApiAnnouncements,
34    notify_on_modify = true,
35);
36impl_db_lookup!(
37    key = ApiAnnouncementKey,
38    query_prefix = ApiAnnouncementPrefix
39);
40
41pub async fn start_api_announcement_service(
42    db: &Database,
43    tg: &TaskGroup,
44    cfg: &ServerConfig,
45    api_secret: Option<String>,
46) -> anyhow::Result<()> {
47    const INITIAL_DEALY_SECONDS: u64 = 5;
48    const FAILURE_RETRY_SECONDS: u64 = 60;
49    const SUCCESS_RETRY_SECONDS: u64 = 600;
50
51    let initial_delay = if insert_signed_api_announcement_if_not_present(db, cfg).await {
52        Duration::ZERO
53    } else {
54        Duration::from_secs(INITIAL_DEALY_SECONDS)
55    };
56
57    let db = db.clone();
58    // FIXME: (@leonardo) how should we handle the connector here ?
59    let api_client = DynGlobalApi::new(
60        // TODO: get from somewhere/unify?
61        guardian_connector_registry_builder()
62            .with_env_var_overrides()
63            .bind()
64            .await,
65        get_api_urls(&db, &cfg.consensus).await,
66        api_secret.as_deref(),
67    );
68
69    let our_peer_id = cfg.local.identity;
70    tg.spawn_cancellable("submit-api-url-announcement", async move {
71        // Give other servers some time to start up in case they were just restarted
72        // together
73        sleep(initial_delay).await;
74        loop {
75            let mut success = true;
76            let announcements = db.begin_transaction_nc()
77                .await
78                .find_by_prefix(&ApiAnnouncementPrefix)
79                .await
80                .map(|(peer_key, peer_announcement)| (peer_key.0, peer_announcement))
81                .collect::<Vec<(PeerId, SignedApiAnnouncement)>>()
82                .await;
83
84            // Submit all API announcements we know (including our own and other peers')
85            // to all federation members (in parallel). Each submit_api_announcement call
86            // broadcasts one announcement to all peers.
87            let results = join_all(announcements.iter().map(|(peer, announcement)| {
88                let api_client = &api_client;
89                async move {
90                    (*peer, api_client.submit_api_announcement(*peer, announcement.clone()).await)
91                }
92            }))
93            .await;
94
95            for (peer, result) in results {
96                if let Err(err) = result {
97                    debug!(target: LOG_NET_API, ?peer, err = %err.fmt_compact(), "Announcing API URL did not succeed for all peers, retrying in {FAILURE_RETRY_SECONDS} seconds");
98                    success = false;
99                }
100            }
101
102            // While we announce all peer API urls, we only want to immediately trigger in case
103            let our_announcement_key = ApiAnnouncementKey(our_peer_id);
104            let our_announcement = db
105                .begin_transaction_nc()
106                .await
107                .get_value(&our_announcement_key)
108                .await
109                .expect("Our announcement is always present");
110            let new_announcement = db.wait_key_check(
111                &our_announcement_key,
112                |new_announcement| {
113                    new_announcement.and_then(
114                        |new_announcement| (new_announcement.api_announcement.nonce != our_announcement.api_announcement.nonce).then_some(())
115                    )
116                });
117
118            let auto_announcement_delay = if success {
119                Duration::from_secs(SUCCESS_RETRY_SECONDS)
120            } else if is_running_in_test_env!() {
121                Duration::from_secs(3)
122            } else {
123                Duration::from_secs(FAILURE_RETRY_SECONDS)
124            };
125
126            select! {
127                _ = new_announcement => {},
128                () = sleep(auto_announcement_delay) => {},
129            }
130        }
131    });
132
133    Ok(())
134}
135
136/// Checks if we already have a signed API endpoint announcement for our own
137/// identity in the database and creates one if not.
138///
139/// Return `true` fresh announcements were inserted because it was not present
140async fn insert_signed_api_announcement_if_not_present(db: &Database, cfg: &ServerConfig) -> bool {
141    let mut dbtx = db.begin_transaction().await;
142    if dbtx
143        .get_value(&ApiAnnouncementKey(cfg.local.identity))
144        .await
145        .is_some()
146    {
147        return false;
148    }
149
150    let api_announcement = ApiAnnouncement::new(
151        cfg.consensus.api_endpoints()[&cfg.local.identity]
152            .url
153            .clone(),
154        0,
155    );
156    let ctx = secp256k1::Secp256k1::new();
157    let signed_announcement =
158        api_announcement.sign(&ctx, &cfg.private.broadcast_secret_key.keypair(&ctx));
159
160    dbtx.insert_entry(
161        &ApiAnnouncementKey(cfg.local.identity),
162        &signed_announcement,
163    )
164    .await;
165    dbtx.commit_tx().await;
166
167    true
168}
169
170/// Returns a list of all peers and their respective API URLs taking into
171/// account guardian metadata and API announcements overwriting the URLs
172/// contained in the original configuration.
173///
174/// Priority order:
175/// 1. Guardian metadata (if available) - uses first URL from api_urls
176/// 2. API announcement (if available)
177/// 3. Configured URL (fallback)
178pub async fn get_api_urls(db: &Database, cfg: &ServerConfigConsensus) -> BTreeMap<PeerId, SafeUrl> {
179    let mut dbtx = db.begin_transaction_nc().await;
180
181    // Load guardian metadata for all peers
182    let guardian_metadata: BTreeMap<PeerId, SignedGuardianMetadata> = dbtx
183        .find_by_prefix(&GuardianMetadataPrefix)
184        .await
185        .map(|(key, metadata)| (key.0, metadata))
186        .collect()
187        .await;
188
189    // Load API announcements for all peers
190    let api_announcements: BTreeMap<PeerId, SignedApiAnnouncement> = dbtx
191        .find_by_prefix(&ApiAnnouncementPrefix)
192        .await
193        .map(|(key, announcement)| (key.0, announcement))
194        .collect()
195        .await;
196
197    // For each peer: prefer guardian metadata, then API announcement, then config
198    cfg.api_endpoints()
199        .iter()
200        .map(|(peer_id, peer_url)| {
201            let url = guardian_metadata
202                .get(peer_id)
203                .and_then(|m| m.guardian_metadata().api_urls.first().cloned())
204                .or_else(|| {
205                    api_announcements
206                        .get(peer_id)
207                        .map(|a| a.api_announcement.api_url.clone())
208                })
209                .unwrap_or_else(|| peer_url.url.clone());
210            (*peer_id, url)
211        })
212        .collect()
213}