From 5950c389c194d203e29b5dd9870ea7bf092c4974 Mon Sep 17 00:00:00 2001 From: Leo Nash Date: Wed, 2 Dec 2026 16:09:26 +0000 Subject: [PATCH 1/2] Protect new wallets from reorgs near their birthday For wallets using Bitcoin Core, a reorg that removes the birthday checkpoint can leave BDK unable to connect replacement blocks to its saved checkpoints. The wallet then stops tracking the active chain: incoming payments can go undiscovered and balances can remain stale. Restarting reloads the same orphaned checkpoint, leaving the user needing wallet recovery. Using the current tip as the birthday exposes a newly created wallet to this failure after even a one-block reorg, including before its first sync. Avoiding historical scanning should not make ordinary chain reorganizations require user intervention. We budget for reorgs of up to 10 blocks. Accepting up to 10 additional blocks of initial scanning gives the wallet a checkpoint outside that window. This bounded startup cost is preferable to leaving a fresh wallet unable to synchronize until recovered. Co-Authored-By: Codex --- CHANGELOG.md | 11 ++- src/builder.rs | 71 ++++++++------- tests/integration_tests_rust.rs | 149 ++++++++++++++++++++++++++++---- 3 files changed, 178 insertions(+), 53 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f1f8d9769..f95aa32125 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,10 +72,10 @@ an LSP when an inbound payment is received through an LSPS2 just-in-time channel. - The Bitcoin Core RPC and REST chain-source builder methods now accept an optional `wallet_rescan_from_height` argument. Passing a height lets fresh wallets rescan from a known - birthday block instead of checkpointing at the current tip, which is useful when restoring a - wallet on a pruned node where the full history is unavailable but the wallet birthday height is - known. Existing wallets are not rewound, and future heights fail the build. Passing `Some(0)` - rescans from genesis; passing `None` keeps the default current-tip checkpoint behavior. (#884) + birthday block, which is useful when restoring a wallet on a pruned node where the full history + is unavailable but the wallet birthday height is known. Existing wallets are not rewound, and + future heights fail the build. Passing `Some(0)` rescans from genesis; passing `None` checkpoints + 10 blocks behind the current tip, or at genesis on shorter chains. (#884) - `EsploraSyncConfig` and `ElectrumSyncConfig` now support `force_wallet_full_scan`. When set, the on-chain wallet keeps using BDK `full_scan` instead of incremental sync until a full scan succeeds, allowing restored wallets to rediscover funds sent to previously-unknown addresses. @@ -97,6 +97,9 @@ transaction. ## Bug Fixes and Improvements +- New Bitcoin Core RPC/REST wallets default to a checkpoint 10 blocks behind the chain tip + (or genesis on shorter chains), allowing reorgs within that window to be replayed. This adds + up to 10 blocks of initial scanning. Explicit rescan heights and existing wallets are unchanged. - `Node::bump_channel_funding_fee` can now fee-bump a splice made with `Node::splice_in_with_all` without spending the anchor reserve or failing for lack of a change output. The splice now spends the wallet's confirmed UTXOs in full, so a bump is paid by adding diff --git a/src/builder.rs b/src/builder.rs index 964684a660..e5410ec31f 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -121,6 +121,8 @@ use crate::{Node, NodeMetrics, PersistedNodeMetrics}; const LSPS_HARDENED_CHILD_INDEX: u32 = 577; const PERSISTER_MAX_PENDING_UPDATES: u64 = 100; +// Keep the initial sparse checkpoint behind the tip so reorgs within this window can be replayed. +const WALLET_BIRTHDAY_BLOCK_BUFFER: u32 = 10; #[derive(Debug, Clone)] enum ChainDataSourceConfig { @@ -453,7 +455,7 @@ impl NodeBuilder { /// * `wallet_rescan_from_height` - Optional wallet birthday height to rescan from (inclusive) on /// first startup, before wallet state exists. Existing wallets are not rewound. The height /// must be at or below the current tip. Passing `Some(0)` rescans from genesis; passing `None` - /// checkpoints at the current tip. + /// checkpoints 10 blocks behind the current tip, or at genesis on shorter chains. #[cfg(feature = "chain-bitcoind")] pub fn set_chain_source_bitcoind_rpc( &mut self, rpc_host: String, rpc_port: u16, rpc_user: String, rpc_password: String, @@ -482,7 +484,7 @@ impl NodeBuilder { /// * `wallet_rescan_from_height` - Optional wallet birthday height to rescan from (inclusive) on /// first startup, before wallet state exists. Existing wallets are not rewound. The height /// must be at or below the current tip. Passing `Some(0)` rescans from genesis; passing `None` - /// checkpoints at the current tip. + /// checkpoints 10 blocks behind the current tip, or at genesis on shorter chains. #[cfg(feature = "chain-bitcoind")] pub fn set_chain_source_bitcoind_rest( &mut self, rest_host: String, rest_port: u16, rpc_host: String, rpc_port: u16, @@ -1127,7 +1129,7 @@ impl Builder { /// * `wallet_rescan_from_height` - Optional wallet birthday height to rescan from (inclusive) on /// first startup, before wallet state exists. Existing wallets are not rewound. The height /// must be at or below the current tip. Passing `Some(0)` rescans from genesis; passing `None` - /// checkpoints at the current tip. + /// checkpoints 10 blocks behind the current tip, or at genesis on shorter chains. pub fn set_chain_source_bitcoind_rpc( &self, rpc_host: String, rpc_port: u16, rpc_user: String, rpc_password: String, wallet_rescan_from_height: Option, @@ -1153,7 +1155,7 @@ impl Builder { /// * `wallet_rescan_from_height` - Optional wallet birthday height to rescan from (inclusive) on /// first startup, before wallet state exists. Existing wallets are not rewound. The height /// must be at or below the current tip. Passing `Some(0)` rescans from genesis; passing `None` - /// checkpoints at the current tip. + /// checkpoints 10 blocks behind the current tip, or at genesis on shorter chains. pub fn set_chain_source_bitcoind_rest( &self, rest_host: String, rest_port: u16, rpc_host: String, rpc_port: u16, rpc_user: String, rpc_password: String, wallet_rescan_from_height: Option, @@ -1880,12 +1882,12 @@ fn build_with_store_internal( BuildError::WalletSetupFailed })?; - // Decide which block (if any) to insert as the initial BDK checkpoint. If the - // bitcoind config provides a wallet rescan height, use the preceding block as the - // checkpoint so synchronization includes the requested height. Otherwise, use the - // current chain tip to avoid any rescan. - let checkpoint_block = match wallet_rescan_from_height { - None => chain_tip_opt, + // Default to a checkpoint behind the tip so a reorg does not immediately invalidate + // the wallet's sparse birthday checkpoint. An explicit rescan height remains inclusive. + let checkpoint_height = match wallet_rescan_from_height { + None => { + chain_tip_opt.map(|tip| tip.height.saturating_sub(WALLET_BIRTHDAY_BLOCK_BUFFER)) + }, #[cfg(feature = "chain-bitcoind")] Some(height) => { if let Some(chain_tip) = chain_tip_opt { @@ -1899,41 +1901,44 @@ fn build_with_store_internal( return Err(BuildError::WalletRescanHeightTooHigh); } } - // `synchronize_listeners` connects blocks strictly above each listener's - // checkpoint. The genesis block is already BDK's initial checkpoint, so - // saturating subtraction also handles a requested height of zero. - let checkpoint_height = height.saturating_sub(1); - + // Synchronization connects blocks strictly above the checkpoint. + Some(height.saturating_sub(1)) + }, + #[cfg(not(feature = "chain-bitcoind"))] + Some(_) => unreachable!("wallet rescans require the chain-bitcoind feature"), + }; + let checkpoint_block: Option = match checkpoint_height { + None => None, + #[cfg(feature = "chain-bitcoind")] + Some(height) => { let utxo_source = chain_source.as_utxo_source().ok_or_else(|| { log_error!( logger, - "Wallet rescan height requested but the chain source does not support block-by-height lookups.", + "Wallet checkpoint requested but the chain source does not support block-by-height lookups." ); BuildError::WalletSetupFailed })?; - let hash_res = runtime.block_on(async { - lightning_block_sync::gossip::UtxoSource::get_block_hash_by_height( - &utxo_source, - checkpoint_height, - ) - .await - }); - match hash_res { - Ok(hash) => Some(BlockLocator::new(hash, checkpoint_height)), - Err(e) => { + let hash = runtime + .block_on(async { + lightning_block_sync::gossip::UtxoSource::get_block_hash_by_height( + &utxo_source, + height, + ) + .await + }) + .map_err(|e| { log_error!( logger, - "Failed to resolve checkpoint block hash at height {} for wallet rescan from height {}: {:?}", - checkpoint_height, + "Failed to resolve wallet checkpoint block hash at height {}: {:?}", height, - e, + e ); - return Err(BuildError::WalletSetupFailed); - }, - } + BuildError::WalletSetupFailed + })?; + Some(BlockLocator::new(hash, height)) }, #[cfg(not(feature = "chain-bitcoind"))] - Some(_) => unreachable!("wallet rescans require the chain-bitcoind feature"), + Some(_) => unreachable!("wallet checkpoints require the chain-bitcoind feature"), }; if let Some(best_block) = checkpoint_block { diff --git a/tests/integration_tests_rust.rs b/tests/integration_tests_rust.rs index c307d02b4e..89f20e4689 100644 --- a/tests/integration_tests_rust.rs +++ b/tests/integration_tests_rust.rs @@ -2806,8 +2806,8 @@ async fn onchain_wallet_recovery_includes_rescan_height() { // 2. Shut the node down and drop all persisted state except the seed. // 3. Advance the chain past the birthday. // 4. Send funds to both addresses and confirm both transactions in the same block. - // 5. Restart a fresh node with just the seed and no rescan height. Its wallet birthday - // is pinned at the funding block, so the node must not see the funds. + // 5. Restart a fresh node with just the seed and no rescan height. Its default scan window + // includes the funding block, so the node must see the funds. // 6. Restart with the original birthday as `wallet_rescan_from_height` and confirm both // transactions are found, preserving the previous test case. // 7. Restart again with the funding block itself as `wallet_rescan_from_height` and confirm @@ -2868,19 +2868,19 @@ async fn onchain_wallet_recovery_includes_rescan_height() { .unwrap(); generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 1).await; - // Step 5: restart a fresh node with only the seed and no rescan height. It must NOT see the - // funds, because its wallet birthday is the block containing both funding transactions. - let mut pinned_config = random_config(); - pinned_config.node_entropy = original_node_entropy; - let pinned_node = setup_node(&chain_source, pinned_config); - pinned_node.sync_wallets().unwrap(); + // Step 5: a fresh node without a rescan height scans the last 10 blocks, including + // the block containing both funding transactions. + let mut default_config = random_config(); + default_config.node_entropy = original_node_entropy; + let default_node = setup_node(&chain_source, default_config); + default_node.sync_wallets().unwrap(); assert_eq!( - pinned_node.list_balances().spendable_onchain_balance_sats, - 0, - "fresh node without rescan height should not scan its wallet birthday block" + default_node.list_balances().spendable_onchain_balance_sats, + premine_amount_sat * 2, + "the default scan window should include both recent funding transactions" ); - pinned_node.stop().unwrap(); - drop(pinned_node); + default_node.stop().unwrap(); + drop(default_node); // Step 6: recover from the original wallet birthday, retaining the previous test's case where // both transactions are found 11 blocks after the configured rescan height. @@ -10251,8 +10251,7 @@ async fn wallet_birthday_survives_restart_before_first_sync() { let addr = helper_node.onchain_payment().new_address().unwrap(); helper_node.stop().unwrap(); - // Pay to the address before the nodes under test are first built, i.e., before their - // birthday. + // Pay before the default scan window of the nodes under test. let premine_amount_sat = 100_000; premine_and_distribute_funds( &bitcoind.client, @@ -10261,7 +10260,8 @@ async fn wallet_birthday_survives_restart_before_first_sync() { Amount::from_sat(premine_amount_sat), ) .await; - generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await; + // Put the payment before the default checkpoint, 10 blocks behind the tip. + generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 16).await; let tip_height: u32 = bitcoind.client.get_blockchain_info().unwrap().blocks.try_into().unwrap(); for chain_source in @@ -10299,3 +10299,120 @@ async fn wallet_birthday_survives_restart_before_first_sync() { } } } + +#[cfg(feature = "chain-bitcoind")] +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn wallet_birthday_margin_survives_reorg() { + for use_rest in [false, true] { + for start_before_reorg in [false, true] { + let mut core_config = corepc_node::Conf::default(); + core_config.network = "regtest"; + core_config.args.push("-rest"); + let bitcoind = BitcoinD::with_conf( + std::env::var("BITCOIND_EXE").expect("set BITCOIND_EXE"), + &core_config, + ) + .unwrap(); + let mining_address = bitcoind.client.new_address().unwrap(); + let chain_source = if use_rest { + TestChainSource::BitcoindRestSync(&bitcoind) + } else { + TestChainSource::BitcoindRpcSync(&bitcoind) + }; + let config = random_config(); + setup_builder!(builder, config.node_config); + configure_chain_source(&chain_source, &mut builder, &config); + + // Learn addresses without leaving wallet state for the node under test. + let helper = + builder.build_with_store(config.node_entropy.into(), InMemoryStore::new()).unwrap(); + let old_address = helper.onchain_payment().new_address().unwrap(); + let replacement_address = helper.onchain_payment().new_address().unwrap(); + drop(helper); + bitcoind.client.generate_to_address(49, &mining_address).unwrap(); + // Height 50 must be excluded; height 51 must be scanned. + bitcoind.client.generate_to_address(1, &old_address).unwrap(); + let old_blocks = bitcoind.client.generate_to_address(1, &old_address).unwrap(); + bitcoind.client.generate_to_address(9, &mining_address).unwrap(); + let store = NamespaceWriteFailingStore::new_for_key("bdk_wallet", "local_chain"); + let build_node = + || builder.build_with_store(config.node_entropy.into(), store.clone()).unwrap(); + let mut node = build_node(); + assert_eq!(store.write_attempts.load(Ordering::Acquire), 1); + if start_before_reorg { + node.start().unwrap(); + node.sync_wallets().unwrap(); + assert_eq!(node.list_balances().total_onchain_balance_sats, 50 * 100_000_000); + } + + // Replace exactly 10 blocks, keeping the checkpoint at height 50. The first + // replacement block pays the wallet, so skipping any replayed blocks loses funds. + bitcoind.client.invalidate_block(old_blocks.0[0].parse().unwrap()).unwrap(); + bitcoind.client.generate_to_address(1, &replacement_address).unwrap(); + bitcoind.client.generate_to_address(10, &mining_address).unwrap(); + if !start_before_reorg { + // Reload the original checkpoint, rather than choosing a new birthday at 51. + drop(node); + node = build_node(); + assert_eq!(store.write_attempts.load(Ordering::Acquire), 1); + node.start().unwrap(); + } + node.sync_wallets().unwrap(); + assert_eq!(node.list_balances().total_onchain_balance_sats, 50 * 100_000_000); + node.stop().unwrap(); + drop(node); + let node = build_node(); + node.start().unwrap(); + node.sync_wallets().unwrap(); + assert_eq!(node.list_balances().total_onchain_balance_sats, 50 * 100_000_000); + node.stop().unwrap(); + } + } +} + +#[cfg(feature = "chain-bitcoind")] +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn wallet_birthday_margin_handles_short_chains() { + for use_rest in [false, true] { + for height in [0, 1, 9, 10, 11] { + let mut core_config = corepc_node::Conf::default(); + core_config.network = "regtest"; + core_config.args.push("-rest"); + let bitcoind = BitcoinD::with_conf( + std::env::var("BITCOIND_EXE").expect("set BITCOIND_EXE"), + &core_config, + ) + .unwrap(); + let chain_source = if use_rest { + TestChainSource::BitcoindRestSync(&bitcoind) + } else { + TestChainSource::BitcoindRpcSync(&bitcoind) + }; + let config = random_config(); + setup_builder!(builder, config.node_config); + configure_chain_source(&chain_source, &mut builder, &config); + let helper = + builder.build_with_store(config.node_entropy.into(), InMemoryStore::new()).unwrap(); + let address = helper.onchain_payment().new_address().unwrap(); + drop(helper); + if height > 0 { + bitcoind.client.generate_to_address(1, &address).unwrap(); + } + if height > 1 { + let mining_address = bitcoind.client.new_address().unwrap(); + bitcoind.client.generate_to_address(height - 1, &mining_address).unwrap(); + } + let node = + builder.build_with_store(config.node_entropy.into(), InMemoryStore::new()).unwrap(); + node.start().unwrap(); + node.sync_wallets().unwrap(); + let expected = if height > 0 && height <= 10 { 50 * 100_000_000 } else { 0 }; + assert_eq!( + node.list_balances().total_onchain_balance_sats, + expected, + "REST={use_rest}, tip={height}" + ); + node.stop().unwrap(); + } + } +} From e3eb88d7be132fd7f6d7079a88970a9300662f54 Mon Sep 17 00:00:00 2001 From: Leo Nash Date: Wed, 2 Dec 2026 23:25:21 +0000 Subject: [PATCH 2/2] Protect explicit wallet rescans from birthday reorgs Requesting a recent rescan height should not leave a new Bitcoin Core wallet more vulnerable to reorgs than using the default. If its birthday checkpoint is removed, the wallet can stop following the active chain. Restarting reloads the same checkpoint, leaving the user needing wallet recovery. Treat the requested height as history we must include, while retaining at least the same 10-block margin as the default. Scanning a little extra history is preferable to requiring wallet recovery after an ordinary reorg, and earlier requests must never lose any requested history. A fresh wallet therefore needs a known chain tip even when an explicit rescan height is supplied. Co-Authored-By: Codex --- CHANGELOG.md | 3 +- src/builder.rs | 47 ++++++++++------ tests/integration_tests_rust.rs | 96 ++++++++++++++++++++------------- 3 files changed, 90 insertions(+), 56 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f95aa32125..d3996f5081 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -99,7 +99,8 @@ ## Bug Fixes and Improvements - New Bitcoin Core RPC/REST wallets default to a checkpoint 10 blocks behind the chain tip (or genesis on shorter chains), allowing reorgs within that window to be replayed. This adds - up to 10 blocks of initial scanning. Explicit rescan heights and existing wallets are unchanged. + up to 10 blocks of initial scanning. Explicit rescan heights scan at least this window as well + as all requested history. Existing wallets are unchanged. - `Node::bump_channel_funding_fee` can now fee-bump a splice made with `Node::splice_in_with_all` without spending the anchor reserve or failing for lack of a change output. The splice now spends the wallet's confirmed UTXOs in full, so a bump is paid by adding diff --git a/src/builder.rs b/src/builder.rs index e5410ec31f..86208fba60 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -455,7 +455,9 @@ impl NodeBuilder { /// * `wallet_rescan_from_height` - Optional wallet birthday height to rescan from (inclusive) on /// first startup, before wallet state exists. Existing wallets are not rewound. The height /// must be at or below the current tip. Passing `Some(0)` rescans from genesis; passing `None` - /// checkpoints 10 blocks behind the current tip, or at genesis on shorter chains. + /// checkpoints 10 blocks behind the current tip, or at genesis on shorter chains. Explicit + /// heights also scan at least this window, starting earlier if needed to include the + /// requested height. #[cfg(feature = "chain-bitcoind")] pub fn set_chain_source_bitcoind_rpc( &mut self, rpc_host: String, rpc_port: u16, rpc_user: String, rpc_password: String, @@ -484,7 +486,9 @@ impl NodeBuilder { /// * `wallet_rescan_from_height` - Optional wallet birthday height to rescan from (inclusive) on /// first startup, before wallet state exists. Existing wallets are not rewound. The height /// must be at or below the current tip. Passing `Some(0)` rescans from genesis; passing `None` - /// checkpoints 10 blocks behind the current tip, or at genesis on shorter chains. + /// checkpoints 10 blocks behind the current tip, or at genesis on shorter chains. Explicit + /// heights also scan at least this window, starting earlier if needed to include the + /// requested height. #[cfg(feature = "chain-bitcoind")] pub fn set_chain_source_bitcoind_rest( &mut self, rest_host: String, rest_port: u16, rpc_host: String, rpc_port: u16, @@ -1129,7 +1133,9 @@ impl Builder { /// * `wallet_rescan_from_height` - Optional wallet birthday height to rescan from (inclusive) on /// first startup, before wallet state exists. Existing wallets are not rewound. The height /// must be at or below the current tip. Passing `Some(0)` rescans from genesis; passing `None` - /// checkpoints 10 blocks behind the current tip, or at genesis on shorter chains. + /// checkpoints 10 blocks behind the current tip, or at genesis on shorter chains. Explicit + /// heights also scan at least this window, starting earlier if needed to include the + /// requested height. pub fn set_chain_source_bitcoind_rpc( &self, rpc_host: String, rpc_port: u16, rpc_user: String, rpc_password: String, wallet_rescan_from_height: Option, @@ -1155,7 +1161,9 @@ impl Builder { /// * `wallet_rescan_from_height` - Optional wallet birthday height to rescan from (inclusive) on /// first startup, before wallet state exists. Existing wallets are not rewound. The height /// must be at or below the current tip. Passing `Some(0)` rescans from genesis; passing `None` - /// checkpoints 10 blocks behind the current tip, or at genesis on shorter chains. + /// checkpoints 10 blocks behind the current tip, or at genesis on shorter chains. Explicit + /// heights also scan at least this window, starting earlier if needed to include the + /// requested height. pub fn set_chain_source_bitcoind_rest( &self, rest_host: String, rest_port: u16, rpc_host: String, rpc_port: u16, rpc_user: String, rpc_password: String, wallet_rescan_from_height: Option, @@ -1855,6 +1863,7 @@ fn build_with_store_internal( // if we are creating a new wallet but failed to learn the current chain tip from // a Bitcoin Core RPC/REST backend, we'd otherwise persist fresh wallet state // pinned at height 0 and force a full-history rescan once the backend comes back. + // Explicit rescan heights also need the tip to enforce the birthday margin. // Abort cleanly instead so the misconfiguration surfaces on the first startup. // Esplora/Electrum backends currently never return a tip at build time, so they // retain their existing behavior. @@ -1864,7 +1873,7 @@ fn build_with_store_internal( #[cfg(not(feature = "chain-bitcoind"))] let uses_bitcoind = false; - if wallet_rescan_from_height.is_none() && chain_tip_opt.is_none() && uses_bitcoind { + if chain_tip_opt.is_none() && uses_bitcoind { log_error!( logger, "Failed to determine chain tip on first startup. Aborting to avoid pinning the wallet birthday to genesis." @@ -1883,26 +1892,30 @@ fn build_with_store_internal( })?; // Default to a checkpoint behind the tip so a reorg does not immediately invalidate - // the wallet's sparse birthday checkpoint. An explicit rescan height remains inclusive. + // the wallet's sparse birthday checkpoint. Scan at least the requested history and + // at least the birthday margin, even when an explicit rescan height is supplied. let checkpoint_height = match wallet_rescan_from_height { None => { chain_tip_opt.map(|tip| tip.height.saturating_sub(WALLET_BIRTHDAY_BLOCK_BUFFER)) }, #[cfg(feature = "chain-bitcoind")] Some(height) => { - if let Some(chain_tip) = chain_tip_opt { - if height > chain_tip.height { - log_error!( - logger, - "Wallet rescan height {} is above current chain tip {}.", - height, - chain_tip.height - ); - return Err(BuildError::WalletRescanHeightTooHigh); - } + let chain_tip = chain_tip_opt.ok_or(BuildError::ChainTipFetchFailed)?; + if height > chain_tip.height { + log_error!( + logger, + "Wallet rescan height {} is above current chain tip {}.", + height, + chain_tip.height + ); + return Err(BuildError::WalletRescanHeightTooHigh); } // Synchronization connects blocks strictly above the checkpoint. - Some(height.saturating_sub(1)) + Some( + height + .saturating_sub(1) + .min(chain_tip.height.saturating_sub(WALLET_BIRTHDAY_BLOCK_BUFFER)), + ) }, #[cfg(not(feature = "chain-bitcoind"))] Some(_) => unreachable!("wallet rescans require the chain-bitcoind feature"), diff --git a/tests/integration_tests_rust.rs b/tests/integration_tests_rust.rs index 89f20e4689..998b2a8e9f 100644 --- a/tests/integration_tests_rust.rs +++ b/tests/integration_tests_rust.rs @@ -2808,13 +2808,13 @@ async fn onchain_wallet_recovery_includes_rescan_height() { // 4. Send funds to both addresses and confirm both transactions in the same block. // 5. Restart a fresh node with just the seed and no rescan height. Its default scan window // includes the funding block, so the node must see the funds. - // 6. Restart with the original birthday as `wallet_rescan_from_height` and confirm both - // transactions are found, preserving the previous test case. + // 6. Move the funds outside the default window, restart with the original birthday as + // `wallet_rescan_from_height`, and confirm both transactions are found. // 7. Restart again with the funding block itself as `wallet_rescan_from_height` and confirm // both transactions are found, proving that the configured height is inclusive. let (bitcoind, electrsd) = setup_bitcoind_and_electrsd(); // We specifically exercise the bitcoind RPC backend because that's where - // `rescan_from_height` is honored precisely (via `get_block_hash_by_height`). + // `rescan_from_height` selects a checkpoint via `get_block_hash_by_height`. let chain_source = TestChainSource::BitcoindRpcSync(&bitcoind); // Mine the initial 101 blocks so bitcoind's wallet can fund our later sends. @@ -2882,6 +2882,10 @@ async fn onchain_wallet_recovery_includes_rescan_height() { default_node.stop().unwrap(); drop(default_node); + // Put the funding block at the default checkpoint, outside the default scan window. + // Finding these payments must now depend on the explicit, inclusive rescan height. + generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 10).await; + // Step 6: recover from the original wallet birthday, retaining the previous test's case where // both transactions are found 11 blocks after the configured rescan height. let mut birthday_recovery_config = random_config(); @@ -2955,29 +2959,31 @@ async fn build_aborts_on_first_startup_bitcoind_tip_fetch_failure() { // A fresh node pointed at an unreachable bitcoind RPC endpoint must not silently // fall back to genesis as the wallet birthday. The build must abort cleanly so the // misconfiguration surfaces immediately. - let config = random_config(); - let entropy = config.node_entropy; + for rescan_height in [None, Some(0), Some(100)] { + let config = random_config(); + let entropy = config.node_entropy; - setup_builder!(builder, config.node_config); - // Pick a localhost port that is extremely unlikely to be bound. The kernel will - // refuse the connection immediately so the test does not have to wait for the - // chain-polling timeout. - let unreachable_port: u16 = 1; - builder.set_chain_source_bitcoind_rpc( - "127.0.0.1".to_string(), - unreachable_port, - "user".to_string(), - "password".to_string(), - None, - ); + setup_builder!(builder, config.node_config); + // Pick a localhost port that is extremely unlikely to be bound. The kernel will + // refuse the connection immediately so the test does not have to wait for the + // chain-polling timeout. + let unreachable_port: u16 = 1; + builder.set_chain_source_bitcoind_rpc( + "127.0.0.1".to_string(), + unreachable_port, + "user".to_string(), + "password".to_string(), + rescan_height, + ); - let res = builder.build(entropy.into()); - match res { - Err(BuildError::ChainTipFetchFailed) => {}, - other => panic!( - "expected BuildError::ChainTipFetchFailed on fresh node with unreachable bitcoind, got {:?}", - other.map(|_| "Ok(_)") - ), + let res = builder.build(entropy.into()); + match res { + Err(BuildError::ChainTipFetchFailed) => {}, + other => panic!( + "expected BuildError::ChainTipFetchFailed on fresh node with unreachable bitcoind, got {:?}", + other.map(|_| "Ok(_)") + ), + } } } @@ -10304,7 +10310,9 @@ async fn wallet_birthday_survives_restart_before_first_sync() { #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn wallet_birthday_margin_survives_reorg() { for use_rest in [false, true] { - for start_before_reorg in [false, true] { + for (start_before_reorg, rescan_height) in + [(false, None), (true, None), (false, Some(60)), (true, Some(60))] + { let mut core_config = corepc_node::Conf::default(); core_config.network = "regtest"; core_config.args.push("-rest"); @@ -10319,7 +10327,7 @@ async fn wallet_birthday_margin_survives_reorg() { } else { TestChainSource::BitcoindRpcSync(&bitcoind) }; - let config = random_config(); + let mut config = random_config(); setup_builder!(builder, config.node_config); configure_chain_source(&chain_source, &mut builder, &config); @@ -10334,6 +10342,9 @@ async fn wallet_birthday_margin_survives_reorg() { bitcoind.client.generate_to_address(1, &old_address).unwrap(); let old_blocks = bitcoind.client.generate_to_address(1, &old_address).unwrap(); bitcoind.client.generate_to_address(9, &mining_address).unwrap(); + // Even an explicit rescan from the tip must retain the 10-block margin. + config.wallet_rescan_from_height = rescan_height; + configure_chain_source(&chain_source, &mut builder, &config); let store = NamespaceWriteFailingStore::new_for_key("bdk_wallet", "local_chain"); let build_node = || builder.build_with_store(config.node_entropy.into(), store.clone()).unwrap(); @@ -10388,7 +10399,7 @@ async fn wallet_birthday_margin_handles_short_chains() { } else { TestChainSource::BitcoindRpcSync(&bitcoind) }; - let config = random_config(); + let mut config = random_config(); setup_builder!(builder, config.node_config); configure_chain_source(&chain_source, &mut builder, &config); let helper = @@ -10402,17 +10413,26 @@ async fn wallet_birthday_margin_handles_short_chains() { let mining_address = bitcoind.client.new_address().unwrap(); bitcoind.client.generate_to_address(height - 1, &mining_address).unwrap(); } - let node = - builder.build_with_store(config.node_entropy.into(), InMemoryStore::new()).unwrap(); - node.start().unwrap(); - node.sync_wallets().unwrap(); - let expected = if height > 0 && height <= 10 { 50 * 100_000_000 } else { 0 }; - assert_eq!( - node.list_balances().total_onchain_balance_sats, - expected, - "REST={use_rest}, tip={height}" - ); - node.stop().unwrap(); + for rescan_height in [None, Some(height as u32), Some(0)] { + config.wallet_rescan_from_height = rescan_height; + configure_chain_source(&chain_source, &mut builder, &config); + let node = builder + .build_with_store(config.node_entropy.into(), InMemoryStore::new()) + .unwrap(); + node.start().unwrap(); + node.sync_wallets().unwrap(); + let expected = if height > 0 && (height <= 10 || rescan_height == Some(0)) { + 50 * 100_000_000 + } else { + 0 + }; + assert_eq!( + node.list_balances().total_onchain_balance_sats, + expected, + "REST={use_rest}, tip={height}, rescan={rescan_height:?}" + ); + node.stop().unwrap(); + } } } }