Skip to main content

fedimint_server/consensus/aleph_bft/
backup.rs

1use 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
12/// Reads the AlephBFT backup, keeping one copy of each unit.
13///
14/// Before fedimint-aleph-bft 0.37.0, AlephBFT handed every unit it replayed
15/// from the backup to the writer again, so each restart within a session
16/// appended a full copy of the session's units. A guardian upgrading out of a
17/// stalled session can still hold such a backup, and decoding every copy at
18/// once can exhaust its memory before it gets to complete the session that
19/// deletes it.
20pub 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            // Keep the first copy: it precedes every unit stored after it, so
44            // the units still appear after their parents.
45            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
63/// Writes the AlephBFT backup with one synced database transaction per unit
64/// of ours instead of one per unit.
65///
66/// AlephBFT only needs our own units to be durable before `append` returns,
67/// since it broadcasts them right after. The units of other peers are held in
68/// memory until then and written in the same transaction, which persists them
69/// before the unit of ours that may reference them. A crash therefore loses at
70/// most units of other peers newer than our last unit, which leaves the backup
71/// consistent and which we fetch from our peers again.
72pub 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;