diff --git a/CHANGELOG.md b/CHANGELOG.md index cb4e2aaa..85926de9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,7 @@ page. See [DEVELOPMENT_CYCLE.md](DEVELOPMENT_CYCLE.md) for more details. - Fixed `key generate` silently producing a 24-word mnemonic for any `--entropy` value other than 12; values other than 12 and 24 are now rejected - Gated `full_scan`'s `--scan-stop-gap` to the Electrum and Esplora backends that use it; RPC and CBF wallets now reject the flag instead of silently ignoring it, while a `STOP_GAP` environment variable keeps working for supported backends and no longer breaks unsupported ones - Changed `payjoin history` to return JSON instead of a rendered table +- Fixed `wallet config --force` silently changing an existing wallet's network, which left the wallet unable to load; it is now rejected ## [4.0.0] diff --git a/src/error.rs b/src/error.rs index 04d1ce6b..4f929200 100644 --- a/src/error.rs +++ b/src/error.rs @@ -67,6 +67,10 @@ pub enum BDKCliError { #[error("Miniscript compiler error: {0}")] MiniscriptCompilerError(#[from] bdk_wallet::miniscript::policy::compiler::CompilerError), + #[cfg(any(feature = "sqlite", feature = "redb"))] + #[error("Wallet load error: {0}")] + LoadWallet(#[from] bdk_wallet::LoadError), + #[error( "Transaction can weigh up to {weight:#} ({} vB) once signed, over the {:#} ({} vB) \ standard limit, so Bitcoin Core nodes will not relay it", @@ -226,6 +230,17 @@ impl From for BDKCliError { } } +#[cfg(any(feature = "sqlite", feature = "redb"))] +#[cfg(any(feature = "sqlite", feature = "redb"))] +impl From> for BDKCliError { + fn from(err: bdk_wallet::LoadWithPersistError) -> Self { + match err { + bdk_wallet::LoadWithPersistError::Persist(e) => e, + bdk_wallet::LoadWithPersistError::InvalidChangeSet(e) => e.into(), + } + } +} + #[cfg(feature = "payjoin")] impl From> for BDKCliError diff --git a/src/handlers/config.rs b/src/handlers/config.rs index dc1ffb9f..bed4f13e 100644 --- a/src/handlers/config.rs +++ b/src/handlers/config.rs @@ -78,6 +78,15 @@ impl AppCommand> for SaveConfigCommand { ))); }; + if let Some(existing) = config.wallets.get(wallet_name.as_str()) + && existing.network != ctx.network.to_string() + { + return Err(Error::Generic(format!( + "Wallet '{}' is configured for network '{}', and --force cannot change it to '{}'.", + wallet_name, existing.network, ctx.network + ))); + } + #[cfg(any( feature = "electrum", feature = "esplora", diff --git a/src/handlers/mod.rs b/src/handlers/mod.rs index 7d3d7f8c..bf8be129 100644 --- a/src/handlers/mod.rs +++ b/src/handlers/mod.rs @@ -70,9 +70,9 @@ impl AppContext { } impl<'a> AppContext> { - pub fn new_offline_wallet(network: Network, datadir: PathBuf, wallet: &'a mut Wallet) -> Self { + pub fn new_offline_wallet(datadir: PathBuf, wallet: &'a mut Wallet) -> Self { Self { - network, + network: wallet.network(), datadir, state: OfflineOperations { wallet }, } @@ -87,14 +87,13 @@ impl<'a> AppContext> { ))] impl<'a> AppContext> { pub fn new_online_wallet( - network: Network, datadir: PathBuf, wallet: &'a mut Wallet, client: &'a BlockchainClient, wallet_name: String, ) -> Self { Self { - network, + network: wallet.network(), datadir, state: OnlineOperations { wallet, @@ -124,3 +123,22 @@ pub trait AsyncAppCommand { async fn execute(&self, ctx: &mut C) -> Result; } + +#[cfg(test)] +mod tests { + use super::*; + + const DESCRIPTOR: &str = "wpkh(tpubD6NzVbkrYhZ4XgiXtGrdW5XDAPFCL9h7we1vwNCpn8tGbBcgfVYjXyhWo4E1xkh56hjod1RhGjxbaTLV3X4FyWuejifB9jusQ46QzG87VKp/0/*)"; + + #[test] + fn offline_wallet_context_uses_wallet_network() { + let mut wallet = Wallet::create_single(DESCRIPTOR) + .network(Network::Regtest) + .create_wallet_no_persist() + .unwrap(); + + let ctx = AppContext::new_offline_wallet(PathBuf::new(), &mut wallet); + + assert_eq!(ctx.network, Network::Regtest); + } +} diff --git a/src/handlers/repl.rs b/src/handlers/repl.rs index b93916e9..53639403 100644 --- a/src/handlers/repl.rs +++ b/src/handlers/repl.rs @@ -54,7 +54,7 @@ pub(crate) async fn respond( let response = match repl_subcommand { ReplSubCommand::Wallet { subcommand } => match subcommand { WalletSubCommand::OfflineWalletSubCommand(cmd) => { - let mut ctx = AppContext::new_offline_wallet(network, datadir, wallet); + let mut ctx = AppContext::new_offline_wallet(datadir, wallet); cmd.execute(&mut ctx).map_err(|e| e.to_string())?; Some(()) } @@ -67,7 +67,6 @@ pub(crate) async fn respond( WalletSubCommand::OnlineWalletSubCommand(cmd) => { let client_ref = client.ok_or("Online commands require a client.".to_string())?; let mut ctx = AppContext::new_online_wallet( - network, datadir, wallet, client_ref, diff --git a/src/main.rs b/src/main.rs index 7ed73d46..9d8ba384 100644 --- a/src/main.rs +++ b/src/main.rs @@ -71,7 +71,6 @@ async fn run(cli_opts: CliOpts) -> Result<(), Error> { let client = runtime.build_client(&wallet)?; { let mut ctx = AppContext::new_online_wallet( - runtime.network, runtime.home_dir.clone(), &mut wallet, &client, @@ -88,11 +87,8 @@ async fn run(cli_opts: CliOpts) -> Result<(), Error> { let mut wallet = runtime.build_wallet(command_requires_db(&cmd))?; { - let mut ctx = AppContext::new_offline_wallet( - runtime.network, - runtime.home_dir.clone(), - &mut wallet, - ); + let mut ctx = + AppContext::new_offline_wallet(runtime.home_dir.clone(), &mut wallet); match cmd { #[cfg(feature = "dns_payment")] @@ -120,11 +116,7 @@ async fn run(cli_opts: CliOpts) -> Result<(), Error> { let runtime = WalletRuntime::load(&home_dir, &wallet_name)?; let mut wallet = runtime.build_wallet(false)?; - let mut ctx = AppContext::new_offline_wallet( - runtime.network, - runtime.home_dir.clone(), - &mut wallet, - ); + let mut ctx = AppContext::new_offline_wallet(runtime.home_dir.clone(), &mut wallet); cmd.run(&mut ctx, &wallet_name) .await? diff --git a/src/persister.rs b/src/persister.rs index 3ff8e61c..2c1493e3 100644 --- a/src/persister.rs +++ b/src/persister.rs @@ -61,13 +61,13 @@ impl WalletPersister for Persister { } #[cfg(any(feature = "sqlite", feature = "redb"))] -pub(crate) fn new_persisted_wallet( +pub(crate) fn new_persisted_wallet

