Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Comment thread
muawiya1 marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand Down
15 changes: 15 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),

Comment thread
muawiya1 marked this conversation as resolved.
Resolved
#[error(
"Transaction can weigh up to {weight:#} ({} vB) once signed, over the {:#} ({} vB) \
standard limit, so Bitcoin Core nodes will not relay it",
Expand Down Expand Up @@ -226,6 +230,17 @@ impl From<bdk_wallet::rusqlite::Error> for BDKCliError {
}
}

#[cfg(any(feature = "sqlite", feature = "redb"))]
#[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
Expand Down
9 changes: 9 additions & 0 deletions src/handlers/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
26 changes: 22 additions & 4 deletions src/handlers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,9 @@ impl AppContext<Init> {
}

impl<'a> AppContext<OfflineOperations<'a>> {
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 },
}
Expand All @@ -87,14 +87,13 @@ impl<'a> AppContext<OfflineOperations<'a>> {
))]
impl<'a> AppContext<OnlineOperations<'a>> {
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,
Expand Down Expand Up @@ -124,3 +123,22 @@ pub trait AsyncAppCommand<C> {

async fn execute(&self, ctx: &mut C) -> Result<Self::Output, Error>;
}

#[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);
}
}
3 changes: 1 addition & 2 deletions src/handlers/repl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
}
Expand All @@ -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,
Expand Down
14 changes: 3 additions & 11 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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")]
Expand Down Expand Up @@ -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?
Expand Down
7 changes: 3 additions & 4 deletions src/persister.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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,
Expand Down
84 changes: 84 additions & 0 deletions tests/integration/init.rs
Comment thread
muawiya1 marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading