1#![deny(clippy::pedantic)]
2#![allow(clippy::missing_errors_doc)]
3#![allow(clippy::missing_panics_doc)]
4#![allow(clippy::module_name_repetitions)]
5#![allow(clippy::return_self_not_must_use)]
6
7pub mod envs;
8
9use std::path::{Path, PathBuf};
10
11use anyhow::Result;
12use bytes::Bytes;
13use clap::{Parser, Subcommand};
14use fedimint_client::module_init::ClientModuleInitRegistry;
15use fedimint_client_module::module::init::ClientModuleInit;
16use fedimint_core::db::{IDatabaseTransactionOpsCore, IRawDatabaseExt};
17use fedimint_core::util::{ensure_single_stdin, handle_version_hash_command, read_secret_file};
18use fedimint_ln_client::LightningClientInit;
19use fedimint_ln_server::LightningInit;
20use fedimint_logging::TracingSetup;
21use fedimint_meta_client::MetaClientInit;
22use fedimint_meta_server::MetaInit;
23use fedimint_mint_client::MintClientInit;
24use fedimint_mint_server::MintInit;
25use fedimint_server::core::{ServerModuleInit, ServerModuleInitRegistry};
26use fedimint_wallet_client::WalletClientInit;
27use fedimint_wallet_server::WalletInit;
28use futures::StreamExt;
29use hex::ToHex;
30
31use crate::dump::DatabaseDump;
32use crate::envs::{FM_DBTOOL_CONFIG_DIR_ENV, FM_DBTOOL_DATABASE_ENV};
33
34mod dump;
35#[cfg(test)]
36mod tests;
37
38#[derive(Debug, Clone, Parser)]
39#[command(version)]
40struct Options {
41 #[clap(long, env = FM_DBTOOL_DATABASE_ENV)]
42 database_dir: String,
43
44 #[clap(long, hide = true)]
45 no_modules: bool,
48
49 #[command(subcommand)]
50 command: DbCommand,
51}
52
53#[derive(Debug, Clone, Subcommand)]
56enum DbCommand {
57 List {
59 #[arg(
60 long,
61 required_unless_present = "prefix_file",
62 conflicts_with = "prefix_file"
63 )]
64 prefix: Option<String>,
65 #[arg(long)]
68 prefix_file: Option<PathBuf>,
69 },
70 Write {
73 #[arg(
74 long,
75 required_unless_present = "key_file",
76 conflicts_with = "key_file"
77 )]
78 key: Option<String>,
79 #[arg(long)]
82 key_file: Option<PathBuf>,
83 #[arg(
84 long,
85 required_unless_present = "value_file",
86 conflicts_with = "value_file"
87 )]
88 value: Option<String>,
89 #[arg(long)]
92 value_file: Option<PathBuf>,
93 },
94 Delete {
96 #[arg(
97 long,
98 required_unless_present = "key_file",
99 conflicts_with = "key_file"
100 )]
101 key: Option<String>,
102 #[arg(long)]
105 key_file: Option<PathBuf>,
106 },
107 DeletePrefix {
109 #[arg(
110 long,
111 required_unless_present = "prefix_file",
112 conflicts_with = "prefix_file"
113 )]
114 prefix: Option<String>,
115 #[arg(long)]
118 prefix_file: Option<PathBuf>,
119 },
120 Dump {
124 #[clap(long, env = FM_DBTOOL_CONFIG_DIR_ENV)]
125 cfg_dir: PathBuf,
126 #[arg(long, required = false)]
127 modules: Option<String>,
128 #[arg(long, required = false)]
129 prefixes: Option<String>,
130 },
131}
132
133fn resolve_hex_source(value: Option<&str>, file: Option<&Path>) -> Result<Bytes> {
134 let input = match (value, file) {
135 (Some(value), None) => value.to_owned(),
136 (None, Some(file)) => read_secret_file(file, 16 * 1024 * 1024)?,
137 _ => anyhow::bail!("Specify exactly one direct or file input"),
138 };
139 let bytes: Vec<u8> = hex::FromHex::from_hex(&input)
140 .map_err(|_| anyhow::anyhow!("Invalid hex-encoded database input"))?;
141 Ok(bytes.into())
142}
143
144fn resolve_hex_pair(
145 key: Option<&str>,
146 key_file: Option<&Path>,
147 value: Option<&str>,
148 value_file: Option<&Path>,
149) -> Result<(Bytes, Bytes)> {
150 if key.is_some() == key_file.is_some() || value.is_some() == value_file.is_some() {
152 anyhow::bail!("Specify exactly one direct or file input");
153 }
154 ensure_single_stdin(key_file.into_iter().chain(value_file))?;
155 Ok((
156 resolve_hex_source(key, key_file)?,
157 resolve_hex_source(value, value_file)?,
158 ))
159}
160
161fn print_kv(key: &[u8], value: &[u8]) {
162 println!(
163 "{} {}",
164 key.encode_hex::<String>(),
165 value.encode_hex::<String>()
166 );
167}
168
169pub struct FedimintDBTool {
170 server_module_inits: ServerModuleInitRegistry,
171 client_module_inits: ClientModuleInitRegistry,
172 cli_args: Options,
173}
174
175impl FedimintDBTool {
176 pub fn new(version_hash: &str) -> anyhow::Result<Self> {
178 handle_version_hash_command(version_hash);
179 TracingSetup::default().init()?;
180
181 Ok(Self {
182 server_module_inits: ServerModuleInitRegistry::new(),
183 client_module_inits: ClientModuleInitRegistry::new(),
184 cli_args: Options::parse(),
185 })
186 }
187
188 pub fn with_server_module_init<T>(mut self, r#gen: T) -> Self
189 where
190 T: ServerModuleInit + 'static + Send + Sync,
191 {
192 self.server_module_inits.attach(r#gen);
193 self
194 }
195
196 pub fn with_client_module_init<T>(mut self, r#gen: T) -> Self
197 where
198 T: ClientModuleInit + 'static + Send + Sync,
199 {
200 self.client_module_inits.attach(r#gen);
201 self
202 }
203
204 #[must_use]
205 pub fn with_default_modules_inits(self) -> Self {
206 self.with_server_module_init(WalletInit)
207 .with_server_module_init(MintInit)
208 .with_server_module_init(LightningInit)
209 .with_server_module_init(fedimint_lnv2_server::LightningInit)
210 .with_server_module_init(MetaInit)
211 .with_client_module_init(WalletClientInit::default())
212 .with_client_module_init(MintClientInit)
213 .with_client_module_init(LightningClientInit::default())
214 .with_client_module_init(fedimint_lnv2_client::LightningClientInit::default())
215 .with_client_module_init(fedimint_walletv2_client::WalletClientInit)
216 .with_client_module_init(MetaClientInit)
217 }
218
219 #[allow(clippy::too_many_lines)]
220 pub async fn run(&self) -> anyhow::Result<()> {
221 let options = &self.cli_args;
222 match &options.command {
223 DbCommand::List {
224 prefix,
225 prefix_file,
226 } => {
227 let prefix = resolve_hex_source(prefix.as_deref(), prefix_file.as_deref())?;
228 let rocksdb = open_db(options).await;
229 let mut dbtx = rocksdb.begin_transaction().await;
230 let prefix_iter = dbtx
231 .raw_find_by_prefix(&prefix)
232 .await?
233 .collect::<Vec<_>>()
234 .await;
235 for (key, value) in prefix_iter {
236 print_kv(&key, &value);
237 }
238 dbtx.commit_tx().await;
239 }
240 DbCommand::Write {
241 key,
242 key_file,
243 value,
244 value_file,
245 } => {
246 let (key, value) = resolve_hex_pair(
247 key.as_deref(),
248 key_file.as_deref(),
249 value.as_deref(),
250 value_file.as_deref(),
251 )?;
252 let rocksdb = open_db(options).await;
253 let mut dbtx = rocksdb.begin_transaction().await;
254 dbtx.raw_insert_bytes(&key, &value)
255 .await
256 .expect("Error inserting entry into RocksDb");
257 dbtx.commit_tx().await;
258 }
259 DbCommand::Delete { key, key_file } => {
260 let key = resolve_hex_source(key.as_deref(), key_file.as_deref())?;
261 let rocksdb = open_db(options).await;
262 let mut dbtx = rocksdb.begin_transaction().await;
263 dbtx.raw_remove_entry(&key)
264 .await
265 .expect("Error removing entry from RocksDb");
266 dbtx.commit_tx().await;
267 }
268 DbCommand::Dump {
269 cfg_dir,
270 modules,
271 prefixes,
272 } => {
273 let modules = match modules {
274 Some(mods) => mods
275 .split(',')
276 .map(|s| s.to_string().to_lowercase())
277 .collect::<Vec<String>>(),
278 None => Vec::new(),
279 };
280
281 let prefix_names = match prefixes {
282 Some(db_prefixes) => db_prefixes
283 .split(',')
284 .map(|s| s.to_string().to_lowercase())
285 .collect::<Vec<String>>(),
286 None => Vec::new(),
287 };
288
289 let (module_inits, client_module_inits) = if options.no_modules {
290 (
291 ServerModuleInitRegistry::new(),
292 ClientModuleInitRegistry::new(),
293 )
294 } else {
295 (
296 self.server_module_inits.clone(),
297 self.client_module_inits.clone(),
298 )
299 };
300
301 let mut dbdump = DatabaseDump::new(
302 cfg_dir.clone(),
303 options.database_dir.clone(),
304 module_inits,
305 client_module_inits,
306 modules,
307 prefix_names,
308 )
309 .await?;
310 dbdump.dump_database().await?;
311 }
312 DbCommand::DeletePrefix {
313 prefix,
314 prefix_file,
315 } => {
316 let prefix = resolve_hex_source(prefix.as_deref(), prefix_file.as_deref())?;
317 let rocksdb = open_db(options).await;
318 let mut dbtx = rocksdb.begin_transaction().await;
319 dbtx.raw_remove_by_prefix(&prefix).await?;
320 dbtx.commit_tx().await;
321 }
322 }
323
324 Ok(())
325 }
326}
327
328async fn open_db(options: &Options) -> fedimint_core::db::Database {
329 fedimint_rocksdb::RocksDb::build(&options.database_dir)
330 .open()
331 .await
332 .map_err(anyhow::Error::from)
333 .unwrap()
334 .into_database()
335}