( network: Network, persister: &mut P, wallet_opts: &WalletOpts, ) -> Result, Error> where - P::Error: std::fmt::Display, + P: WalletPersister, { let ext_descriptor = wallet_opts.ext_descriptor.clone(); let int_descriptor = wallet_opts.int_descriptor.clone(); @@ -91,8 +91,7 @@ where let wallet_opt = wallet_load_params .check_network(network) - .load_wallet(persister) - .map_err(|e| Error::Generic(e.to_string()))?; + .load_wallet(persister)?; let wallet = match wallet_opt { Some(wallet) => wallet, diff --git a/tests/integration/init.rs b/tests/integration/init.rs index e1725e4f..c9202242 100644 --- a/tests/integration/init.rs +++ b/tests/integration/init.rs @@ -1067,6 +1067,90 @@ rpc_password = "preserved-password" Some("preserved-password") ); } + + #[test] + fn test_config_force_rejects_network_change() { + let temp_dir = TempDir::new().unwrap(); + let regtest = BdkCli::new("regtest", Some(temp_dir.path().to_path_buf())); + let signet = BdkCli::new("signet", Some(temp_dir.path().to_path_buf())); + let wallet_name = "network_wallet"; + let config_path = temp_dir.path().join("config.toml"); + + save_wallet(®test, wallet_name); + let before = fs::read_to_string(&config_path).unwrap(); + + let desc = signet + .cmd("descriptor", &["--type", "tr"]) + .output() + .expect("Command to generate descriptors failed"); + let desc_values: Value = + serde_json::from_slice(&desc.stdout).expect("Invalid JSON from output descriptor"); + let pub_desc = &desc_values["public_descriptors"]; + + let mut command = signet.build_base_cmd(); + command + .arg("wallet") + .args(["--wallet", wallet_name]) + .arg("config") + .arg("--force") + .args(["--ext-descriptor", pub_desc["external"].as_str().unwrap()]) + .args(["--int-descriptor", pub_desc["internal"].as_str().unwrap()]) + .args(["--database-type", "sqlite"]); + + #[cfg(feature = "rpc")] + command.args(["--client-type", "rpc", "--url", "http://localhost:18443"]); + + command + .assert() + .failure() + .stderr(predicate::str::contains( + "Wallet 'network_wallet' is configured for network 'regtest', and --force cannot change it to 'signet'", + )); + + let after = fs::read_to_string(&config_path).unwrap(); + assert_eq!( + before, after, + "rejected --force must not change config.toml" + ); + } + + #[test] + fn test_config_force_same_network_updates_settings() { + let temp_dir = TempDir::new().unwrap(); + let cli = BdkCli::new("regtest", Some(temp_dir.path().to_path_buf())); + let wallet_name = "network_wallet"; + let config_path = temp_dir.path().join("config.toml"); + + save_wallet(&cli, wallet_name); + let before = fs::read_to_string(&config_path).unwrap(); + + let desc = cli + .cmd("descriptor", &["--type", "tr"]) + .output() + .expect("Command to generate descriptors failed"); + let desc_values: Value = + serde_json::from_slice(&desc.stdout).expect("Invalid JSON from output descriptor"); + let pub_desc = &desc_values["public_descriptors"]; + + let mut command = cli.build_base_cmd(); + command + .arg("wallet") + .args(["--wallet", wallet_name]) + .arg("config") + .arg("--force") + .args(["--ext-descriptor", pub_desc["external"].as_str().unwrap()]) + .args(["--int-descriptor", pub_desc["internal"].as_str().unwrap()]) + .args(["--database-type", "sqlite"]); + + #[cfg(feature = "rpc")] + command.args(["--client-type", "rpc", "--url", "http://localhost:18443"]); + + command.assert().success(); + + let after = fs::read_to_string(&config_path).unwrap(); + assert_ne!(before, after, "--force should save the new descriptors"); + assert!(after.contains("network = \"regtest\"")); + } } // SILENT PAYMENTS