fedimint_dummy_server/
db.rs

1use fedimint_core::db::IDatabaseTransactionOpsCoreTyped;
2use fedimint_core::encoding::{Decodable, Encodable};
3use fedimint_core::secp256k1::PublicKey;
4use fedimint_core::{Amount, OutPoint, impl_db_lookup, impl_db_record};
5use fedimint_server_core::migration::ServerModuleDbMigrationFnContext;
6use futures::StreamExt;
7use serde::Serialize;
8use strum_macros::EnumIter;
9
10use crate::{Dummy, DummyOutputOutcome};
11
12/// Namespaces DB keys for this module
13#[repr(u8)]
14#[derive(Clone, EnumIter, Debug)]
15pub enum DbKeyPrefix {
16    Funds = 0x01,
17    Outcome = 0x02,
18}
19
20// TODO: Boilerplate-code
21impl std::fmt::Display for DbKeyPrefix {
22    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
23        write!(f, "{self:?}")
24    }
25}
26
27/// Example old version 0 of DB entries
28// TODO: can we simplify this by just using macros?
29#[derive(Debug, Clone, Encodable, Decodable, Eq, PartialEq, Hash, Serialize)]
30pub struct DummyFundsKeyV0(pub PublicKey);
31
32#[derive(Debug, Encodable, Decodable)]
33pub struct DummyFundsKeyPrefixV0;
34
35impl_db_record!(
36    key = DummyFundsKeyV0,
37    value = (),
38    db_prefix = DbKeyPrefix::Funds,
39);
40impl_db_lookup!(key = DummyFundsKeyV0, query_prefix = DummyFundsKeyPrefixV0);
41
42/// Lookup funds for a user by key or prefix
43#[derive(Debug, Clone, Encodable, Decodable, Eq, PartialEq, Hash, Serialize)]
44pub struct DummyFundsKeyV1(pub PublicKey);
45
46#[derive(Debug, Encodable, Decodable)]
47pub struct DummyFundsPrefixV1;
48
49impl_db_record!(
50    key = DummyFundsKeyV1,
51    value = Amount,
52    db_prefix = DbKeyPrefix::Funds,
53);
54impl_db_lookup!(key = DummyFundsKeyV1, query_prefix = DummyFundsPrefixV1);
55
56/// Example DB migration from version 0 to version 1
57pub async fn migrate_to_v1(
58    mut ctx: ServerModuleDbMigrationFnContext<'_, Dummy>,
59) -> Result<(), anyhow::Error> {
60    let mut dbtx = ctx.dbtx();
61    // Select old entries
62    let v0_entries = dbtx
63        .find_by_prefix(&DummyFundsKeyPrefixV0)
64        .await
65        .collect::<Vec<(DummyFundsKeyV0, ())>>()
66        .await;
67
68    // Remove old entries
69    dbtx.remove_by_prefix(&DummyFundsKeyPrefixV0).await;
70
71    // Migrate to new entries
72    for (v0_key, _v0_val) in v0_entries {
73        let v1_key = DummyFundsKeyV1(v0_key.0);
74        dbtx.insert_new_entry(&v1_key, &Amount::ZERO).await;
75    }
76    Ok(())
77}
78
79/// Lookup tx outputs by key or prefix
80#[derive(Debug, Clone, Encodable, Decodable, Eq, PartialEq, Hash, Serialize)]
81pub struct DummyOutcomeKey(pub OutPoint);
82
83#[derive(Debug, Encodable, Decodable)]
84pub struct DummyOutcomePrefix;
85
86impl_db_record!(
87    key = DummyOutcomeKey,
88    value = DummyOutputOutcome,
89    db_prefix = DbKeyPrefix::Outcome,
90);
91impl_db_lookup!(key = DummyOutcomeKey, query_prefix = DummyOutcomePrefix);