From 24d30ba9024ac19dc1f20b6338252371d1c0fb6d Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Wed, 2 Dec 2026 10:09:33 +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 held in memory until the wallet's first sync persisted it. A restart, 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. Backport of 73865bd5a889a37a8591c77e324d83814dd3cc67 Reported-by: vnprclanker Co-Authored-By: HAL 9000 --- src/builder.rs | 35 +++++++++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/src/builder.rs b/src/builder.rs index 27582b6af8..41a07d1844 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -14,7 +14,7 @@ use std::time::SystemTime; use std::{fmt, fs}; use bdk_wallet::template::Bip84; -use bdk_wallet::{KeychainKind, Wallet as BdkWallet}; +use bdk_wallet::{KeychainKind, Wallet as BdkWallet, WalletPersister}; use bip39::Mnemonic; use bitcoin::bip32::{ChildNumber, Xpriv}; use bitcoin::secp256k1::PublicKey; @@ -1321,9 +1321,11 @@ fn build_with_store_internal( let bdk_wallet = match wallet_opt { Some(wallet) => wallet, None => { - let mut wallet = BdkWallet::create(descriptor, change_descriptor) + // 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(&mut wallet_persister) + .create_wallet_no_persist() .map_err(|e| { log_error!(logger, "Failed to set up wallet: {}", e); BuildError::WalletSetupFailed @@ -1343,7 +1345,32 @@ 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().ok_or_else(|| { + log_error!(logger, "Failed to persist initial wallet state: no changes staged"); + BuildError::WalletSetupFailed + })?; + WalletPersister::persist(&mut wallet_persister, &initial_change_set).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)) + .extract_keys() + .check_network(config.network) + .load_wallet(&mut wallet_persister) + .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 a1fd5fa248c997e785e6779932555baaa0638498 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Wed, 2 Dec 2026 10:09:33 +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. 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. Backport of 227e9ad5cf95bfd681089ec03a87e8d58aee6b20 Co-Authored-By: HAL 9000 --- tests/integration_tests_rust.rs | 156 ++++++++++++++++++++++++++++++++ 1 file changed, 156 insertions(+) diff --git a/tests/integration_tests_rust.rs b/tests/integration_tests_rust.rs index 0ed9d68237..29c4b5c65c 100644 --- a/tests/integration_tests_rust.rs +++ b/tests/integration_tests_rust.rs @@ -8,7 +8,10 @@ mod common; use std::collections::HashSet; +use std::future::Future; +use std::pin::Pin; use std::str::FromStr; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use bitcoin::address::NetworkUnchecked; @@ -35,6 +38,7 @@ use ldk_node::{Builder, DynStore, Event, NodeError}; use lightning::ln::channelmanager::PaymentId; use lightning::routing::gossip::{NodeAlias, NodeId}; use lightning::routing::router::RouteParametersConfig; +use lightning::util::persist::{KVStore, KVStoreSync}; use lightning_invoice::{Bolt11InvoiceDescription, Description}; use lightning_types::payment::{PaymentHash, PaymentPreimage}; use log::LevelFilter; @@ -2450,3 +2454,155 @@ async fn lsps2_lsp_trusts_client_but_client_does_not_claim() { Some(6) ); } + +/// A store counting the writes attempted for a single key. +struct WriteCountingStore { + inner: TestSyncStore, + primary_namespace: &'static str, + key: &'static str, + write_attempts: AtomicUsize, +} + +impl WriteCountingStore { + fn new(inner: TestSyncStore, primary_namespace: &'static str, key: &'static str) -> Self { + Self { inner, primary_namespace, key, write_attempts: AtomicUsize::new(0) } + } + + fn count_write(&self, primary_namespace: &str, key: &str) { + if primary_namespace == self.primary_namespace && key == self.key { + self.write_attempts.fetch_add(1, Ordering::AcqRel); + } + } +} + +impl KVStore for WriteCountingStore { + fn read( + &self, primary_namespace: &str, secondary_namespace: &str, key: &str, + ) -> Pin, lightning::io::Error>> + Send>> { + KVStore::read(&self.inner, primary_namespace, secondary_namespace, key) + } + + fn write( + &self, primary_namespace: &str, secondary_namespace: &str, key: &str, buf: Vec, + ) -> Pin> + Send>> { + self.count_write(primary_namespace, key); + KVStore::write(&self.inner, primary_namespace, secondary_namespace, key, buf) + } + + fn remove( + &self, primary_namespace: &str, secondary_namespace: &str, key: &str, lazy: bool, + ) -> Pin> + Send>> { + KVStore::remove(&self.inner, primary_namespace, secondary_namespace, key, lazy) + } + + fn list( + &self, primary_namespace: &str, secondary_namespace: &str, + ) -> Pin, lightning::io::Error>> + Send>> { + KVStore::list(&self.inner, primary_namespace, secondary_namespace) + } +} + +impl KVStoreSync for WriteCountingStore { + fn read( + &self, primary_namespace: &str, secondary_namespace: &str, key: &str, + ) -> lightning::io::Result> { + KVStoreSync::read(&self.inner, primary_namespace, secondary_namespace, key) + } + + fn write( + &self, primary_namespace: &str, secondary_namespace: &str, key: &str, buf: Vec, + ) -> lightning::io::Result<()> { + self.count_write(primary_namespace, key); + KVStoreSync::write(&self.inner, primary_namespace, secondary_namespace, key, buf) + } + + fn remove( + &self, primary_namespace: &str, secondary_namespace: &str, key: &str, lazy: bool, + ) -> lightning::io::Result<()> { + KVStoreSync::remove(&self.inner, primary_namespace, secondary_namespace, key, lazy) + } + + fn list( + &self, primary_namespace: &str, secondary_namespace: &str, + ) -> lightning::io::Result> { + KVStoreSync::list(&self.inner, primary_namespace, secondary_namespace) + } +} + +#[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); + let seed_bytes = vec![42u8; 64]; + + // Learn one of the wallet's addresses via a throwaway node sharing the seed. + let helper_node = setup_node(&chain_source, random_config(true), Some(seed_bytes.clone())); + 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; + + for use_rest_sync in [false, true] { + let config = random_config(true); + let store = Arc::new(WriteCountingStore::new( + TestSyncStore::new(config.node_config.storage_dir_path.clone().into()), + "bdk_wallet", + "local_chain", + )); + let build_node = || { + setup_builder!(builder, config.node_config); + let host = bitcoind.params.rpc_socket.ip().to_string(); + let port = bitcoind.params.rpc_socket.port(); + let values = bitcoind.params.get_cookie_values().unwrap().unwrap(); + if use_rest_sync { + builder.set_chain_source_bitcoind_rest( + host.clone(), + port, + host, + port, + values.user, + values.password, + ); + } else { + builder.set_chain_source_bitcoind_rpc(host, port, values.user, values.password); + } + #[cfg(feature = "uniffi")] + builder.set_entropy_seed_bytes(seed_bytes.clone()).unwrap(); + #[cfg(not(feature = "uniffi"))] + { + let mut bytes = [0u8; 64]; + bytes.copy_from_slice(&seed_bytes); + builder.set_entropy_seed_bytes(bytes); + } + let kv_store: Arc = store.clone(); + builder.build_with_store(kv_store).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(); + + // A wallet that kept its birthday doesn't see the earlier payment. + assert_eq!(node.list_balances().total_onchain_balance_sats, 0); + node.stop().unwrap(); + } +}