fedimint_cli/
db.rs

1//! Database keys for fedimint-cli
2//!
3//! These keys use the UserData prefix (0xb0) as recommended for external/CLI
4//! data that shouldn't be in the core client database schema.
5
6use fedimint_client::db::DbKeyPrefix as ClientDbKeyPrefix;
7use fedimint_core::db::{Database, IDatabaseTransactionOpsCoreTyped};
8use fedimint_core::encoding::{Decodable, Encodable};
9use fedimint_core::{PeerId, impl_db_record};
10use serde::{Deserialize, Serialize};
11
12/// Sub-prefix for CLI-specific data under UserData (0xb0)
13const CLI_USER_DATA_SUB_PREFIX: u8 = 0x00;
14
15/// Get a CLI-specific database with the UserData prefix already applied
16pub fn cli_database(db: &Database) -> Database {
17    db.with_prefix(vec![
18        ClientDbKeyPrefix::UserData as u8,
19        CLI_USER_DATA_SUB_PREFIX,
20    ])
21}
22
23/// Key prefix enum for CLI database keys
24#[repr(u8)]
25#[derive(Clone, Debug)]
26pub enum CliDbKeyPrefix {
27    AdminCreds = 0x00,
28}
29
30impl std::fmt::Display for CliDbKeyPrefix {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        write!(
33            f,
34            "{}",
35            match self {
36                CliDbKeyPrefix::AdminCreds => "AdminCreds",
37            }
38        )
39    }
40}
41
42/// Key for storing admin credentials
43#[derive(Debug, Clone, Encodable, Decodable)]
44pub struct AdminCredsKey;
45
46/// The stored admin credentials value
47#[derive(Debug, Clone, Encodable, Decodable, Serialize, Deserialize)]
48pub struct StoredAdminCreds {
49    /// Guardian's own peer_id
50    pub peer_id: PeerId,
51    /// Authentication password (stored as String, will be wrapped in ApiAuth
52    /// when used)
53    pub auth: String,
54}
55
56impl_db_record!(
57    key = AdminCredsKey,
58    value = StoredAdminCreds,
59    db_prefix = CliDbKeyPrefix::AdminCreds,
60);
61
62/// Load stored admin credentials from the CLI database
63pub async fn load_admin_creds(db: &Database) -> Option<StoredAdminCreds> {
64    let cli_db = cli_database(db);
65    cli_db
66        .begin_transaction_nc()
67        .await
68        .get_value(&AdminCredsKey)
69        .await
70}
71
72/// Store admin credentials in the CLI database
73pub async fn store_admin_creds(db: &Database, creds: &StoredAdminCreds) {
74    let cli_db = cli_database(db);
75    let mut dbtx = cli_db.begin_transaction().await;
76    dbtx.insert_entry(&AdminCredsKey, creds).await;
77    dbtx.commit_tx().await;
78}