fedimint_dbtool/
dump.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
use std::collections::BTreeMap;
use std::path::PathBuf;

use anyhow::Context;
use erased_serde::Serialize;
use fedimint_client::db::ClientConfigKey;
use fedimint_client::module::init::ClientModuleInitRegistry;
use fedimint_core::config::{ClientConfig, CommonModuleInitRegistry, ServerModuleInitRegistry};
use fedimint_core::core::ModuleKind;
use fedimint_core::db::{
    Database, DatabaseTransaction, DatabaseVersionKey, IDatabaseTransactionOpsCore,
    IDatabaseTransactionOpsCoreTyped,
};
use fedimint_core::encoding::Encodable;
use fedimint_core::module::registry::{ModuleDecoderRegistry, ModuleRegistry};
use fedimint_rocksdb::RocksDbReadOnly;
use fedimint_server::config::io::read_server_config;
use fedimint_server::config::ServerConfig;
use fedimint_server::consensus::db as ConsensusRange;
use fedimint_server::net::api::announcement::ApiAnnouncementPrefix;
use futures::StreamExt;
use ln_gateway::Gateway;
use strum::IntoEnumIterator;

macro_rules! push_db_pair_items_no_serde {
    ($dbtx:ident, $prefix_type:expr, $key_type:ty, $value_type:ty, $map:ident, $key_literal:literal) => {
        let db_items = IDatabaseTransactionOpsCoreTyped::find_by_prefix($dbtx, &$prefix_type)
            .await
            .map(|(key, val)| {
                (
                    Encodable::consensus_encode_to_hex(&key),
                    SerdeWrapper::from_encodable(&val),
                )
            })
            .collect::<BTreeMap<_, _>>()
            .await;

        $map.insert($key_literal.to_string(), Box::new(db_items));
    };
}

