Skip to main content

fedimint_server/
db.rs

1use std::collections::BTreeSet;
2
3use bitcoin::hex::DisplayHex as _;
4use fedimint_core::db::{
5    DatabaseTransaction, IDatabaseTransactionOpsCore as _, MODULE_GLOBAL_PREFIX,
6};
7use fedimint_core::encoding::{Decodable, Encodable};
8use fedimint_core::impl_db_record;
9use futures::StreamExt as _;
10use strum::{EnumIter, IntoEnumIterator as _};
11
12#[repr(u8)]
13#[derive(Clone, EnumIter, Debug)]
14pub enum DbKeyPrefix {
15    AcceptedItem = 0x01,
16    AcceptedTransaction = 0x02,
17    SignedSessionOutcome = 0x04,
18    AlephUnits = 0x05,
19    // TODO: do we want to split the server DB into consensus/non-consensus?
20    ApiAnnouncements = 0x06,
21    ServerInfo = 0x07,
22    GuardianMetadata = 0x08,
23    PeerAvailability = 0x09,
24    PeerAvailabilityResets = 0x0a,
25
26    DatabaseVersion = fedimint_core::db::DbKeyPrefix::DatabaseVersion as u8,
27    ClientBackup = fedimint_core::db::DbKeyPrefix::ClientBackup as u8,
28    Module = MODULE_GLOBAL_PREFIX,
29}
30
31pub(crate) async fn verify_server_db_integrity_dbtx(dbtx: &mut DatabaseTransaction<'_>) {
32    let prefixes: BTreeSet<u8> = DbKeyPrefix::iter().map(|prefix| prefix as u8).collect();
33
34    let mut records = dbtx.raw_find_by_prefix(&[]).await.expect("DB fail");
35    while let Some((k, v)) = records.next().await {
36        // We don't want to waste time checking these
37        if k[0] == DbKeyPrefix::Module as u8 {
38            break;
39        }
40
41        assert!(
42            prefixes.contains(&k[0]),
43            "Unexpected server db record found: {}: {}",
44            k.as_hex(),
45            v.as_hex()
46        );
47    }
48}
49
50impl std::fmt::Display for DbKeyPrefix {
51    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
52        write!(f, "{self:?}")
53    }
54}
55
56#[derive(Clone, Debug, Encodable, Decodable)]
57pub struct ServerInfoKey;
58
59#[derive(Clone, Debug, Encodable, Decodable)]
60pub struct ServerInfo {
61    /// The initial version that set up the consensus
62    pub init_version: String,
63    /// The last version that passed db migration checks
64    pub last_version: String,
65}
66
67impl_db_record!(
68    key = ServerInfoKey,
69    value = ServerInfo,
70    db_prefix = DbKeyPrefix::ServerInfo,
71    notify_on_modify = false,
72);