From 5950c389c194d203e29b5dd9870ea7bf092c4974 Mon Sep 17 00:00:00 2001 From: Leo Nash Date: Wed, 2 Dec 2026 16:09:26 +0000 Subject: [PATCH 01/10] 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 02/10] 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(); + } } } } From 084151b14e45c274e735dbd7dad4876a57775cbb Mon Sep 17 00:00:00 2001 From: Leo Nash Date: Fri, 4 Dec 2026 17:56:00 +0000 Subject: [PATCH 03/10] f: Assert recovery needs the explicit rescan height --- tests/integration_tests_rust.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/integration_tests_rust.rs b/tests/integration_tests_rust.rs index 998b2a8e9f..3346684d68 100644 --- a/tests/integration_tests_rust.rs +++ b/tests/integration_tests_rust.rs @@ -2886,6 +2886,14 @@ async fn onchain_wallet_recovery_includes_rescan_height() { // Finding these payments must now depend on the explicit, inclusive rescan height. generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 10).await; + let mut outside_window_config = random_config(); + outside_window_config.node_entropy = original_node_entropy; + let outside_window_node = setup_node(&chain_source, outside_window_config); + outside_window_node.sync_wallets().unwrap(); + assert_eq!(outside_window_node.list_balances().total_onchain_balance_sats, 0); + outside_window_node.stop().unwrap(); + drop(outside_window_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. let mut birthday_recovery_config = random_config(); From 3e0c9bcc008fab37dc0fdb1a34c69cc357d02726 Mon Sep 17 00:00:00 2001 From: Leo Nash Date: Fri, 4 Dec 2026 17:58:42 +0000 Subject: [PATCH 04/10] f: Align the wallet birthday margin with LDK's block history --- CHANGELOG.md | 6 +++--- src/builder.rs | 14 +++++++------ tests/integration_tests_rust.rs | 36 +++++++++++++++++++-------------- 3 files changed, 32 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d3996f5081..1ea15755cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -75,7 +75,7 @@ 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) + 12 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,9 +97,9 @@ transaction. ## Bug Fixes and Improvements -- New Bitcoin Core RPC/REST wallets default to a checkpoint 10 blocks behind the chain tip +- New Bitcoin Core RPC/REST wallets default to a checkpoint 12 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 scan at least this window as well + up to 12 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 diff --git a/src/builder.rs b/src/builder.rs index 86208fba60..cfbe7a349e 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -29,6 +29,7 @@ use bitcoin::Network; use bitcoin_payment_instructions::dns_resolver::DNSHrnResolver; #[cfg(feature = "unified-payments")] use bitcoin_payment_instructions::onion_message_resolver::LDKOnionMessageDNSSECHrnResolver; +use lightning::chain::channelmonitor::ANTI_REORG_DELAY; use lightning::chain::{chainmonitor, BlockLocator}; use lightning::ln::channelmanager::{self, ChainParameters, ChannelManagerReadArgs}; use lightning::ln::msgs::{RoutingMessageHandler, SocketAddress}; @@ -121,8 +122,9 @@ 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; +// Match the ancestor-history capacity of LDK's BlockLocator. Keeping the initial sparse +// checkpoint behind the tip allows reorgs within this window to be replayed. +const WALLET_BIRTHDAY_BLOCK_BUFFER: u32 = ANTI_REORG_DELAY * 2; #[derive(Debug, Clone)] enum ChainDataSourceConfig { @@ -455,7 +457,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 10 blocks behind the current tip, or at genesis on shorter chains. Explicit + /// checkpoints 12 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")] @@ -486,7 +488,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 10 blocks behind the current tip, or at genesis on shorter chains. Explicit + /// checkpoints 12 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")] @@ -1133,7 +1135,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 10 blocks behind the current tip, or at genesis on shorter chains. Explicit + /// checkpoints 12 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( @@ -1161,7 +1163,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 10 blocks behind the current tip, or at genesis on shorter chains. Explicit + /// checkpoints 12 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( diff --git a/tests/integration_tests_rust.rs b/tests/integration_tests_rust.rs index 3346684d68..2450dd7600 100644 --- a/tests/integration_tests_rust.rs +++ b/tests/integration_tests_rust.rs @@ -2799,6 +2799,7 @@ async fn do_onchain_wallet_full_scan_stop_gap_recovers_far_funds( #[cfg(feature = "chain-bitcoind")] #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn onchain_wallet_recovery_includes_rescan_height() { + let birthday_margin = (ANTI_REORG_DELAY * 2) as usize; // End-to-end test for `wallet_rescan_from_height` against a bitcoind chain source. The // scenario: // @@ -2868,7 +2869,7 @@ async fn onchain_wallet_recovery_includes_rescan_height() { .unwrap(); generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 1).await; - // Step 5: a fresh node without a rescan height scans the last 10 blocks, including + // Step 5: a fresh node without a rescan height scans the birthday margin, including // the block containing both funding transactions. let mut default_config = random_config(); default_config.node_entropy = original_node_entropy; @@ -2884,7 +2885,7 @@ async fn onchain_wallet_recovery_includes_rescan_height() { // 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; + generate_blocks_and_wait(&bitcoind.client, &electrsd.client, birthday_margin).await; let mut outside_window_config = random_config(); outside_window_config.node_entropy = original_node_entropy; @@ -10255,6 +10256,7 @@ async fn lsps2_service_funding_fee_does_not_spend_anchor_reserve() { #[cfg(feature = "chain-bitcoind")] #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn wallet_birthday_survives_restart_before_first_sync() { + let birthday_margin = (ANTI_REORG_DELAY * 2) as usize; let (bitcoind, electrsd) = setup_bitcoind_and_electrsd(); let chain_source = TestChainSource::BitcoindRpcSync(&bitcoind); @@ -10274,8 +10276,8 @@ async fn wallet_birthday_survives_restart_before_first_sync() { Amount::from_sat(premine_amount_sat), ) .await; - // Put the payment before the default checkpoint, 10 blocks behind the tip. - generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 16).await; + // Put the payment before the default checkpoint, outside the birthday margin. + generate_blocks_and_wait(&bitcoind.client, &electrsd.client, birthday_margin + 6).await; let tip_height: u32 = bitcoind.client.get_blockchain_info().unwrap().blocks.try_into().unwrap(); for chain_source in @@ -10317,9 +10319,11 @@ 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() { + let birthday_margin = (ANTI_REORG_DELAY * 2) as usize; + let tip_height = (50 + birthday_margin) as u32; for use_rest in [false, true] { for (start_before_reorg, rescan_height) in - [(false, None), (true, None), (false, Some(60)), (true, Some(60))] + [(false, None), (true, None), (false, Some(tip_height)), (true, Some(tip_height))] { let mut core_config = corepc_node::Conf::default(); core_config.network = "regtest"; @@ -10349,8 +10353,8 @@ async fn wallet_birthday_margin_survives_reorg() { // 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(); - // Even an explicit rescan from the tip must retain the 10-block margin. + bitcoind.client.generate_to_address(birthday_margin - 1, &mining_address).unwrap(); + // Even an explicit rescan from the tip must retain the birthday 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"); @@ -10364,11 +10368,11 @@ async fn wallet_birthday_margin_survives_reorg() { 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 + // Replace the entire birthday margin, 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(); + bitcoind.client.generate_to_address(birthday_margin, &mining_address).unwrap(); if !start_before_reorg { // Reload the original checkpoint, rather than choosing a new birthday at 51. drop(node); @@ -10392,8 +10396,9 @@ async fn wallet_birthday_margin_survives_reorg() { #[cfg(feature = "chain-bitcoind")] #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn wallet_birthday_margin_handles_short_chains() { + let birthday_margin = (ANTI_REORG_DELAY * 2) as usize; for use_rest in [false, true] { - for height in [0, 1, 9, 10, 11] { + for height in [0, 1, birthday_margin - 1, birthday_margin, birthday_margin + 1] { let mut core_config = corepc_node::Conf::default(); core_config.network = "regtest"; core_config.args.push("-rest"); @@ -10429,11 +10434,12 @@ async fn wallet_birthday_margin_handles_short_chains() { .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 - }; + let expected = + if height > 0 && (height <= birthday_margin || rescan_height == Some(0)) { + 50 * 100_000_000 + } else { + 0 + }; assert_eq!( node.list_balances().total_onchain_balance_sats, expected, From 62cc4606246528714438332ba070c631531ab7f7 Mon Sep 17 00:00:00 2001 From: Leo Nash Date: Fri, 4 Dec 2026 17:59:45 +0000 Subject: [PATCH 05/10] f: Report birthday lookup failures as chain fetch errors --- src/builder.rs | 15 +++++++-------- tests/integration_tests_rust.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/src/builder.rs b/src/builder.rs index cfbe7a349e..40d5d356c2 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -237,12 +237,11 @@ pub enum BuildError { AsyncPaymentsConfigMismatch, /// An attempt to setup a DNS Resolver failed. DNSResolverSetupFailed, - /// We failed to determine the current chain tip on first startup. + /// We failed to fetch the current tip hash or the wallet birthday hash on first startup. /// - /// Returned when a fresh node is built against a Bitcoin Core RPC or REST chain source that - /// is unreachable or misconfigured, so we cannot learn the tip height/hash to use as the - /// wallet birthday. Falling back to genesis would silently force a full-history rescan on - /// the next successful startup, so we abort instead. + /// Returned when a fresh node's Bitcoin Core RPC or REST chain source fails to provide the + /// current tip hash or the wallet birthday hash. Falling back to genesis would silently + /// force a full-history rescan on the next successful startup, so we abort instead. ChainTipFetchFailed, /// The configured wallet rescan height is above the current chain tip. WalletRescanHeightTooHigh, @@ -287,7 +286,7 @@ impl fmt::Display for BuildError { Self::ChainTipFetchFailed => { write!( f, - "Failed to determine the current chain tip on first startup. Verify the chain data source is reachable and correctly configured." + "Failed to fetch the current tip hash or the wallet birthday hash on first startup. Verify the chain data source is reachable and correctly configured." ) }, Self::WalletRescanHeightTooHigh => { @@ -1944,11 +1943,11 @@ fn build_with_store_internal( .map_err(|e| { log_error!( logger, - "Failed to resolve wallet checkpoint block hash at height {}: {:?}", + "Failed to resolve the wallet birthday hash at height {}: {:?}", height, e ); - BuildError::WalletSetupFailed + BuildError::ChainTipFetchFailed })?; Some(BlockLocator::new(hash, height)) }, diff --git a/tests/integration_tests_rust.rs b/tests/integration_tests_rust.rs index 2450dd7600..24e1b97306 100644 --- a/tests/integration_tests_rust.rs +++ b/tests/integration_tests_rust.rs @@ -2924,6 +2924,32 @@ async fn onchain_wallet_recovery_includes_rescan_height() { ); } +#[cfg(feature = "chain-bitcoind")] +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn build_reports_birthday_lookup_failure_as_chain_fetch_failure() { + let mut core_config = corepc_node::Conf::default(); + // Allow fetching the current tip hash, but reject getblockhash for the wallet birthday hash. + core_config.args.push( + "-rpcwhitelist=__cookie__:getblockchaininfo,getblockheader,createwallet,loadwallet,stop", + ); + let bitcoind = + BitcoinD::with_conf(std::env::var("BITCOIND_EXE").unwrap(), &core_config).unwrap(); + let chain_source = TestChainSource::BitcoindRpcSync(&bitcoind); + for rescan_height in [None, Some(0)] { + let mut config = random_config(); + config.wallet_rescan_from_height = rescan_height; + setup_builder!(builder, config.node_config); + configure_chain_source(&chain_source, &mut builder, &config); + let logs = Arc::new(CollectingLogWriter::new()); + builder.set_custom_logger(logs.clone()); + let store = NamespaceWriteFailingStore::new("bdk_wallet"); + let result = builder.build_with_store(config.node_entropy.into(), store.clone()); + assert!(logs.contains("Failed to resolve the wallet birthday hash at height 0")); + assert_eq!(result.map(|_| ()), Err(BuildError::ChainTipFetchFailed)); + assert_eq!(store.write_attempts.load(Ordering::Acquire), 0); + } +} + #[cfg(feature = "chain-bitcoind")] #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn build_fails_when_wallet_rescan_height_is_above_tip() { From 51b92127d648910b5fb93f54d03309306c680d5e Mon Sep 17 00:00:00 2001 From: Leo Nash Date: Fri, 4 Dec 2026 18:04:26 +0000 Subject: [PATCH 06/10] f: Simplify birthday checkpoint selection --- src/builder.rs | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/src/builder.rs b/src/builder.rs index 40d5d356c2..649804f91f 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -1895,31 +1895,24 @@ 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. 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) => { - let chain_tip = chain_tip_opt.ok_or(BuildError::ChainTipFetchFailed)?; - if height > chain_tip.height { + let checkpoint_height = if let Some(chain_tip) = chain_tip_opt { + let mut height = chain_tip.height.saturating_sub(WALLET_BIRTHDAY_BLOCK_BUFFER); + if let Some(rescan_height) = wallet_rescan_from_height { + if rescan_height > chain_tip.height { log_error!( logger, "Wallet rescan height {} is above current chain tip {}.", - height, + rescan_height, chain_tip.height ); return Err(BuildError::WalletRescanHeightTooHigh); } // Synchronization connects blocks strictly above the checkpoint. - 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"), + height = height.min(rescan_height.saturating_sub(1)); + } + Some(height) + } else { + None }; let checkpoint_block: Option = match checkpoint_height { None => None, From bc4bb375f74f084ead90e22512805fb8a6dc984b Mon Sep 17 00:00:00 2001 From: Leo Nash Date: Fri, 4 Dec 2026 18:04:27 +0000 Subject: [PATCH 07/10] f: Explain the recovery test without historical context --- tests/integration_tests_rust.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/tests/integration_tests_rust.rs b/tests/integration_tests_rust.rs index 24e1b97306..41e063597b 100644 --- a/tests/integration_tests_rust.rs +++ b/tests/integration_tests_rust.rs @@ -2845,8 +2845,7 @@ async fn onchain_wallet_recovery_includes_rescan_height() { // Step 3: advance the chain past the original wallet birthday. generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 10).await; - // Step 4: queue both transactions before mining so they are confirmed in the same block, as - // exercised by the previous version of this test. + // Step 4: queue both transactions before mining so they are confirmed in the same block. let txid_1 = bitcoind .client .send_to_address(&addr_1, Amount::from_sat(premine_amount_sat)) @@ -2895,8 +2894,7 @@ async fn onchain_wallet_recovery_includes_rescan_height() { outside_window_node.stop().unwrap(); drop(outside_window_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. + // Step 6: recover from the original birthday and verify that both funding transactions are found. let mut birthday_recovery_config = random_config(); birthday_recovery_config.node_entropy = original_node_entropy; birthday_recovery_config.wallet_rescan_from_height = Some(birthday_height); From 9e96f18095c268fc2bc882434cfb5f9ec6d7295f Mon Sep 17 00:00:00 2001 From: Leo Nash Date: Fri, 4 Dec 2026 18:04:40 +0000 Subject: [PATCH 08/10] f: Document the limits of birthday reorg protection --- CHANGELOG.md | 3 ++- src/builder.rs | 12 ++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ea15755cf..392f494434 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -100,7 +100,8 @@ - New Bitcoin Core RPC/REST wallets default to a checkpoint 12 blocks behind the chain tip (or genesis on shorter chains), allowing reorgs within that window to be replayed. This adds up to 12 blocks of initial scanning. Explicit rescan heights scan at least this window as well - as all requested history. Existing wallets are unchanged. + as all requested history. Existing wallets are unchanged. Deeper reorgs that remove the + birthday checkpoint can still prevent wallet synchronization and require recovery. - `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 649804f91f..9ac94ac989 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -459,6 +459,9 @@ impl NodeBuilder { /// checkpoints 12 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. + /// + /// This margin does not guarantee recovery from deeper reorgs. If a reorg removes the + /// birthday checkpoint, the wallet may stop synchronizing and require recovery. #[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, @@ -490,6 +493,9 @@ impl NodeBuilder { /// checkpoints 12 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. + /// + /// This margin does not guarantee recovery from deeper reorgs. If a reorg removes the + /// birthday checkpoint, the wallet may stop synchronizing and require recovery. #[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, @@ -1137,6 +1143,9 @@ impl Builder { /// checkpoints 12 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. + /// + /// This margin does not guarantee recovery from deeper reorgs. If a reorg removes the + /// birthday checkpoint, the wallet may stop synchronizing and require recovery. 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, @@ -1165,6 +1174,9 @@ impl Builder { /// checkpoints 12 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. + /// + /// This margin does not guarantee recovery from deeper reorgs. If a reorg removes the + /// birthday checkpoint, the wallet may stop synchronizing and require recovery. 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, From 6deeccac2a4354c71c478a6636a79fc5e5d67d7b Mon Sep 17 00:00:00 2001 From: Leo Nash Date: Fri, 4 Dec 2026 18:22:40 +0000 Subject: [PATCH 09/10] f: Bound wallet checkpoint lookups by the chain polling timeout --- src/builder.rs | 24 +++++++++++++++--------- src/chain/bitcoind.rs | 2 +- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/builder.rs b/src/builder.rs index 9ac94ac989..27fd282dfe 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -1937,23 +1937,29 @@ fn build_with_store_internal( ); BuildError::WalletSetupFailed })?; - let hash = runtime - .block_on(async { + let hash = match runtime.block_on(async { + tokio::time::timeout( + std::time::Duration::from_secs( + crate::chain::bitcoind::CHAIN_POLLING_TIMEOUT_SECS, + ), lightning_block_sync::gossip::UtxoSource::get_block_hash_by_height( &utxo_source, height, - ) - .await - }) - .map_err(|e| { + ), + ) + .await + }) { + Ok(Ok(hash)) => hash, + failure => { log_error!( logger, "Failed to resolve the wallet birthday hash at height {}: {:?}", height, - e + failure ); - BuildError::ChainTipFetchFailed - })?; + return Err(BuildError::ChainTipFetchFailed); + }, + }; Some(BlockLocator::new(hash, height)) }, #[cfg(not(feature = "chain-bitcoind"))] diff --git a/src/chain/bitcoind.rs b/src/chain/bitcoind.rs index ea32aac901..530871ebb6 100644 --- a/src/chain/bitcoind.rs +++ b/src/chain/bitcoind.rs @@ -50,7 +50,7 @@ use crate::types::{Broadcaster, ChainMonitor, ChannelManager, DynStore, Sweeper, use crate::{Error, PersistedNodeMetrics}; const CHAIN_POLLING_INTERVAL_SECS: u64 = 2; -const CHAIN_POLLING_TIMEOUT_SECS: u64 = 10; +pub(crate) const CHAIN_POLLING_TIMEOUT_SECS: u64 = 10; type BitcoindSpvClient = SpvClient, BitcoindClient>, Arc>; From d6f580ea7de0e3365fc13f2ad5fea148db3f6b31 Mon Sep 17 00:00:00 2001 From: Leo Nash Date: Fri, 4 Dec 2026 18:23:46 +0000 Subject: [PATCH 10/10] f: Verify replacement payments after birthday reorgs --- tests/integration_tests_rust.rs | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/tests/integration_tests_rust.rs b/tests/integration_tests_rust.rs index 41e063597b..fce2eed4ee 100644 --- a/tests/integration_tests_rust.rs +++ b/tests/integration_tests_rust.rs @@ -10395,7 +10395,11 @@ async fn wallet_birthday_margin_survives_reorg() { // Replace the entire birthday margin, 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(); + let replacement_blocks = + bitcoind.client.generate_to_address(1, &replacement_address).unwrap(); + let replacement_block = + bitcoind.client.get_block(replacement_blocks.0[0].parse().unwrap()).unwrap(); + let replacement_txid = replacement_block.txdata[0].compute_txid(); bitcoind.client.generate_to_address(birthday_margin, &mining_address).unwrap(); if !start_before_reorg { // Reload the original checkpoint, rather than choosing a new birthday at 51. @@ -10406,12 +10410,34 @@ async fn wallet_birthday_margin_survives_reorg() { } node.sync_wallets().unwrap(); assert_eq!(node.list_balances().total_onchain_balance_sats, 50 * 100_000_000); + assert!( + node.list_all_payments().iter().any(|payment| matches!( + payment.kind, + PaymentKind::Onchain { + txid, + status: ConfirmationStatus::Confirmed { height: 51, .. }, + .. + } if txid == replacement_txid + )), + "replacement payment must be confirmed, REST={use_rest}, started={start_before_reorg}, rescan={rescan_height:?}" + ); 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); + assert!( + node.list_all_payments().iter().any(|payment| matches!( + payment.kind, + PaymentKind::Onchain { + txid, + status: ConfirmationStatus::Confirmed { height: 51, .. }, + .. + } if txid == replacement_txid + )), + "replacement payment must be confirmed, REST={use_rest}, started={start_before_reorg}, rescan={rescan_height:?}" + ); node.stop().unwrap(); } }