Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 31 additions & 4 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand All @@ -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
})?
},
};

Expand Down
156 changes: 156 additions & 0 deletions tests/integration_tests_rust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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<Box<dyn Future<Output = Result<Vec<u8>, 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<u8>,
) -> Pin<Box<dyn Future<Output = Result<(), lightning::io::Error>> + 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<Box<dyn Future<Output = Result<(), lightning::io::Error>> + Send>> {
KVStore::remove(&self.inner, primary_namespace, secondary_namespace, key, lazy)
}

fn list(
&self, primary_namespace: &str, secondary_namespace: &str,
) -> Pin<Box<dyn Future<Output = Result<Vec<String>, 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<Vec<u8>> {
KVStoreSync::read(&self.inner, primary_namespace, secondary_namespace, key)
}

fn write(
&self, primary_namespace: &str, secondary_namespace: &str, key: &str, buf: Vec<u8>,
) -> 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<Vec<String>> {
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<DynStore> = 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();
}
}
Loading