1use std::collections::BTreeMap;
2use std::fs;
3use std::path::{Path, PathBuf};
4use std::sync::Arc;
5use std::time::{Duration, Instant};
6
7use aleph_bft::Keychain as KeychainTrait;
8use anyhow::{Context, anyhow, bail};
9use async_channel::Receiver;
10use fedimint_api_client::api::{DynGlobalApi, FederationApiExt, ServerError};
11use fedimint_api_client::query::FilterMap;
12use fedimint_core::config::P2PMessage;
13use fedimint_core::core::{DynOutput, MODULE_INSTANCE_ID_GLOBAL};
14use fedimint_core::db::{
15 Database, DatabaseError, DatabaseResult, DatabaseTransaction, IDatabaseTransactionOpsCoreTyped,
16};
17use fedimint_core::encoding::Decodable;
18use fedimint_core::endpoint_constants::AWAIT_SIGNED_SESSION_OUTCOME_ENDPOINT;
19use fedimint_core::envs::is_running_in_test_env;
20use fedimint_core::module::audit::Audit;
21use fedimint_core::module::registry::ModuleDecoderRegistry;
22use fedimint_core::module::{ApiRequestErased, SerdeModuleEncoding};
23use fedimint_core::net::DynP2PConnections;
24use fedimint_core::runtime::spawn;
25use fedimint_core::secp256k1::schnorr;
26use fedimint_core::session_outcome::{
27 AcceptedItem, ConsensusItem, SessionOutcome, SignedSessionOutcome,
28};
29use fedimint_core::task::{TaskGroup, TaskHandle, sleep};
30use fedimint_core::timing::TimeReporter;
31use fedimint_core::util::FmtCompact as _;
32use fedimint_core::{NumPeers, NumPeersExt, PeerId, timing};
33use fedimint_server_core::{ServerModuleRegistry, ServerModuleRegistryExt};
34use futures::StreamExt;
35use rand::Rng;
36use rand::seq::IteratorRandom;
37use tokio::sync::watch;
38use tracing::{Level, debug, error, info, instrument, trace, warn};
39
40use crate::LOG_CONSENSUS;
41use crate::config::ServerConfig;
42use crate::consensus::aleph_bft::backup::{BackupReader, BackupWriter};
43use crate::consensus::aleph_bft::data_provider::{DataProvider, UnitData};
44use crate::consensus::aleph_bft::finalization_handler::{FinalizationHandler, OrderedUnit};
45use crate::consensus::aleph_bft::keychain::Keychain;
46use crate::consensus::aleph_bft::network::Network;
47use crate::consensus::aleph_bft::spawner::Spawner;
48use crate::consensus::aleph_bft::to_node_index;
49use crate::consensus::db::{
50 AcceptedItemKey, AcceptedItemPrefix, AcceptedTransactionKey, AlephUnitsPrefix,
51 SignedSessionOutcomeKey, SignedSessionOutcomePrefix,
52};
53use crate::consensus::debug::{DebugConsensusItem, DebugConsensusItemCompact};
54use crate::consensus::peer_availability::PeerActivity;
55use crate::consensus::transaction::{TxProcessingMode, process_transaction_with_dbtx};
56use crate::metrics::{
57 CONSENSUS_ITEM_PROCESSING_DURATION_SECONDS,
58 CONSENSUS_ITEM_PROCESSING_MODULE_AUDIT_DURATION_SECONDS, CONSENSUS_ITEMS_PROCESSED_TOTAL,
59 CONSENSUS_ORDERING_LATENCY_SECONDS, CONSENSUS_PEER_CONTRIBUTION_SESSION_IDX,
60 CONSENSUS_SESSION_COUNT,
61};
62
63const DB_CHECKPOINTS_DIR: &str = "db_checkpoints";
65
66const MAX_ITEM_PROCESSING_ATTEMPTS: usize = 10;
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum ShutdownRequest {
75 AtSession,
77 AfterCurrentSession,
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub struct ScheduledShutdown {
84 pub session: u64,
87 pub request: ShutdownRequest,
88}
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum ConsensusStop {
93 TaskShutdown,
96 ScheduledShutdown(ShutdownRequest),
99}
100
101pub struct ConsensusEngine {
103 pub modules: ServerModuleRegistry,
104 pub db: Database,
105 pub federation_api: DynGlobalApi,
106 pub cfg: ServerConfig,
107 pub submission_receiver: Receiver<ConsensusItem>,
108 pub shutdown_receiver: watch::Receiver<Option<ScheduledShutdown>>,
109 pub connections: DynP2PConnections<P2PMessage>,
110 pub ci_status_senders: BTreeMap<PeerId, watch::Sender<Option<u64>>>,
111 pub ord_latency_sender: watch::Sender<Option<Duration>>,
112 pub accepted_item_sender: watch::Sender<()>,
114 pub completed_session_sender: watch::Sender<super::session_cache::CompletedSession>,
116 pub task_group: TaskGroup,
117 pub data_dir: PathBuf,
118 pub db_checkpoint_retention: u64,
119 pub session_timeout: Duration,
120 pub peer_activity: Arc<std::sync::Mutex<PeerActivity>>,
121}
122
123impl ConsensusEngine {
124 fn num_peers(&self) -> NumPeers {
125 self.cfg.consensus.broadcast_public_keys.to_num_peers()
126 }
127
128 fn identity(&self) -> PeerId {
129 self.cfg.local.identity
130 }
131
132 #[instrument(target = LOG_CONSENSUS, name = "run", skip_all, fields(id=%self.cfg.local.identity))]
133 pub async fn run(self) -> anyhow::Result<ConsensusStop> {
134 if self.num_peers().total() == 1 {
135 self.run_single_guardian(self.task_group.make_handle())
136 .await
137 } else {
138 self.run_consensus(self.task_group.make_handle()).await
139 }
140 }
141
142 pub async fn run_single_guardian(
143 &self,
144 task_handle: TaskHandle,
145 ) -> anyhow::Result<ConsensusStop> {
146 assert_eq!(self.num_peers(), NumPeers::from(1));
147
148 self.initialize_checkpoint_directory(self.get_finished_session_count().await)?;
149
150 while !task_handle.is_shutting_down() {
151 let session_index = self.get_finished_session_count().await;
152
153 CONSENSUS_SESSION_COUNT.set(session_index as i64);
154
155 let mut item_index = self.pending_accepted_items().await.len() as u64;
156
157 let session_start_time = std::time::Instant::now();
158
159 while let Ok(item) = self.submission_receiver.recv().await {
160 if self
161 .process_consensus_item(session_index, item_index, item, self.identity())
162 .await
163 .is_ok()
164 {
165 item_index += 1;
166 }
167
168 if session_start_time.elapsed() > Duration::from_mins(1) {
170 break;
171 }
172 }
173
174 let session_outcome = SessionOutcome {
175 items: self.pending_accepted_items().await,
176 };
177
178 let header = session_outcome.header(session_index);
179 let signature = Keychain::new(&self.cfg).sign_schnorr(&header);
180 let signatures = BTreeMap::from_iter([(self.identity(), signature)]);
181
182 self.complete_session(
183 session_index,
184 SignedSessionOutcome {
185 session_outcome,
186 signatures,
187 },
188 )
189 .await;
190
191 self.checkpoint_database(session_index);
192
193 info!(target: LOG_CONSENSUS, "Session {session_index} completed");
194
195 let due = due_shutdown(*self.shutdown_receiver.borrow(), session_index);
196 if let Some(request) = due {
197 return Ok(ConsensusStop::ScheduledShutdown(request));
198 }
199 }
200
201 info!(target: LOG_CONSENSUS, "Consensus task shut down");
202
203 Ok(ConsensusStop::TaskShutdown)
204 }
205
206 pub async fn run_consensus(&self, task_handle: TaskHandle) -> anyhow::Result<ConsensusStop> {
207 assert!(self.num_peers().total() >= 4);
209
210 self.initialize_checkpoint_directory(self.get_finished_session_count().await)?;
211
212 while !task_handle.is_shutting_down() {
213 let session_index = self.get_finished_session_count().await;
214
215 CONSENSUS_SESSION_COUNT.set(session_index as i64);
216
217 let is_recovery = self.is_recovery().await;
218
219 info!(
220 target: LOG_CONSENSUS,
221 session_index,
222 is_recovery,
223 "Starting consensus session"
224 );
225
226 let session = tokio::time::timeout(
232 self.session_timeout,
233 self.run_session(self.connections.clone(), session_index),
234 )
235 .await
236 .context("Consensus session timed out, exiting...")?;
237
238 if session.is_none() {
239 return Ok(ConsensusStop::TaskShutdown);
240 }
241
242 info!(target: LOG_CONSENSUS, ?session_index, "Completed consensus session");
243
244 let due = due_shutdown(*self.shutdown_receiver.borrow(), session_index);
245 if let Some(request) = due {
246 info!(target: LOG_CONSENSUS, "Initiating shutdown, waiting for peers to complete the session...");
247
248 sleep(Duration::from_mins(1)).await;
249
250 return Ok(ConsensusStop::ScheduledShutdown(request));
251 }
252 }
253
254 info!(target: LOG_CONSENSUS, "Consensus task shut down");
255
256 Ok(ConsensusStop::TaskShutdown)
257 }
258
259 pub async fn run_session(
260 &self,
261 connections: DynP2PConnections<P2PMessage>,
262 session_index: u64,
263 ) -> Option<()> {
264 const EXP_SLOWDOWN_ROUNDS: u16 = 1000;
282 const BASE: f64 = 1.02;
283
284 let rounds_per_session = self.cfg.consensus.broadcast_rounds_per_session;
285 let round_delay = f64::from(self.cfg.local.broadcast_round_delay_ms);
286
287 let mut delay_config = aleph_bft::default_delay_config();
288
289 delay_config.unit_creation_delay = Arc::new(move |round_index| {
290 let jitter = if is_running_in_test_env!() {
294 rand::thread_rng().gen_range(0.5..=1.5)
295 } else {
296 1.0
297 };
298
299 let delay = if round_index == 0 {
300 0.0
301 } else {
302 round_delay
303 * BASE.powf(round_index.saturating_sub(rounds_per_session as usize) as f64)
304 * jitter
305 };
306
307 Duration::from_millis(delay.round() as u64)
308 });
309
310 let config = aleph_bft::create_config(
311 self.num_peers().total().into(),
312 self.identity().to_usize().into(),
313 session_index,
314 self.cfg
315 .consensus
316 .broadcast_rounds_per_session
317 .checked_add(EXP_SLOWDOWN_ROUNDS)
318 .expect("Rounds per session exceed maximum of u16::Max - EXP_SLOWDOWN_ROUNDS"),
319 delay_config,
320 Duration::from_hours(87600),
321 )
322 .expect("The exponential slowdown exceeds 10 years");
323
324 let (unit_data_sender, unit_data_receiver) = async_channel::unbounded();
327 let (signature_sender, signature_receiver) = watch::channel(None);
328 let (timestamp_sender, timestamp_receiver) = async_channel::unbounded();
329 let (terminator_sender, terminator_receiver) = futures::channel::oneshot::channel();
330
331 let (signed_outcomes_sender, signed_outcomes_receiver) = async_channel::unbounded();
333 let (signatures_sender, signatures_receiver) = async_channel::unbounded();
334
335 let aleph_handle = spawn(
336 "aleph run session",
337 aleph_bft::run_session(
338 config,
339 aleph_bft::LocalIO::new(
340 DataProvider::new(
341 self.submission_receiver.clone(),
342 signature_receiver,
343 timestamp_sender,
344 self.is_recovery().await,
345 ),
346 FinalizationHandler::new(unit_data_sender),
347 BackupWriter::new(self.db.clone()).await,
348 BackupReader::new(self.db.clone()),
349 ),
350 Network::new(
351 connections.clone(),
352 self.peer_activity.clone(),
353 signed_outcomes_sender,
354 signatures_sender,
355 self.db.clone(),
356 ),
357 Keychain::new(&self.cfg),
358 Spawner::new(self.task_group.make_subgroup()),
359 aleph_bft::Terminator::create_root(terminator_receiver, "Terminator"),
360 ),
361 );
362
363 self.ord_latency_sender.send_replace(None);
364
365 let signed_session_outcome = self
366 .complete_signed_session_outcome(
367 session_index,
368 unit_data_receiver,
369 signature_sender,
370 timestamp_receiver,
371 signed_outcomes_receiver,
372 signatures_receiver,
373 connections,
374 )
375 .await?;
376
377 assert!(
378 self.validate_signed_session_outcome(&signed_session_outcome, session_index),
379 "Our created signed session outcome fails validation"
380 );
381
382 info!(target: LOG_CONSENSUS, ?session_index, "Terminating Aleph BFT session");
383
384 let _ = terminator_sender.send(());
388 let _ = aleph_handle.await;
389
390 self.complete_session(session_index, signed_session_outcome)
394 .await;
395
396 self.checkpoint_database(session_index);
397
398 Some(())
399 }
400
401 async fn is_recovery(&self) -> bool {
402 self.db
403 .begin_transaction_nc()
404 .await
405 .find_by_prefix(&AlephUnitsPrefix)
406 .await
407 .next()
408 .await
409 .is_some()
410 }
411
412 #[allow(clippy::too_many_arguments)]
413 pub async fn complete_signed_session_outcome(
414 &self,
415 session_index: u64,
416 ordered_unit_receiver: Receiver<OrderedUnit>,
417 signature_sender: watch::Sender<Option<schnorr::Signature>>,
418 timestamp_receiver: Receiver<Instant>,
419 signed_outcomes_receiver: Receiver<(PeerId, SignedSessionOutcome)>,
420 signatures_receiver: Receiver<(PeerId, schnorr::Signature)>,
421 _connections: DynP2PConnections<P2PMessage>,
422 ) -> Option<SignedSessionOutcome> {
423 let mut item_index = 0;
426
427 let mut index_broadcast_interval = tokio::time::interval(Duration::from_secs(3));
429
430 let mut request_signed_session_outcome = Box::pin(async {
431 self.request_signed_session_outcome(&self.federation_api, session_index)
432 .await
433 });
434
435 loop {
439 tokio::select! {
440 result = ordered_unit_receiver.recv() => {
441 let ordered_unit = result.ok()?;
442
443 if ordered_unit.round >= self.cfg.consensus.broadcast_rounds_per_session {
444 info!(
445 target: LOG_CONSENSUS,
446 session_index,
447 "Reached Aleph BFT round limit, stopping item collection"
448 );
449 break;
450 }
451
452 if let Some(UnitData::Batch(bytes)) = ordered_unit.data {
453 if ordered_unit.creator == self.identity() {
454 match timestamp_receiver.try_recv() {
455 Ok(timestamp) => {
456 let latency = match *self.ord_latency_sender.borrow() {
457 Some(latency) => (9 * latency + timestamp.elapsed()) / 10,
458 None => timestamp.elapsed()
459 };
460
461 self.ord_latency_sender.send_replace(Some(latency));
462
463 CONSENSUS_ORDERING_LATENCY_SECONDS.observe(timestamp.elapsed().as_secs_f64());
464 }
465 Err(err) => {
466 debug!(target: LOG_CONSENSUS, err = %err.fmt_compact(), "Missing submission timestamp. This is normal in recovery");
467 }
468 }
469 }
470
471 match Vec::<ConsensusItem>::consensus_decode_whole(&bytes, &self.decoders()) {
472 Ok(items) => {
473 for item in items {
474 if let Ok(()) = self.process_consensus_item(
475 session_index,
476 item_index,
477 item,
478 ordered_unit.creator
479 ).await {
480 item_index += 1;
481 }
482 }
483 }
484 Err(err) => {
485 error!(
486 target: LOG_CONSENSUS,
487 session_index,
488 peer = %ordered_unit.creator,
489 err = %err.fmt_compact(),
490 "Failed to decode consensus items from peer"
491 );
492 }
493 }
494 }
495 },
496 signed_session_outcome = &mut request_signed_session_outcome => {
498 info!(
499 target: LOG_CONSENSUS,
500 ?session_index,
501 "Recovered signed session outcome from peers while processing consensus items"
502 );
503
504 let pending_accepted_items = self.pending_accepted_items().await;
505
506 let (processed, unprocessed) = signed_session_outcome
508 .session_outcome
509 .items
510 .split_at(pending_accepted_items.len());
511
512 info!(
513 target: LOG_CONSENSUS,
514 session_index,
515 processed = %processed.len(),
516 unprocessed = %unprocessed.len(),
517 "Processing remaining items..."
518 );
519
520 assert!(
521 processed.iter().eq(pending_accepted_items.iter()),
522 "Consensus Failure: pending accepted items disagree with federation consensus"
523 );
524
525 for (accepted_item, item_index) in unprocessed.iter().zip(processed.len()..) {
526 if let Err(err) = self.process_consensus_item(
527 session_index,
528 item_index as u64,
529 accepted_item.item.clone(),
530 accepted_item.peer
531 ).await {
532 panic!(
533 "Consensus Failure: rejected item accepted by federation consensus: {accepted_item:?}, items: {}+{}, session_idx: {session_index}, item_idx: {item_index}, err: {err}",
534 processed.len(),
535 unprocessed.len(),
536 );
537 }
538 }
539
540 return Some(signed_session_outcome);
541 },
542 result = signed_outcomes_receiver.recv() => {
543 let (peer_id, p2p_outcome) = result.ok()?;
544
545 if self.validate_signed_session_outcome(&p2p_outcome, session_index) {
547 info!(
548 target: LOG_CONSENSUS,
549 session_index,
550 peer_id = %peer_id,
551 "Received SignedSessionOutcome via P2P while collection signatures"
552 );
553
554 let pending_accepted_items = self.pending_accepted_items().await;
555
556 let (processed, unprocessed) = p2p_outcome
558 .session_outcome
559 .items
560 .split_at(pending_accepted_items.len());
561
562 info!(
563 target: LOG_CONSENSUS,
564 ?session_index,
565 processed = %processed.len(),
566 unprocessed = %unprocessed.len(),
567 "Processing remaining items..."
568 );
569
570 assert!(
571 processed.iter().eq(pending_accepted_items.iter()),
572 "Consensus Failure: pending accepted items disagree with federation consensus"
573 );
574
575 for (accepted_item, item_index) in unprocessed.iter().zip(processed.len()..) {
576 if let Err(err) = self.process_consensus_item(
577 session_index,
578 item_index as u64,
579 accepted_item.item.clone(),
580 accepted_item.peer
581 ).await {
582 panic!(
583 "Consensus Failure: rejected item accepted by federation consensus: {accepted_item:?}, items: {}+{}, session_idx: {session_index}, item_idx: {item_index}, err: {err}",
584 processed.len(),
585 unprocessed.len(),
586 );
587 }
588 }
589
590 info!(
591 target: LOG_CONSENSUS,
592 ?session_index,
593 peer_id = %peer_id,
594 "Successfully recovered session via P2P"
595 );
596
597 return Some(p2p_outcome);
598 }
599
600 debug!(
601 target: LOG_CONSENSUS,
602 %peer_id,
603 "Invalid P2P SignedSessionOutcome"
604 );
605 }
606 _ = index_broadcast_interval.tick() => {
607 }
613 }
614 }
615
616 let items = self.pending_accepted_items().await;
617
618 assert_eq!(item_index, items.len() as u64);
619
620 info!(target: LOG_CONSENSUS, ?session_index, ?item_index, "Processed all items for session");
621
622 let session_outcome = SessionOutcome { items };
623
624 let header = session_outcome.header(session_index);
625
626 info!(
627 target: LOG_CONSENSUS,
628 ?session_index,
629 "Signing session header..."
630 );
631
632 let keychain = Keychain::new(&self.cfg);
633
634 let our_signature = keychain.sign_schnorr(&header);
635
636 #[allow(clippy::disallowed_methods)]
638 signature_sender.send(Some(our_signature)).ok()?;
639
640 let mut signatures = BTreeMap::from_iter([(self.identity(), our_signature)]);
641
642 let items_dump = tokio::sync::OnceCell::new();
643
644 let mut signature_broadcast_interval = tokio::time::interval(Duration::from_secs(1));
646
647 while signatures.len() < self.num_peers().threshold() {
650 tokio::select! {
651 result = ordered_unit_receiver.recv() => {
653 let ordered_unit = result.ok()?;
654
655 if let Some(UnitData::Signature(signature)) = ordered_unit.data {
656 info!(
657 target: LOG_CONSENSUS,
658 ?session_index,
659 peer = %ordered_unit.creator,
660 "Collected signature from peer via AlephBFT, verifying..."
661 );
662
663 if keychain.verify(&header, &signature, to_node_index(ordered_unit.creator)){
664 signatures.insert(ordered_unit.creator, schnorr::Signature::from_slice(&signature).expect("AlephBFT signature is valid"));
665 } else {
666 error!(
667 target: LOG_CONSENSUS,
668 ?session_index,
669 peer = %ordered_unit.creator,
670 "Consensus Failure: invalid header signature from peer"
671 );
672
673 items_dump.get_or_init(|| async {
674 for (idx, item) in session_outcome.items.iter().enumerate() {
675 info!(target: LOG_CONSENSUS, idx, item = %DebugConsensusItemCompact(item), "Item");
676 }
677 }).await;
678 }
679 }
680 }
681 result = signatures_receiver.recv() => {
682 let (peer_id, signature) = result.ok()?;
683
684 if keychain.verify_schnorr(&header, &signature, peer_id) {
685 signatures.insert(peer_id, signature);
686
687 info!(
688 target: LOG_CONSENSUS,
689 session_index,
690 peer_id = %peer_id,
691 "Collected signature from peer via P2P"
692 );
693 }
694
695 debug!(
696 target: LOG_CONSENSUS,
697 session_index,
698 peer_id = %peer_id,
699 "Invalid P2P signature from peer"
700 );
701 }
702 signed_session_outcome = &mut request_signed_session_outcome => {
704 info!(
705 target: LOG_CONSENSUS,
706 ?session_index,
707 "Recovered signed session outcome from peers while collecting signatures"
708 );
709
710 assert_eq!(
711 header,
712 signed_session_outcome.session_outcome.header(session_index),
713 "Consensus Failure: header disagrees with federation consensus"
714 );
715
716 return Some(signed_session_outcome);
717 },
718 result = signed_outcomes_receiver.recv() => {
719 let (peer_id, p2p_outcome) = result.ok()?;
720
721 if self.validate_signed_session_outcome(&p2p_outcome, session_index) {
722 assert_eq!(
723 header,
724 p2p_outcome.session_outcome.header(session_index),
725 "Consensus Failure: header disagrees with federation consensus"
726 );
727
728 info!(
729 target: LOG_CONSENSUS,
730 session_index,
731 %peer_id,
732 "Recovered session via P2P while collecting signatures"
733 );
734
735 return Some(p2p_outcome);
736 }
737
738 debug!(
739 target: LOG_CONSENSUS,
740 %peer_id,
741 "Invalid P2P SignedSessionOutcome"
742 );
743 }
744 _ = signature_broadcast_interval.tick() => {
745 }
751 _ = index_broadcast_interval.tick() => {
752 }
758 }
759 }
760
761 info!(
762 target: LOG_CONSENSUS,
763 session_index,
764 "Successfully collected threshold of signatures"
765 );
766
767 Some(SignedSessionOutcome {
768 session_outcome,
769 signatures,
770 })
771 }
772
773 #[allow(unused)]
775 fn random_peer(&self) -> PeerId {
776 self.num_peers()
777 .peer_ids()
778 .filter(|p| *p != self.identity())
779 .choose(&mut rand::thread_rng())
780 .expect("We have at least three peers")
781 }
782
783 fn validate_signed_session_outcome(
785 &self,
786 outcome: &SignedSessionOutcome,
787 session_index: u64,
788 ) -> bool {
789 if outcome.signatures.len() != self.num_peers().threshold() {
790 return false;
791 }
792
793 let keychain = Keychain::new(&self.cfg);
794 let header = outcome.session_outcome.header(session_index);
795
796 outcome
797 .signatures
798 .iter()
799 .all(|(signer_id, sig)| keychain.verify_schnorr(&header, sig, *signer_id))
800 }
801
802 fn decoders(&self) -> ModuleDecoderRegistry {
803 self.modules.decoder_registry()
804 }
805
806 pub async fn pending_accepted_items(&self) -> Vec<AcceptedItem> {
807 self.db
808 .begin_transaction_nc()
809 .await
810 .find_by_prefix(&AcceptedItemPrefix)
811 .await
812 .map(|entry| entry.1)
813 .collect()
814 .await
815 }
816
817 pub async fn complete_session(
818 &self,
819 session_index: u64,
820 signed_session_outcome: SignedSessionOutcome,
821 ) {
822 let mut dbtx = self.db.begin_transaction().await;
823
824 dbtx.remove_by_prefix(&AlephUnitsPrefix).await;
825
826 dbtx.remove_by_prefix(&AcceptedItemPrefix).await;
827
828 if dbtx
829 .insert_entry(
830 &SignedSessionOutcomeKey(session_index),
831 &signed_session_outcome,
832 )
833 .await
834 .is_some()
835 {
836 panic!("We tried to overwrite a signed session outcome");
837 }
838
839 super::session_cache::publish_on_commit(
840 &mut dbtx,
841 self.completed_session_sender.clone(),
842 session_index,
843 &signed_session_outcome,
844 );
845 dbtx.commit_tx_result()
846 .await
847 .expect("This is the only place where we write to this key");
848 }
849
850 fn db_checkpoints_dir(&self) -> PathBuf {
852 self.data_dir.join(DB_CHECKPOINTS_DIR)
853 }
854
855 fn initialize_checkpoint_directory(&self, current_session: u64) -> anyhow::Result<()> {
859 let checkpoint_dir = self.db_checkpoints_dir();
860
861 if checkpoint_dir.exists() {
862 debug!(
863 target: LOG_CONSENSUS,
864 ?current_session,
865 "Removing database checkpoints up to `current_session`"
866 );
867
868 for checkpoint in fs::read_dir(checkpoint_dir)?.flatten() {
869 if let Ok(file_name) = checkpoint.file_name().into_string()
871 && let Ok(session) = file_name.parse::<u64>()
872 && current_session >= self.db_checkpoint_retention
873 && session < current_session - self.db_checkpoint_retention
874 {
875 fs::remove_dir_all(checkpoint.path())?;
876 }
877 }
878 } else {
879 fs::create_dir_all(&checkpoint_dir)?;
880 }
881
882 Ok(())
883 }
884
885 fn checkpoint_database(&self, session_index: u64) {
889 if self.db_checkpoint_retention == 0 {
892 return;
893 }
894
895 let checkpoint_dir = self.db_checkpoints_dir();
896 let session_checkpoint_dir = checkpoint_dir.join(format!("{session_index}"));
897
898 {
899 let _timing = timing::TimeReporter::new("database-checkpoint").level(Level::TRACE);
900 match self.db.checkpoint(&session_checkpoint_dir) {
901 Ok(()) => {
902 debug!(target: LOG_CONSENSUS, ?session_checkpoint_dir, ?session_index, "Created db checkpoint");
903 }
904 Err(err) => {
905 warn!(target: LOG_CONSENSUS, ?session_checkpoint_dir, ?session_index, err = %err.fmt_compact(), "Could not create db checkpoint");
906 }
907 }
908 }
909
910 {
911 let _timing = timing::TimeReporter::new("remove-database-checkpoint").level(Level::TRACE);
913 if let Err(err) = self.delete_old_database_checkpoint(session_index, &checkpoint_dir) {
914 warn!(target: LOG_CONSENSUS, err = %err.fmt_compact(), "Could not delete old checkpoints");
915 }
916 }
917 }
918
919 fn delete_old_database_checkpoint(
922 &self,
923 session_index: u64,
924 checkpoint_dir: &Path,
925 ) -> anyhow::Result<()> {
926 if self.db_checkpoint_retention > session_index {
927 return Ok(());
928 }
929
930 let delete_session_index = session_index - self.db_checkpoint_retention;
931 let checkpoint_to_delete = checkpoint_dir.join(delete_session_index.to_string());
932 if checkpoint_to_delete.exists() {
933 fs::remove_dir_all(checkpoint_to_delete)?;
934 }
935
936 Ok(())
937 }
938
939 #[instrument(target = LOG_CONSENSUS, skip(self, item), level = "info")]
940 pub async fn process_consensus_item(
941 &self,
942 session_index: u64,
943 item_index: u64,
944 item: ConsensusItem,
945 peer: PeerId,
946 ) -> anyhow::Result<()> {
947 let _timing = timing::TimeReporter::new("process_consensus_item").level(Level::TRACE);
948
949 let timing_prom = CONSENSUS_ITEM_PROCESSING_DURATION_SECONDS
950 .with_label_values(&[&peer.to_usize().to_string()])
951 .start_timer();
952
953 trace!(
954 target: LOG_CONSENSUS,
955 %peer,
956 item = ?DebugConsensusItem(&item),
957 "Processing consensus item"
958 );
959
960 self.ci_status_senders
961 .get(&peer)
962 .expect("No ci status sender for peer")
963 .send_replace(Some(session_index));
964
965 CONSENSUS_PEER_CONTRIBUTION_SESSION_IDX
966 .with_label_values(&[
967 &self.cfg.local.identity.to_usize().to_string(),
968 &peer.to_usize().to_string(),
969 ])
970 .set(session_index as i64);
971
972 let mut attempt: usize = 1;
973
974 let outcome = loop {
975 match self
976 .process_consensus_item_attempt(item_index, &item, peer)
977 .await
978 {
979 Ok(outcome) => break outcome,
980 Err(err) => {
981 assert!(
987 matches!(err, DatabaseError::SnapshotTooOld(_)),
988 "Committing consensus item failed: {err}"
989 );
990
991 assert!(
992 attempt < MAX_ITEM_PROCESSING_ATTEMPTS,
993 "Committing consensus item failed after {attempt} attempts: {err}"
994 );
995
996 warn!(
997 target: LOG_CONSENSUS,
998 %peer,
999 item_index,
1000 attempt,
1001 err = %err.fmt_compact(),
1002 "Consensus item transaction could not be validated - reprocessing item"
1003 );
1004
1005 attempt += 1;
1006 }
1007 }
1008 };
1009
1010 outcome?;
1011
1012 timing_prom.observe_duration();
1013
1014 Ok(())
1015 }
1016
1017 async fn process_consensus_item_attempt(
1023 &self,
1024 item_index: u64,
1025 item: &ConsensusItem,
1026 peer: PeerId,
1027 ) -> DatabaseResult<anyhow::Result<()>> {
1028 let mut dbtx = self.db.begin_transaction().await;
1029
1030 dbtx.ignore_uncommitted();
1031
1032 if let Some(existing_item) = dbtx.get_value(&AcceptedItemKey(item_index)).await {
1036 if existing_item.item == *item && existing_item.peer == peer {
1037 return Ok(Ok(()));
1038 }
1039
1040 return Ok(Err(anyhow!(
1041 "Item was discarded previously: existing: {existing_item:?} {}, current: {item:?}, {peer}",
1042 existing_item.peer
1043 )));
1044 }
1045
1046 if let Err(err) = self
1047 .process_consensus_item_with_db_transaction(&mut dbtx.to_ref_nc(), item, peer)
1048 .await
1049 {
1050 trace!(
1052 target: LOG_CONSENSUS,
1053 %peer,
1054 item = ?DebugConsensusItem(item),
1055 err = %err.fmt_compact(),
1056 "Rejected consensus item"
1057 );
1058
1059 return Ok(Err(err));
1060 }
1061
1062 dbtx.warn_uncommitted();
1065
1066 dbtx.insert_entry(
1067 &AcceptedItemKey(item_index),
1068 &AcceptedItem {
1069 item: item.clone(),
1070 peer,
1071 },
1072 )
1073 .await;
1074
1075 debug!(
1076 target: LOG_CONSENSUS,
1077 %peer,
1078 item = ?DebugConsensusItem(item),
1079 "Processed consensus item"
1080 );
1081 let mut audit = Audit::default();
1082
1083 for (module_instance_id, kind, module) in self.modules.iter_modules() {
1084 let _module_audit_timing =
1085 TimeReporter::new(format!("audit module {module_instance_id}")).level(Level::TRACE);
1086
1087 let timing_prom = CONSENSUS_ITEM_PROCESSING_MODULE_AUDIT_DURATION_SECONDS
1088 .with_label_values(&[
1089 MODULE_INSTANCE_ID_GLOBAL.to_string().as_str(),
1090 kind.as_str(),
1091 ])
1092 .start_timer();
1093
1094 module
1095 .audit(
1096 &mut dbtx
1097 .to_ref_with_prefix_module_id(module_instance_id)
1098 .0
1099 .into_nc(),
1100 &mut audit,
1101 module_instance_id,
1102 )
1103 .await;
1104
1105 timing_prom.observe_duration();
1106 }
1107
1108 assert!(
1109 audit
1110 .net_assets()
1111 .expect("Overflow while checking balance sheet")
1112 .milli_sat
1113 >= 0,
1114 "Balance sheet of the fed has gone negative, this should never happen! {audit}"
1115 );
1116
1117 dbtx.commit_tx_result().await?;
1118
1119 self.accepted_item_sender.send_replace(());
1120
1121 CONSENSUS_ITEMS_PROCESSED_TOTAL
1125 .with_label_values(&[&peer.to_usize().to_string()])
1126 .inc();
1127
1128 Ok(Ok(()))
1129 }
1130
1131 async fn process_consensus_item_with_db_transaction(
1132 &self,
1133 dbtx: &mut DatabaseTransaction<'_>,
1134 consensus_item: &ConsensusItem,
1135 peer_id: PeerId,
1136 ) -> anyhow::Result<()> {
1137 self.decoders().assert_reject_mode();
1140
1141 match consensus_item {
1142 ConsensusItem::Module(module_item) => {
1143 let instance_id = module_item.module_instance_id();
1144
1145 let module_dbtx = &mut dbtx.to_ref_with_prefix_module_id(instance_id).0;
1146
1147 self.modules
1148 .get_expect(instance_id)
1149 .process_consensus_item(module_dbtx, module_item, peer_id)
1150 .await
1151 }
1152 ConsensusItem::Transaction(transaction) => {
1153 let txid = transaction.tx_hash();
1154 if dbtx
1155 .get_value(&AcceptedTransactionKey(txid))
1156 .await
1157 .is_some()
1158 {
1159 debug!(
1160 target: LOG_CONSENSUS,
1161 %txid,
1162 "Transaction already accepted"
1163 );
1164 bail!("Transaction is already accepted");
1165 }
1166
1167 let modules_ids = transaction
1168 .outputs
1169 .iter()
1170 .map(DynOutput::module_instance_id)
1171 .collect::<Vec<_>>();
1172
1173 process_transaction_with_dbtx(
1174 self.modules.clone(),
1175 dbtx,
1176 transaction,
1177 self.cfg.consensus.version,
1178 TxProcessingMode::Consensus,
1179 )
1180 .await
1181 .map_err(|error| anyhow!(error.to_string()))?;
1182
1183 debug!(target: LOG_CONSENSUS, %txid, "Transaction accepted");
1184 dbtx.insert_entry(&AcceptedTransactionKey(txid), &modules_ids)
1185 .await;
1186
1187 Ok(())
1188 }
1189 ConsensusItem::Default { variant, .. } => {
1190 warn!(
1195 target: LOG_CONSENSUS,
1196 "Minor consensus version mismatch: unexpected consensus item type: {variant}"
1197 );
1198
1199 bail!("Unexpected consensus item type: {variant}")
1200 }
1201 }
1202 }
1203
1204 async fn request_signed_session_outcome(
1205 &self,
1206 federation_api: &DynGlobalApi,
1207 index: u64,
1208 ) -> SignedSessionOutcome {
1209 let decoders = self.decoders();
1210 let keychain = Keychain::new(&self.cfg);
1211 let threshold = self.num_peers().threshold();
1212
1213 let filter_map = move |response: SerdeModuleEncoding<SignedSessionOutcome>| {
1214 let signed_session_outcome = response
1215 .try_into_inner(&decoders)
1216 .map_err(|x| ServerError::ResponseDeserialization(Box::new(x)))?;
1217 let header = signed_session_outcome.session_outcome.header(index);
1218 if signed_session_outcome.signatures.len() == threshold
1219 && signed_session_outcome
1220 .signatures
1221 .iter()
1222 .all(|(peer_id, sig)| keychain.verify_schnorr(&header, sig, *peer_id))
1223 {
1224 Ok(signed_session_outcome)
1225 } else {
1226 Err(ServerError::InvalidResponse(
1227 "Invalid signatures".to_string(),
1228 ))
1229 }
1230 };
1231
1232 federation_api
1233 .request_with_strategy_retry(
1234 FilterMap::new(filter_map.clone()),
1235 AWAIT_SIGNED_SESSION_OUTCOME_ENDPOINT.to_string(),
1236 ApiRequestErased::new(index),
1237 )
1238 .await
1239 }
1240
1241 async fn get_finished_session_count(&self) -> u64 {
1244 get_finished_session_count_static(&mut self.db.begin_transaction_nc().await).await
1245 }
1246}
1247
1248fn due_shutdown(
1253 scheduled: Option<ScheduledShutdown>,
1254 completed_session: u64,
1255) -> Option<ShutdownRequest> {
1256 scheduled
1257 .filter(|scheduled| scheduled.session <= completed_session)
1258 .map(|scheduled| scheduled.request)
1259}
1260
1261pub async fn get_finished_session_count_static(dbtx: &mut DatabaseTransaction<'_>) -> u64 {
1262 dbtx.find_by_prefix_sorted_descending(&SignedSessionOutcomePrefix)
1263 .await
1264 .next()
1265 .await
1266 .map_or(0, |entry| (entry.0.0) + 1)
1267}
1268
1269#[cfg(test)]
1270mod tests;