fedimint_server/consensus/aleph_bft/
backup.rs1use std::collections::BTreeSet;
2
3use async_trait::async_trait;
4use bitcoin::hashes::{Hash as _, sha256};
5use fedimint_core::db::{Database, IDatabaseTransactionOpsCoreTyped};
6use futures::StreamExt as _;
7use tracing::info;
8
9use crate::LOG_CONSENSUS;
10use crate::consensus::db::{AlephUnitsKey, AlephUnitsPrefix};
11
12pub struct BackupReader {
21 db: Database,
22}
23
24impl BackupReader {
25 pub fn new(db: Database) -> Self {
26 Self { db }
27 }
28}
29
30#[async_trait]
31impl aleph_bft::BackupReader for BackupReader {
32 async fn read(&mut self) -> std::io::Result<Vec<u8>> {
33 let mut dbtx = self.db.begin_transaction_nc().await;
34
35 let mut stored = 0_usize;
36 let mut loaded = BTreeSet::new();
37 let mut backup = Vec::new();
38
39 let mut units = dbtx.find_by_prefix(&AlephUnitsPrefix).await;
40 while let Some((_, unit)) = units.next().await {
41 stored += 1;
42
43 if loaded.insert(sha256::Hash::hash(&unit)) {
46 backup.extend_from_slice(&unit);
47 }
48 }
49
50 if stored != 0 {
51 info!(
52 target: LOG_CONSENSUS,
53 units_len = %stored,
54 unique_units_len = %loaded.len(),
55 "Recovering from an in-session-shutdown"
56 );
57 }
58
59 Ok(backup)
60 }
61}
62
63pub struct BackupWriter {
73 db: Database,
74 units_index: u64,
75 buffer: Vec<Vec<u8>>,
76}
77
78impl BackupWriter {
79 pub async fn new(db: Database) -> Self {
80 let units_index = db
81 .begin_transaction_nc()
82 .await
83 .find_by_prefix_sorted_descending(&AlephUnitsPrefix)
84 .await
85 .next()
86 .await
87 .map_or(0, |entry| (entry.0.0) + 1);
88
89 Self {
90 db,
91 units_index,
92 buffer: Vec::new(),
93 }
94 }
95}
96
97#[async_trait]
98impl aleph_bft::BackupWriter for BackupWriter {
99 async fn append(&mut self, data: &[u8], flush: bool) -> std::io::Result<()> {
100 self.buffer.push(data.to_owned());
101
102 if !flush {
103 return Ok(());
104 }
105
106 let mut dbtx = self.db.begin_transaction().await;
107
108 for unit in self.buffer.drain(..) {
109 dbtx.insert_new_entry(&AlephUnitsKey(self.units_index), &unit)
110 .await;
111
112 self.units_index += 1;
113 }
114
115 dbtx.commit_tx_result()
116 .await
117 .expect("This is the only place where we write to this key");
118
119 Ok(())
120 }
121}
122
123#[cfg(test)]
124mod tests;