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 + }) + })? }, }; 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(); + } + } +}