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