Skip to main content

fedimint_server/net/api/
guardian_metadata.rs

1use std::time::{Duration, UNIX_EPOCH};
2
3use fedimint_api_client::api::DynGlobalApi;
4use fedimint_core::db::{Database, IDatabaseTransactionOpsCoreTyped};
5use fedimint_core::encoding::{Decodable, Encodable};
6use fedimint_core::envs::is_running_in_test_env;
7use fedimint_core::net::guardian_metadata::{GuardianMetadata, SignedGuardianMetadata};
8use fedimint_core::task::{TaskGroup, sleep};
9use fedimint_core::util::FmtCompact;
10use fedimint_core::{PeerId, impl_db_lookup, impl_db_record, secp256k1};
11use fedimint_logging::LOG_NET_API;
12use futures::future::join_all;
13use futures::stream::StreamExt;
14use tokio::select;
15use tracing::{debug, info};
16
17use crate::IrohNextApiSettings;
18use crate::config::ServerConfig;
19use crate::db::DbKeyPrefix;
20use crate::net::iroh::{derive_iroh_v1_api_secret_key, guardian_connector_registry_builder};
21
22fn ensure_iroh_next_remains_available(
23    existing_endpoint: Option<&str>,
24    configured_endpoint: Option<&str>,
25) -> anyhow::Result<()> {
26    if let Some(existing_endpoint) = existing_endpoint {
27        anyhow::ensure!(
28            configured_endpoint == Some(existing_endpoint),
29            "Iroh 1.0 API endpoint {existing_endpoint} was previously advertised and must remain \
30             enabled unchanged; disabling or rotating it is unsupported"
31        );
32    }
33    Ok(())
34}
35
36fn reconcile_iroh_next_endpoint(
37    metadata: &mut GuardianMetadata,
38    configured_endpoint: Option<String>,
39) -> anyhow::Result<bool> {
40    ensure_iroh_next_remains_available(
41        metadata.iroh_next_endpoint.as_deref(),
42        configured_endpoint.as_deref(),
43    )?;
44    if metadata.iroh_next_endpoint == configured_endpoint {
45        return Ok(false);
46    }
47    metadata.iroh_next_endpoint = configured_endpoint;
48    Ok(true)
49}
50
51#[derive(Clone, Debug, Encodable, Decodable)]
52pub struct GuardianMetadataKey(pub PeerId);
53
54#[derive(Clone, Debug, Encodable, Decodable)]
55pub struct GuardianMetadataPrefix;
56
57impl_db_record!(
58    key = GuardianMetadataKey,
59    value = SignedGuardianMetadata,
60    db_prefix = DbKeyPrefix::GuardianMetadata,
61    notify_on_modify = true,
62);
63impl_db_lookup!(
64    key = GuardianMetadataKey,
65    query_prefix = GuardianMetadataPrefix
66);
67
68/// Build the federation API client used to publish guardian metadata.
69pub async fn prepare_guardian_metadata_service(
70    db: &Database,
71    cfg: &ServerConfig,
72    api_secret: Option<String>,
73) -> anyhow::Result<DynGlobalApi> {
74    Ok(DynGlobalApi::new(
75        guardian_connector_registry_builder()
76            .with_env_var_overrides()
77            .bind()
78            .await,
79        super::announcement::get_api_urls(db, &cfg.consensus).await,
80        api_secret.as_deref(),
81    ))
82}
83
84/// Store and publish this guardian's current metadata.
85pub fn start_guardian_metadata_service(
86    db: &Database,
87    tg: &TaskGroup,
88    cfg: &ServerConfig,
89    api_client: DynGlobalApi,
90    metadata_updated: bool,
91) {
92    const INITIAL_DELAY_SECONDS: u64 = 5;
93    const FAILURE_RETRY_SECONDS: u64 = 60;
94    const SUCCESS_RETRY_SECONDS: u64 = 600;
95
96    let initial_delay = if metadata_updated {
97        Duration::ZERO
98    } else {
99        Duration::from_secs(INITIAL_DELAY_SECONDS)
100    };
101
102    let db = db.clone();
103    let our_peer_id = cfg.local.identity;
104    tg.spawn_cancellable("submit-guardian-metadata", async move {
105        // Give other servers some time to start up in case they were just restarted together
106        sleep(initial_delay).await;
107        loop {
108            let mut success = true;
109            let metadata_list = db
110                .begin_transaction_nc()
111                .await
112                .find_by_prefix(&GuardianMetadataPrefix)
113                .await
114                .map(|(peer_key, peer_metadata)| (peer_key.0, peer_metadata))
115                .collect::<Vec<(PeerId, SignedGuardianMetadata)>>()
116                .await;
117
118            info!(
119                target: LOG_NET_API,
120                len = %metadata_list.len(),
121                "Submitting guardian metadata"
122            );
123            // Submit all metadata we know (including our own and other peers') to all
124            // federation members (in parallel). Each submit_guardian_metadata call
125            // broadcasts one piece of metadata to all peers.
126            let results = join_all(metadata_list.iter().map(|(peer, metadata)| {
127                let api_client = &api_client;
128                async move {
129                    (*peer, api_client.submit_guardian_metadata(*peer, metadata.clone()).await)
130                }
131            }))
132            .await;
133
134            info!(
135                target: LOG_NET_API,
136                len = %metadata_list.len(),
137                "Done"
138            );
139            for (peer, result) in results {
140                if let Err(err) = result {
141                    debug!(target: LOG_NET_API, ?peer, err = %err.fmt_compact(), "Submitting guardian metadata did not succeed for all peers, retrying in {FAILURE_RETRY_SECONDS} seconds");
142                    success = false;
143                }
144            }
145
146            // While we announce all peer metadata, we only want to immediately trigger in case ours changes
147            let our_metadata_key = GuardianMetadataKey(our_peer_id);
148            let our_metadata = db
149                .begin_transaction_nc()
150                .await
151                .get_value(&our_metadata_key)
152                .await
153                .expect("Our guardian metadata is always present");
154
155            let new_metadata = db.wait_key_check(&our_metadata_key, |new_metadata| {
156                new_metadata.and_then(|new_metadata| {
157                    (new_metadata.tagged_hash() != our_metadata.tagged_hash()).then_some(())
158                })
159            });
160
161
162            let auto_announcement_delay = if success {
163                Duration::from_secs(SUCCESS_RETRY_SECONDS)
164            } else if is_running_in_test_env!() {
165                Duration::from_secs(3)
166            } else {
167                Duration::from_secs(FAILURE_RETRY_SECONDS)
168            };
169
170            select! {
171                _ = new_metadata => {},
172                () = sleep(auto_announcement_delay) => {},
173            }
174        }
175    });
176}
177
178/// Reconciles and signs the server-owned Iroh endpoint in guardian metadata.
179///
180/// Existing administrator-owned URLs and Pkarr ID are preserved. Returns `true`
181/// if metadata was inserted or updated and should be broadcast.
182pub async fn reconcile_guardian_metadata(
183    db: &Database,
184    cfg: &ServerConfig,
185    iroh_next_api_settings: Option<&IrohNextApiSettings>,
186) -> anyhow::Result<bool> {
187    let key = GuardianMetadataKey(cfg.local.identity);
188    let mut dbtx = db.begin_transaction().await;
189    let existing = dbtx.get_value(&key).await;
190
191    let mut guardian_metadata = existing.as_ref().map_or_else(
192        || {
193            GuardianMetadata::new(
194                cfg.consensus
195                    .api_endpoints()
196                    .get(&cfg.local.identity)
197                    .map(|endpoint| vec![endpoint.url.clone()])
198                    .unwrap_or_default(),
199                super::pkarr_publish::pkarr_id_z32(&cfg.private.broadcast_secret_key),
200                0,
201            )
202        },
203        |existing| existing.guardian_metadata().clone(),
204    );
205
206    let iroh_next_endpoint = iroh_next_api_settings.map(|_| {
207        derive_iroh_v1_api_secret_key(&cfg.private.broadcast_secret_key)
208            .public()
209            .to_string()
210    });
211
212    let endpoint_changed =
213        reconcile_iroh_next_endpoint(&mut guardian_metadata, iroh_next_endpoint)?;
214    if existing.is_some() && !endpoint_changed {
215        return Ok(false);
216    }
217
218    let now = fedimint_core::time::now()
219        .duration_since(UNIX_EPOCH)
220        .expect("System time should be after UNIX_EPOCH")
221        .as_secs();
222    guardian_metadata.timestamp_secs = existing.as_ref().map_or(now, |metadata| {
223        now.max(
224            metadata
225                .guardian_metadata()
226                .timestamp_secs
227                .saturating_add(1),
228        )
229    });
230
231    let ctx = secp256k1::Secp256k1::new();
232    let signed_metadata =
233        guardian_metadata.sign(&ctx, &cfg.private.broadcast_secret_key.keypair(&ctx));
234
235    dbtx.insert_entry(&key, &signed_metadata).await;
236    dbtx.commit_tx().await;
237
238    Ok(true)
239}
240
241#[cfg(test)]
242mod tests;