#[derive(Debug, serde::Serialize)]
struct SerdeWrapper(#[serde(with = "hex::serde")] Vec<u8>);

impl SerdeWrapper {
    fn from_encodable<T: Encodable>(e: &T) -> SerdeWrapper {
        SerdeWrapper(e.consensus_encode_to_vec())
    }
}

/// Structure to hold the deserialized structs from the database.
/// Also includes metadata on which sections of the database to read.
pub struct DatabaseDump {
    serialized: BTreeMap<String, Box<dyn Serialize>>,
    read_only_db: Database,
    modules: Vec<String>,
    prefixes: Vec<String>,
    server_cfg: Option<ServerConfig>,
    module_inits: ServerModuleInitRegistry,
    client_cfg: Option<ClientConfig>,
    client_module_inits: ClientModuleInitRegistry,
}

impl DatabaseDump {
    pub async fn new(
        cfg_dir: PathBuf,
        data_dir: String,
        password: String,
        module_inits: ServerModuleInitRegistry,
        client_module_inits: ClientModuleInitRegistry,
        modules: Vec<String>,
        prefixes: Vec<String>,
    ) -> anyhow::Result<DatabaseDump> {
        let Ok(read_only_rocks_db) = RocksDbReadOnly::open_read_only(data_dir.clone()) else {
            panic!("Error reading RocksDB database. Quitting...");
        };

        let read_only_db = Database::new(read_only_rocks_db, ModuleRegistry::default());

        let (server_cfg, client_cfg, decoders) = if let Ok(cfg) =
            read_server_config(&password, &cfg_dir).context("Failed to read server config")
        {
            // Successfully read the server's config, that means this database is a server
            // db
            let decoders = module_inits
                .available_decoders(cfg.iter_module_instances())
                .unwrap()
                .with_fallback();
            (Some(cfg), None, decoders)
        } else {
            // Check if this database is a client database by reading the `ClientConfig`
            // from the database.

            let mut dbtx = read_only_db.begin_transaction_nc().await;
            let client_cfg_or = dbtx.get_value(&ClientConfigKey).await;

            if let Some(client_cfg) = client_cfg_or {
                // Successfully read the client config, that means this database is a client db
                let kinds = client_cfg.modules.iter().map(|(k, v)| (*k, &v.kind));
                let decoders = client_module_inits
                    .available_decoders(kinds)
                    .unwrap()
                    .with_fallback();
                (None, Some(client_cfg), decoders)
            } else {
                (None, None, ModuleDecoderRegistry::default())
            }
        };

        Ok(DatabaseDump {
            serialized: BTreeMap::new(),
            read_only_db: read_only_db.with_decoders(decoders),
            modules,
            prefixes,
            server_cfg,
            module_inits,
            client_module_inits,
            client_cfg,
        })
    }
}

impl DatabaseDump {
    /// Prints the contents of the `BTreeMap` to a pretty JSON string
    fn print_database(&self) {
        let json = serde_json::to_string_pretty(&self.serialized).unwrap();
        println!("{json}");
    }

    async fn serialize_module(
        &mut self,
        module_id: &u16,
        kind: &ModuleKind,
        inits: CommonModuleInitRegistry,
    ) -> anyhow::Result<()> {
        if !self.modules.is_empty() && !self.modules.contains(&kind.to_string()) {
            return Ok(());
        }
        let mut dbtx = self.read_only_db.begin_transaction_nc().await;
        let db_version = dbtx.get_value(&DatabaseVersionKey(*module_id)).await;
        let mut isolated_dbtx = dbtx.to_ref_with_prefix_module_id(*module_id).0;

        match inits.get(kind) {
            None => {
                tracing::warn!(module_id, %kind, "Detected configuration for unsupported module");

                let mut module_serialized = BTreeMap::new();
                let filtered_prefixes = (0u8..=255).filter(|f| {
                    self.prefixes.is_empty()
                        || self.prefixes.contains(&f.to_string().to_lowercase())
                });

                let isolated_dbtx = &mut isolated_dbtx;

                for prefix in filtered_prefixes {
                    let db_items = isolated_dbtx
                        .raw_find_by_prefix(&[prefix])
                        .await?
                        .map(|(k, v)| {
                            (
                                k.consensus_encode_to_hex(),
                                Box::new(v.consensus_encode_to_hex()),
                            )
                        })
                        .collect::<BTreeMap<String, Box<_>>>()
                        .await;

                    module_serialized.extend(db_items);
                }
                self.serialized
                    .insert(format!("{kind}-{module_id}"), Box::new(module_serialized));
            }
            Some(init) => {
                let mut module_serialized = init
                    .dump_database(&mut isolated_dbtx.to_ref_nc(), self.prefixes.clone())
                    .await
                    .collect::<BTreeMap<String, _>>();

                if let Some(db_version) = db_version {
                    module_serialized.insert("Version".to_string(), Box::new(db_version));
                } else {
                    module_serialized
                        .insert("Version".to_string(), Box::new("Not Specified".to_string()));
                }

                self.serialized
                    .insert(format!("{kind}-{module_id}"), Box::new(module_serialized));
            }
        }

        Ok(())
    }

    async fn serialize_gateway(&mut self) -> anyhow::Result<()> {
        let mut dbtx = self.read_only_db.begin_transaction_nc().await;
        let gateway_serialized = Gateway::dump_database(&mut dbtx, self.prefixes.clone()).await;
        self.serialized
            .insert("gateway".to_string(), Box::new(gateway_serialized));
        Ok(())
    }

    /// Iterates through all the specified ranges in the database and retrieves
    /// the data for each range. Prints serialized contents at the end.
    pub async fn dump_database(&mut self) -> anyhow::Result<()> {
        if let Some(cfg) = self.server_cfg.clone() {
            if self.modules.is_empty() || self.modules.contains(&"consensus".to_string()) {
                self.retrieve_consensus_data().await;
            }

            for (module_id, module_cfg) in &cfg.consensus.modules {
                let kind = &module_cfg.kind;
                self.serialize_module(module_id, kind, self.module_inits.to_common())
                    .await?;
            }

            self.print_database();
            return Ok(());
        }

        if let Some(cfg) = self.client_cfg.clone() {
            for (module_id, module_cfg) in &cfg.modules {
                let kind = &module_cfg.kind;
                let mut modules = Vec::new();
                if let Some(module) = self.client_module_inits.get(kind) {
                    modules.push(module.to_dyn_common());
                }

                let registry = CommonModuleInitRegistry::from(modules);
                self.serialize_module(module_id, kind, registry).await?;
            }

            self.print_database();
            return Ok(());
        }

        self.serialize_gateway().await?;
        self.print_database();

        Ok(())
    }

    /// Iterates through each of the prefixes within the consensus range and
    /// retrieves the corresponding data.
    async fn retrieve_consensus_data(&mut self) {
        let filtered_prefixes = ConsensusRange::DbKeyPrefix::iter().filter(|prefix| {
            self.prefixes.is_empty() || self.prefixes.contains(&prefix.to_string().to_lowercase())
        });
        let mut dbtx = self.read_only_db.begin_transaction_nc().await;
        let mut consensus: BTreeMap<String, Box<dyn Serialize>> = BTreeMap::new();

        for table in filtered_prefixes {
            Self::write_serialized_consensus_range(table, &mut dbtx, &mut consensus).await;
        }

        self.serialized
            .insert("Consensus".to_string(), Box::new(consensus));
    }

    async fn write_serialized_consensus_range(
        table: ConsensusRange::DbKeyPrefix,
        dbtx: &mut DatabaseTransaction<'_>,
        consensus: &mut BTreeMap<String, Box<dyn Serialize>>,
    ) {
        match table {
            ConsensusRange::DbKeyPrefix::AcceptedItem => {
                push_db_pair_items_no_serde!(
                    dbtx,
                    ConsensusRange::AcceptedItemPrefix,
                    ConsensusRange::AcceptedItemKey,
                    fedimint_server::consensus::AcceptedItem,
                    consensus,
                    "Accepted Items"
                );
            }
            ConsensusRange::DbKeyPrefix::AcceptedTransaction => {
                push_db_pair_items_no_serde!(
                    dbtx,
                    ConsensusRange::AcceptedTransactionKeyPrefix,
                    ConsensusRange::AcceptedTransactionKey,
                    fedimint_server::consensus::AcceptedTransaction,
                    consensus,
                    "Accepted Transactions"
                );
            }
            ConsensusRange::DbKeyPrefix::SignedSessionOutcome => {
                push_db_pair_items_no_serde!(
                    dbtx,
                    ConsensusRange::SignedSessionOutcomePrefix,
                    ConsensusRange::SignedBlockKey,
                    fedimint_server::consensus::SignedBlock,
                    consensus,
                    "Signed Blocks"
                );
            }
            ConsensusRange::DbKeyPrefix::AlephUnits => {
                push_db_pair_items_no_serde!(
                    dbtx,
                    ConsensusRange::AlephUnitsPrefix,
                    ConsensusRange::AlephUnitsKey,
                    Vec<u8>,
                    consensus,
                    "Aleph Units"
                );
            }
            // Module is a global prefix for all module data
            ConsensusRange::DbKeyPrefix::Module => {}
            ConsensusRange::DbKeyPrefix::ApiAnnouncements => {
                push_db_pair_items_no_serde!(
                    dbtx,
                    ApiAnnouncementPrefix,
                    ApiAnnouncementKey,
                    fedimint_core::net::api_announcement::SignedApiAnnouncement,
                    consensus,
                    "API Announcements"
                );
            }
        }
    }
}