Skip to main content

fedimint_gateway_server/
federation_manager.rs

1use std::collections::BTreeMap;
2use std::sync::Arc;
3use std::sync::atomic::{AtomicU64, Ordering};
4use std::time::SystemTime;
5
6use bitcoin::secp256k1::Keypair;
7use fedimint_client::ClientHandleArc;
8use fedimint_core::config::{
9    FederationId, FederationIdPrefix, JsonClientConfig, META_FEDERATION_NAME_KEY,
10};
11use fedimint_core::core::Account;
12use fedimint_core::db::{Committable, DatabaseTransaction, NonCommittable};
13use fedimint_core::invite_code::InviteCode;
14use fedimint_core::module::AmountUnit;
15use fedimint_core::util::{FmtCompact as _, Spanned};
16use fedimint_core::{PeerId, TieredCounts};
17use fedimint_gateway_common::FederationInfo;
18use fedimint_gateway_server_db::GatewayDbtxNcExt as _;
19use fedimint_gw_client::GatewayClientModule;
20use fedimint_gwv2_client::{GatewayClientModuleV2, GatewayOperationMetaV2};
21use fedimint_logging::LOG_GATEWAY;
22use fedimint_mint_client::MintClientModule;
23use fedimint_mintv2_client::MintClientModule as MintV2ClientModule;
24use tracing::{info, warn};
25
26use crate::error::{AdminGatewayError, FederationNotConnected};
27use crate::{AdminResult, Registration};
28
29/// The first index that the gateway will assign to a federation.
30/// Note: This starts at 1 because LNv1 uses the `federation_index` as an SCID.
31/// An SCID of 0 is considered invalid by LND's HTLC interceptor.
32const INITIAL_INDEX: u64 = 1;
33
34// TODO: Add support for client lookup by payment hash (for LNv2).
35#[derive(Debug)]
36pub struct FederationManager {
37    /// Map of `FederationId` -> `Client`. Used for efficient retrieval of the
38    /// client while handling incoming HTLCs.
39    clients: BTreeMap<FederationId, Spanned<fedimint_client::ClientHandleArc>>,
40
41    /// Map of federation indices to `FederationId`. Use for efficient retrieval
42    /// of the client while handling incoming HTLCs.
43    /// Can be removed after LNv1 removal.
44    index_to_federation: BTreeMap<u64, FederationId>,
45
46    /// Tracker for federation index assignments. When connecting a new
47    /// federation, this value is incremented and assigned to the federation
48    /// as the `federation_index`
49    next_index: AtomicU64,
50}
51
52impl FederationManager {
53    pub fn new() -> Self {
54        Self {
55            clients: BTreeMap::new(),
56            index_to_federation: BTreeMap::new(),
57            next_index: AtomicU64::new(INITIAL_INDEX),
58        }
59    }
60
61    pub fn add_client(&mut self, index: u64, client: Spanned<fedimint_client::ClientHandleArc>) {
62        let federation_id = client.borrow().with_sync(|c| c.federation_id());
63        self.clients.insert(federation_id, client);
64        self.index_to_federation.insert(index, federation_id);
65    }
66
67    pub async fn leave_federation(
68        &mut self,
69        federation_id: FederationId,
70        dbtx: &mut DatabaseTransaction<'_, NonCommittable>,
71        registrations: Vec<&Registration>,
72    ) -> AdminResult<FederationInfo> {
73        let federation_info = self.federation_info(federation_id, dbtx).await?;
74
75        for registration in registrations {
76            self.unannounce_from_federation(federation_id, registration.keypair)
77                .await;
78        }
79
80        self.remove_client(federation_id).await?;
81
82        Ok(federation_info)
83    }
84
85    async fn remove_client(&mut self, federation_id: FederationId) -> AdminResult<()> {
86        let client = self
87            .clients
88            .remove(&federation_id)
89            .ok_or(FederationNotConnected {
90                federation_id_prefix: federation_id.to_prefix(),
91            })?
92            .into_value();
93
94        self.index_to_federation
95            .retain(|_, fid| *fid != federation_id);
96
97        match Arc::into_inner(client) {
98            Some(client) => {
99                client.shutdown().await;
100                Ok(())
101            }
102            _ => Err(AdminGatewayError::ClientRemovalError(format!(
103                "Federation client {federation_id} is not unique, failed to shutdown client"
104            ))),
105        }
106    }
107
108    /// Waits for ongoing incoming LNv1 and LNv2 payments to complete before
109    /// returning.
110    pub async fn wait_for_incoming_payments(&self) -> AdminResult<()> {
111        for client in self.clients.values() {
112            let active_operations = client.value().get_active_operations().await;
113            let operation_log = client.value().operation_log();
114            for op_id in active_operations {
115                let log_entry = operation_log.get_operation(op_id).await;
116                if let Some(entry) = log_entry {
117                    match entry.operation_module_kind() {
118                        "lnv2" => {
119                            let Ok(meta) = entry.try_meta::<GatewayOperationMetaV2>() else {
120                                warn!(
121                                    target: LOG_GATEWAY,
122                                    operation_id = %op_id.fmt_short(),
123                                    "Skipping LNv2 operation with invalid metadata while waiting for incoming payments",
124                                );
125                                continue;
126                            };
127                            if !meta.waits_for_completion() {
128                                continue;
129                            }
130                            let lnv2 = client
131                                .value()
132                                .get_first_module::<GatewayClientModuleV2>()
133                                .map_err(anyhow::Error::from)?;
134                            lnv2.await_completion(op_id).await;
135                        }
136                        "ln" => {
137                            let lnv1 = client
138                                .value()
139                                .get_first_module::<GatewayClientModule>()
140                                .map_err(anyhow::Error::from)?;
141                            lnv1.await_completion(op_id).await;
142                        }
143                        _ => {}
144                    }
145                }
146            }
147        }
148
149        info!(target: LOG_GATEWAY, "Finished waiting for incoming payments");
150        Ok(())
151    }
152
153    async fn unannounce_from_federation(
154        &self,
155        federation_id: FederationId,
156        gateway_keypair: Keypair,
157    ) {
158        if let Ok(client) = self
159            .clients
160            .get(&federation_id)
161            .ok_or(FederationNotConnected {
162                federation_id_prefix: federation_id.to_prefix(),
163            })
164            && let Ok(ln) = client.value().get_first_module::<GatewayClientModule>()
165        {
166            ln.remove_from_federation(gateway_keypair).await;
167        }
168    }
169
170    /// Iterates through all of the federations the gateway is registered with
171    /// and requests to remove the registration record.
172    pub async fn unannounce_from_all_federations(&self, gateway_keypair: Keypair) {
173        let removal_futures = self
174            .clients
175            .values()
176            .filter_map(|client| {
177                client
178                    .value()
179                    .get_first_module::<GatewayClientModule>()
180                    .ok()
181                    .map(|lnv1| async move {
182                        lnv1.remove_from_federation(gateway_keypair).await;
183                    })
184            })
185            .collect::<Vec<_>>();
186
187        futures::future::join_all(removal_futures).await;
188    }
189
190    pub fn get_client_for_index(&self, short_channel_id: u64) -> Option<Spanned<ClientHandleArc>> {
191        let federation_id = self.index_to_federation.get(&short_channel_id)?;
192        // TODO(tvolk131): Cloning the client here could cause issues with client
193        // shutdown (see `remove_client` above). Perhaps this function should take a
194        // lambda and pass it into `client.with_sync`.
195        match self.clients.get(federation_id).cloned() {
196            Some(client) => Some(client),
197            _ => {
198                panic!(
199                    "`FederationManager.index_to_federation` is out of sync with `FederationManager.clients`! This is a bug."
200                );
201            }
202        }
203    }
204
205    pub fn get_client_for_federation_id_prefix(
206        &self,
207        federation_id_prefix: FederationIdPrefix,
208    ) -> Option<Spanned<ClientHandleArc>> {
209        self.clients.iter().find_map(|(fid, client)| {
210            if fid.to_prefix() == federation_id_prefix {
211                Some(client.clone())
212            } else {
213                None
214            }
215        })
216    }
217
218    pub fn has_federation(&self, federation_id: FederationId) -> bool {
219        self.clients.contains_key(&federation_id)
220    }
221
222    pub fn client(&self, federation_id: &FederationId) -> Option<&Spanned<ClientHandleArc>> {
223        self.clients.get(federation_id)
224    }
225
226    pub async fn federation_info(
227        &self,
228        federation_id: FederationId,
229        dbtx: &mut DatabaseTransaction<'_, NonCommittable>,
230    ) -> std::result::Result<FederationInfo, FederationNotConnected> {
231        self.clients
232            .get(&federation_id)
233            .ok_or(FederationNotConnected {
234                federation_id_prefix: federation_id.to_prefix(),
235            })?
236            .borrow()
237            .with(|client| async move {
238                let balance_msat = client
239                    .get_balance_for_btc(Account::Primary)
240                    .await
241                    // If primary module is not available, we're not really connected yet
242                    .map_err(|_err| FederationNotConnected {
243                        federation_id_prefix: federation_id.to_prefix(),
244                    })?;
245
246                let config = dbtx.load_federation_config(federation_id).await.ok_or(
247                    FederationNotConnected {
248                        federation_id_prefix: federation_id.to_prefix(),
249                    },
250                )?;
251                let last_backup_time =
252                    dbtx.load_backup_record(federation_id)
253                        .await
254                        .ok_or(FederationNotConnected {
255                            federation_id_prefix: federation_id.to_prefix(),
256                        })?;
257
258                Ok(FederationInfo {
259                    federation_id,
260                    federation_name: self.federation_name(client).await,
261                    balance_msat,
262                    config,
263                    last_backup_time,
264                })
265            })
266            .await
267    }
268
269    pub async fn federation_name(&self, client: &ClientHandleArc) -> Option<String> {
270        if let Some(name) = client
271            .meta_service()
272            .get_cached_field::<String>(client.db(), META_FEDERATION_NAME_KEY)
273            .await
274            .and_then(|value| value.value)
275        {
276            return Some(name);
277        }
278
279        // Existing federations may still have only an immutable name, including
280        // when their Meta module has other fields but no federation name.
281        let client_config = client.config().await;
282        let federation_name = client_config.global.federation_name();
283        federation_name.map(String::from)
284    }
285
286    pub async fn federation_info_all_federations(
287        &self,
288        mut dbtx: DatabaseTransaction<'_, NonCommittable>,
289    ) -> Vec<FederationInfo> {
290        let mut federation_infos = Vec::new();
291        for (federation_id, client) in &self.clients {
292            let balance_msat = match client
293                .borrow()
294                .with(|client| client.get_balance_for_btc(Account::Primary))
295                .await
296            {
297                Ok(balance_msat) => balance_msat,
298                Err(err) => {
299                    warn!(
300                        target: LOG_GATEWAY,
301                        err = %err.fmt_compact(),
302                        "Skipped Federation due to lack of primary module"
303                    );
304                    continue;
305                }
306            };
307
308            let config = dbtx.load_federation_config(*federation_id).await;
309            let last_backup_time = dbtx
310                .load_backup_record(*federation_id)
311                .await
312                .unwrap_or_default();
313            if let Some(config) = config {
314                federation_infos.push(FederationInfo {
315                    federation_id: *federation_id,
316                    federation_name: self.federation_name(client.value()).await,
317                    balance_msat,
318                    config,
319                    last_backup_time,
320                });
321            }
322        }
323        federation_infos
324    }
325
326    pub async fn get_federation_config(
327        &self,
328        federation_id: FederationId,
329    ) -> AdminResult<JsonClientConfig> {
330        let client = self
331            .clients
332            .get(&federation_id)
333            .ok_or(FederationNotConnected {
334                federation_id_prefix: federation_id.to_prefix(),
335            })?;
336        Ok(client
337            .borrow()
338            .with(|client| client.get_config_json())
339            .await)
340    }
341
342    pub async fn get_all_federation_configs(&self) -> BTreeMap<FederationId, JsonClientConfig> {
343        let mut federations = BTreeMap::new();
344        for (federation_id, client) in &self.clients {
345            federations.insert(
346                *federation_id,
347                client
348                    .borrow()
349                    .with(|client| client.get_config_json())
350                    .await,
351            );
352        }
353        federations
354    }
355
356    pub async fn backup_federation(
357        &self,
358        federation_id: &FederationId,
359        dbtx: &mut DatabaseTransaction<'_, Committable>,
360        now: SystemTime,
361    ) {
362        if let Some(client) = self.client(federation_id) {
363            let metadata: BTreeMap<String, String> = BTreeMap::new();
364            #[allow(deprecated)]
365            if client
366                .value()
367                .backup_to_federation(fedimint_client::backup::Metadata::from_json_serialized(
368                    metadata,
369                ))
370                .await
371                .is_ok()
372            {
373                dbtx.save_federation_backup_record(*federation_id, Some(now))
374                    .await;
375                info!(federation_id = %federation_id, "Successfully backed up federation");
376            }
377        }
378    }
379
380    pub async fn all_invite_codes(
381        &self,
382    ) -> BTreeMap<FederationId, BTreeMap<PeerId, (String, InviteCode)>> {
383        let mut invite_codes = BTreeMap::new();
384
385        for (federation_id, client) in &self.clients {
386            let config = client.value().config().await;
387            let api_endpoints = &config.global.api_endpoints;
388
389            let mut fed_invite_codes = BTreeMap::new();
390            for (peer_id, peer_url) in api_endpoints {
391                if let Some(code) = client.value().invite_code(*peer_id).await {
392                    fed_invite_codes.insert(*peer_id, (peer_url.name.clone(), code));
393                }
394            }
395
396            invite_codes.insert(*federation_id, fed_invite_codes);
397        }
398
399        invite_codes
400    }
401
402    pub async fn get_note_summary(
403        &self,
404        federation_id: &FederationId,
405    ) -> AdminResult<TieredCounts> {
406        let client = self.client(federation_id).ok_or(FederationNotConnected {
407            federation_id_prefix: federation_id.to_prefix(),
408        })?;
409        let counts = if let Ok(mint) = client.value().get_first_module::<MintClientModule>() {
410            let mut dbtx = mint.client_ctx.module_db().begin_transaction_nc().await;
411            mint.get_note_counts_by_denomination(&mut dbtx).await
412        } else if let Ok(mint) = client
413            .value()
414            .get_primary_module_for_unit::<MintV2ClientModule>(AmountUnit::BITCOIN)
415        {
416            let mut counts = TieredCounts::default();
417            for (denomination, count) in mint.get_count_by_denomination(Account::Primary).await {
418                counts.inc(
419                    denomination.amount(),
420                    usize::try_from(count).expect("Note count fits in usize"),
421                );
422            }
423            counts
424        } else {
425            return Err(AdminGatewayError::Unexpected(anyhow::anyhow!(
426                "No mint module available"
427            )));
428        };
429        info!(target: LOG_GATEWAY, ?counts, "Note counts");
430        Ok(counts)
431    }
432
433    // TODO(tvolk131): Set this value in the constructor.
434    pub fn set_next_index(&self, next_index: u64) {
435        self.next_index.store(next_index, Ordering::SeqCst);
436    }
437
438    pub fn pop_next_index(&self) -> AdminResult<u64> {
439        let next_index = self.next_index.fetch_add(1, Ordering::Relaxed);
440
441        // Check for overflow.
442        if next_index == INITIAL_INDEX.wrapping_sub(1) {
443            return Err(AdminGatewayError::GatewayConfigurationError(
444                "Federation Index overflow".to_string(),
445            ));
446        }
447
448        Ok(next_index)
449    }
450}