1use std::cmp::Ordering;
3use std::collections::BTreeMap;
4use std::future::pending;
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7use std::time::{Duration, SystemTime};
8
9use anyhow::{Context, Result, ensure};
10use async_trait::async_trait;
11use bitcoin::hashes::sha256;
12use fedimint_api_client::api::{
13 LegacyFederationStatus, LegacyP2PConnectionStatus, LegacyPeerStatus, StatusResponse,
14};
15use fedimint_core::admin_client::{GuardianConfigBackup, ServerStatusLegacy, SetupStatus};
16use fedimint_core::backup::{
17 BackupStatistics, ClientBackupKey, ClientBackupKeyPrefix, ClientBackupSnapshot,
18};
19use fedimint_core::config::{ClientConfig, JsonClientConfig, META_FEDERATION_NAME_KEY};
20use fedimint_core::core::backup::{BACKUP_REQUEST_MAX_PAYLOAD_SIZE_BYTES, SignedBackupRequest};
21use fedimint_core::core::{DynOutputOutcome, ModuleInstanceId, ModuleKind};
22use fedimint_core::db::{
23 Committable, Database, DatabaseTransaction, IDatabaseTransactionOpsCoreTyped,
24};
25#[allow(deprecated)]
26use fedimint_core::endpoint_constants::AWAIT_OUTPUT_OUTCOME_ENDPOINT;
27use fedimint_core::endpoint_constants::{
28 API_ANNOUNCEMENTS_ENDPOINT, AUDIT_ENDPOINT, AUTH_ENDPOINT, AWAIT_OUTPUTS_OUTCOMES_ENDPOINT,
29 AWAIT_SESSION_OUTCOME_ENDPOINT, AWAIT_SIGNED_SESSION_OUTCOME_ENDPOINT,
30 AWAIT_TRANSACTION_ENDPOINT, BACKUP_ENDPOINT, BACKUP_STATISTICS_ENDPOINT, CHAIN_ID_ENDPOINT,
31 CLIENT_CONFIG_ENDPOINT, CLIENT_CONFIG_JSON_ENDPOINT, CONSENSUS_ORD_LATENCY_ENDPOINT,
32 FEDERATION_ID_ENDPOINT, FEDIMINTD_VERSION_ENDPOINT, GUARDIAN_CONFIG_BACKUP_ENDPOINT,
33 GUARDIAN_METADATA_ENDPOINT, INVITE_CODE_ENDPOINT, P2P_CONNECTION_STATUS_ENDPOINT,
34 PEER_AVAILABILITY_ENDPOINT, RECOVER_ENDPOINT, RESET_PEER_AVAILABILITY_ENDPOINT,
35 SERVER_CONFIG_CONSENSUS_HASH_ENDPOINT, SESSION_COUNT_ENDPOINT, SESSION_STATUS_ENDPOINT,
36 SESSION_STATUS_V2_ENDPOINT, SETUP_STATUS_ENDPOINT, SHUTDOWN_AFTER_CURRENT_SESSION_ENDPOINT,
37 SHUTDOWN_ENDPOINT, SIGN_API_ANNOUNCEMENT_ENDPOINT, SIGN_GUARDIAN_METADATA_ENDPOINT,
38 STATUS_ENDPOINT, SUBMIT_API_ANNOUNCEMENT_ENDPOINT, SUBMIT_GUARDIAN_METADATA_ENDPOINT,
39 SUBMIT_TRANSACTION_ENDPOINT, VERSION_ENDPOINT,
40};
41use fedimint_core::invite_code::InviteCode;
42use fedimint_core::module::audit::{Audit, AuditSummary};
43use fedimint_core::module::{
44 ApiAuth, ApiEndpoint, ApiEndpointContext, ApiError, ApiRequestErased, ApiResult, ApiVersion,
45 SerdeModuleEncoding, SerdeModuleEncodingBase64, SupportedApiVersionsSummary,
46 admin_api_endpoint, public_api_endpoint,
47};
48use fedimint_core::net::api_announcement::{
49 ApiAnnouncement, SignedApiAnnouncement, SignedApiAnnouncementSubmission,
50};
51use fedimint_core::net::auth::GuardianAuthToken;
52use fedimint_core::peer_availability::{PeerAvailability, ResetPeerAvailabilityRequest};
53use fedimint_core::secp256k1::{PublicKey, SECP256K1};
54use fedimint_core::session_outcome::{ConsensusItem, SessionStatus, SessionStatusV2};
55use fedimint_core::task::TaskGroup;
56use fedimint_core::transaction::{
57 SerdeTransaction, Transaction, TransactionError, TransactionSubmissionOutcome,
58};
59use fedimint_core::util::{FmtCompact, SafeUrl};
60use fedimint_core::version::non_zero_version_hash;
61use fedimint_core::{ChainId, OutPoint, OutPointRange, PeerId, TransactionId, secp256k1};
62use fedimint_logging::LOG_NET_API;
63use fedimint_server_core::bitcoin_rpc::ServerBitcoinRpcMonitor;
64use fedimint_server_core::dashboard_ui::{
65 IDashboardApi, P2PConnectionStatus, ServerBitcoinRpcStatus,
66};
67use fedimint_server_core::{DynServerModule, ServerModuleRegistry, ServerModuleRegistryExt};
68use futures::StreamExt;
69use tokio::sync::watch::{self, Receiver, Sender};
70use tracing::{debug, info, warn};
71
72use crate::config::io::{CONSENSUS_CONFIG, JSON_EXT, LOCAL_CONFIG, PRIVATE_CONFIG};
73use crate::config::{ServerConfig, legacy_consensus_config_hash};
74use crate::consensus::db::{AcceptedItemPrefix, AcceptedTransactionKey, SignedSessionOutcomeKey};
75use crate::consensus::engine::{
76 ScheduledShutdown, ShutdownRequest, get_finished_session_count_static,
77};
78use crate::consensus::session_cache::OutcomeFormat;
79use crate::consensus::transaction::{TxProcessingMode, process_transaction_with_dbtx};
80use crate::metrics::{BACKUP_WRITE_SIZE_BYTES, STORED_BACKUPS_COUNT};
81use crate::net::api::HasApiContext;
82use crate::net::api::announcement::{ApiAnnouncementKey, ApiAnnouncementPrefix, get_api_urls};
83use crate::net::p2p::{P2PConnectionState, P2PStatusReceivers};
84
85const MAX_OUTPUTS_OUTCOMES_BATCH: usize = 1024;
93
94const MAX_BACKUP_FUTURE_TIMESTAMP_SECS: u64 = 60 * 60;
99
100fn backup_timestamp_is_too_far_in_future(timestamp: SystemTime, now: SystemTime) -> bool {
101 timestamp
102 .duration_since(now)
103 .is_ok_and(|lead| lead > Duration::from_secs(MAX_BACKUP_FUTURE_TIMESTAMP_SECS))
104}
105
106fn checked_outputs_outcomes_count(outpoint_range: OutPointRange) -> Result<usize> {
112 let count = outpoint_range
113 .checked_count()
114 .context("Outpoint range is descending or too large")?;
115
116 ensure!(
117 count <= MAX_OUTPUTS_OUTCOMES_BATCH,
118 "Outpoint range must cover at most {MAX_OUTPUTS_OUTCOMES_BATCH} outputs, got {count}"
119 );
120
121 Ok(count)
122}
123
124fn legacy_peer_status(
138 p2p_receiver: &watch::Receiver<P2PConnectionState>,
139 ci_receiver: &watch::Receiver<Option<u64>>,
140 session_count: u64,
141) -> LegacyPeerStatus {
142 let p2p_connected = p2p_receiver.borrow().connected.is_some();
143 let last_contribution = *ci_receiver.borrow();
144
145 LegacyPeerStatus {
146 connection_status: if p2p_connected {
147 LegacyP2PConnectionStatus::Connected
148 } else {
149 LegacyP2PConnectionStatus::Disconnected
150 },
151 last_contribution,
152 flagged: last_contribution.unwrap_or(0) + 1 < session_count,
153 }
154}
155
156#[derive(Clone)]
157pub struct ConsensusApi {
158 pub cfg: ServerConfig,
160 pub db: Database,
162 pub availability: Arc<super::peer_availability::AvailabilityTracker>,
163 pub modules: ServerModuleRegistry,
165 pub client_cfg: ClientConfig,
167 pub force_api_secret: Option<String>,
168 pub submission_sender: async_channel::Sender<ConsensusItem>,
170 pub shutdown_receiver: Receiver<Option<ScheduledShutdown>>,
171 pub shutdown_sender: Sender<Option<ScheduledShutdown>>,
172 pub ord_latency_receiver: watch::Receiver<Option<Duration>>,
173 pub accepted_item_receiver: watch::Receiver<()>,
175 pub completed_session_receiver: watch::Receiver<super::session_cache::CompletedSession>,
177 pub p2p_status_receivers: P2PStatusReceivers,
178 pub ci_status_receivers: BTreeMap<PeerId, Receiver<Option<u64>>>,
179 pub bitcoin_rpc_connection: ServerBitcoinRpcMonitor,
180 pub supported_api_versions: SupportedApiVersionsSummary,
181 pub auth_ui: Option<ApiAuth>,
182 pub auth_api: Option<ApiAuth>,
183 pub code_version_str: String,
184 pub code_version_hash: String,
185 pub task_group: TaskGroup,
186}
187
188impl ConsensusApi {
189 pub fn api_versions_summary(&self) -> &SupportedApiVersionsSummary {
190 &self.supported_api_versions
191 }
192
193 pub fn get_active_api_secret(&self) -> Option<String> {
194 self.force_api_secret.clone()
197 }
198
199 pub async fn submit_transaction(
203 &self,
204 transaction: Transaction,
205 ) -> Result<TransactionId, TransactionError> {
206 let txid = transaction.tx_hash();
207
208 debug!(target: LOG_NET_API, %txid, "Received a submitted transaction");
209
210 let mut accepted_item = self.accepted_item_receiver.clone();
213 let mut completed_session = self.completed_session_receiver.clone();
214
215 accepted_item.mark_unchanged();
216 completed_session.mark_unchanged();
217
218 let mut dbtx = self.db.begin_transaction_nc().await;
220 if dbtx
222 .get_value(&AcceptedTransactionKey(txid))
223 .await
224 .is_some()
225 {
226 debug!(target: LOG_NET_API, %txid, "Transaction already accepted");
227 return Ok(txid);
228 }
229
230 dbtx.ignore_uncommitted();
232
233 process_transaction_with_dbtx(
234 self.modules.clone(),
235 &mut dbtx,
236 &transaction,
237 self.cfg.consensus.version,
238 TxProcessingMode::Submission,
239 )
240 .await
241 .inspect_err(|err| {
242 debug!(target: LOG_NET_API, %txid, err = %err.fmt_compact(), "Transaction rejected");
243 })?;
244
245 drop(dbtx);
246
247 let _ = self
248 .submission_sender
249 .send(ConsensusItem::Transaction(transaction.clone()))
250 .await
251 .inspect_err(|err| {
252 warn!(target: LOG_NET_API, %txid, err = %err.fmt_compact(), "Unable to submit the tx into consensus");
253 });
254
255 loop {
256 let (changed, session_completed) = tokio::select! {
257 changed = accepted_item.changed() => (changed, false),
258 changed = completed_session.changed() => (changed, true),
259 };
260
261 if changed.is_err() {
264 pending::<()>().await;
265 }
266
267 let mut dbtx = self.db.begin_transaction_nc().await;
268
269 if dbtx
272 .get_value(&AcceptedTransactionKey(txid))
273 .await
274 .is_some()
275 {
276 return Ok(txid);
277 }
278
279 dbtx.ignore_uncommitted();
280
281 process_transaction_with_dbtx(
282 self.modules.clone(),
283 &mut dbtx,
284 &transaction,
285 self.cfg.consensus.version,
286 TxProcessingMode::Submission,
287 )
288 .await
289 .inspect_err(|err| {
290 debug!(target: LOG_NET_API, %txid, err = %err.fmt_compact(), "Transaction rejected");
291 })?;
292
293 drop(dbtx);
294
295 if session_completed {
296 let _ = self
300 .submission_sender
301 .send(ConsensusItem::Transaction(transaction.clone()))
302 .await
303 .inspect_err(|err| {
304 warn!(target: LOG_NET_API, %txid, err = %err.fmt_compact(), "Unable to submit the tx into consensus");
305 });
306 }
307 }
308 }
309
310 pub async fn await_transaction(
311 &self,
312 txid: TransactionId,
313 ) -> (Vec<ModuleInstanceId>, DatabaseTransaction<'_, Committable>) {
314 debug!(target: LOG_NET_API, %txid, "Awaiting transaction acceptance");
315 self.db
316 .wait_key_check(&AcceptedTransactionKey(txid), std::convert::identity)
317 .await
318 }
319
320 pub async fn await_output_outcome(
321 &self,
322 outpoint: OutPoint,
323 ) -> Result<SerdeModuleEncoding<DynOutputOutcome>> {
324 debug!(target: LOG_NET_API, %outpoint, "Awaiting output outcome");
325 let (module_ids, mut dbtx) = self.await_transaction(outpoint.txid).await;
326
327 let module_id = module_ids
328 .into_iter()
329 .nth(outpoint.out_idx as usize)
330 .with_context(|| format!("Outpoint index out of bounds {outpoint:?}"))?;
331
332 #[allow(deprecated)]
333 let outcome = self
334 .modules
335 .get_expect(module_id)
336 .output_status(
337 &mut dbtx.to_ref_with_prefix_module_id(module_id).0.into_nc(),
338 outpoint,
339 module_id,
340 )
341 .await
342 .context("No output outcome for outpoint")?;
343
344 Ok((&outcome).into())
345 }
346
347 pub async fn await_outputs_outcomes(
348 &self,
349 outpoint_range: OutPointRange,
350 ) -> Result<Vec<Option<SerdeModuleEncoding<DynOutputOutcome>>>> {
351 let count = checked_outputs_outcomes_count(outpoint_range)?;
354
355 let (module_ids, mut dbtx) = self.await_transaction(outpoint_range.txid()).await;
357
358 let mut outcomes = Vec::with_capacity(count);
359
360 for outpoint in outpoint_range {
361 let module_id = module_ids
362 .get(outpoint.out_idx as usize)
363 .with_context(|| format!("Outpoint index out of bounds {outpoint:?}"))?;
364
365 #[allow(deprecated)]
366 let outcome = self
367 .modules
368 .get_expect(*module_id)
369 .output_status(
370 &mut dbtx.to_ref_with_prefix_module_id(*module_id).0.into_nc(),
371 outpoint,
372 *module_id,
373 )
374 .await
375 .map(|outcome| (&outcome).into());
376
377 outcomes.push(outcome);
378 }
379
380 Ok(outcomes)
381 }
382
383 pub fn session_count(&self) -> u64 {
384 self.completed_session_receiver
385 .borrow()
386 .as_ref()
387 .map_or(0, |latest| latest.index + 1)
388 }
389
390 async fn await_session_outcome(
391 &self,
392 index: u64,
393 format: OutcomeFormat,
394 ) -> Arc<serde_json::Value> {
395 super::session_cache::await_outcome(
396 &self.db,
397 &self.completed_session_receiver,
398 index,
399 format,
400 )
401 .await
402 }
403
404 pub async fn session_status(&self, session_index: u64) -> SessionStatusV2 {
405 let mut dbtx = self.db.begin_transaction_nc().await;
406
407 match session_index.cmp(&get_finished_session_count_static(&mut dbtx).await) {
408 Ordering::Greater => SessionStatusV2::Initial,
409 Ordering::Equal => SessionStatusV2::Pending(
410 dbtx.find_by_prefix(&AcceptedItemPrefix)
411 .await
412 .map(|entry| entry.1)
413 .collect()
414 .await,
415 ),
416 Ordering::Less => SessionStatusV2::Complete(
417 dbtx.get_value(&SignedSessionOutcomeKey(session_index))
418 .await
419 .expect("There are no gaps in session outcomes"),
420 ),
421 }
422 }
423
424 pub fn get_federation_status(&self) -> ApiResult<LegacyFederationStatus> {
425 let session_count = self.session_count();
426 let scheduled_shutdown = self
427 .shutdown_receiver
428 .borrow()
429 .map(|scheduled| scheduled.session);
430
431 let status_by_peer = self
432 .p2p_status_receivers
433 .iter()
434 .map(|(peer, p2p_receiver)| {
435 let ci_receiver = self.ci_status_receivers.get(peer).unwrap();
436
437 (
438 *peer,
439 legacy_peer_status(p2p_receiver, ci_receiver, session_count),
440 )
441 })
442 .collect::<BTreeMap<_, _>>();
443
444 let peers_flagged = status_by_peer
445 .values()
446 .filter(|status| status.flagged)
447 .count() as u64;
448
449 let peers_online = status_by_peer
450 .values()
451 .filter(|status| status.connection_status == LegacyP2PConnectionStatus::Connected)
452 .count() as u64;
453
454 let peers_offline = status_by_peer
455 .values()
456 .filter(|status| status.connection_status == LegacyP2PConnectionStatus::Disconnected)
457 .count() as u64;
458
459 Ok(LegacyFederationStatus {
460 session_count,
461 status_by_peer,
462 peers_online,
463 peers_offline,
464 peers_flagged,
465 scheduled_shutdown,
466 })
467 }
468
469 fn shutdown(&self, index: Option<u64>) {
470 self.shutdown_sender
471 .send_replace(index.map(|session| ScheduledShutdown {
472 session,
473 request: ShutdownRequest::AtSession,
474 }));
475 }
476
477 fn shutdown_after_current_session(&self) {
488 let current_session = self.session_count();
489 self.shutdown_sender
490 .send_if_modified(|scheduled| schedule_shutdown_after(scheduled, current_session));
491 }
492
493 async fn get_federation_audit(&self) -> ApiResult<AuditSummary> {
494 let mut dbtx = self.db.begin_transaction_nc().await;
495 dbtx.ignore_uncommitted();
499
500 let mut audit = Audit::default();
501 let mut module_instance_id_to_kind = BTreeMap::new();
502 for (module_instance_id, kind, module) in self.modules.iter_modules() {
503 module_instance_id_to_kind.insert(module_instance_id, kind.as_str().to_string());
504 module
505 .audit(
506 &mut dbtx.to_ref_with_prefix_module_id(module_instance_id).0,
507 &mut audit,
508 module_instance_id,
509 )
510 .await;
511 }
512 Ok(AuditSummary::from_audit(
513 &audit,
514 &module_instance_id_to_kind,
515 ))
516 }
517
518 fn get_guardian_config_backup(&self, _auth: &GuardianAuthToken) -> GuardianConfigBackup {
522 let mut tar_archive_builder = tar::Builder::new(Vec::new());
523
524 let mut append = |name: &Path, data: &[u8]| {
525 let mut header = tar::Header::new_gnu();
526 header.set_path(name).expect("Error setting path");
527 header.set_size(data.len() as u64);
528 header.set_mode(0o644);
529 header.set_cksum();
530 tar_archive_builder
531 .append(&header, data)
532 .expect("Error adding data to tar archive");
533 };
534
535 append(
536 &PathBuf::from(LOCAL_CONFIG).with_extension(JSON_EXT),
537 &serde_json::to_vec(&self.cfg.local).expect("Error encoding local config"),
538 );
539
540 append(
541 &PathBuf::from(CONSENSUS_CONFIG).with_extension(JSON_EXT),
542 &serde_json::to_vec(&self.cfg.consensus).expect("Error encoding consensus config"),
543 );
544
545 append(
546 &PathBuf::from(PRIVATE_CONFIG).with_extension(JSON_EXT),
547 &serde_json::to_vec(&self.cfg.private).expect("Error encoding private config"),
548 );
549
550 let tar_archive_bytes = tar_archive_builder
551 .into_inner()
552 .expect("Error building tar archive");
553
554 GuardianConfigBackup { tar_archive_bytes }
555 }
556
557 async fn handle_backup_request(
558 &self,
559 dbtx: &mut DatabaseTransaction<'_>,
560 request: SignedBackupRequest,
561 ) -> Result<(), ApiError> {
562 let request = request
563 .verify_valid(SECP256K1)
564 .map_err(|_| ApiError::bad_request("invalid request".into()))?;
565
566 if backup_timestamp_is_too_far_in_future(request.timestamp, fedimint_core::time::now()) {
567 return Err(ApiError::bad_request(
568 "timestamp too far in the future".into(),
569 ));
570 }
571
572 if request.payload.len() > BACKUP_REQUEST_MAX_PAYLOAD_SIZE_BYTES {
573 return Err(ApiError::bad_request("snapshot too large".into()));
574 }
575 debug!(target: LOG_NET_API, id = %request.id, len = request.payload.len(), "Received client backup request");
576 if let Some(prev) = dbtx.get_value(&ClientBackupKey(request.id)).await
577 && request.timestamp <= prev.timestamp
578 {
579 debug!(target: LOG_NET_API, id = %request.id, len = request.payload.len(), "Received client backup request with old timestamp - ignoring");
580 return Err(ApiError::bad_request("timestamp too small".into()));
581 }
582
583 info!(target: LOG_NET_API, id = %request.id, len = request.payload.len(), "Storing new client backup");
584 let overwritten = dbtx
585 .insert_entry(
586 &ClientBackupKey(request.id),
587 &ClientBackupSnapshot {
588 timestamp: request.timestamp,
589 data: request.payload.clone(),
590 },
591 )
592 .await
593 .is_some();
594 BACKUP_WRITE_SIZE_BYTES.observe(request.payload.len() as f64);
595 if !overwritten {
596 dbtx.on_commit(|| STORED_BACKUPS_COUNT.inc());
597 }
598
599 Ok(())
600 }
601
602 async fn handle_recover_request(
603 &self,
604 dbtx: &mut DatabaseTransaction<'_>,
605 id: PublicKey,
606 ) -> Option<ClientBackupSnapshot> {
607 dbtx.get_value(&ClientBackupKey(id)).await
608 }
609
610 async fn api_announcements(&self) -> BTreeMap<PeerId, SignedApiAnnouncement> {
613 self.db
614 .begin_transaction_nc()
615 .await
616 .find_by_prefix(&ApiAnnouncementPrefix)
617 .await
618 .map(|(announcement_key, announcement)| (announcement_key.0, announcement))
619 .collect()
620 .await
621 }
622
623 fn fedimintd_version(&self) -> String {
625 self.code_version_str.clone()
626 }
627
628 async fn submit_api_announcement(
631 &self,
632 peer_id: PeerId,
633 announcement: SignedApiAnnouncement,
634 ) -> Result<(), ApiError> {
635 let Some(peer_key) = self.cfg.consensus.broadcast_public_keys.get(&peer_id) else {
636 return Err(ApiError::bad_request("Peer not in federation".into()));
637 };
638
639 if !announcement.verify(SECP256K1, peer_key) {
640 return Err(ApiError::bad_request("Invalid signature".into()));
641 }
642
643 self.db
645 .autocommit(
646 |dbtx, _| {
647 let announcement = announcement.clone();
648 Box::pin(async move {
649 if let Some(existing_announcement) =
650 dbtx.get_value(&ApiAnnouncementKey(peer_id)).await
651 {
652 if existing_announcement.api_announcement
657 == announcement.api_announcement
658 {
659 return Ok(());
660 }
661
662 if existing_announcement.api_announcement.nonce
665 >= announcement.api_announcement.nonce
666 {
667 return Err(ApiError::bad_request(
668 "Outdated or redundant announcement".into(),
669 ));
670 }
671 }
672
673 dbtx.insert_entry(&ApiAnnouncementKey(peer_id), &announcement)
674 .await;
675 Ok(())
676 })
677 },
678 None,
679 )
680 .await
681 .map_err(|e| match e {
682 fedimint_core::db::AutocommitError::ClosureError { error, .. } => error,
683 fedimint_core::db::AutocommitError::CommitFailed { last_error, .. } => {
684 ApiError::server_error(format!("Database commit failed: {last_error}"))
685 }
686 })
687 }
688
689 async fn sign_api_announcement(&self, new_url: SafeUrl) -> SignedApiAnnouncement {
690 self.db
691 .autocommit(
692 |dbtx, _| {
693 let new_url_inner = new_url.clone();
694 Box::pin(async move {
695 let new_nonce = dbtx
696 .get_value(&ApiAnnouncementKey(self.cfg.local.identity))
697 .await
698 .map_or(0, |a| a.api_announcement.nonce + 1);
699 let announcement = ApiAnnouncement {
700 api_url: new_url_inner,
701 nonce: new_nonce,
702 };
703 let ctx = secp256k1::Secp256k1::new();
704 let signed_announcement = announcement
705 .sign(&ctx, &self.cfg.private.broadcast_secret_key.keypair(&ctx));
706
707 dbtx.insert_entry(
708 &ApiAnnouncementKey(self.cfg.local.identity),
709 &signed_announcement,
710 )
711 .await;
712
713 Result::<_, ()>::Ok(signed_announcement)
714 })
715 },
716 None,
717 )
718 .await
719 .expect("Will not terminate on error")
720 }
721
722 async fn guardian_metadata_list(
723 &self,
724 ) -> BTreeMap<PeerId, fedimint_core::net::guardian_metadata::SignedGuardianMetadata> {
725 use crate::net::api::guardian_metadata::{GuardianMetadataKey, GuardianMetadataPrefix};
726
727 self.db
728 .begin_transaction_nc()
729 .await
730 .find_by_prefix(&GuardianMetadataPrefix)
731 .await
732 .map(|(key, metadata): (GuardianMetadataKey, _)| (key.0, metadata))
733 .collect()
734 .await
735 }
736
737 async fn submit_guardian_metadata(
738 &self,
739 peer_id: PeerId,
740 metadata: fedimint_core::net::guardian_metadata::SignedGuardianMetadata,
741 ) -> Result<(), ApiError> {
742 use crate::net::api::guardian_metadata::GuardianMetadataKey;
743
744 let Some(peer_key) = self.cfg.consensus.broadcast_public_keys.get(&peer_id) else {
745 return Err(ApiError::bad_request("Peer not in federation".into()));
746 };
747
748 let now = fedimint_core::time::duration_since_epoch();
749 if let Err(e) = metadata.verify(SECP256K1, peer_key, now) {
750 return Err(ApiError::bad_request(format!(
751 "Invalid signature or timestamp: {e}"
752 )));
753 }
754
755 let mut dbtx = self.db.begin_transaction().await;
756
757 if let Some(existing_metadata) = dbtx.get_value(&GuardianMetadataKey(peer_id)).await {
758 if existing_metadata.bytes == metadata.bytes {
762 return Ok(());
763 }
764
765 if metadata.guardian_metadata().timestamp_secs
767 <= existing_metadata.guardian_metadata().timestamp_secs
768 {
769 return Err(ApiError::bad_request(
770 "New metadata timestamp is not newer than existing".into(),
771 ));
772 }
773 }
774
775 dbtx.insert_entry(&GuardianMetadataKey(peer_id), &metadata)
776 .await;
777 dbtx.commit_tx().await;
778
779 Ok(())
780 }
781
782 async fn sign_guardian_metadata(
783 &self,
784 new_metadata: fedimint_core::net::guardian_metadata::GuardianMetadata,
785 ) -> fedimint_core::net::guardian_metadata::SignedGuardianMetadata {
786 sign_guardian_metadata_preserving_iroh_endpoint(
787 &self.db,
788 self.cfg.local.identity,
789 &self.cfg.private.broadcast_secret_key,
790 new_metadata,
791 )
792 .await
793 }
794
795 async fn get_invite_code(&self, api_secret: Option<String>) -> InviteCode {
796 let identity = self.cfg.local.identity;
797 let mut api_urls = get_api_urls(&self.db, &self.cfg.consensus).await;
798
799 InviteCode::new(
800 api_urls
801 .remove(&identity)
802 .expect("API URL for our identity must be present"),
803 identity,
804 self.cfg.calculate_federation_id(),
805 api_secret,
806 )
807 }
808}
809
810async fn sign_guardian_metadata_preserving_iroh_endpoint(
811 db: &Database,
812 identity: PeerId,
813 broadcast_secret_key: &secp256k1::SecretKey,
814 new_metadata: fedimint_core::net::guardian_metadata::GuardianMetadata,
815) -> fedimint_core::net::guardian_metadata::SignedGuardianMetadata {
816 use crate::net::api::guardian_metadata::GuardianMetadataKey;
817
818 db.autocommit(
819 |dbtx, _| {
820 let mut new_metadata = new_metadata.clone();
821 Box::pin(async move {
822 new_metadata.iroh_next_endpoint = dbtx
823 .get_value(&GuardianMetadataKey(identity))
824 .await
825 .and_then(|metadata| metadata.guardian_metadata().iroh_next_endpoint.clone());
826
827 let ctx = secp256k1::Secp256k1::new();
828 let signed_metadata = new_metadata.sign(&ctx, &broadcast_secret_key.keypair(&ctx));
829
830 dbtx.insert_entry(&GuardianMetadataKey(identity), &signed_metadata)
831 .await;
832
833 Result::<_, ()>::Ok(signed_metadata)
834 })
835 },
836 None,
837 )
838 .await
839 .expect("Will not terminate on error")
840}
841
842#[async_trait]
843impl HasApiContext<ConsensusApi> for ConsensusApi {
844 async fn context(
845 &self,
846 request: &ApiRequestErased,
847 id: Option<ModuleInstanceId>,
848 ) -> (&ConsensusApi, ApiEndpointContext) {
849 let mut db = self.db.clone();
850 if let Some(id) = id {
851 db = self.db.with_prefix_module_id(id).0;
852 }
853 let has_auth = match (&self.auth_api, &request.auth) {
854 (Some(server_auth), Some(req_auth)) => server_auth.verify(req_auth.as_str()),
855 _ => false,
856 };
857
858 (self, ApiEndpointContext::new(db, has_auth))
859 }
860}
861
862#[async_trait]
863impl HasApiContext<DynServerModule> for ConsensusApi {
864 async fn context(
865 &self,
866 request: &ApiRequestErased,
867 id: Option<ModuleInstanceId>,
868 ) -> (&DynServerModule, ApiEndpointContext) {
869 let (_, context): (&ConsensusApi, _) = self.context(request, id).await;
870 (
871 self.modules.get_expect(id.expect("required module id")),
872 context,
873 )
874 }
875}
876
877#[async_trait]
878impl IDashboardApi for ConsensusApi {
879 fn auth_ui(&self) -> Option<ApiAuth> {
880 self.auth_ui.clone()
881 }
882
883 async fn guardian_id(&self) -> PeerId {
884 self.cfg.local.identity
885 }
886
887 async fn guardian_names(&self) -> BTreeMap<PeerId, String> {
888 self.cfg
889 .consensus
890 .api_endpoints()
891 .iter()
892 .map(|(peer_id, endpoint)| (*peer_id, endpoint.name.clone()))
893 .collect()
894 }
895
896 async fn federation_name(&self) -> Option<String> {
897 self.cfg
898 .consensus
899 .meta
900 .get(META_FEDERATION_NAME_KEY)
901 .cloned()
902 }
903
904 async fn session_count(&self) -> u64 {
905 self.session_count()
906 }
907
908 async fn get_session_status(&self, session_idx: u64) -> SessionStatusV2 {
909 self.session_status(session_idx).await
910 }
911
912 async fn consensus_ord_latency(&self) -> Option<Duration> {
913 *self.ord_latency_receiver.borrow()
914 }
915
916 async fn p2p_connection_status(&self) -> BTreeMap<PeerId, Option<P2PConnectionStatus>> {
917 self.p2p_status_receivers
918 .iter()
919 .map(|(peer, receiver)| (*peer, receiver.borrow().connected.clone()))
920 .collect()
921 }
922
923 async fn federation_invite_code(&self) -> String {
924 self.get_invite_code(self.get_active_api_secret())
925 .await
926 .to_string()
927 }
928
929 async fn peer_availability(
930 &self,
931 ) -> Option<fedimint_server_core::dashboard_ui::DashboardPeerAvailability> {
932 let (updated_at_secs, report) = super::peer_availability::report_with_timestamp(
933 &self.db,
934 fedimint_core::time::duration_since_epoch().as_secs(),
935 )
936 .await;
937 (updated_at_secs != 0).then_some(
938 fedimint_server_core::dashboard_ui::DashboardPeerAvailability {
939 updated_at_secs,
940 report,
941 },
942 )
943 }
944
945 async fn federation_audit(&self) -> AuditSummary {
946 self.get_federation_audit()
947 .await
948 .expect("Failed to get federation audit")
949 }
950
951 async fn bitcoin_rpc_url(&self) -> SafeUrl {
952 self.bitcoin_rpc_connection.url()
953 }
954
955 async fn bitcoin_rpc_status(&self) -> Option<ServerBitcoinRpcStatus> {
956 self.bitcoin_rpc_connection.status()
957 }
958
959 async fn download_guardian_config_backup(
960 &self,
961 guardian_auth: &GuardianAuthToken,
962 ) -> GuardianConfigBackup {
963 self.get_guardian_config_backup(guardian_auth)
964 }
965
966 fn get_module_by_kind(&self, kind: ModuleKind) -> Option<&DynServerModule> {
967 self.modules
968 .iter_modules()
969 .find_map(|(_, module_kind, module)| {
970 if *module_kind == kind {
971 Some(module)
972 } else {
973 None
974 }
975 })
976 }
977
978 async fn fedimintd_version(&self) -> String {
979 self.code_version_str.clone()
980 }
981
982 async fn fedimintd_version_hash(&self) -> Option<String> {
983 non_zero_version_hash(&self.code_version_hash).map(str::to_owned)
984 }
985}
986
987pub fn server_endpoints() -> Vec<ApiEndpoint<ConsensusApi>> {
988 vec![
989 public_api_endpoint! {
990 VERSION_ENDPOINT,
991 ApiVersion::new(0, 0),
992 async |fedimint: &ConsensusApi, _context, _v: ()| -> SupportedApiVersionsSummary {
993 Ok(fedimint.api_versions_summary().to_owned())
994 }
995 },
996 public_api_endpoint! {
997 SUBMIT_TRANSACTION_ENDPOINT,
998 ApiVersion::new(0, 0),
999 async |fedimint: &ConsensusApi, _context, transaction: SerdeTransaction| -> SerdeModuleEncoding<TransactionSubmissionOutcome> {
1000 let transaction = transaction
1001 .try_into_inner(&fedimint.modules.decoder_registry())
1002 .map_err(|e| ApiError::bad_request(e.to_string()))?;
1003
1004 Ok((&TransactionSubmissionOutcome(fedimint.submit_transaction(transaction).await)).into())
1007 }
1008 },
1009 public_api_endpoint! {
1010 AWAIT_TRANSACTION_ENDPOINT,
1011 ApiVersion::new(0, 0),
1012 async |fedimint: &ConsensusApi, _context, tx_hash: TransactionId| -> TransactionId {
1013 fedimint.await_transaction(tx_hash).await;
1014
1015 Ok(tx_hash)
1016 }
1017 },
1018 public_api_endpoint! {
1019 AWAIT_OUTPUT_OUTCOME_ENDPOINT,
1020 ApiVersion::new(0, 0),
1021 async |fedimint: &ConsensusApi, _context, outpoint: OutPoint| -> SerdeModuleEncoding<DynOutputOutcome> {
1022 let outcome = fedimint
1023 .await_output_outcome(outpoint)
1024 .await
1025 .map_err(|e| ApiError::bad_request(e.to_string()))?;
1026
1027 Ok(outcome)
1028 }
1029 },
1030 public_api_endpoint! {
1031 AWAIT_OUTPUTS_OUTCOMES_ENDPOINT,
1032 ApiVersion::new(0, 8),
1033 async |fedimint: &ConsensusApi, _context, outpoint_range: OutPointRange| -> Vec<Option<SerdeModuleEncoding<DynOutputOutcome>>> {
1034 let outcomes = fedimint
1035 .await_outputs_outcomes(outpoint_range)
1036 .await
1037 .map_err(|e| ApiError::bad_request(e.to_string()))?;
1038
1039 Ok(outcomes)
1040 }
1041 },
1042 public_api_endpoint! {
1043 INVITE_CODE_ENDPOINT,
1044 ApiVersion::new(0, 0),
1045 async |fedimint: &ConsensusApi, _context, _v: ()| -> String {
1046 Ok(fedimint.get_invite_code(fedimint.get_active_api_secret()).await.to_string())
1047 }
1048 },
1049 public_api_endpoint! {
1050 FEDERATION_ID_ENDPOINT,
1051 ApiVersion::new(0, 2),
1052 async |fedimint: &ConsensusApi, _context, _v: ()| -> String {
1053 Ok(fedimint.cfg.calculate_federation_id().to_string())
1054 }
1055 },
1056 public_api_endpoint! {
1057 CLIENT_CONFIG_ENDPOINT,
1058 ApiVersion::new(0, 0),
1059 async |fedimint: &ConsensusApi, _context, _v: ()| -> ClientConfig {
1060 Ok(fedimint.client_cfg.clone())
1061 }
1062 },
1063 public_api_endpoint! {
1065 CLIENT_CONFIG_JSON_ENDPOINT,
1066 ApiVersion::new(0, 0),
1067 async |fedimint: &ConsensusApi, _context, _v: ()| -> JsonClientConfig {
1068 Ok(fedimint.client_cfg.to_json())
1069 }
1070 },
1071 public_api_endpoint! {
1072 SERVER_CONFIG_CONSENSUS_HASH_ENDPOINT,
1073 ApiVersion::new(0, 0),
1074 async |fedimint: &ConsensusApi, _context, _v: ()| -> sha256::Hash {
1075 Ok(legacy_consensus_config_hash(&fedimint.cfg.consensus))
1076 }
1077 },
1078 public_api_endpoint! {
1079 STATUS_ENDPOINT,
1080 ApiVersion::new(0, 0),
1081 async |fedimint: &ConsensusApi, _context, _v: ()| -> StatusResponse {
1082 Ok(StatusResponse {
1083 server: ServerStatusLegacy::ConsensusRunning,
1084 federation: Some(fedimint.get_federation_status()?)
1085 })}
1086 },
1087 public_api_endpoint! {
1088 SETUP_STATUS_ENDPOINT,
1089 ApiVersion::new(0, 0),
1090 async |_f: &ConsensusApi, _c, _v: ()| -> SetupStatus {
1091 Ok(SetupStatus::ConsensusIsRunning)
1092 }
1093 },
1094 public_api_endpoint! {
1095 CONSENSUS_ORD_LATENCY_ENDPOINT,
1096 ApiVersion::new(0, 0),
1097 async |fedimint: &ConsensusApi, _c, _v: ()| -> Option<Duration> {
1098 Ok(*fedimint.ord_latency_receiver.borrow())
1099 }
1100 },
1101 public_api_endpoint! {
1102 P2P_CONNECTION_STATUS_ENDPOINT,
1103 ApiVersion::new(0, 0),
1104 async |fedimint: &ConsensusApi, _c, _v: ()| -> BTreeMap<PeerId, Option<P2PConnectionStatus>> {
1105 Ok(fedimint.p2p_status_receivers
1106 .iter()
1107 .map(|(peer, receiver)| (*peer, receiver.borrow().connected.clone()))
1108 .collect())
1109 }
1110 },
1111 public_api_endpoint! {
1112 PEER_AVAILABILITY_ENDPOINT,
1113 ApiVersion::new(0, 0),
1114 async |fedimint: &ConsensusApi, _c, _v: ()| -> PeerAvailability {
1115 Ok(super::peer_availability::report(&fedimint.db, fedimint_core::time::duration_since_epoch().as_secs()).await)
1116 }
1117 },
1118 admin_api_endpoint! {
1119 RESET_PEER_AVAILABILITY_ENDPOINT,
1120 ApiVersion::new(0, 11),
1121 async |fedimint: &ConsensusApi, context, request: ResetPeerAvailabilityRequest| -> () {
1122 if !fedimint.cfg.consensus.broadcast_public_keys.contains_key(&request.peer_id) {
1123 return Err(ApiError::bad_request("Unknown peer".to_owned()));
1124 }
1125 Ok(fedimint.availability.reset(
1126 &fedimint.db, request.peer_id,
1127 fedimint_core::time::duration_since_epoch().as_secs(),
1128 ).await?)
1129 }
1130 },
1131 public_api_endpoint! {
1132 SESSION_COUNT_ENDPOINT,
1133 ApiVersion::new(0, 0),
1134 async |fedimint: &ConsensusApi, _context, _v: ()| -> u64 {
1135 Ok(fedimint.session_count())
1136 }
1137 },
1138 public_api_endpoint! {
1139 AWAIT_SESSION_OUTCOME_ENDPOINT,
1140 ApiVersion::new(0, 0),
1141 async |fedimint: &ConsensusApi, _context, index: u64| -> Arc<serde_json::Value> {
1142 Ok(fedimint.await_session_outcome(index, OutcomeFormat::Unsigned).await)
1143 }
1144 },
1145 public_api_endpoint! {
1146 AWAIT_SIGNED_SESSION_OUTCOME_ENDPOINT,
1147 ApiVersion::new(0, 0),
1148 async |fedimint: &ConsensusApi, _context, index: u64| -> Arc<serde_json::Value> {
1149 Ok(fedimint.await_session_outcome(index, OutcomeFormat::Signed).await)
1150 }
1151 },
1152 public_api_endpoint! {
1153 SESSION_STATUS_ENDPOINT,
1154 ApiVersion::new(0, 1),
1155 async |fedimint: &ConsensusApi, _context, index: u64| -> SerdeModuleEncoding<SessionStatus> {
1156 Ok((&SessionStatus::from(fedimint.session_status(index).await)).into())
1157 }
1158 },
1159 public_api_endpoint! {
1160 SESSION_STATUS_V2_ENDPOINT,
1161 ApiVersion::new(0, 5),
1162 async |fedimint: &ConsensusApi, _context, index: u64| -> SerdeModuleEncodingBase64<SessionStatusV2> {
1163 Ok((&fedimint.session_status(index).await).into())
1164 }
1165 },
1166 admin_api_endpoint! {
1167 SHUTDOWN_ENDPOINT,
1168 ApiVersion::new(0, 3),
1169 async |fedimint: &ConsensusApi, context, index: Option<u64>| -> () {
1170 fedimint.shutdown(index);
1171 Ok(())
1172 }
1173 },
1174 admin_api_endpoint! {
1175 SHUTDOWN_AFTER_CURRENT_SESSION_ENDPOINT,
1176 ApiVersion::new(0, 10),
1177 async |fedimint: &ConsensusApi, context, _v: ()| -> () {
1178 fedimint.shutdown_after_current_session();
1179 Ok(())
1180 }
1181 },
1182 admin_api_endpoint! {
1183 AUDIT_ENDPOINT,
1184 ApiVersion::new(0, 0),
1185 async |fedimint: &ConsensusApi, context, _v: ()| -> AuditSummary {
1186 Ok(fedimint.get_federation_audit().await?)
1187 }
1188 },
1189 admin_api_endpoint! {
1190 GUARDIAN_CONFIG_BACKUP_ENDPOINT,
1191 ApiVersion::new(0, 2),
1192 async |fedimint: &ConsensusApi, context, auth, _v: ()| -> GuardianConfigBackup {
1193 Ok(fedimint.get_guardian_config_backup(&auth))
1194 }
1195 },
1196 public_api_endpoint! {
1197 BACKUP_ENDPOINT,
1198 ApiVersion::new(0, 0),
1199 async |fedimint: &ConsensusApi, context, request: SignedBackupRequest| -> () {
1200 let db = context.db();
1201 let mut dbtx = db.begin_transaction().await;
1202 fedimint
1203 .handle_backup_request(&mut dbtx.to_ref_nc(), request).await?;
1204 dbtx.commit_tx_result().await?;
1205 Ok(())
1206
1207 }
1208 },
1209 public_api_endpoint! {
1210 RECOVER_ENDPOINT,
1211 ApiVersion::new(0, 0),
1212 async |fedimint: &ConsensusApi, context, id: PublicKey| -> Option<ClientBackupSnapshot> {
1213 let db = context.db();
1214 let mut dbtx = db.begin_transaction_nc().await;
1215 Ok(fedimint
1216 .handle_recover_request(&mut dbtx, id).await)
1217 }
1218 },
1219 admin_api_endpoint! {
1220 AUTH_ENDPOINT,
1221 ApiVersion::new(0, 0),
1222 async |_fedimint: &ConsensusApi, context, _v: ()| -> () {
1223 Ok(())
1224 }
1225 },
1226 public_api_endpoint! {
1227 API_ANNOUNCEMENTS_ENDPOINT,
1228 ApiVersion::new(0, 3),
1229 async |fedimint: &ConsensusApi, _context, _v: ()| -> BTreeMap<PeerId, SignedApiAnnouncement> {
1230 Ok(fedimint.api_announcements().await)
1231 }
1232 },
1233 public_api_endpoint! {
1234 SUBMIT_API_ANNOUNCEMENT_ENDPOINT,
1235 ApiVersion::new(0, 3),
1236 async |fedimint: &ConsensusApi, _context, submission: SignedApiAnnouncementSubmission| -> () {
1237 fedimint.submit_api_announcement(submission.peer_id, submission.signed_api_announcement).await
1238 }
1239 },
1240 admin_api_endpoint! {
1241 SIGN_API_ANNOUNCEMENT_ENDPOINT,
1242 ApiVersion::new(0, 3),
1243 async |fedimint: &ConsensusApi, context, new_url: SafeUrl| -> SignedApiAnnouncement {
1244 Ok(fedimint.sign_api_announcement(new_url).await)
1245 }
1246 },
1247 public_api_endpoint! {
1248 GUARDIAN_METADATA_ENDPOINT,
1249 ApiVersion::new(0, 9),
1250 async |fedimint: &ConsensusApi, _context, _v: ()| -> BTreeMap<PeerId, fedimint_core::net::guardian_metadata::SignedGuardianMetadata> {
1251 Ok(fedimint.guardian_metadata_list().await)
1252 }
1253 },
1254 public_api_endpoint! {
1255 SUBMIT_GUARDIAN_METADATA_ENDPOINT,
1256 ApiVersion::new(0, 9),
1257 async |fedimint: &ConsensusApi, _context, submission: fedimint_core::net::guardian_metadata::SignedGuardianMetadataSubmission| -> () {
1258 fedimint.submit_guardian_metadata(submission.peer_id, submission.signed_guardian_metadata).await
1259 }
1260 },
1261 admin_api_endpoint! {
1262 SIGN_GUARDIAN_METADATA_ENDPOINT,
1263 ApiVersion::new(0, 9),
1264 async |fedimint: &ConsensusApi, context, metadata: fedimint_core::net::guardian_metadata::GuardianMetadata| -> fedimint_core::net::guardian_metadata::SignedGuardianMetadata {
1265 Ok(fedimint.sign_guardian_metadata(metadata).await)
1266 }
1267 },
1268 public_api_endpoint! {
1269 FEDIMINTD_VERSION_ENDPOINT,
1270 ApiVersion::new(0, 4),
1271 async |fedimint: &ConsensusApi, _context, _v: ()| -> String {
1272 Ok(fedimint.fedimintd_version())
1273 }
1274 },
1275 admin_api_endpoint! {
1276 BACKUP_STATISTICS_ENDPOINT,
1277 ApiVersion::new(0, 5),
1278 async |_fedimint: &ConsensusApi, context, _v: ()| -> BackupStatistics {
1279 let db = context.db();
1280 let mut dbtx = db.begin_transaction_nc().await;
1281 Ok(backup_statistics_static(&mut dbtx).await)
1282 }
1283 },
1284 public_api_endpoint! {
1285 CHAIN_ID_ENDPOINT,
1286 ApiVersion::new(0, 9),
1287 async |fedimint: &ConsensusApi, _context, _v: ()| -> ChainId {
1288 fedimint
1289 .bitcoin_rpc_connection
1290 .get_chain_id()
1291 .await
1292 .map_err(|e| ApiError::server_error(e.to_string()))
1293 }
1294 },
1295 ]
1296}
1297
1298pub(crate) async fn backup_statistics_static(
1299 dbtx: &mut DatabaseTransaction<'_>,
1300) -> BackupStatistics {
1301 const DAY_SECS: u64 = 24 * 60 * 60;
1302 const WEEK_SECS: u64 = 7 * DAY_SECS;
1303 const MONTH_SECS: u64 = 30 * DAY_SECS;
1304 const QUARTER_SECS: u64 = 3 * MONTH_SECS;
1305
1306 let mut backup_stats = BackupStatistics::default();
1307
1308 let mut all_backups_stream = dbtx.find_by_prefix(&ClientBackupKeyPrefix).await;
1309 while let Some((_, backup)) = all_backups_stream.next().await {
1310 backup_stats.num_backups += 1;
1311 backup_stats.total_size += backup.data.len();
1312
1313 let age_secs = backup.timestamp.elapsed().unwrap_or_default().as_secs();
1314 if age_secs < DAY_SECS {
1315 backup_stats.refreshed_1d += 1;
1316 }
1317 if age_secs < WEEK_SECS {
1318 backup_stats.refreshed_1w += 1;
1319 }
1320 if age_secs < MONTH_SECS {
1321 backup_stats.refreshed_1m += 1;
1322 }
1323 if age_secs < QUARTER_SECS {
1324 backup_stats.refreshed_3m += 1;
1325 }
1326 }
1327
1328 backup_stats
1329}
1330
1331fn schedule_shutdown_after(
1334 scheduled: &mut Option<ScheduledShutdown>,
1335 current_session: u64,
1336) -> bool {
1337 let session = scheduled
1338 .map(|scheduled| scheduled.session)
1339 .filter(|session| *session <= current_session)
1340 .unwrap_or(current_session);
1341 let after_current_session = Some(ScheduledShutdown {
1342 session,
1343 request: ShutdownRequest::AfterCurrentSession,
1344 });
1345 if *scheduled == after_current_session {
1346 return false;
1347 }
1348 *scheduled = after_current_session;
1349 true
1350}
1351
1352#[cfg(test)]
1353mod tests;