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::util::{FmtCompactAnyhow as _, Spanned};
11use fedimint_gateway_common::FederationInfo;
12use fedimint_gateway_server_db::GatewayDbtxNcExt as _;
13use fedimint_gw_client::GatewayClientModule;
14use fedimint_gwv2_client::GatewayClientModuleV2;
15use fedimint_logging::LOG_GATEWAY;
16use tracing::{info, warn};
17
18use crate::error::{AdminGatewayError, FederationNotConnected};
19use crate::{AdminResult, Registration};
20
21const INITIAL_INDEX: u64 = 1;
25
26#[derive(Debug)]
28pub struct FederationManager {
29 clients: BTreeMap<FederationId, Spanned<fedimint_client::ClientHandleArc>>,
32
33 index_to_federation: BTreeMap<u64, FederationId>,
37
38 next_index: AtomicU64,
42}
43
44impl FederationManager {
45 pub fn new() -> Self {
46 Self {
47 clients: BTreeMap::new(),
48 index_to_federation: BTreeMap::new(),
49 next_index: AtomicU64::new(INITIAL_INDEX),
50 }
51 }
52
53 pub fn add_client(&mut self, index: u64, client: Spanned<fedimint_client::ClientHandleArc>) {
54 let federation_id = client.borrow().with_sync(|c| c.federation_id());
55 self.clients.insert(federation_id, client);
56 self.index_to_federation.insert(index, federation_id);
57 }
58
59 pub async fn leave_federation(
60 &mut self,
61 federation_id: FederationId,
62 dbtx: &mut DatabaseTransaction<'_, NonCommittable>,
63 registrations: Vec<&Registration>,
64 ) -> AdminResult<FederationInfo> {
65 let federation_info = self.federation_info(federation_id, dbtx).await?;
66
67 for registration in registrations {
68 self.unannounce_from_federation(federation_id, registration.keypair)
69 .await;
70 }
71
72 self.remove_client(federation_id).await?;
73
74 Ok(federation_info)
75 }
76
77 async fn remove_client(&mut self, federation_id: FederationId) -> AdminResult<()> {
78 let client = self
79 .clients
80 .remove(&federation_id)
81 .ok_or(FederationNotConnected {
82 federation_id_prefix: federation_id.to_prefix(),
83 })?
84 .into_value();
85
86 self.index_to_federation
87 .retain(|_, fid| *fid != federation_id);
88
89 match Arc::into_inner(client) {
90 Some(client) => {
91 client.shutdown().await;
92 Ok(())
93 }
94 _ => Err(AdminGatewayError::ClientRemovalError(format!(
95 "Federation client {federation_id} is not unique, failed to shutdown client"
96 ))),
97 }
98 }
99
100 pub async fn wait_for_incoming_payments(&self) -> AdminResult<()> {
103 for client in self.clients.values() {
104 let active_operations = client.value().get_active_operations().await;
105 let operation_log = client.value().operation_log();
106 for op_id in active_operations {
107 let log_entry = operation_log.get_operation(op_id).await;
108 if let Some(entry) = log_entry {
109 match entry.operation_module_kind() {
110 "lnv2" => {
111 let lnv2 =
112 client.value().get_first_module::<GatewayClientModuleV2>()?;
113 lnv2.await_completion(op_id).await;
114 }
115 "ln" => {
116 let lnv1 = client.value().get_first_module::<GatewayClientModule>()?;
117 lnv1.await_completion(op_id).await;
118 }
119 _ => {}
120 }
121 }
122 }
123 }
124
125 info!(target: LOG_GATEWAY, "Finished waiting for incoming payments");
126 Ok(())
127 }
128
129 async fn unannounce_from_federation(
130 &self,
131 federation_id: FederationId,
132 gateway_keypair: Keypair,
133 ) {
134 if let Ok(client) = self
135 .clients
136 .get(&federation_id)
137 .ok_or(FederationNotConnected {
138 federation_id_prefix: federation_id.to_prefix(),
139 })
140 && let Ok(ln) = client.value().get_first_module::<GatewayClientModule>()
141 {
142 ln.remove_from_federation(gateway_keypair).await;
143 }
144 }
145
146 pub async fn unannounce_from_all_federations(&self, gateway_keypair: Keypair) {
149 let removal_futures = self
150 .clients
151 .values()
152 .map(|client| async {
153 client
154 .value()
155 .get_first_module::<GatewayClientModule>()
156 .expect("Must have client module")
157 .remove_from_federation(gateway_keypair)
158 .await;
159 })
160 .collect::<Vec<_>>();
161
162 futures::future::join_all(removal_futures).await;
163 }
164
165 pub fn get_client_for_index(&self, short_channel_id: u64) -> Option<Spanned<ClientHandleArc>> {
166 let federation_id = self.index_to_federation.get(&short_channel_id)?;
167 match self.clients.get(federation_id).cloned() {
171 Some(client) => Some(client),
172 _ => {
173 panic!(
174 "`FederationManager.index_to_federation` is out of sync with `FederationManager.clients`! This is a bug."
175 );
176 }
177 }
178 }
179
180 pub fn get_client_for_federation_id_prefix(
181 &self,
182 federation_id_prefix: FederationIdPrefix,
183 ) -> Option<Spanned<ClientHandleArc>> {
184 self.clients.iter().find_map(|(fid, client)| {
185 if fid.to_prefix() == federation_id_prefix {
186 Some(client.clone())
187 } else {
188 None
189 }
190 })
191 }
192
193 pub fn has_federation(&self, federation_id: FederationId) -> bool {
194 self.clients.contains_key(&federation_id)
195 }
196
197 pub fn client(&self, federation_id: &FederationId) -> Option<&Spanned<ClientHandleArc>> {
198 self.clients.get(federation_id)
199 }
200
201 pub async fn federation_info(
202 &self,
203 federation_id: FederationId,
204 dbtx: &mut DatabaseTransaction<'_, NonCommittable>,
205 ) -> std::result::Result<FederationInfo, FederationNotConnected> {
206 self.clients
207 .get(&federation_id)
208 .expect("`FederationManager.index_to_federation` is out of sync with `FederationManager.clients`! This is a bug.")
209 .borrow()
210 .with(|client| async move {
211 let balance_msat = client.get_balance_for_btc().await
212 .map_err(|_err| FederationNotConnected { federation_id_prefix: federation_id.to_prefix() })?;
214
215 let config = dbtx.load_federation_config(federation_id).await.ok_or(FederationNotConnected {
216 federation_id_prefix: federation_id.to_prefix(),
217 })?;
218 let last_backup_time = dbtx.load_backup_record(federation_id).await.ok_or(FederationNotConnected {
219 federation_id_prefix: federation_id.to_prefix(),
220 })?;
221
222 Ok(FederationInfo {
223 federation_id,
224 federation_name: self.federation_name(client).await,
225 balance_msat,
226 config,
227 last_backup_time,
228 })
229 })
230 .await
231 }
232
233 pub async fn federation_name(&self, client: &ClientHandleArc) -> Option<String> {
234 let client_config = client.config().await;
235 let federation_name = client_config.global.federation_name();
236 federation_name.map(String::from)
237 }
238
239 pub async fn federation_info_all_federations(
240 &self,
241 mut dbtx: DatabaseTransaction<'_, NonCommittable>,
242 ) -> Vec<FederationInfo> {
243 let mut federation_infos = Vec::new();
244 for (federation_id, client) in &self.clients {
245 let balance_msat = match client
246 .borrow()
247 .with(|client| client.get_balance_for_btc())
248 .await
249 {
250 Ok(balance_msat) => balance_msat,
251 Err(err) => {
252 warn!(
253 target: LOG_GATEWAY,
254 err = %err.fmt_compact_anyhow(),
255 "Skipped Federation due to lack of primary module"
256 );
257 continue;
258 }
259 };
260
261 let config = dbtx.load_federation_config(*federation_id).await;
262 let last_backup_time = dbtx
263 .load_backup_record(*federation_id)
264 .await
265 .unwrap_or_default();
266 if let Some(config) = config {
267 federation_infos.push(FederationInfo {
268 federation_id: *federation_id,
269 federation_name: self.federation_name(client.value()).await,
270 balance_msat,
271 config,
272 last_backup_time,
273 });
274 }
275 }
276 federation_infos
277 }
278
279 pub async fn get_federation_config(
280 &self,
281 federation_id: FederationId,
282 ) -> AdminResult<JsonClientConfig> {
283 let client = self
284 .clients
285 .get(&federation_id)
286 .ok_or(FederationNotConnected {
287 federation_id_prefix: federation_id.to_prefix(),
288 })?;
289 Ok(client
290 .borrow()
291 .with(|client| client.get_config_json())
292 .await)
293 }
294
295 pub async fn get_all_federation_configs(&self) -> BTreeMap<FederationId, JsonClientConfig> {
296 let mut federations = BTreeMap::new();
297 for (federation_id, client) in &self.clients {
298 federations.insert(
299 *federation_id,
300 client
301 .borrow()
302 .with(|client| client.get_config_json())
303 .await,
304 );
305 }
306 federations
307 }
308
309 pub async fn backup_federation(
310 &self,
311 federation_id: &FederationId,
312 dbtx: &mut DatabaseTransaction<'_, Committable>,
313 now: SystemTime,
314 ) {
315 if let Some(client) = self.client(federation_id) {
316 let metadata: BTreeMap<String, String> = BTreeMap::new();
317 if client
318 .value()
319 .backup_to_federation(fedimint_client::backup::Metadata::from_json_serialized(
320 metadata,
321 ))
322 .await
323 .is_ok()
324 {
325 dbtx.save_federation_backup_record(*federation_id, Some(now))
326 .await;
327 info!(federation_id = %federation_id, "Successfully backed up federation");
328 }
329 }
330 }
331
332 pub fn set_next_index(&self, next_index: u64) {
334 self.next_index.store(next_index, Ordering::SeqCst);
335 }
336
337 pub fn pop_next_index(&self) -> AdminResult<u64> {
338 let next_index = self.next_index.fetch_add(1, Ordering::Relaxed);
339
340 if next_index == INITIAL_INDEX.wrapping_sub(1) {
342 return Err(AdminGatewayError::GatewayConfigurationError(
343 "Federation Index overflow".to_string(),
344 ));
345 }
346
347 Ok(next_index)
348 }
349}