From 36ea7d785607bf4079dad42da6bbf580e01fd884 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Thu, 19 Nov 2026 11:33:16 +0100 Subject: [PATCH 1/2] Persist wallet birthday in initial wallet state When creating a new on-chain wallet, we first persisted it at genesis and only then inserted the checkpoint acting as its birthday, which was never persisted explicitly. It only reached the store because filling the address pool later in the build happens to flush the wallet's staged changes. A crash or failed write in between left a persisted wallet that reloads at genesis and tries to rescan the whole chain, which never succeeds against a pruned bitcoind. We now apply the checkpoint before the wallet is first persisted, so that its initial state always includes the birthday. As BDK can't turn a wallet created in memory into a persisted one, we write that state ourselves and load the wallet back from the persister. Reported-by: vnprclanker Co-Authored-By: HAL 9000 --- src/builder.rs | 42 +++++++++++++++++++++++++++++++++--------- 1 file changed, 33 insertions(+), 9 deletions(-) diff --git a/src/builder.rs b/src/builder.rs index a8cba83db3..cd7b73884e 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -20,7 +20,7 @@ use std::time::SystemTime; use bdk_wallet::descriptor::IntoWalletDescriptor; use bdk_wallet::signer::SignersContainer; use bdk_wallet::template::Bip84; -use bdk_wallet::{KeychainKind, Wallet as BdkWallet}; +use bdk_wallet::{AsyncWalletPersister, KeychainKind, Wallet as BdkWallet}; use bitcoin::bip32::{ChildNumber, Xpriv}; use bitcoin::key::Secp256k1; use bitcoin::secp256k1::PublicKey; @@ -1876,13 +1876,11 @@ fn build_with_store_internal( return Err(BuildError::ChainTipFetchFailed); } - let mut wallet = runtime - .block_on(async { - BdkWallet::create(descriptor, change_descriptor) - .network(config.network) - .create_wallet_async(&mut wallet_persister) - .await - }) + // We hold off on persisting the wallet until its initial checkpoint is in place, as + // a wallet persisted without it would reload at genesis. + let mut wallet = BdkWallet::create(descriptor.clone(), change_descriptor.clone()) + .network(config.network) + .create_wallet_no_persist() .map_err(|e| { log_error!(logger, "Failed to set up wallet: {}", e); BuildError::WalletSetupFailed @@ -1959,7 +1957,33 @@ fn build_with_store_internal( BuildError::WalletSetupFailed })?; } - wallet + + // BDK can't turn a wallet created in memory into a persisted one, so we write its + // initial state ourselves and load it back, which the persister serves from memory. + let initial_change_set = wallet.take_staged().unwrap_or_default(); + runtime.block_on(async { + AsyncWalletPersister::persist(&mut wallet_persister, &initial_change_set) + .await + .map_err(|e| { + log_error!(logger, "Failed to persist initial wallet state: {}", e); + BuildError::WalletSetupFailed + })?; + + BdkWallet::load() + .descriptor(KeychainKind::External, Some(descriptor)) + .descriptor(KeychainKind::Internal, Some(change_descriptor)) + .check_network(config.network) + .load_wallet_async(&mut wallet_persister) + .await + .map_err(|e| { + log_error!(logger, "Failed to load initial wallet state: {}", e); + BuildError::WalletSetupFailed + })? + .ok_or_else(|| { + log_error!(logger, "Failed to load initial wallet state: no data found"); + BuildError::WalletSetupFailed + }) + })? }, }; From 58941ddfa19ec3310952a5f2131f1e11fc9396a0 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Thu, 19 Nov 2026 11:33:16 +0100 Subject: [PATCH 2/2] Test wallet birthday survives early restart Nothing covered that a node restarted between its first build and its first wallet sync keeps the wallet birthday rather than rescanning from genesis, nor that a rejected build leaves no wallet behind. We add an integration test that builds a fresh node against bitcoind, drops it before it syncs, and checks that the wallet's chain state was written exactly once and that the rebuilt node doesn't pick up a payment confirmed before its birthday. It covers the RPC and REST chain sources, with and without an explicit rescan height. Co-Authored-By: HAL 9000 --- tests/integration_tests_rust.rs | 80 +++++++++++++++++++++++++++++++-- 1 file changed, 76 insertions(+), 4 deletions(-) diff --git a/tests/integration_tests_rust.rs b/tests/integration_tests_rust.rs index c831c98ade..e8c453cfd3 100644 --- a/tests/integration_tests_rust.rs +++ b/tests/integration_tests_rust.rs @@ -404,6 +404,8 @@ struct NamespaceWriteFailingStore { /// When set, only writes to this key in `primary_namespace` fail. key: Option<&'static str>, failing: Arc, + /// The number of writes the store targets that were attempted, failing or not. + write_attempts: Arc, } impl NamespaceWriteFailingStore { @@ -413,6 +415,7 @@ impl NamespaceWriteFailingStore { primary_namespace, key: None, failing: Arc::new(AtomicBool::new(false)), + write_attempts: Arc::new(AtomicUsize::new(0)), } } @@ -439,9 +442,12 @@ impl KVStore for NamespaceWriteFailingStore { ) -> impl Future> + 'static + Send { // The inner store writes as soon as it is asked, not when its future is polled, so a // failing write is never asked for. - let fail = primary_namespace == self.primary_namespace - && self.key.map_or(true, |k| k == key) - && self.failing.load(Ordering::Acquire); + let is_targeted = + primary_namespace == self.primary_namespace && self.key.map_or(true, |k| k == key); + if is_targeted { + self.write_attempts.fetch_add(1, Ordering::AcqRel); + } + let fail = is_targeted && self.failing.load(Ordering::Acquire); let write = (!fail).then(|| { KVStore::write(&*self.inner, primary_namespace, secondary_namespace, key, buf) }); @@ -2930,13 +2936,17 @@ async fn build_fails_when_wallet_rescan_height_is_above_tip() { Some(current_tip_height + 1), ); - match builder.build(entropy.into()) { + let store = NamespaceWriteFailingStore::new("bdk_wallet"); + match builder.build_with_store(entropy.into(), store.clone()) { Err(err) => { assert_eq!(err, BuildError::WalletRescanHeightTooHigh); assert_eq!(err.to_string(), "Wallet rescan height is above the current chain tip."); }, Ok(_) => panic!("expected build to fail for future wallet rescan height"), } + + // The rejected build must not leave a wallet behind that a later build would load. + assert_eq!(store.write_attempts.load(Ordering::Acquire), 0); } #[cfg(feature = "chain-bitcoind")] @@ -9863,3 +9873,65 @@ async fn lsps2_service_funding_fee_does_not_spend_anchor_reserve() { client_node.stop().unwrap(); payer_node.stop().unwrap(); } + +#[cfg(feature = "chain-bitcoind")] +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn wallet_birthday_survives_restart_before_first_sync() { + let (bitcoind, electrsd) = setup_bitcoind_and_electrsd(); + let chain_source = TestChainSource::BitcoindRpcSync(&bitcoind); + + // Learn one of the wallet's addresses via a throwaway node sharing the entropy. + let helper_config = random_config(); + let node_entropy = helper_config.node_entropy; + let helper_node = setup_node(&chain_source, helper_config); + 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. + let premine_amount_sat = 100_000; + premine_and_distribute_funds( + &bitcoind.client, + &electrsd.client, + vec![addr], + Amount::from_sat(premine_amount_sat), + ) + .await; + generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await; + + let tip_height: u32 = bitcoind.client.get_blockchain_info().unwrap().blocks.try_into().unwrap(); + for chain_source in + [TestChainSource::BitcoindRpcSync(&bitcoind), TestChainSource::BitcoindRestSync(&bitcoind)] + { + for rescan_height in [None, Some(tip_height), Some(0)] { + let mut config = random_config(); + config.node_entropy = node_entropy; + config.wallet_rescan_from_height = rescan_height; + let store = NamespaceWriteFailingStore::new_for_key("bdk_wallet", "local_chain"); + let build_node = || { + setup_builder!(builder, config.node_config); + configure_chain_source(&chain_source, &mut builder, &config); + builder.build_with_store(config.node_entropy.into(), store.clone()).unwrap() + }; + + // Build the node for the first time, but drop it before it ever syncs. Its birthday + // must be part of the first write of the wallet's chain state, as a wallet persisted + // without it would reload at genesis. + drop(build_node()); + assert_eq!(store.write_attempts.load(Ordering::Acquire), 1); + + generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 1).await; + + let node = build_node(); + assert_eq!(store.write_attempts.load(Ordering::Acquire), 1); + node.start().unwrap(); + node.sync_wallets().unwrap(); + + // Only a wallet asked to rescan from genesis sees the earlier payment. + let expected_balance_sat = + if rescan_height == Some(0) { premine_amount_sat } else { 0 }; + assert_eq!(node.list_balances().total_onchain_balance_sats, expected_balance_sat); + node.stop().unwrap(); + } + } +}