From caa67e48729aee8338ab771ab8751d418ddb62c5 Mon Sep 17 00:00:00 2001 From: emma31-dev Date: Thu, 3 Dec 2026 21:27:31 +0100 Subject: [PATCH] fix(create_tx): reject recipients from the wrong network Validate recipient addresses and silent payment codes against the wallet's network before building a transaction. - Carry recipients as Address and convert them with recipient_script, which requires the wallet's network. - Apply the same check to create_sp_tx, create_dns_tx and bump_fee --shrink. - Validate sign_message/verify_message addresses against the wallet network. - Include the underlying cause in address parse errors so network mismatches name the offending address and network. --- CHANGELOG.md | 1 + src/error.rs | 15 ++- src/handlers/dns/mod.rs | 14 ++- src/handlers/offline.rs | 69 ++++++++---- src/utils/common.rs | 140 ++++++++++++++++++++++-- tests/integration/offline.rs | 204 ++++++++++++++++++++++++++++++++--- tests/integration/online.rs | 29 ++++- 7 files changed, 425 insertions(+), 47 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e7a266cc..1d7c8ae6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,7 @@ page. See [DEVELOPMENT_CYCLE.md](DEVELOPMENT_CYCLE.md) for more details. - 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 +- Fixed transaction creation to reject addresses and silent payment codes from a different network instead of building an unspendable PSBT - Changed `receive_payjoin`, `send_payjoin`, `resume_payjoin`, `payjoin_history` and `resolve_dns_recipient` to print their JSON directly instead of as a string inside a `message` field; `resolve_dns_recipient` now leaves out `description`, `min_amount` and `max_amount` when they are not set ## [4.0.0] diff --git a/src/error.rs b/src/error.rs index 9d4c68e9..918ba410 100644 --- a/src/error.rs +++ b/src/error.rs @@ -84,7 +84,7 @@ pub enum BDKCliError { )] NonStandardTxWeight { weight: Weight }, - #[error("ParseError: {0}")] + #[error("ParseError: {}", display_parse_error(.0))] ParseError(#[from] bdk_wallet::bitcoin::address::ParseError), #[error("ParseOutPointError: {0}")] @@ -256,3 +256,16 @@ where BDKCliError::Generic(e.to_string()) } } + +/// Format an address parse error together with its underlying cause. +/// +/// `rust-bitcoin`'s `ParseError` only prints a generic summary such as +/// "validation error"; the useful detail (e.g. which network an address belongs +/// to) lives in its source. +fn display_parse_error(error: &bdk_wallet::bitcoin::address::ParseError) -> String { + use std::error::Error as _; + match error.source() { + Some(source) => source.to_string(), + None => error.to_string(), + } +} diff --git a/src/handlers/dns/mod.rs b/src/handlers/dns/mod.rs index 1d1f7b5c..7df0d52c 100644 --- a/src/handlers/dns/mod.rs +++ b/src/handlers/dns/mod.rs @@ -8,9 +8,13 @@ use crate::handlers::{AppContext, AsyncAppCommand, Init, OfflineOperations}; use crate::utils::{ check_standard_weight, max_signed_weight, parse_dns_recipient, parse_fee_rate, parse_op_return_base64, parse_op_return_string, parse_outpoint, parse_recipient, + recipient_script, }; use bdk_wallet::KeychainKind; -use bdk_wallet::bitcoin::{Amount, FeeRate, OutPoint, ScriptBuf, Sequence, script::PushBytesBuf}; +use bdk_wallet::bitcoin::address::NetworkUnchecked; +use bdk_wallet::bitcoin::{ + Address, Amount, FeeRate, OutPoint, ScriptBuf, Sequence, script::PushBytesBuf, +}; use bitcoin_payment_instructions::PaymentMethod; use clap::Parser; use serde_json::{Value, json}; @@ -64,7 +68,7 @@ impl AsyncAppCommand> for ResolveDnsRecipientCommand { #[derive(Parser, Debug, Clone, PartialEq)] pub struct CreateDnsTxCommand { #[arg(env = "ADDRESS_SAT", long = "to", value_parser = parse_recipient)] - pub recipients: Vec<(ScriptBuf, u64)>, + pub recipients: Vec<(Address, u64)>, #[arg(long = "to_dns", value_parser = parse_dns_recipient)] pub dns_recipients: Vec<(String, u64)>, #[arg(long = "dns_resolver", default_value = "8.8.8.8")] @@ -106,7 +110,11 @@ pub struct CreateDnsTxCommand { impl AsyncAppCommand>> for CreateDnsTxCommand { async fn execute(&self, ctx: &mut AppContext>) -> Result { let network = ctx.network; - let mut recipients: Vec<(ScriptBuf, u64)> = self.recipients.clone(); + let mut recipients: Vec<(ScriptBuf, u64)> = self + .recipients + .iter() + .map(|(address, amount)| Ok((recipient_script(address, network)?, *amount))) + .collect::>()?; for (hrn, amount_sat) in &self.dns_recipients { log::info!("Resolving DNS instructions for recipient {hrn}"); diff --git a/src/handlers/offline.rs b/src/handlers/offline.rs index 15e1210d..5cc069e1 100644 --- a/src/handlers/offline.rs +++ b/src/handlers/offline.rs @@ -3,30 +3,34 @@ use crate::error::BDKCliError as Error; use crate::handlers::{AppCommand, AppContext, OfflineOperations}; use crate::utils::output::FormatOutput; use crate::utils::{ - check_standard_weight, max_signed_weight, parse_address, parse_fee_rate, - parse_op_return_base64, parse_op_return_string, parse_outpoint, parse_recipient, + check_standard_weight, max_signed_weight, parse_fee_rate, parse_op_return_base64, + parse_op_return_string, parse_outpoint, parse_recipient, recipient_script, }; +use bdk_wallet::bitcoin::address::NetworkUnchecked; use bdk_wallet::bitcoin::base64::{Engine, prelude::BASE64_STANDARD}; -use bdk_wallet::bitcoin::{Address, Amount, FeeRate, OutPoint, Psbt, ScriptBuf, Sequence, Txid}; -use bdk_wallet::bitcoin::{consensus::encode::serialize_hex, script::PushBytesBuf}; +use bdk_wallet::bitcoin::consensus::encode::serialize_hex; +use bdk_wallet::bitcoin::script::PushBytesBuf; +use bdk_wallet::bitcoin::{Address, Amount, FeeRate, OutPoint, Psbt, Sequence, Txid}; use bdk_wallet::{KeychainKind, SignOptions}; use clap::Parser; use serde_json::{Value, json}; use std::collections::BTreeMap; #[cfg(feature = "silent-payments")] use { - crate::utils::common::parse_sp_code_value_pairs, + crate::utils::common::{parse_sp_code_value_pairs, sp_code_valid_for_network}, bdk_sp::{ bitcoin::{PrivateKey, PublicKey}, encoding::SilentPaymentCode, send::psbt::derive_sp, }, + bdk_wallet::bitcoin::ScriptBuf, bdk_wallet::bitcoin::key::Secp256k1, bdk_wallet::keys::{DescriptorPublicKey, DescriptorSecretKey, SinglePubKey}, std::collections::HashMap, }; #[cfg(feature = "message_signer")] use { + crate::utils::parse_address, crate::utils::parse_signature_format, bdk_message_signer::{MessageProof, MessageSigner}, }; @@ -188,7 +192,7 @@ impl AppCommand>> for BalanceCommand { pub struct CreateTxCommand { /// Adds a recipient to the transaction. #[arg(env = "ADDRESS_SAT", long = "to", required = true, value_parser = parse_recipient)] - pub recipients: Vec<(ScriptBuf, u64)>, + pub recipients: Vec<(Address, u64)>, /// Sends all the funds (or all the selected utxos). Requires only one recipient with value 0. #[arg(long = "send_all", short = 'a')] @@ -245,13 +249,14 @@ pub struct CreateTxCommand { impl AppCommand>> for CreateTxCommand { fn execute(&self, ctx: &mut AppContext>) -> Result { + let network = ctx.state.wallet.network(); let mut tx_builder = ctx.state.wallet.build_tx(); if self.send_all { if self.recipients.len() == 1 { tx_builder .drain_wallet() - .drain_to(self.recipients[0].0.clone()); + .drain_to(recipient_script(&self.recipients[0].0, network)?); } else { return Err(Error::Generic( "Wallet can only be drained to a single output".to_string(), @@ -260,10 +265,14 @@ impl AppCommand>> for CreateTxCommand { } else { let recipients = self .recipients - .clone() - .into_iter() - .map(|(script, amount)| (script, Amount::from_sat(amount))) - .collect(); + .iter() + .map(|(address, amount)| { + Ok(( + recipient_script(address, network)?, + Amount::from_sat(*amount), + )) + }) + .collect::>()?; tx_builder.set_recipients(recipients); } @@ -320,7 +329,7 @@ pub struct CreateSpTxCommand { // Clap Doesn't support complex vector parsing https://github.com/clap-rs/clap/issues/1704. // Address and amount parsing is done at run time in handler function. #[arg(env = "ADDRESS_SAT", long = "to", required = false, value_parser = parse_recipient)] - pub recipients: Option>, + pub recipients: Option, u64)>>, /// Parse silent payment recipients #[arg(long = "to-sp", required = true, value_parser = parse_sp_code_value_pairs)] pub silent_payment_recipients: Vec<(SilentPaymentCode, u64)>, @@ -368,13 +377,21 @@ pub struct CreateSpTxCommand { #[cfg(feature = "silent-payments")] impl AppCommand>> for CreateSpTxCommand { fn execute(&self, ctx: &mut AppContext>) -> Result { + let network = ctx.state.wallet.network(); let mut tx_builder = ctx.state.wallet.build_tx(); let sp_recipients: Vec = self .silent_payment_recipients .iter() - .map(|(sp_code, _)| sp_code.clone()) - .collect(); + .map(|(sp_code, _)| { + if !sp_code_valid_for_network(sp_code, network) { + return Err(Error::Generic(format!( + "Silent payment code {sp_code} is not valid for {network}" + ))); + } + Ok(sp_code.clone()) + }) + .collect::>()?; if self.send_all { if sp_recipients.len() == 1 && self.recipients.is_none() { @@ -385,7 +402,9 @@ impl AppCommand>> for CreateSpTxCommand { && sp_recipients.is_empty() { if recipients.len() == 1 { - tx_builder.drain_wallet().drain_to(recipients[0].0.clone()); + tx_builder + .drain_wallet() + .drain_to(recipient_script(&recipients[0].0, network)?); } else { return Err(Error::Generic( "Wallet can only be drain to a single output".to_string(), @@ -409,7 +428,13 @@ impl AppCommand>> for CreateSpTxCommand { if let Some(recipients) = &self.recipients { let recipients = recipients .iter() - .map(|(script, amount)| (script.clone(), Amount::from_sat(*amount))); + .map(|(address, amount)| { + Ok(( + recipient_script(address, network)?, + Amount::from_sat(*amount), + )) + }) + .collect::, Error>>()?; outputs.extend(recipients); } @@ -538,8 +563,8 @@ pub struct BumpFeeCommand { pub txid: Txid, /// Allows the wallet to reduce the amount to the specified address in order to increase fees. - #[arg(env = "SHRINK_ADDRESS", long = "shrink", value_parser = parse_address)] - pub shrink_address: Option
, + #[arg(env = "SHRINK_ADDRESS", long = "shrink")] + pub shrink_address: Option>, /// Make a PSBT that can be signed by offline signers and hardware wallets. Forces the addition of `non_witness_utxo` and more details to let the signer identify the change output. #[arg(long = "offline_signer")] @@ -566,14 +591,14 @@ pub struct BumpFeeCommand { impl AppCommand>> for BumpFeeCommand { fn execute(&self, ctx: &mut AppContext>) -> Result { + let network = ctx.state.wallet.network(); let wallet = &mut ctx.state.wallet; let mut tx_builder = wallet.build_fee_bump(self.txid)?; tx_builder.fee_rate(self.fee_rate); if let Some(address) = &self.shrink_address { - let script_pubkey = address.script_pubkey(); - tx_builder.drain_to(script_pubkey); + tx_builder.drain_to(recipient_script(address, network)?); } if self.offline_signer { @@ -760,7 +785,7 @@ pub struct SignMessageCommand { impl AppCommand>> for SignMessageCommand { fn execute(&self, ctx: &mut AppContext>) -> Result { let wallet = &mut ctx.state.wallet; - let address: Address = parse_address(&self.address)?; + let address: Address = parse_address(&self.address, wallet.network())?; let signature_format = parse_signature_format(&self.signature_type)?; if !wallet.is_mine(address.script_pubkey()) { @@ -802,7 +827,7 @@ impl AppCommand>> for VerifyMessageCommand { fn execute(&self, ctx: &mut AppContext>) -> Result { let wallet = &ctx.state.wallet; - let address: Address = parse_address(&self.address)?; + let address: Address = parse_address(&self.address, wallet.network())?; let parsed_proof = MessageProof::from_base64(&self.proof) .map_err(|e| Error::Generic(format!("Invalid proof format: {e}")))?; diff --git a/src/utils/common.rs b/src/utils/common.rs index 21514f0b..d201eda1 100644 --- a/src/utils/common.rs +++ b/src/utils/common.rs @@ -15,6 +15,7 @@ use bdk_wallet::Wallet; ))] use bdk_wallet::WalletEvent; use bdk_wallet::bip39::Mnemonic; +use bdk_wallet::bitcoin::address::NetworkUnchecked; use bdk_wallet::bitcoin::base64::{Engine, prelude::BASE64_STANDARD}; use bdk_wallet::bitcoin::bip32::{Fingerprint, Xpriv}; use bdk_wallet::bitcoin::key::Secp256k1; @@ -72,17 +73,42 @@ pub(crate) fn is_final(psbt: &Psbt) -> Result<(), Error> { } /// Parse the recipient (Address,Amount) argument from cli input. -pub(crate) fn parse_recipient(s: &str) -> Result<(ScriptBuf, u64), String> { +pub(crate) fn parse_recipient(s: &str) -> Result<(Address, u64), String> { let parts: Vec<_> = s.split(':').collect(); if parts.len() != 2 { return Err("Invalid format".to_string()); } - let addr = Address::from_str(parts[0]) - .map_err(|e| e.to_string())? - .assume_checked(); + let addr = Address::from_str(parts[0]).map_err(|e| e.to_string())?; let val = u64::from_str(parts[1]).map_err(|e| e.to_string())?; - Ok((addr.script_pubkey(), val)) + Ok((addr, val)) +} + +/// Convert a recipient address to a script pubkey, requiring the wallet's network. +pub(crate) fn recipient_script( + address: &Address, + network: Network, +) -> Result { + Ok(address.clone().require_network(network)?.script_pubkey()) +} + +/// Whether a silent payment code can be used to pay on `network`. +/// +/// The `tsp` prefix is shared by testnet, testnet4 and signet, so codes have to +/// be matched by network family rather than by equality: `bdk_sp` reports every +/// `tsp` code as [`Network::Testnet`] no matter which of those networks it came +/// from. Only the prefix matters, the keys and the payment derivation are the +/// same on all networks. +#[cfg(feature = "silent-payments")] +pub(crate) fn sp_code_valid_for_network(code: &SilentPaymentCode, network: Network) -> bool { + match network { + Network::Bitcoin => code.network == Network::Bitcoin, + Network::Testnet | Network::Testnet4 | Network::Signet => matches!( + code.network, + Network::Testnet | Network::Testnet4 | Network::Signet + ), + Network::Regtest => code.network == Network::Regtest, + } } #[cfg(any(feature = "electrum", feature = "esplora", feature = "rpc"))] @@ -104,10 +130,11 @@ pub(crate) fn parse_outpoint(s: &str) -> Result { Ok(OutPoint::from_str(s)?) } -/// Parse an address string into `Address`. -pub(crate) fn parse_address(address_str: &str) -> Result { +/// Parse an address string into `Address`, requiring `network`. +#[cfg(feature = "message_signer")] +pub(crate) fn parse_address(address_str: &str, network: Network) -> Result { let unchecked_address = Address::from_str(address_str)?; - Ok(unchecked_address.assume_checked()) + Ok(unchecked_address.require_network(network)?) } /// Parse a fee rate, given in sat/vB, from input. @@ -758,4 +785,101 @@ mod tests { ); } } + + #[test] + fn recipient_script_accepts_addresses_valid_for_the_network() { + let regtest = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080" + .parse::>() + .unwrap(); + assert_eq!( + recipient_script(®test, Network::Regtest).unwrap(), + regtest.assume_checked_ref().script_pubkey() + ); + + // `tb1` addresses belong to testnet, testnet4 and signet alike. + let testnet = "tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx" + .parse::>() + .unwrap(); + for network in [Network::Testnet, Network::Testnet4, Network::Signet] { + assert!( + recipient_script(&testnet, network).is_ok(), + "a tb1 address should be valid on {network}" + ); + } + } + + #[test] + fn recipient_script_rejects_addresses_from_another_network() { + let testnet = "tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx" + .parse::>() + .unwrap(); + + for network in [Network::Bitcoin, Network::Regtest] { + let error = recipient_script(&testnet, network).unwrap_err(); + assert!( + error.to_string().contains("is not valid on"), + "unexpected error for {network}: {error}" + ); + } + } + + #[cfg(feature = "silent-payments")] + mod silent_payment_network_tests { + use super::*; + + fn code(network: Network) -> SilentPaymentCode { + let scan = bdk_sp::bitcoin::secp256k1::PublicKey::from_str( + "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + ) + .unwrap(); + let spend = bdk_sp::bitcoin::secp256k1::PublicKey::from_str( + "02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5", + ) + .unwrap(); + SilentPaymentCode::new_v0(scan, spend, network) + } + + #[test] + fn testnet_codes_are_accepted_on_every_test_network() { + // Parsing a `tsp` code always reports `Network::Testnet`, but the + // same code must also be accepted on testnet4 and signet. + let encoded = code(Network::Testnet).to_string(); + let parsed = SilentPaymentCode::try_from(encoded.as_str()).unwrap(); + assert_eq!(parsed.network, Network::Testnet); + + for network in [Network::Testnet, Network::Testnet4, Network::Signet] { + assert!( + sp_code_valid_for_network(&parsed, network), + "a tsp code should be valid on {network}" + ); + } + assert!(!sp_code_valid_for_network(&parsed, Network::Bitcoin)); + assert!(!sp_code_valid_for_network(&parsed, Network::Regtest)); + } + + #[test] + fn mainnet_and_regtest_codes_are_not_interchangeable() { + let mainnet = code(Network::Bitcoin); + assert!(sp_code_valid_for_network(&mainnet, Network::Bitcoin)); + for network in [ + Network::Testnet, + Network::Testnet4, + Network::Signet, + Network::Regtest, + ] { + assert!(!sp_code_valid_for_network(&mainnet, network)); + } + + let regtest = code(Network::Regtest); + assert!(sp_code_valid_for_network(®test, Network::Regtest)); + for network in [ + Network::Bitcoin, + Network::Testnet, + Network::Testnet4, + Network::Signet, + ] { + assert!(!sp_code_valid_for_network(®test, network)); + } + } + } } diff --git a/tests/integration/offline.rs b/tests/integration/offline.rs index 772ff53f..38e44a2b 100644 --- a/tests/integration/offline.rs +++ b/tests/integration/offline.rs @@ -8,12 +8,16 @@ mod test_offline { static WALLET_NAME: &str = "test_config_wallet"; /// A `--to` argument, the wallet is unfunded, so nothing is spent. - static RECIPIENT: &str = "tb1p4tp4l6glyr2gs94neqcpr5gha7344nfyznfkc8szkreflscsdkgqsdent4:10000"; + static RECIPIENT: &str = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080:10000"; /// Helper to spin up a sandboxed CLI with the generated descriptors fn setup_wallet_config() -> (BdkCli, Command) { + setup_wallet_config_for("regtest") + } + + fn setup_wallet_config_for(network: &str) -> (BdkCli, Command) { let temp_dir = TempDir::new().unwrap(); - let cli = BdkCli::new("regtest", Some(temp_dir.path().to_path_buf())); + let cli = BdkCli::new(network, Some(temp_dir.path().to_path_buf())); // generate descriptors let desc = cli @@ -174,16 +178,10 @@ mod test_offline { cmd_init.assert().success(); // create transaction - cli.wallet_cmd(&[ - "--wallet", - WALLET_NAME, - "create_tx", - "--to", - "tb1p4tp4l6glyr2gs94neqcpr5gha7344nfyznfkc8szkreflscsdkgqsdent4:1000", - ]) - .assert() - .failure() - .stderr(predicate::str::contains("Insufficient")); + cli.wallet_cmd(&["--wallet", WALLET_NAME, "create_tx", "--to", RECIPIENT]) + .assert() + .failure() + .stderr(predicate::str::contains("Insufficient")); } #[test] @@ -379,6 +377,188 @@ mod test_offline { .stdout(predicate::str::contains("\"valid\": false")); } + #[cfg(feature = "message_signer")] + #[test] + fn test_sign_message_rejects_address_from_wrong_network() { + let (cli, mut cmd_init) = setup_wallet_config(); + cmd_init.assert().success(); + + // Wallet is regtest, address is testnet. + cli.wallet_cmd(&[ + "--wallet", + WALLET_NAME, + "sign_message", + "--message", + "wrong network", + "--address", + "tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx", + ]) + .assert() + .failure() + .stderr(predicate::str::contains("is not valid on regtest")); + } + + #[test] + fn test_create_tx_rejects_address_from_wrong_network() { + let (cli, mut cmd_init) = setup_wallet_config(); + cmd_init.assert().success(); + + // Wallet is regtest, recipient is testnet. + let recipient = "tb1p4tp4l6glyr2gs94neqcpr5gha7344nfyznfkc8szkreflscsdkgqsdent4:1000"; + cli.wallet_cmd(&["--wallet", WALLET_NAME, "create_tx", "--to", recipient]) + .assert() + .failure() + .stderr(predicate::str::contains("is not valid on regtest")); + } + + #[cfg(feature = "silent-payments")] + #[test] + fn test_create_sp_tx_rejects_address_from_wrong_network() { + let (cli, mut cmd_init) = setup_wallet_config(); + cmd_init.assert().success(); + + let sp_code = cli + .cmd( + "silent_payment_code", + &[ + "--scan_key", + "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "--spend_key", + "02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5", + ], + ) + .output() + .unwrap(); + let sp_code: Value = serde_json::from_slice(&sp_code.stdout).unwrap(); + let sp_recipient = format!("{}:1000", sp_code["message"].as_str().unwrap()); + + // Wallet is regtest, recipient is testnet. + let recipient = "tb1p4tp4l6glyr2gs94neqcpr5gha7344nfyznfkc8szkreflscsdkgqsdent4:1000"; + cli.wallet_cmd(&[ + "--wallet", + WALLET_NAME, + "create_sp_tx", + "--to", + recipient, + "--to-sp", + &sp_recipient, + ]) + .assert() + .failure() + .stderr(predicate::str::contains("is not valid on regtest")); + } + + #[cfg(feature = "silent-payments")] + #[test] + fn test_create_sp_tx_rejects_code_from_wrong_network() { + let (cli, mut cmd_init) = setup_wallet_config(); + cmd_init.assert().success(); + + // Wallet is regtest, silent payment code is testnet. + let sp_code = BdkCli::new("testnet", cli.datadir.clone()) + .cmd( + "silent_payment_code", + &[ + "--scan_key", + "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "--spend_key", + "02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5", + ], + ) + .output() + .unwrap(); + let sp_code: Value = serde_json::from_slice(&sp_code.stdout).unwrap(); + let sp_recipient = format!("{}:1000", sp_code["message"].as_str().unwrap()); + + cli.wallet_cmd(&[ + "--wallet", + WALLET_NAME, + "create_sp_tx", + "--to-sp", + &sp_recipient, + ]) + .assert() + .failure() + .stderr(predicate::str::contains("is not valid for regtest")); + } + + #[cfg(feature = "silent-payments")] + #[test] + fn test_create_sp_tx_accepts_testnet_code_on_signet() { + let (cli, mut cmd_init) = setup_wallet_config_for("signet"); + cmd_init.assert().success(); + + // A signet `tsp` code parses as `Network::Testnet` in bdk_sp, but it + // must still be accepted by a signet wallet. + let sp_code = cli + .cmd( + "silent_payment_code", + &[ + "--scan_key", + "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "--spend_key", + "02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5", + ], + ) + .output() + .unwrap(); + let sp_code: Value = serde_json::from_slice(&sp_code.stdout).unwrap(); + let message = sp_code["message"].as_str().unwrap(); + assert!( + message.starts_with("tsp1"), + "a signet code should use the shared tsp prefix, got {message}" + ); + let sp_recipient = format!("{message}:1000"); + + // The wallet is empty, so the command fails on funds, not on the code. + cli.wallet_cmd(&[ + "--wallet", + WALLET_NAME, + "create_sp_tx", + "--to-sp", + &sp_recipient, + ]) + .assert() + .failure() + .stderr(predicate::str::contains("Insufficient")) + .stderr(predicate::str::contains("not valid on").not()); + } + + #[cfg(feature = "dns_payment")] + #[test] + fn test_create_dns_tx_rejects_address_from_wrong_network() { + let (cli, mut cmd_init) = setup_wallet_config(); + cmd_init.assert().success(); + + // Wallet is regtest, recipient is testnet. + let recipient = "tb1p4tp4l6glyr2gs94neqcpr5gha7344nfyznfkc8szkreflscsdkgqsdent4:1000"; + cli.wallet_cmd(&["--wallet", WALLET_NAME, "create_dns_tx", "--to", recipient]) + .assert() + .failure() + .stderr(predicate::str::contains("is not valid on regtest")); + } + + #[test] + fn test_create_tx_send_all_rejects_address_from_wrong_network() { + let (cli, mut cmd_init) = setup_wallet_config(); + cmd_init.assert().success(); + + // `--send_all` goes through `drain_to`, which must validate the address + // before it is turned into an output script. + let recipient = "tb1p4tp4l6glyr2gs94neqcpr5gha7344nfyznfkc8szkreflscsdkgqsdent4:0"; + cli.wallet_cmd(&[ + "--wallet", + WALLET_NAME, + "create_tx", + "--send_all", + "--to", + recipient, + ]) + .assert() + .failure() + .stderr(predicate::str::contains("is not valid on regtest")); + } + #[test] fn test_create_tx_send_all_rejects_multiple_recipients() { let (cli, mut cmd_init) = setup_wallet_config(); diff --git a/tests/integration/online.rs b/tests/integration/online.rs index 00066120..22b8bee6 100644 --- a/tests/integration/online.rs +++ b/tests/integration/online.rs @@ -10,7 +10,7 @@ mod test_online { use tempfile::TempDir; static WALLET_NAME: &str = "test_online_wallet"; - static RECIPIENT: &str = "tb1p4tp4l6glyr2gs94neqcpr5gha7344nfyznfkc8szkreflscsdkgqsdent4"; + static RECIPIENT: &str = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080"; /// Spins up the envt, a Regtest node + electrs, and saves the wallet config. fn setup_online_wallet() -> (BdkCli, Command, TestEnv) { @@ -415,6 +415,33 @@ mod test_online { .expect("electrs did not see the broadcast tx"); cli_sync(&cli); + // A shrink address from another network must be rejected instead of + // silently building a PSBT that pays it. + let output = cli + .wallet_cmd(&[ + "--wallet", + WALLET_NAME, + "bump_fee", + "--txid", + &original_txid.to_string(), + "--fee_rate", + "10.0", + "--shrink", + "tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx", + ]) + .output() + .expect("failed to spawn `bump_fee --shrink`"); + assert!( + !output.status.success(), + "bump_fee should reject a shrink address from another network, got: {}", + String::from_utf8_lossy(&output.stdout) + ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("is not valid on regtest"), + "unexpected error message: {stderr}" + ); + // Bump to a much higher fee rate; this should replace the original tx. let bumped_json = run_wallet_json( &cli,