]> Untitled Git - bdk-cli/commitdiff
fix(wallet): prevent wallet network changes and clarify mismatch errors
authorMuawiya Abubakar <muawiyaabk@gmail.com>
Wed, 18 Nov 2026 20:34:25 +0000 (21:34 +0100)
committerMuawiya Abubakar <muawiyaabk@gmail.com>
Mon, 23 Nov 2026 02:24:59 +0000 (03:24 +0100)
Running `wallet config --force` without the original `--network` saved
the default network (testnet) over the existing one. The config then no
longer matched the wallet database, and the wallet failed to load with
a generic error.

- Reject a `--force` that would change an existing wallet's network
- Clarify the wallet load error for a network mismatch

Fixes #359

CHANGELOG.md
src/error.rs
src/handlers/config.rs
src/persister.rs
tests/integration/init.rs

index cb4e2aaaa2b403c76a4c6d9fa4a52381b08ac9fb..85926de97accb360c81da2a8ce30580edd22cded 100644 (file)
@@ -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]
 
index 3a5b89aa7bfd80b3ad0dda0b67f88a75347e701f..9d4c68e92ecfb6be39b112277932beb1d76b1f3b 100644 (file)
@@ -71,6 +71,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",
@@ -230,6 +234,16 @@ impl From<bdk_wallet::rusqlite::Error> for BDKCliError {
     }
 }
 
+#[cfg(any(feature = "sqlite", feature = "redb"))]
+impl From<bdk_wallet::LoadWithPersistError<BDKCliError>> for BDKCliError {
+    fn from(err: bdk_wallet::LoadWithPersistError<BDKCliError>) -> Self {
+        match err {
+            bdk_wallet::LoadWithPersistError::Persist(e) => e,
+            bdk_wallet::LoadWithPersistError::InvalidChangeSet(e) => e.into(),
+        }
+    }
+}
+
 #[cfg(feature = "payjoin")]
 impl<ApiErr, StorageErr, ErrorState>
     From<payjoin::persist::PersistedError<ApiErr, StorageErr, ErrorState>> for BDKCliError
index dc1ffb9f7e267e3db141550db05b969f70c9ecf2..bed4f13ef77c85b0ce49a918b1f88972707c3e72 100644 (file)
@@ -78,6 +78,15 @@ impl AppCommand<AppContext<Init>> 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",
index 3ff8e61c5feced91702bb9886a2a10c276a7bdfe..2c1493e34f52bf895ead6a61b6e6fc0a71d7d893 100644 (file)
@@ -61,13 +61,13 @@ impl WalletPersister for Persister {
 }
 
 #[cfg(any(feature = "sqlite", feature = "redb"))]
-pub(crate) fn new_persisted_wallet<P: WalletPersister>(
+pub(crate) fn new_persisted_wallet<P>(
     network: Network,
     persister: &mut P,
     wallet_opts: &WalletOpts,
 ) -> Result<PersistedWallet<P>, Error>
 where
-    P::Error: std::fmt::Display,
+    P: WalletPersister<Error = Error>,
 {
     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,
index e1725e4f0588505abe92b06e76f5aa730f4c5749..c9202242f3d47027c0170e19fbbac1723948e989 100644 (file)
@@ -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(&regtest, 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