diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f1f8d9769..392f494434 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 + 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,6 +97,11 @@ transaction. ## Bug Fixes and Improvements +- 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. 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 964684a660..27fd282dfe 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,6 +122,9 @@ use crate::{Node, NodeMetrics, PersistedNodeMetrics}; const LSPS_HARDENED_CHILD_INDEX: u32 = 577; const PERSISTER_MAX_PENDING_UPDATES: u64 = 100; +// 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 { @@ -233,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, @@ -283,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 => { @@ -453,7 +456,12 @@ 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 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, @@ -482,7 +490,12 @@ 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 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, @@ -1127,7 +1140,12 @@ 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 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, @@ -1153,7 +1171,12 @@ 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 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, @@ -1853,6 +1876,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. @@ -1862,7 +1886,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." @@ -1880,60 +1904,66 @@ 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. Scan at least the requested history and + // at least the birthday margin, even when an explicit rescan height is supplied. + 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 {}.", + rescan_height, + chain_tip.height + ); + return Err(BuildError::WalletRescanHeightTooHigh); + } + // Synchronization connects blocks strictly above the checkpoint. + height = height.min(rescan_height.saturating_sub(1)); + } + Some(height) + } else { + None + }; + let checkpoint_block: Option = match checkpoint_height { + None => None, #[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); - } - } - // `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); - 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, + 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 - }); - match hash_res { - Ok(hash) => Some(BlockLocator::new(hash, checkpoint_height)), - Err(e) => { + }) { + Ok(Ok(hash)) => hash, + failure => { log_error!( logger, - "Failed to resolve checkpoint block hash at height {} for wallet rescan from height {}: {:?}", - checkpoint_height, + "Failed to resolve the wallet birthday hash at height {}: {:?}", height, - e, + failure ); - return Err(BuildError::WalletSetupFailed); + return Err(BuildError::ChainTipFetchFailed); }, - } + }; + 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/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>; diff --git a/tests/integration_tests_rust.rs b/tests/integration_tests_rust.rs index c307d02b4e..fce2eed4ee 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: // @@ -2806,15 +2807,15 @@ 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. - // 6. Restart with the original birthday as `wallet_rescan_from_height` and confirm both - // transactions are found, preserving the previous test case. + // 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. 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. @@ -2844,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)) @@ -2868,22 +2868,33 @@ 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 birthday margin, 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); + + // 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, birthday_margin).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 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 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); @@ -2911,6 +2922,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() { @@ -2955,29 +2992,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(_)") + ), + } } } @@ -10241,6 +10280,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); @@ -10251,8 +10291,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 +10300,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, 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 @@ -10299,3 +10339,164 @@ 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(tip_height)), (true, Some(tip_height))] + { + 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 mut 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(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"); + 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 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(); + 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. + 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); + 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(); + } + } +} + +#[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, 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"); + 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 mut 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(); + } + 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 <= birthday_margin || 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(); + } + } + } +}