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, GatewayOperationMetaV2};
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
24const INITIAL_INDEX: u64 = 1;
28
29#[derive(Debug)]
31pub struct FederationManager {
32 clients: BTreeMap<FederationId, Spanned<fedimint_client::ClientHandleArc>>,
35
36 index_to_federation: BTreeMap<u64, FederationId>,
40
41 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 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 Ok(meta) = entry.try_meta::<GatewayOperationMetaV2>() else {
115 warn!(
116 target: LOG_GATEWAY,
117 operation_id = %op_id.fmt_short(),
118 "Skipping LNv2 operation with invalid metadata while waiting for incoming payments",
119 );
120 continue;
121 };
122 if !meta.waits_for_completion() {
123 continue;
124 }
125 let lnv2 =
126 client.value().get_first_module::<GatewayClientModuleV2>()?;
127 lnv2.await_completion(op_id).await;
128 }
129 "ln" => {
130 let lnv1 = client.value().get_first_module::<GatewayClientModule>()?;
131 lnv1.await_completion(op_id).await;
132 }
133 _ => {}
134 }
135 }
136 }
137 }
138
139 info!(target: LOG_GATEWAY, "Finished waiting for incoming payments");
140 Ok(())
141 }
142
143 async fn unannounce_from_federation(
144 &self,
145 federation_id: FederationId,
146 gateway_keypair: Keypair,
147 ) {
148 if let Ok(client) = self
149 .clients
150 .get(&federation_id)
151 .ok_or(FederationNotConnected {
152 federation_id_prefix: federation_id.to_prefix(),
153 })
154 && let Ok(ln) = client.value().get_first_module::<GatewayClientModule>()
155 {
156 ln.remove_from_federation(gateway_keypair).await;
157 }
158 }
159
160 pub async fn unannounce_from_all_federations(&self, gateway_keypair: Keypair) {
163 let removal_futures = self
164 .clients
165 .values()
166 .filter_map(|client| {
167 client
168 .value()
169 .get_first_module::<GatewayClientModule>()
170 .ok()
171 .map(|lnv1| async move {
172 lnv1.remove_from_federation(gateway_keypair).await;
173 })
174 })
175 .collect::<Vec<_>>();
176
177 futures::future::join_all(removal_futures).await;
178 }
179
180 pub fn get_client_for_index(&self, short_channel_id: u64) -> Option<Spanned<ClientHandleArc>> {
181 let federation_id = self.index_to_federation.get(&short_channel_id)?;
182 match self.clients.get(federation_id).cloned() {
186 Some(client) => Some(client),
187 _ => {
188 panic!(
189 "`FederationManager.index_to_federation` is out of sync with `FederationManager.clients`! This is a bug."
190 );
191 }
192 }
193 }
194
195 pub fn get_client_for_federation_id_prefix(
196 &self,
197 federation_id_prefix: FederationIdPrefix,
198 ) -> Option<Spanned<ClientHandleArc>> {
199 self.clients.iter().find_map(|(fid, client)| {
200 if fid.to_prefix() == federation_id_prefix {
201 Some(client.clone())
202 } else {
203 None
204 }
205 })
206 }
207
208 pub fn has_federation(&self, federation_id: FederationId) -> bool {
209 self.clients.contains_key(&federation_id)
210 }
211
212 pub fn client(&self, federation_id: &FederationId) -> Option<&Spanned<ClientHandleArc>> {
213 self.clients.get(federation_id)
214 }
215
216 pub async fn federation_info(
217 &self,
218 federation_id: FederationId,
219 dbtx: &mut DatabaseTransaction<'_, NonCommittable>,
220 ) -> std::result::Result<FederationInfo, FederationNotConnected> {
221 self.clients
222 .get(&federation_id)
223 .ok_or(FederationNotConnected {
224 federation_id_prefix: federation_id.to_prefix(),
225 })?
226 .borrow()
227 .with(|client| async move {
228 let balance_msat = client
229 .get_balance_for_btc()
230 .await
231 .map_err(|_err| FederationNotConnected {
233 federation_id_prefix: federation_id.to_prefix(),
234 })?;
235
236 let config = dbtx.load_federation_config(federation_id).await.ok_or(
237 FederationNotConnected {
238 federation_id_prefix: federation_id.to_prefix(),
239 },
240 )?;
241 let last_backup_time =
242 dbtx.load_backup_record(federation_id)
243 .await
244 .ok_or(FederationNotConnected {
245 federation_id_prefix: federation_id.to_prefix(),
246 })?;
247
248 Ok(FederationInfo {
249 federation_id,
250 federation_name: self.federation_name(client).await,
251 balance_msat,
252 config,
253 last_backup_time,
254 })
255 })
256 .await
257 }
258
259 pub async fn federation_name(&self, client: &ClientHandleArc) -> Option<String> {
260 let client_config = client.config().await;
261 let federation_name = client_config.global.federation_name();
262 federation_name.map(String::from)
263 }
264
265 pub async fn federation_info_all_federations(
266 &self,
267 mut dbtx: DatabaseTransaction<'_, NonCommittable>,
268 ) -> Vec<FederationInfo> {
269 let mut federation_infos = Vec::new();
270 for (federation_id, client) in &self.clients {
271 let balance_msat = match client
272 .borrow()
273 .with(|client| client.get_balance_for_btc())
274 .await
275 {
276 Ok(balance_msat) => balance_msat,
277 Err(err) => {
278 warn!(
279 target: LOG_GATEWAY,
280 err = %err.fmt_compact_anyhow(),
281 "Skipped Federation due to lack of primary module"
282 );
283 continue;
284 }
285 };
286
287 let config = dbtx.load_federation_config(*federation_id).await;
288 let last_backup_time = dbtx
289 .load_backup_record(*federation_id)
290 .await
291 .unwrap_or_default();
292 if let Some(config) = config {
293 federation_infos.push(FederationInfo {
294 federation_id: *federation_id,
295 federation_name: self.federation_name(client.value()).await,
296 balance_msat,
297 config,
298 last_backup_time,
299 });
300 }
301 }
302 federation_infos
303 }
304
305 pub async fn get_federation_config(
306 &self,
307 federation_id: FederationId,
308 ) -> AdminResult<JsonClientConfig> {
309 let client = self
310 .clients
311 .get(&federation_id)
312 .ok_or(FederationNotConnected {
313 federation_id_prefix: federation_id.to_prefix(),
314 })?;
315 Ok(client
316 .borrow()
317 .with(|client| client.get_config_json())
318 .await)
319 }
320
321 pub async fn get_all_federation_configs(&self) -> BTreeMap<FederationId, JsonClientConfig> {
322 let mut federations = BTreeMap::new();
323 for (federation_id, client) in &self.clients {
324 federations.insert(
325 *federation_id,
326 client
327 .borrow()
328 .with(|client| client.get_config_json())
329 .await,
330 );
331 }
332 federations
333 }
334
335 pub async fn backup_federation(
336 &self,
337 federation_id: &FederationId,
338 dbtx: &mut DatabaseTransaction<'_, Committable>,
339 now: SystemTime,
340 ) {
341 if let Some(client) = self.client(federation_id) {
342 let metadata: BTreeMap<String, String> = BTreeMap::new();
343 #[allow(deprecated)]
344 if client
345 .value()
346 .backup_to_federation(fedimint_client::backup::Metadata::from_json_serialized(
347 metadata,
348 ))
349 .await
350 .is_ok()
351 {
352 dbtx.save_federation_backup_record(*federation_id, Some(now))
353 .await;
354 info!(federation_id = %federation_id, "Successfully backed up federation");
355 }
356 }
357 }
358
359 pub async fn all_invite_codes(
360 &self,
361 ) -> BTreeMap<FederationId, BTreeMap<PeerId, (String, InviteCode)>> {
362 let mut invite_codes = BTreeMap::new();
363
364 for (federation_id, client) in &self.clients {
365 let config = client.value().config().await;
366 let api_endpoints = &config.global.api_endpoints;
367
368 let mut fed_invite_codes = BTreeMap::new();
369 for (peer_id, peer_url) in api_endpoints {
370 if let Some(code) = client.value().invite_code(*peer_id).await {
371 fed_invite_codes.insert(*peer_id, (peer_url.name.clone(), code));
372 }
373 }
374
375 invite_codes.insert(*federation_id, fed_invite_codes);
376 }
377
378 invite_codes
379 }
380
381 pub async fn get_note_summary(
382 &self,
383 federation_id: &FederationId,
384 ) -> AdminResult<TieredCounts> {
385 let client = self.client(federation_id).ok_or(FederationNotConnected {
386 federation_id_prefix: federation_id.to_prefix(),
387 })?;
388 let mint = client.value().get_first_module::<MintClientModule>()?;
389 let mut dbtx = mint.client_ctx.module_db().begin_transaction_nc().await;
390 let counts = mint.get_note_counts_by_denomination(&mut dbtx).await;
391 info!(target: LOG_GATEWAY, ?counts, "Note counts");
392 Ok(counts)
393 }
394
395 pub fn set_next_index(&self, next_index: u64) {
397 self.next_index.store(next_index, Ordering::SeqCst);
398 }
399
400 pub fn pop_next_index(&self) -> AdminResult<u64> {
401 let next_index = self.next_index.fetch_add(1, Ordering::Relaxed);
402
403 if next_index == INITIAL_INDEX.wrapping_sub(1) {
405 return Err(AdminGatewayError::GatewayConfigurationError(
406 "Federation Index overflow".to_string(),
407 ));
408 }
409
410 Ok(next_index)
411 }
412}