From 8c8275e800be95061c25856ebedbde365cae6df7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 16:19:52 +0100 Subject: [PATCH 01/16] perf: sync additional wallets apart from the primary The primary wallet and every additional wallet (monitored address types and derived accounts) ran in one join on one Electrum connection, so the primary's result waited for the slowest additional wallet, and the server answered the primary's requests only after theirs. With five Paykit accounts a sync took 10-18 s and all of them regularly hit the 40 s deadline together. Additional wallets now sync in their own background loop on additional_wallet_sync_interval_secs (BackgroundSyncConfig and RuntimeSyncIntervals, default 80 s), each pass with its own in-flight guard, and Electrum syncs them over their own connection, opened on their first sync. sync_wallets() still syncs all wallets, running both passes concurrently. SyncCompleted fires for the primary pass only; the eviction check runs under a lock with applying results so overlapping passes report each eviction once. Verified: cargo test --lib; cargo check --features uniffi; cargo test --test multi_address_types_tests derived_accounts (one bitcoind start flake, passed on rerun) --- CHANGELOG.md | 1 + bindings/ldk_node.udl | 2 + src/chain/electrum.rs | 162 ++++++++++++++++---- src/chain/esplora.rs | 74 ++++++--- src/chain/mod.rs | 238 +++++++++++++++++++---------- src/config.rs | 27 +++- tests/multi_address_types_tests.rs | 74 ++++++++- 7 files changed, 451 insertions(+), 127 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ff7fb9169d..1a418962f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -87,6 +87,7 @@ ## Synonym Fork Additions +- Additional on-chain wallets (monitored address types and derived accounts) sync in the background on their own `additional_wallet_sync_interval_secs` interval, apart from the primary wallet, and over their own Electrum connection, so their sync no longer delays or times out the primary wallet's. - Added `build_with_vss_store_and_lnurl_auth_key_domain`, which signs VSS LNURL-auth for a fixed key domain while calling the auth server on a subdomain of it, so wallets keep their VSS identity when the auth server moves to that subdomain. - Accept incoming payments up to the full channel value, instead of 10% of it, on nodes that cannot announce channels (no node alias or listening addresses), for channels opened after the update. - Expose the exact prepared transaction fee so applications can validate the approved total before broadcast. diff --git a/bindings/ldk_node.udl b/bindings/ldk_node.udl index 984688b6b2..47112cd7df 100644 --- a/bindings/ldk_node.udl +++ b/bindings/ldk_node.udl @@ -51,12 +51,14 @@ dictionary BackgroundSyncConfig { u64 onchain_wallet_sync_interval_secs; u64 lightning_wallet_sync_interval_secs; u64 fee_rate_cache_update_interval_secs; + u64 additional_wallet_sync_interval_secs = 80; }; dictionary RuntimeSyncIntervals { u64 onchain_wallet_sync_interval_secs; u64 lightning_wallet_sync_interval_secs; u64 fee_rate_cache_update_interval_secs; + u64 additional_wallet_sync_interval_secs = 80; }; dictionary EsploraSyncConfig { diff --git a/src/chain/electrum.rs b/src/chain/electrum.rs index ba2dd35a4a..08dcb09ff1 100644 --- a/src/chain/electrum.rs +++ b/src/chain/electrum.rs @@ -31,7 +31,7 @@ use tokio::task::JoinHandle; use super::{ non_final_rejection, periodically_archive_fully_resolved_monitors, BroadcastResponse, - WalletSyncStatus, + OnchainSyncScope, WalletSyncStatus, }; use crate::config::{ AddressTypeRuntimeConfig, Config, ElectrumSyncConfig, BDK_CLIENT_STOP_GAP, @@ -194,6 +194,8 @@ pub(super) struct ElectrumChainSource { pub(super) sync_config: ElectrumSyncConfig, electrum_runtime_status: RwLock, onchain_wallet_sync_status: Mutex, + additional_wallet_sync_status: Mutex, + sync_apply_lock: Mutex<()>, lightning_wallet_sync_status: Mutex, fee_estimator: Arc, pub(super) kv_store: Arc, @@ -218,6 +220,8 @@ impl ElectrumChainSource { sync_config, electrum_runtime_status, onchain_wallet_sync_status, + additional_wallet_sync_status: Mutex::new(WalletSyncStatus::Completed), + sync_apply_lock: Mutex::new(()), lightning_wallet_sync_status, fee_estimator, kv_store, @@ -252,11 +256,18 @@ impl ElectrumChainSource { } } + fn wallet_sync_status(&self, scope: OnchainSyncScope) -> &Mutex { + match scope { + OnchainSyncScope::Primary => &self.onchain_wallet_sync_status, + OnchainSyncScope::Additional => &self.additional_wallet_sync_status, + } + } + pub(crate) async fn sync_onchain_wallet( - &self, onchain_wallet: Arc, + &self, onchain_wallet: Arc, scope: OnchainSyncScope, ) -> super::WalletSyncOutcome { let receiver_res = { - let mut status_lock = self.onchain_wallet_sync_status.lock().unwrap(); + let mut status_lock = self.wallet_sync_status(scope).lock().unwrap(); status_lock.register_or_subscribe_pending_sync() }; if let Some(mut sync_receiver) = receiver_res { @@ -273,11 +284,11 @@ impl ElectrumChainSource { } let outcome = self - .sync_onchain_wallet_inner(onchain_wallet) + .sync_onchain_wallet_inner(onchain_wallet, scope) .await .unwrap_or_else(super::WalletSyncOutcome::failed); - self.onchain_wallet_sync_status + self.wallet_sync_status(scope) .lock() .unwrap() .propagate_result_to_subscribers(outcome.result()); @@ -286,7 +297,7 @@ impl ElectrumChainSource { } async fn sync_onchain_wallet_inner( - &self, onchain_wallet: Arc, + &self, onchain_wallet: Arc, scope: OnchainSyncScope, ) -> Result { let electrum_client: Arc = if let Some(client) = self.electrum_runtime_status.read().unwrap().client().as_ref() { @@ -302,8 +313,21 @@ impl ElectrumChainSource { let primary_incremental = self.node_metrics.read().unwrap().latest_onchain_wallet_sync_timestamp.is_some(); - let additional_accounts = - self.address_type_runtime_config.read().unwrap().additional_wallet_accounts(); + let additional_accounts = match scope { + OnchainSyncScope::Primary => Vec::new(), + OnchainSyncScope::Additional => { + self.address_type_runtime_config.read().unwrap().additional_wallet_accounts() + }, + }; + if scope == OnchainSyncScope::Additional && additional_accounts.is_empty() { + return Ok(super::WalletSyncOutcome::new(Vec::new(), None)); + } + // Additional wallets use their own connection: an Electrum server answers a connection's + // requests in order, so on a shared one the primary's would wait behind theirs. + let connection = match scope { + OnchainSyncScope::Primary => electrum_client.main_connection(), + OnchainSyncScope::Additional => electrum_client.additional_connection().await?, + }; let additional_sync_requests = super::collect_additional_sync_requests( &additional_accounts, &onchain_wallet, @@ -312,10 +336,16 @@ impl ElectrumChainSource { )?; let additional_full_scan_settings = additional_wallet_full_scan_settings(&self.sync_config); - let primary_request: super::WalletSyncRequest = if primary_incremental { - super::WalletSyncRequest::Incremental(onchain_wallet.get_incremental_sync_request()) - } else { - super::WalletSyncRequest::FullScan(onchain_wallet.get_full_scan_request()) + let primary_request = match scope { + OnchainSyncScope::Additional => None, + OnchainSyncScope::Primary if primary_incremental => { + Some(super::WalletSyncRequest::Incremental( + onchain_wallet.get_incremental_sync_request(), + )) + }, + OnchainSyncScope::Primary => { + Some(super::WalletSyncRequest::FullScan(onchain_wallet.get_full_scan_request())) + }, }; // Collect cached transactions once and share via Arc to avoid cloning @@ -331,12 +361,15 @@ impl ElectrumChainSource { { let client = Arc::clone(&electrum_client); + let connection = Arc::clone(&connection); let txs = Arc::clone(&cached_txs); match primary_request { - super::WalletSyncRequest::Incremental(req) => { + None => {}, + Some(super::WalletSyncRequest::Incremental(req)) => { join_set.spawn(async move { let result: Result = client .get_incremental_sync_wallet_update( + &connection, req, txs.iter().cloned(), BDK_ELECTRUM_CLIENT_BATCH_SIZE, @@ -347,10 +380,11 @@ impl ElectrumChainSource { (None, result) }); }, - super::WalletSyncRequest::FullScan(req) => { + Some(super::WalletSyncRequest::FullScan(req)) => { join_set.spawn(async move { let result: Result = client .get_full_scan_wallet_update( + &connection, req, txs.iter().cloned(), PRIMARY_WALLET_FULL_SCAN_SETTINGS, @@ -366,6 +400,7 @@ impl ElectrumChainSource { for (wallet_account, sync_req) in additional_sync_requests { let client = Arc::clone(&electrum_client); + let connection = Arc::clone(&connection); let txs = Arc::clone(&cached_txs); let incremental_batch_size = additional_wallet_incremental_batch_size( wallet_account.account_index, @@ -384,6 +419,7 @@ impl ElectrumChainSource { join_set.spawn(async move { let result: Result = client .get_incremental_sync_wallet_update( + &connection, req, txs.iter().cloned(), incremental_batch_size, @@ -402,6 +438,7 @@ impl ElectrumChainSource { join_set.spawn(async move { let result: Result = client .get_full_scan_wallet_update( + &connection, req, txs.iter().cloned(), additional_full_scan_settings, @@ -442,7 +479,8 @@ impl ElectrumChainSource { }; } - if primary_update.is_none() && primary_error.is_none() { + if scope == OnchainSyncScope::Primary && primary_update.is_none() && primary_error.is_none() + { log_error!(self.logger, "Primary wallet sync task failed unexpectedly"); primary_error = Some(Error::WalletOperationFailed); } @@ -454,6 +492,7 @@ impl ElectrumChainSource { &onchain_wallet, &self.node_metrics, &self.logger, + &self.sync_apply_lock, ); if outcome.primary_applied { log_info!( @@ -463,6 +502,14 @@ impl ElectrumChainSource { now.elapsed().as_millis() ); } + if scope == OnchainSyncScope::Additional { + log_info!( + self.logger, + "Sync of {} additional on-chain wallets finished in {}ms.", + additional_accounts.len(), + now.elapsed().as_millis() + ); + } if outcome.any_applied { if let Err(e) = onchain_wallet.update_payment_store_for_all_transactions() { @@ -480,7 +527,11 @@ impl ElectrumChainSource { } } - Ok(super::WalletSyncOutcome::new(outcome.events, outcome.error)) + Ok(super::WalletSyncOutcome { + events: outcome.events, + evicted_txids: outcome.evicted_txids, + error: outcome.error, + }) } pub(crate) async fn sync_lightning_wallet( @@ -718,7 +769,8 @@ impl ElectrumRuntimeStatus { } } -/// The connection shared by wallet sync, fee updates, balance lookups and broadcasts. +/// One Electrum connection. The main one is shared by primary wallet sync, fee updates, balance +/// lookups and broadcasts; additional wallets sync over a second one. struct MainElectrumClient { electrum_client: Arc, bdk_electrum_client: Arc>>, @@ -733,11 +785,16 @@ impl MainElectrumClient { } } +/// A replaceable Electrum connection: a call that finds it broken swaps in a new one. +type ElectrumConnection = Arc>>; + struct ElectrumRuntimeClient { // electrum-client only reconnects a `Client` once no other call holds it, and a call left // waiting on a dropped connection can hold it forever. A call that finds the connection // broken therefore replaces the whole client instead of relying on that internal reconnect. - main_client: Arc>>, + main_client: ElectrumConnection, + // Opened on the first sync of additional wallets, so nodes without them keep two connections. + additional_client: tokio::sync::OnceCell, connect_main: Arc Result + Send + Sync>, tx_sync: Arc>>, runtime_handle: Handle, @@ -787,6 +844,7 @@ impl ElectrumRuntimeClient { Arc::new(move || MainElectrumClient::connect(&server_url, &electrum_config)); Ok(Self { main_client: Arc::new(RwLock::new(Arc::new(main_client))), + additional_client: tokio::sync::OnceCell::new(), connect_main, tx_sync, runtime_handle, @@ -804,12 +862,47 @@ impl ElectrumRuntimeClient { Arc::clone(&self.main_client.read().unwrap()) } - /// Starts replacing `failed` with a client on a new connection, unless another caller already - /// did. The task reports whether the current client differs from `failed`. Callers never wait - /// past their own deadline for it: a dropped handle keeps reconnecting in the background. + fn main_connection(&self) -> ElectrumConnection { + Arc::clone(&self.main_client) + } + + async fn additional_connection(&self) -> Result { + let connection = self + .additional_client + .get_or_try_init(|| async { + let connect = Arc::clone(&self.connect_main); + let client = self + .runtime_handle + .spawn_blocking(move || connect()) + .await + .map_err(|_| Error::ConnectionFailed)? + .map_err(|e| { + log_error!( + self.logger, + "Failed to connect to Electrum server for additional wallets: {}", + e + ); + Error::ConnectionFailed + })?; + Ok::<_, Error>(Arc::new(RwLock::new(Arc::new(client)))) + }) + .await?; + Ok(Arc::clone(connection)) + } + fn reconnect_main_client(&self, failed: &Arc) -> JoinHandle { + self.reconnect_client(&self.main_client, failed) + } + + /// Starts replacing `failed` in `connection` with a client on a new connection, unless another + /// caller already did. The task reports whether the current client differs from `failed`. + /// Callers never wait past their own deadline for it: a dropped handle keeps reconnecting in + /// the background. + fn reconnect_client( + &self, connection: &ElectrumConnection, failed: &Arc, + ) -> JoinHandle { let (main_client, connect_main, logger, failed) = ( - Arc::clone(&self.main_client), + Arc::clone(connection), Arc::clone(&self.connect_main), Arc::clone(&self.logger), Arc::clone(failed), @@ -912,11 +1005,11 @@ impl ElectrumRuntimeClient { } async fn get_full_scan_wallet_update( - &self, request: BdkFullScanRequest, + &self, connection: &ElectrumConnection, request: BdkFullScanRequest, cached_txs: impl IntoIterator>>, settings: FullScanSettings, timeout: Duration, ) -> Result, Error> { - let main_client = self.main_client(); + let main_client = Arc::clone(&connection.read().unwrap()); let bdk_electrum_client = Arc::clone(&main_client.bdk_electrum_client); bdk_electrum_client.populate_tx_cache(cached_txs); @@ -940,7 +1033,7 @@ impl ElectrumRuntimeClient { Err(e) => { log_error!(self.logger, "Sync of on-chain wallet failed: {}", e); if electrum_connection_broken(&e) { - drop(self.reconnect_main_client(&main_client)); + drop(self.reconnect_client(connection, &main_client)); } Err(Error::WalletOperationFailed) }, @@ -948,11 +1041,11 @@ impl ElectrumRuntimeClient { } async fn get_incremental_sync_wallet_update( - &self, request: BdkSyncRequest<(BdkKeyChainKind, u32)>, + &self, connection: &ElectrumConnection, request: BdkSyncRequest<(BdkKeyChainKind, u32)>, cached_txs: impl IntoIterator>>, batch_size: usize, timeout: Duration, ) -> Result { - let main_client = self.main_client(); + let main_client = Arc::clone(&connection.read().unwrap()); let bdk_electrum_client = Arc::clone(&main_client.bdk_electrum_client); bdk_electrum_client.populate_tx_cache(cached_txs); @@ -976,7 +1069,7 @@ impl ElectrumRuntimeClient { Err(e) => { log_error!(self.logger, "Incremental sync of on-chain wallet failed: {}", e); if electrum_connection_broken(&e) { - drop(self.reconnect_main_client(&main_client)); + drop(self.reconnect_client(connection, &main_client)); } Err(Error::WalletOperationFailed) }, @@ -1648,6 +1741,19 @@ mod tests { assert!(Arc::ptr_eq(&client.main_client(), &stale)); } + #[test] + fn additional_wallets_get_their_own_connection_opened_once() { + let server = FakeElectrumServer::start(); + let logger = Arc::new(Logger::new_log_facade()); + let runtime = Runtime::new(Arc::clone(&logger)).unwrap(); + let client = test_runtime_client(&server, &runtime, logger); + + let additional = runtime.block_on(client.additional_connection()).unwrap(); + assert!(!Arc::ptr_eq(&additional.read().unwrap(), &client.main_client())); + let again = runtime.block_on(client.additional_connection()).unwrap(); + assert!(Arc::ptr_eq(&additional, &again)); + } + #[test] fn electrum_connection_counts_as_broken_only_after_it_was_closed_or_reset() { let pipe = || ElectrumError::IOError(std::io::ErrorKind::BrokenPipe.into()); diff --git a/src/chain/esplora.rs b/src/chain/esplora.rs index e95c8d631d..8506f2df36 100644 --- a/src/chain/esplora.rs +++ b/src/chain/esplora.rs @@ -19,7 +19,7 @@ use lightning_transaction_sync::EsploraSyncClient; use super::{ non_final_rejection, periodically_archive_fully_resolved_monitors, BroadcastResponse, - WalletSyncStatus, + OnchainSyncScope, WalletSyncStatus, }; use crate::config::{ AddressTypeRuntimeConfig, Config, EsploraSyncConfig, BDK_CLIENT_CONCURRENCY, @@ -39,6 +39,8 @@ pub(super) struct EsploraChainSource { pub(super) sync_config: EsploraSyncConfig, esplora_client: EsploraAsyncClient, onchain_wallet_sync_status: Mutex, + additional_wallet_sync_status: Mutex, + sync_apply_lock: Mutex<()>, tx_sync: Arc>>, lightning_wallet_sync_status: Mutex, fee_estimator: Arc, @@ -98,6 +100,8 @@ impl EsploraChainSource { sync_config, esplora_client, onchain_wallet_sync_status, + additional_wallet_sync_status: Mutex::new(WalletSyncStatus::Completed), + sync_apply_lock: Mutex::new(()), tx_sync, lightning_wallet_sync_status, fee_estimator, @@ -109,11 +113,18 @@ impl EsploraChainSource { } } + fn wallet_sync_status(&self, scope: OnchainSyncScope) -> &Mutex { + match scope { + OnchainSyncScope::Primary => &self.onchain_wallet_sync_status, + OnchainSyncScope::Additional => &self.additional_wallet_sync_status, + } + } + pub(super) async fn sync_onchain_wallet( - &self, onchain_wallet: Arc, + &self, onchain_wallet: Arc, scope: OnchainSyncScope, ) -> super::WalletSyncOutcome { let receiver_res = { - let mut status_lock = self.onchain_wallet_sync_status.lock().unwrap(); + let mut status_lock = self.wallet_sync_status(scope).lock().unwrap(); status_lock.register_or_subscribe_pending_sync() }; if let Some(mut sync_receiver) = receiver_res { @@ -130,11 +141,11 @@ impl EsploraChainSource { } let outcome = self - .sync_onchain_wallet_inner(onchain_wallet) + .sync_onchain_wallet_inner(onchain_wallet, scope) .await .unwrap_or_else(super::WalletSyncOutcome::failed); - self.onchain_wallet_sync_status + self.wallet_sync_status(scope) .lock() .unwrap() .propagate_result_to_subscribers(outcome.result()); @@ -143,13 +154,20 @@ impl EsploraChainSource { } async fn sync_onchain_wallet_inner( - &self, onchain_wallet: Arc, + &self, onchain_wallet: Arc, scope: OnchainSyncScope, ) -> Result { let primary_incremental = self.node_metrics.read().unwrap().latest_onchain_wallet_sync_timestamp.is_some(); - let additional_accounts = - self.address_type_runtime_config.read().unwrap().additional_wallet_accounts(); + let additional_accounts = match scope { + OnchainSyncScope::Primary => Vec::new(), + OnchainSyncScope::Additional => { + self.address_type_runtime_config.read().unwrap().additional_wallet_accounts() + }, + }; + if scope == OnchainSyncScope::Additional && additional_accounts.is_empty() { + return Ok(super::WalletSyncOutcome::new(Vec::new(), None)); + } let additional_sync_requests = super::collect_additional_sync_requests( &additional_accounts, &onchain_wallet, @@ -157,10 +175,16 @@ impl EsploraChainSource { &self.logger, )?; - let primary_request: super::WalletSyncRequest = if primary_incremental { - super::WalletSyncRequest::Incremental(onchain_wallet.get_incremental_sync_request()) - } else { - super::WalletSyncRequest::FullScan(onchain_wallet.get_full_scan_request()) + let primary_request = match scope { + OnchainSyncScope::Additional => None, + OnchainSyncScope::Primary if primary_incremental => { + Some(super::WalletSyncRequest::Incremental( + onchain_wallet.get_incremental_sync_request(), + )) + }, + OnchainSyncScope::Primary => { + Some(super::WalletSyncRequest::FullScan(onchain_wallet.get_full_scan_request())) + }, }; // Primary wallet is identified by address_type = None in the JoinSet results. @@ -176,7 +200,8 @@ impl EsploraChainSource { let client = self.esplora_client.clone(); match primary_request { - super::WalletSyncRequest::Incremental(req) => { + None => {}, + Some(super::WalletSyncRequest::Incremental(req)) => { join_set.spawn(async move { let result = tokio::time::timeout( Duration::from_secs(BDK_WALLET_SYNC_TIMEOUT_SECS), @@ -187,7 +212,7 @@ impl EsploraChainSource { (None, result) }); }, - super::WalletSyncRequest::FullScan(req) => { + Some(super::WalletSyncRequest::FullScan(req)) => { join_set.spawn(async move { let result = tokio::time::timeout( Duration::from_secs(BDK_WALLET_SYNC_TIMEOUT_SECS), @@ -304,7 +329,8 @@ impl EsploraChainSource { }; } - if primary_update.is_none() && primary_error.is_none() { + if scope == OnchainSyncScope::Primary && primary_update.is_none() && primary_error.is_none() + { log_error!(self.logger, "Primary wallet sync task failed unexpectedly"); primary_error = Some(Error::WalletOperationFailed); } @@ -316,6 +342,7 @@ impl EsploraChainSource { &onchain_wallet, &self.node_metrics, &self.logger, + &self.sync_apply_lock, ); if outcome.primary_applied { log_info!( @@ -325,6 +352,14 @@ impl EsploraChainSource { now.elapsed().as_millis() ); } + if scope == OnchainSyncScope::Additional { + log_info!( + self.logger, + "Sync of {} additional on-chain wallets finished in {}ms.", + additional_accounts.len(), + now.elapsed().as_millis() + ); + } if outcome.any_applied { if let Err(e) = onchain_wallet.update_payment_store_for_all_transactions() { @@ -342,7 +377,11 @@ impl EsploraChainSource { } } - Ok(super::WalletSyncOutcome::new(outcome.events, outcome.error)) + Ok(super::WalletSyncOutcome { + events: outcome.events, + evicted_txids: outcome.evicted_txids, + error: outcome.error, + }) } pub(super) async fn sync_lightning_wallet( @@ -643,11 +682,10 @@ mod broadcast_tests { use std::net::TcpListener; use std::thread; + use super::*; use crate::io::test_utils::InMemoryStore; use crate::runtime::Runtime; - use super::*; - #[test] fn esplora_broadcast_http_requires_matching_txid_acknowledgement() { let tx = Transaction { diff --git a/src/chain/mod.rs b/src/chain/mod.rs index 5d10567e7f..d1fb16f546 100644 --- a/src/chain/mod.rs +++ b/src/chain/mod.rs @@ -42,6 +42,16 @@ pub(super) enum WalletSyncRequest { Incremental(SyncRequest<(KeychainKind, u32)>), } +/// Which on-chain wallets a sync pass covers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum OnchainSyncScope { + /// The primary account-`0` wallet. + Primary, + /// Monitored account-`0` address types and derived accounts. They sync apart from the primary + /// wallet, on their own interval, so their sync never delays or times out the primary's. + Additional, +} + pub(crate) enum WalletSyncStatus { Completed, InProgress { subscribers: tokio::sync::broadcast::Sender> }, @@ -158,15 +168,12 @@ fn check_evicted_transactions( evicted_txids } -// Check for evicted transactions and emit events for them. -async fn check_and_emit_evicted_transactions( - prev_unconfirmed_txids: Vec, wallet: &crate::wallet::Wallet, - event_queue: &EventQueue, logger: &Logger, +// Emit events for transactions a sync found evicted from the mempool. +async fn emit_evicted_transactions( + evicted_txids: Vec, event_queue: &EventQueue, logger: &Logger, ) where L2::Target: LdkLogger, { - let evicted_txids = check_evicted_transactions(prev_unconfirmed_txids, wallet, logger); - for txid in evicted_txids { if let Err(e) = event_queue.add_event(Event::OnchainTransactionEvicted { txid }).await { log_error!(logger, "Failed to push evicted transaction event to queue: {}", e); @@ -231,16 +238,17 @@ pub(super) struct AdditionalSyncOutcome { pub(super) struct WalletSyncOutcome { pub(super) events: Vec, + pub(super) evicted_txids: Vec, pub(super) error: Option, } impl WalletSyncOutcome { pub(super) fn new(events: Vec, error: Option) -> Self { - Self { events, error } + Self { events, evicted_txids: Vec::new(), error } } pub(super) fn failed(error: Error) -> Self { - Self { events: Vec::new(), error: Some(error) } + Self { events: Vec::new(), evicted_txids: Vec::new(), error: Some(error) } } pub(super) fn result(&self) -> Result<(), Error> { @@ -250,6 +258,7 @@ impl WalletSyncOutcome { pub(super) struct AppliedWalletSyncOutcome { pub(super) events: Vec, + pub(super) evicted_txids: Vec, pub(super) any_applied: bool, pub(super) primary_applied: bool, pub(super) error: Option, @@ -298,11 +307,16 @@ pub(super) fn apply_additional_sync_results( AdditionalSyncOutcome { events, any_applied, error } } +/// Applies a pass's results. `apply_lock` serializes passes that overlap (primary and additional), +/// so each reports only the evictions its own updates caused. pub(super) fn apply_wallet_sync_results( primary_update: Option, primary_error: Option, task_error: Option, additional_results: Vec<(OnchainWalletAccount, Result)>, onchain_wallet: &Wallet, node_metrics: &Arc>, logger: &Arc, + apply_lock: &Mutex<()>, ) -> AppliedWalletSyncOutcome { + let _apply_guard = apply_lock.lock().unwrap(); + let prev_unconfirmed_txids = onchain_wallet.get_unconfirmed_txids(); let mut events = Vec::new(); let mut primary_applied = false; let mut error = primary_error; @@ -327,9 +341,11 @@ pub(super) fn apply_wallet_sync_results( apply_additional_sync_results(additional_results, onchain_wallet, node_metrics, logger); events.extend(additional_outcome.events); error = error.or(additional_outcome.error); + let evicted_txids = check_evicted_transactions(prev_unconfirmed_txids, onchain_wallet, logger); AppliedWalletSyncOutcome { events, + evicted_txids, any_applied: primary_applied || additional_outcome.any_applied, primary_applied, error, @@ -377,6 +393,7 @@ mod sync_tests { &node.wallet, &node.node_metrics, &node.logger, + &Mutex::new(()), ); assert!(outcome.primary_applied); @@ -865,31 +882,45 @@ impl ChainSource { &self, wallet: Arc, channel_manager: Option>, chain_monitor: Option>, ) -> Result<(), Error> { + // The primary and additional wallets sync concurrently, each applying its own results as + // soon as they arrive. let event_queue = self.event_queue.lock().unwrap().clone(); - if let Some(event_queue) = event_queue { - // Use event-emitting sync path - self.sync_onchain_wallet_with_events( - Some(&event_queue), - channel_manager.as_ref(), - chain_monitor.as_ref(), - self.config(), - ) - .await - } else { - // Simple sync without events (event_queue not set) - match &self.kind { - ChainSourceKind::Esplora(esplora_chain_source) => { - esplora_chain_source.sync_onchain_wallet(wallet).await.result() - }, - ChainSourceKind::Electrum(electrum_chain_source) => { - electrum_chain_source.sync_onchain_wallet(wallet).await.result() - }, - ChainSourceKind::Bitcoind(_) => { - // Bitcoind sync is handled differently - Ok(()) - }, + let sync_scope = |scope| { + let (event_queue, wallet) = (event_queue.clone(), Arc::clone(&wallet)); + let (channel_manager, chain_monitor) = (channel_manager.clone(), chain_monitor.clone()); + async move { + if let Some(event_queue) = event_queue { + // Use event-emitting sync path + self.sync_onchain_wallet_with_events( + Some(&event_queue), + channel_manager.as_ref(), + chain_monitor.as_ref(), + self.config(), + scope, + ) + .await + } else { + // Simple sync without events (event_queue not set) + match &self.kind { + ChainSourceKind::Esplora(esplora_chain_source) => { + esplora_chain_source.sync_onchain_wallet(wallet, scope).await.result() + }, + ChainSourceKind::Electrum(electrum_chain_source) => { + electrum_chain_source.sync_onchain_wallet(wallet, scope).await.result() + }, + ChainSourceKind::Bitcoind(_) => { + // Bitcoind sync is handled differently + Ok(()) + }, + } + } } - } + }; + let (primary, additional) = tokio::join!( + sync_scope(OnchainSyncScope::Primary), + sync_scope(OnchainSyncScope::Additional) + ); + primary.and(additional) } fn config(&self) -> Option<&Arc> { @@ -901,6 +932,75 @@ impl ChainSource { } async fn start_tx_based_sync_loop( + &self, stop_sync_receiver: tokio::sync::watch::Receiver<()>, + config_receiver: tokio::sync::watch::Receiver, + channel_manager: Arc, chain_monitor: Arc, + output_sweeper: Arc, background_sync_config: &BackgroundSyncConfig, + logger: Arc, + ) { + // Polled side by side, so neither loop waits on the other's sync. + tokio::join!( + self.run_additional_wallet_sync_loop( + stop_sync_receiver.clone(), + config_receiver.clone(), + &channel_manager, + &chain_monitor, + background_sync_config, + &logger, + ), + self.run_tx_based_sync_loop( + stop_sync_receiver, + config_receiver, + Arc::clone(&channel_manager), + Arc::clone(&chain_monitor), + output_sweeper, + background_sync_config, + Arc::clone(&logger), + ), + ); + } + + // Syncs the additional on-chain wallets on their own interval. + async fn run_additional_wallet_sync_loop( + &self, mut stop_sync_receiver: tokio::sync::watch::Receiver<()>, + mut config_receiver: tokio::sync::watch::Receiver, + channel_manager: &Arc, chain_monitor: &Arc, + background_sync_config: &BackgroundSyncConfig, logger: &Arc, + ) { + let new_interval = |secs: u64| { + let mut interval = tokio::time::interval(Duration::from_secs( + secs.max(WALLET_SYNC_INTERVAL_MINIMUM_SECS), + )); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + interval + }; + let mut sync_interval = + new_interval(background_sync_config.additional_wallet_sync_interval_secs); + loop { + tokio::select! { + _ = stop_sync_receiver.changed() => { + log_trace!(logger, "Stopping background syncing of additional on-chain wallets."); + return; + } + Ok(()) = config_receiver.changed() => { + let secs = config_receiver.borrow().additional_wallet_sync_interval_secs; + sync_interval = new_interval(secs); + } + _ = sync_interval.tick() => { + let event_queue = self.event_queue.lock().unwrap().clone(); + let _ = self.sync_onchain_wallet_with_events( + event_queue.as_ref(), + Some(channel_manager), + Some(chain_monitor), + self.config(), + OnchainSyncScope::Additional, + ).await; + } + } + } + } + + async fn run_tx_based_sync_loop( &self, mut stop_sync_receiver: tokio::sync::watch::Receiver<()>, mut config_receiver: tokio::sync::watch::Receiver, channel_manager: Arc, chain_monitor: Arc, @@ -947,10 +1047,11 @@ impl ChainSource { let new_config = config_receiver.borrow().clone(); log_info!( logger, - "Background sync intervals updated: onchain={}s, lightning={}s, fee_rate={}s", + "Background sync intervals updated: onchain={}s, lightning={}s, fee_rate={}s, additional_wallets={}s", new_config.onchain_wallet_sync_interval_secs, new_config.lightning_wallet_sync_interval_secs, new_config.fee_rate_cache_update_interval_secs, + new_config.additional_wallet_sync_interval_secs, ); // Reset intervals with new durations (enforce minimum) @@ -986,6 +1087,7 @@ impl ChainSource { Some(&channel_manager), Some(&chain_monitor), self.config(), + OnchainSyncScope::Primary, ).await; } _ = fee_rate_update_interval.tick() => { @@ -1032,18 +1134,15 @@ impl ChainSource { async fn sync_onchain_wallet_with_events( &self, event_queue: Option<&Arc>>>, channel_manager: Option<&Arc>, chain_monitor: Option<&Arc>, - config: Option<&Arc>, + config: Option<&Arc>, scope: OnchainSyncScope, ) -> Result<(), Error> { let wallet = self.onchain_wallet.lock().unwrap().clone(); let wallet = wallet.ok_or(Error::WalletOperationFailed)?; match &self.kind { ChainSourceKind::Esplora(esplora_chain_source) => { - // Track unconfirmed transactions before sync to detect evictions - let prev_unconfirmed_txids = wallet.get_unconfirmed_txids(); - - let WalletSyncOutcome { events: wallet_events, error: sync_error } = - esplora_chain_source.sync_onchain_wallet(Arc::clone(&wallet)).await; + let WalletSyncOutcome { events: wallet_events, evicted_txids, error: sync_error } = + esplora_chain_source.sync_onchain_wallet(Arc::clone(&wallet), scope).await; // Process wallet events if event queue is provided if let Some(event_queue) = event_queue { @@ -1063,23 +1162,17 @@ impl ChainSource { } if let Some(event_queue) = event_queue { - // Check for evicted transactions - check_and_emit_evicted_transactions( - prev_unconfirmed_txids, - &wallet, - event_queue, - &self.logger, - ) - .await; - - // Emit SyncCompleted event - let synced_height = wallet.current_best_block().height; - event_queue - .add_event(Event::SyncCompleted { - sync_type: SyncType::OnchainWallet, - synced_block_height: synced_height, - }) - .await?; + emit_evicted_transactions(evicted_txids, event_queue, &self.logger).await; + + if scope == OnchainSyncScope::Primary { + let synced_height = wallet.current_best_block().height; + event_queue + .add_event(Event::SyncCompleted { + sync_type: SyncType::OnchainWallet, + synced_block_height: synced_height, + }) + .await?; + } // Check for balance changes and emit BalanceChanged event if needed if let (Some(cm), Some(chain_mon), Some(cfg)) = (channel_manager, chain_monitor, config) @@ -1135,11 +1228,8 @@ impl ChainSource { Ok(()) }, ChainSourceKind::Electrum(electrum_chain_source) => { - // Track unconfirmed transactions before sync to detect evictions - let prev_unconfirmed_txids = wallet.get_unconfirmed_txids(); - - let WalletSyncOutcome { events: wallet_events, error: sync_error } = - electrum_chain_source.sync_onchain_wallet(Arc::clone(&wallet)).await; + let WalletSyncOutcome { events: wallet_events, evicted_txids, error: sync_error } = + electrum_chain_source.sync_onchain_wallet(Arc::clone(&wallet), scope).await; // Process wallet events if event queue is provided if let Some(event_queue) = event_queue { @@ -1159,23 +1249,17 @@ impl ChainSource { } if let Some(event_queue) = event_queue { - // Check for evicted transactions - check_and_emit_evicted_transactions( - prev_unconfirmed_txids, - &wallet, - event_queue, - &self.logger, - ) - .await; - - // Emit SyncCompleted event - let synced_height = wallet.current_best_block().height; - event_queue - .add_event(Event::SyncCompleted { - sync_type: SyncType::OnchainWallet, - synced_block_height: synced_height, - }) - .await?; + emit_evicted_transactions(evicted_txids, event_queue, &self.logger).await; + + if scope == OnchainSyncScope::Primary { + let synced_height = wallet.current_best_block().height; + event_queue + .add_event(Event::SyncCompleted { + sync_type: SyncType::OnchainWallet, + synced_block_height: synced_height, + }) + .await?; + } // Check for balance changes and emit BalanceChanged event if needed if let (Some(cm), Some(chain_mon), Some(cfg)) = diff --git a/src/config.rs b/src/config.rs index b1068b9582..d9a46bb7f2 100644 --- a/src/config.rs +++ b/src/config.rs @@ -700,6 +700,7 @@ pub(crate) fn default_user_config(config: &Config) -> UserConfig { /// | `onchain_wallet_sync_interval_secs` | 80 | /// | `lightning_wallet_sync_interval_secs` | 30 | /// | `fee_rate_cache_update_interval_secs` | 600 | +/// | `additional_wallet_sync_interval_secs` | 80 | #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct BackgroundSyncConfig { /// The time in-between background sync attempts of the onchain wallet, in seconds. @@ -716,6 +717,15 @@ pub struct BackgroundSyncConfig { /// /// **Note:** A minimum of 10 seconds is enforced when background syncing is enabled. pub fee_rate_cache_update_interval_secs: u64, + + /// The time in-between background sync attempts of the additional on-chain wallets + /// (monitored account-`0` address types and derived accounts), in seconds. + /// + /// These wallets sync apart from the primary wallet, so their sync never delays or times out + /// the primary wallet's. Electrum syncs them over their own connection. + /// + /// **Note:** A minimum of 10 seconds is enforced when background syncing is enabled. + pub additional_wallet_sync_interval_secs: u64, } impl Default for BackgroundSyncConfig { @@ -724,6 +734,7 @@ impl Default for BackgroundSyncConfig { onchain_wallet_sync_interval_secs: DEFAULT_BDK_WALLET_SYNC_INTERVAL_SECS, lightning_wallet_sync_interval_secs: DEFAULT_LDK_WALLET_SYNC_INTERVAL_SECS, fee_rate_cache_update_interval_secs: DEFAULT_FEE_RATE_CACHE_UPDATE_INTERVAL_SECS, + additional_wallet_sync_interval_secs: DEFAULT_BDK_WALLET_SYNC_INTERVAL_SECS, } } } @@ -740,6 +751,7 @@ impl Default for BackgroundSyncConfig { /// | `onchain_wallet_sync_interval_secs` | 80 | /// | `lightning_wallet_sync_interval_secs` | 30 | /// | `fee_rate_cache_update_interval_secs` | 600 | +/// | `additional_wallet_sync_interval_secs` | 80 | /// /// [`Node::update_sync_intervals`]: crate::Node::update_sync_intervals #[derive(Debug, Clone, PartialEq, Eq)] @@ -758,6 +770,12 @@ pub struct RuntimeSyncIntervals { /// /// **Note:** A minimum of 10 seconds is enforced. pub fee_rate_cache_update_interval_secs: u64, + + /// Interval for syncing the additional on-chain wallets (monitored account-`0` address types + /// and derived accounts), in seconds. + /// + /// **Note:** A minimum of 10 seconds is enforced. + pub additional_wallet_sync_interval_secs: u64, } impl Default for RuntimeSyncIntervals { @@ -766,6 +784,7 @@ impl Default for RuntimeSyncIntervals { onchain_wallet_sync_interval_secs: DEFAULT_BDK_WALLET_SYNC_INTERVAL_SECS, lightning_wallet_sync_interval_secs: DEFAULT_LDK_WALLET_SYNC_INTERVAL_SECS, fee_rate_cache_update_interval_secs: DEFAULT_FEE_RATE_CACHE_UPDATE_INTERVAL_SECS, + additional_wallet_sync_interval_secs: DEFAULT_BDK_WALLET_SYNC_INTERVAL_SECS, } } } @@ -777,6 +796,7 @@ impl RuntimeSyncIntervals { /// - On-chain wallet sync: 5 minutes (was 80 seconds) /// - Lightning wallet sync: 2 minutes (was 30 seconds) /// - Fee rate cache: 30 minutes (was 10 minutes) + /// - Additional on-chain wallets sync: 5 minutes (was 80 seconds) /// /// Ideal for Android foreground services when the app goes to background. pub fn battery_saving() -> Self { @@ -784,6 +804,7 @@ impl RuntimeSyncIntervals { onchain_wallet_sync_interval_secs: 300, // 5 minutes lightning_wallet_sync_interval_secs: 120, // 2 minutes fee_rate_cache_update_interval_secs: 1800, // 30 minutes + additional_wallet_sync_interval_secs: 300, // 5 minutes } } } @@ -794,6 +815,7 @@ impl From for BackgroundSyncConfig { onchain_wallet_sync_interval_secs: intervals.onchain_wallet_sync_interval_secs, lightning_wallet_sync_interval_secs: intervals.lightning_wallet_sync_interval_secs, fee_rate_cache_update_interval_secs: intervals.fee_rate_cache_update_interval_secs, + additional_wallet_sync_interval_secs: intervals.additional_wallet_sync_interval_secs, } } } @@ -850,8 +872,9 @@ pub struct ElectrumSyncConfig { /// /// Set to `0` to use the safe 10-second default. The effective maximum is 255 seconds (the /// underlying `electrum_client` crate uses a `u8`); larger values are capped with a warning. - /// Note that two TCP connections are opened at node start (on-chain and Lightning sync), so - /// budget accordingly when tuning this value. Defaults to 10 seconds. + /// Note that two TCP connections are opened at node start (on-chain and Lightning sync), and a + /// third on the first sync of additional wallets, so budget accordingly when tuning this value. + /// Defaults to 10 seconds. pub connection_timeout_secs: u64, /// Batch size for Electrum full scans of non-primary wallets. /// diff --git a/tests/multi_address_types_tests.rs b/tests/multi_address_types_tests.rs index 01aaf977fc..0a97b10829 100644 --- a/tests/multi_address_types_tests.rs +++ b/tests/multi_address_types_tests.rs @@ -3697,9 +3697,11 @@ mod derived_accounts { use bitcoin::{Address, Amount, CompressedPublicKey, FeeRate, Network}; use electrsd::corepc_node::{Conf as BitcoindConf, Node as BitcoinD}; use electrum_client::ElectrumApi; - use ldk_node::config::{AddressType, ElectrumSyncConfig, OnchainWalletAccountConfig}; + use ldk_node::config::{ + AddressType, BackgroundSyncConfig, ElectrumSyncConfig, OnchainWalletAccountConfig, + }; use ldk_node::payment::KeychainKind; - use ldk_node::{Builder, NodeError}; + use ldk_node::{Builder, NodeError, RuntimeSyncIntervals}; use crate::common::{ distribute_funds_unconfirmed, generate_blocks_and_wait, invalidate_blocks, open_channel, @@ -4134,6 +4136,74 @@ mod derived_accounts { node.stop().unwrap(); } + #[tokio::test(flavor = "multi_thread", worker_threads = 1)] + async fn test_electrum_background_sync_keeps_additional_wallets_on_their_own_interval() { + let (bitcoind, electrsd) = setup_bitcoind_and_electrsd(); + premine_blocks(&bitcoind.client, &electrsd.client).await; + + let config = node_config(AddressType::NativeSegwit, vec![]); + crate::common::setup_builder!(builder, config.node_config); + let electrum_url = format!("tcp://{}", electrsd.electrum_url); + let sync_config = ElectrumSyncConfig { + background_sync_config: Some(BackgroundSyncConfig { + onchain_wallet_sync_interval_secs: 10, + lightning_wallet_sync_interval_secs: 10, + fee_rate_cache_update_interval_secs: 600, + additional_wallet_sync_interval_secs: 3_600, + }), + ..Default::default() + }; + builder.set_chain_source_electrum(electrum_url, Some(sync_config)); + builder.set_log_facade_logger(); + let node = builder.build().unwrap(); + node.start().unwrap(); + + let xpub = node.export_onchain_wallet_account_xpub(AddressType::NativeSegwit, 1).unwrap(); + node.add_onchain_wallet_account(AddressType::NativeSegwit, 1, xpub).unwrap(); + let primary_address = node.onchain_payment().new_address().unwrap(); + let derived_address = + node.onchain_payment().new_address_for_account(AddressType::NativeSegwit, 1).unwrap(); + distribute_funds_unconfirmed( + &bitcoind.client, + &electrsd.client, + vec![primary_address, derived_address], + Amount::from_sat(100_000), + ) + .await; + generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 1).await; + + let balance = |account_index| { + node.get_balance_for_onchain_wallet_account(AddressType::NativeSegwit, account_index) + .unwrap() + .total_sats + }; + let wait_for_balance = |account_index| async move { + for _ in 0..60 { + if balance(account_index) == 100_000 { + return; + } + tokio::time::sleep(Duration::from_millis(500)).await; + } + panic!("account {} was not synced in the background", account_index); + }; + + // The primary wallet syncs on its own interval; the derived account waits for its own. + wait_for_balance(0).await; + assert_eq!(balance(1), 0); + + // A shorter interval set at runtime picks the derived account up. + node.update_sync_intervals(RuntimeSyncIntervals { + onchain_wallet_sync_interval_secs: 10, + lightning_wallet_sync_interval_secs: 10, + fee_rate_cache_update_interval_secs: 600, + additional_wallet_sync_interval_secs: 10, + }) + .unwrap(); + wait_for_balance(1).await; + + node.stop().unwrap(); + } + #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_derived_account_rejects_wrong_seed_xpub_and_account_zero() { let (_bitcoind, electrsd) = setup_bitcoind_and_electrsd(); From b3ecd09eb3cccfc48f015b6d0def8d83e41174d8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 16:40:34 +0100 Subject: [PATCH 02/16] fix: keep additional wallet passes from racing the primary's events The primary and additional passes now overlap, so their event emission is serialized: BalanceChanged compares against the balance the other pass last reported. SyncCompleted fires after either pass, so apps that refresh on it see additional-account payments. Evictions are reported even when another wallet in the pass failed. Electrum: additional wallets share one connection that the server answers in order, so every request in a pass gets the deadline of the whole pass, and the connection, idle between passes, is pinged first and reconnected if the server or a NAT dropped it. The background-interval test now covers Esplora too. Verified: cargo test --lib; cargo check --features uniffi --tests; cargo test --test multi_address_types_tests derived_accounts (20 pass, two bitcoind start failures and one Bitcoind reorg test rerun alone) --- src/chain/electrum.rs | 60 ++++++++++--- src/chain/mod.rs | 49 ++++++----- tests/multi_address_types_tests.rs | 136 +++++++++++++++++------------ 3 files changed, 152 insertions(+), 93 deletions(-) diff --git a/src/chain/electrum.rs b/src/chain/electrum.rs index 08dcb09ff1..2e25815b6c 100644 --- a/src/chain/electrum.rs +++ b/src/chain/electrum.rs @@ -189,6 +189,28 @@ fn derived_wallet_incremental_sync_timeout( Duration::from_secs(BDK_WALLET_SYNC_TIMEOUT_SECS.saturating_add(request_count)) } +/// The deadline one additional wallet's sync would get on its own. +fn additional_wallet_sync_timeout( + wallet_account: crate::config::OnchainWalletAccount, request: &super::WalletSyncRequest, + full_scan_settings: FullScanSettings, +) -> Duration { + match request { + super::WalletSyncRequest::Incremental(_) if wallet_account.account_index == 0 => { + Duration::from_secs(BDK_WALLET_SYNC_TIMEOUT_SECS) + }, + super::WalletSyncRequest::Incremental(req) => derived_wallet_incremental_sync_timeout( + req.progress(), + additional_wallet_incremental_batch_size( + wallet_account.account_index, + full_scan_settings, + ), + ), + super::WalletSyncRequest::FullScan(req) => { + additional_wallet_full_scan_timeout(full_scan_settings, req.keychains().len()) + }, + } +} + pub(super) struct ElectrumChainSource { server_url: String, pub(super) sync_config: ElectrumSyncConfig, @@ -398,6 +420,16 @@ impl ElectrumChainSource { } } + // The additional wallets share one connection, which the server answers in order, so each + // gets the deadline of the whole pass: the base timeout plus every wallet's request share. + let base_timeout = Duration::from_secs(BDK_WALLET_SYNC_TIMEOUT_SECS); + let pass_timeout = + additional_sync_requests.iter().fold(base_timeout, |total, (account, req)| { + let timeout = + additional_wallet_sync_timeout(*account, req, additional_full_scan_settings); + total.saturating_add(timeout.saturating_sub(base_timeout)) + }); + for (wallet_account, sync_req) in additional_sync_requests { let client = Arc::clone(&electrum_client); let connection = Arc::clone(&connection); @@ -408,14 +440,6 @@ impl ElectrumChainSource { ); match sync_req { super::WalletSyncRequest::Incremental(req) => { - let timeout = if wallet_account.account_index == 0 { - Duration::from_secs(BDK_WALLET_SYNC_TIMEOUT_SECS) - } else { - derived_wallet_incremental_sync_timeout( - req.progress(), - incremental_batch_size, - ) - }; join_set.spawn(async move { let result: Result = client .get_incremental_sync_wallet_update( @@ -423,7 +447,7 @@ impl ElectrumChainSource { req, txs.iter().cloned(), incremental_batch_size, - timeout, + pass_timeout, ) .await .map(|u| u.into()); @@ -431,10 +455,6 @@ impl ElectrumChainSource { }); }, super::WalletSyncRequest::FullScan(req) => { - let timeout = additional_wallet_full_scan_timeout( - additional_full_scan_settings, - req.keychains().len(), - ); join_set.spawn(async move { let result: Result = client .get_full_scan_wallet_update( @@ -442,7 +462,7 @@ impl ElectrumChainSource { req, txs.iter().cloned(), additional_full_scan_settings, - timeout, + pass_timeout, ) .await .map(|u| u.into()); @@ -887,6 +907,18 @@ impl ElectrumRuntimeClient { Ok::<_, Error>(Arc::new(RwLock::new(Arc::new(client)))) }) .await?; + + // Only additional syncs use this connection, so it idles between passes, and a server or + // NAT may have dropped it meanwhile. Find out before the pass, and reconnect if so. + let client = Arc::clone(&connection.read().unwrap()); + let electrum_client = Arc::clone(&client.electrum_client); + let ping = self.runtime_handle.spawn_blocking(move || electrum_client.ping()).await; + if let Ok(Err(e)) = ping { + if electrum_connection_broken(&e) { + log_info!(self.logger, "Additional wallets' Electrum connection was closed: {}", e); + let _ = self.reconnect_client(connection, &client).await; + } + } Ok(Arc::clone(connection)) } diff --git a/src/chain/mod.rs b/src/chain/mod.rs index d1fb16f546..5ff215718f 100644 --- a/src/chain/mod.rs +++ b/src/chain/mod.rs @@ -112,6 +112,9 @@ pub(crate) struct ChainSource { onchain_wallet: Arc>>>, event_queue: Arc>>>>>, sync_config_sender: Option>, + // Serializes the primary and additional passes' event emission, so `BalanceChanged` compares + // against the balance the other pass last reported. + sync_events_lock: tokio::sync::Mutex<()>, } enum ChainSourceKind { @@ -633,6 +636,7 @@ impl ChainSource { onchain_wallet: Arc::new(Mutex::new(None)), event_queue: Arc::new(Mutex::new(None)), sync_config_sender, + sync_events_lock: tokio::sync::Mutex::new(()), }, None, ) @@ -670,6 +674,7 @@ impl ChainSource { onchain_wallet: Arc::new(Mutex::new(None)), event_queue: Arc::new(Mutex::new(None)), sync_config_sender, + sync_events_lock: tokio::sync::Mutex::new(()), }, None, ) @@ -702,6 +707,7 @@ impl ChainSource { onchain_wallet: Arc::new(Mutex::new(None)), event_queue: Arc::new(Mutex::new(None)), sync_config_sender: None, + sync_events_lock: tokio::sync::Mutex::new(()), }, best_block, ) @@ -735,6 +741,7 @@ impl ChainSource { onchain_wallet: Arc::new(Mutex::new(None)), event_queue: Arc::new(Mutex::new(None)), sync_config_sender: None, + sync_events_lock: tokio::sync::Mutex::new(()), }, best_block, ) @@ -1143,6 +1150,7 @@ impl ChainSource { ChainSourceKind::Esplora(esplora_chain_source) => { let WalletSyncOutcome { events: wallet_events, evicted_txids, error: sync_error } = esplora_chain_source.sync_onchain_wallet(Arc::clone(&wallet), scope).await; + let _events_guard = self.sync_events_lock.lock().await; // Process wallet events if event queue is provided if let Some(event_queue) = event_queue { @@ -1155,6 +1163,8 @@ impl ChainSource { chain_monitor, ) .await?; + // Applied even when another wallet in the pass failed. + emit_evicted_transactions(evicted_txids, event_queue, &self.logger).await; } if let Some(error) = sync_error { @@ -1162,17 +1172,13 @@ impl ChainSource { } if let Some(event_queue) = event_queue { - emit_evicted_transactions(evicted_txids, event_queue, &self.logger).await; - - if scope == OnchainSyncScope::Primary { - let synced_height = wallet.current_best_block().height; - event_queue - .add_event(Event::SyncCompleted { - sync_type: SyncType::OnchainWallet, - synced_block_height: synced_height, - }) - .await?; - } + let synced_height = wallet.current_best_block().height; + event_queue + .add_event(Event::SyncCompleted { + sync_type: SyncType::OnchainWallet, + synced_block_height: synced_height, + }) + .await?; // Check for balance changes and emit BalanceChanged event if needed if let (Some(cm), Some(chain_mon), Some(cfg)) = (channel_manager, chain_monitor, config) @@ -1230,6 +1236,7 @@ impl ChainSource { ChainSourceKind::Electrum(electrum_chain_source) => { let WalletSyncOutcome { events: wallet_events, evicted_txids, error: sync_error } = electrum_chain_source.sync_onchain_wallet(Arc::clone(&wallet), scope).await; + let _events_guard = self.sync_events_lock.lock().await; // Process wallet events if event queue is provided if let Some(event_queue) = event_queue { @@ -1242,6 +1249,8 @@ impl ChainSource { chain_monitor, ) .await?; + // Applied even when another wallet in the pass failed. + emit_evicted_transactions(evicted_txids, event_queue, &self.logger).await; } if let Some(error) = sync_error { @@ -1249,17 +1258,13 @@ impl ChainSource { } if let Some(event_queue) = event_queue { - emit_evicted_transactions(evicted_txids, event_queue, &self.logger).await; - - if scope == OnchainSyncScope::Primary { - let synced_height = wallet.current_best_block().height; - event_queue - .add_event(Event::SyncCompleted { - sync_type: SyncType::OnchainWallet, - synced_block_height: synced_height, - }) - .await?; - } + let synced_height = wallet.current_best_block().height; + event_queue + .add_event(Event::SyncCompleted { + sync_type: SyncType::OnchainWallet, + synced_block_height: synced_height, + }) + .await?; // Check for balance changes and emit BalanceChanged event if needed if let (Some(cm), Some(chain_mon), Some(cfg)) = diff --git a/tests/multi_address_types_tests.rs b/tests/multi_address_types_tests.rs index 0a97b10829..1eab11bc16 100644 --- a/tests/multi_address_types_tests.rs +++ b/tests/multi_address_types_tests.rs @@ -3698,7 +3698,8 @@ mod derived_accounts { use electrsd::corepc_node::{Conf as BitcoindConf, Node as BitcoinD}; use electrum_client::ElectrumApi; use ldk_node::config::{ - AddressType, BackgroundSyncConfig, ElectrumSyncConfig, OnchainWalletAccountConfig, + AddressType, BackgroundSyncConfig, ElectrumSyncConfig, EsploraSyncConfig, + OnchainWalletAccountConfig, }; use ldk_node::payment::KeychainKind; use ldk_node::{Builder, NodeError, RuntimeSyncIntervals}; @@ -4137,71 +4138,92 @@ mod derived_accounts { } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] - async fn test_electrum_background_sync_keeps_additional_wallets_on_their_own_interval() { + async fn test_background_sync_keeps_additional_wallets_on_their_own_interval() { let (bitcoind, electrsd) = setup_bitcoind_and_electrsd(); premine_blocks(&bitcoind.client, &electrsd.client).await; - - let config = node_config(AddressType::NativeSegwit, vec![]); - crate::common::setup_builder!(builder, config.node_config); - let electrum_url = format!("tcp://{}", electrsd.electrum_url); - let sync_config = ElectrumSyncConfig { - background_sync_config: Some(BackgroundSyncConfig { - onchain_wallet_sync_interval_secs: 10, - lightning_wallet_sync_interval_secs: 10, - fee_rate_cache_update_interval_secs: 600, - additional_wallet_sync_interval_secs: 3_600, - }), - ..Default::default() + let intervals = |additional_wallet_sync_interval_secs| BackgroundSyncConfig { + onchain_wallet_sync_interval_secs: 10, + lightning_wallet_sync_interval_secs: 10, + fee_rate_cache_update_interval_secs: 600, + additional_wallet_sync_interval_secs, }; - builder.set_chain_source_electrum(electrum_url, Some(sync_config)); - builder.set_log_facade_logger(); - let node = builder.build().unwrap(); - node.start().unwrap(); - let xpub = node.export_onchain_wallet_account_xpub(AddressType::NativeSegwit, 1).unwrap(); - node.add_onchain_wallet_account(AddressType::NativeSegwit, 1, xpub).unwrap(); - let primary_address = node.onchain_payment().new_address().unwrap(); - let derived_address = - node.onchain_payment().new_address_for_account(AddressType::NativeSegwit, 1).unwrap(); - distribute_funds_unconfirmed( - &bitcoind.client, - &electrsd.client, - vec![primary_address, derived_address], - Amount::from_sat(100_000), - ) - .await; - generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 1).await; + for electrum in [true, false] { + let config = node_config(AddressType::NativeSegwit, vec![]); + crate::common::setup_builder!(builder, config.node_config); + let background_sync_config = Some(intervals(3_600)); + if electrum { + let sync_config = + ElectrumSyncConfig { background_sync_config, ..Default::default() }; + builder.set_chain_source_electrum( + format!("tcp://{}", electrsd.electrum_url), + Some(sync_config), + ); + } else { + builder.set_chain_source_esplora( + format!("http://{}", electrsd.esplora_url.as_ref().unwrap()), + Some(EsploraSyncConfig { background_sync_config }), + ); + } + builder.set_log_facade_logger(); + let node = builder.build().unwrap(); + node.start().unwrap(); + + let xpub = + node.export_onchain_wallet_account_xpub(AddressType::NativeSegwit, 1).unwrap(); + node.add_onchain_wallet_account(AddressType::NativeSegwit, 1, xpub).unwrap(); + let primary_address = node.onchain_payment().new_address().unwrap(); + let derived_address = node + .onchain_payment() + .new_address_for_account(AddressType::NativeSegwit, 1) + .unwrap(); + distribute_funds_unconfirmed( + &bitcoind.client, + &electrsd.client, + vec![primary_address, derived_address], + Amount::from_sat(100_000), + ) + .await; + generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 1).await; - let balance = |account_index| { - node.get_balance_for_onchain_wallet_account(AddressType::NativeSegwit, account_index) + let balance = |account_index| { + node.get_balance_for_onchain_wallet_account( + AddressType::NativeSegwit, + account_index, + ) .unwrap() .total_sats - }; - let wait_for_balance = |account_index| async move { - for _ in 0..60 { - if balance(account_index) == 100_000 { - return; + }; + let wait_for_balance = |account_index| async move { + for _ in 0..60 { + if balance(account_index) == 100_000 { + return; + } + tokio::time::sleep(Duration::from_millis(500)).await; } - tokio::time::sleep(Duration::from_millis(500)).await; - } - panic!("account {} was not synced in the background", account_index); - }; - - // The primary wallet syncs on its own interval; the derived account waits for its own. - wait_for_balance(0).await; - assert_eq!(balance(1), 0); - - // A shorter interval set at runtime picks the derived account up. - node.update_sync_intervals(RuntimeSyncIntervals { - onchain_wallet_sync_interval_secs: 10, - lightning_wallet_sync_interval_secs: 10, - fee_rate_cache_update_interval_secs: 600, - additional_wallet_sync_interval_secs: 10, - }) - .unwrap(); - wait_for_balance(1).await; + panic!( + "account {} was not synced in the background (electrum: {})", + account_index, electrum + ); + }; + + // The primary wallet syncs on its own interval; the derived account waits for its own. + wait_for_balance(0).await; + assert_eq!(balance(1), 0); + + // A shorter interval set at runtime picks the derived account up. + let shorter = intervals(10); + node.update_sync_intervals(RuntimeSyncIntervals { + onchain_wallet_sync_interval_secs: shorter.onchain_wallet_sync_interval_secs, + lightning_wallet_sync_interval_secs: shorter.lightning_wallet_sync_interval_secs, + fee_rate_cache_update_interval_secs: shorter.fee_rate_cache_update_interval_secs, + additional_wallet_sync_interval_secs: shorter.additional_wallet_sync_interval_secs, + }) + .unwrap(); + wait_for_balance(1).await; - node.stop().unwrap(); + node.stop().unwrap(); + } } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] From 39e743cf127ae579fd5854b7aff82f3637372b7c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 17:29:50 +0100 Subject: [PATCH 03/16] fix: emit SyncCompleted once every wallet has synced and dedupe events across passes --- src/chain/electrum.rs | 3 +- src/chain/esplora.rs | 3 +- src/chain/mod.rs | 235 ++++++++++++++++++++++++++++++++++-------- 3 files changed, 196 insertions(+), 45 deletions(-) diff --git a/src/chain/electrum.rs b/src/chain/electrum.rs index 2e25815b6c..f022036a06 100644 --- a/src/chain/electrum.rs +++ b/src/chain/electrum.rs @@ -342,7 +342,7 @@ impl ElectrumChainSource { }, }; if scope == OnchainSyncScope::Additional && additional_accounts.is_empty() { - return Ok(super::WalletSyncOutcome::new(Vec::new(), None)); + return Ok(super::WalletSyncOutcome::skipped()); } // Additional wallets use their own connection: an Electrum server answers a connection's // requests in order, so on a shared one the primary's would wait behind theirs. @@ -551,6 +551,7 @@ impl ElectrumChainSource { events: outcome.events, evicted_txids: outcome.evicted_txids, error: outcome.error, + skipped: false, }) } diff --git a/src/chain/esplora.rs b/src/chain/esplora.rs index 8506f2df36..bea60a657b 100644 --- a/src/chain/esplora.rs +++ b/src/chain/esplora.rs @@ -166,7 +166,7 @@ impl EsploraChainSource { }, }; if scope == OnchainSyncScope::Additional && additional_accounts.is_empty() { - return Ok(super::WalletSyncOutcome::new(Vec::new(), None)); + return Ok(super::WalletSyncOutcome::skipped()); } let additional_sync_requests = super::collect_additional_sync_requests( &additional_accounts, @@ -381,6 +381,7 @@ impl EsploraChainSource { events: outcome.events, evicted_txids: outcome.evicted_txids, error: outcome.error, + skipped: false, }) } diff --git a/src/chain/mod.rs b/src/chain/mod.rs index 5ff215718f..feda11112b 100644 --- a/src/chain/mod.rs +++ b/src/chain/mod.rs @@ -9,7 +9,7 @@ mod bitcoind; mod electrum; mod esplora; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet, VecDeque}; use std::ops::Deref; use std::sync::{Arc, Mutex, RwLock}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; @@ -52,6 +52,71 @@ pub(crate) enum OnchainSyncScope { Additional, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +enum OnchainTxEventKind { + Received, + Confirmed, + Reorged, + Replaced, +} + +const MAX_EMITTED_TX_EVENTS: usize = 1000; + +// A transaction paying both the primary and an additional wallet shows up in both passes, so +// wallet events are deduplicated across passes, not per pass. Bounded: the oldest go first. +#[derive(Default)] +struct EmittedTxEvents { + seen: HashSet<(Txid, OnchainTxEventKind)>, + order: VecDeque<(Txid, OnchainTxEventKind)>, +} + +impl EmittedTxEvents { + // Returns `false` if the event was already emitted. + fn insert(&mut self, txid: Txid, kind: OnchainTxEventKind) -> bool { + if !self.seen.insert((txid, kind)) { + return false; + } + self.order.push_back((txid, kind)); + if self.order.len() > MAX_EMITTED_TX_EVENTS { + if let Some(oldest) = self.order.pop_front() { + self.seen.remove(&oldest); + } + } + true + } + + // Lets the event be emitted again, e.g. a confirmation after a reorg. + fn remove(&mut self, txid: Txid, kind: OnchainTxEventKind) { + if self.seen.remove(&(txid, kind)) { + self.order.retain(|entry| *entry != (txid, kind)); + } + } +} + +// State shared by the primary and additional passes' event emission. +#[derive(Default)] +struct SyncEventsState { + primary_synced: bool, + additional_synced: bool, + emitted_tx_events: EmittedTxEvents, +} + +impl SyncEventsState { + // Records a successful pass and returns whether it should emit `SyncCompleted`. It is only + // emitted once both the primary and the additional wallets have synced since start, so it + // always means every wallet has synced. A pass with no additional wallets emits it only when + // it is the one that completes the pair. + fn record_synced(&mut self, scope: OnchainSyncScope, skipped: bool) -> bool { + let was_complete = self.primary_synced && self.additional_synced; + match scope { + OnchainSyncScope::Primary => self.primary_synced = true, + OnchainSyncScope::Additional => self.additional_synced = true, + } + let complete = self.primary_synced && self.additional_synced; + complete && (!skipped || !was_complete) + } +} + pub(crate) enum WalletSyncStatus { Completed, InProgress { subscribers: tokio::sync::broadcast::Sender> }, @@ -114,7 +179,7 @@ pub(crate) struct ChainSource { sync_config_sender: Option>, // Serializes the primary and additional passes' event emission, so `BalanceChanged` compares // against the balance the other pass last reported. - sync_events_lock: tokio::sync::Mutex<()>, + sync_events: tokio::sync::Mutex, } enum ChainSourceKind { @@ -174,10 +239,13 @@ fn check_evicted_transactions( // Emit events for transactions a sync found evicted from the mempool. async fn emit_evicted_transactions( evicted_txids: Vec, event_queue: &EventQueue, logger: &Logger, + emitted_tx_events: &mut EmittedTxEvents, ) where L2::Target: LdkLogger, { for txid in evicted_txids { + // A rebroadcast of an evicted transaction is reported as received again. + emitted_tx_events.remove(txid, OnchainTxEventKind::Received); if let Err(e) = event_queue.add_event(Event::OnchainTransactionEvicted { txid }).await { log_error!(logger, "Failed to push evicted transaction event to queue: {}", e); } @@ -243,15 +311,21 @@ pub(super) struct WalletSyncOutcome { pub(super) events: Vec, pub(super) evicted_txids: Vec, pub(super) error: Option, + // An additional pass with no additional wallets to sync. + pub(super) skipped: bool, } impl WalletSyncOutcome { pub(super) fn new(events: Vec, error: Option) -> Self { - Self { events, evicted_txids: Vec::new(), error } + Self { events, evicted_txids: Vec::new(), error, skipped: false } } pub(super) fn failed(error: Error) -> Self { - Self { events: Vec::new(), evicted_txids: Vec::new(), error: Some(error) } + Self::new(Vec::new(), Some(error)) + } + + pub(super) fn skipped() -> Self { + Self { skipped: true, ..Self::new(Vec::new(), None) } } pub(super) fn result(&self) -> Result<(), Error> { @@ -407,6 +481,28 @@ mod sync_tests { assert!(node.node_metrics.read().unwrap().latest_onchain_wallet_sync_timestamp.is_some()); } + #[test] + fn sync_completed_waits_for_both_scopes() { + let mut state = SyncEventsState::default(); + assert!(!state.record_synced(OnchainSyncScope::Primary, false)); + // No additional wallets: the skipped pass completes the pair. + assert!(state.record_synced(OnchainSyncScope::Additional, true)); + assert!(!state.record_synced(OnchainSyncScope::Additional, true)); + assert!(state.record_synced(OnchainSyncScope::Primary, false)); + assert!(state.record_synced(OnchainSyncScope::Additional, false)); + } + + #[test] + fn tx_events_dedupe_across_passes_until_reorg() { + let txid = Txid::all_zeros(); + let mut emitted = EmittedTxEvents::default(); + assert!(emitted.insert(txid, OnchainTxEventKind::Received)); + assert!(!emitted.insert(txid, OnchainTxEventKind::Received)); + assert!(emitted.insert(txid, OnchainTxEventKind::Confirmed)); + emitted.remove(txid, OnchainTxEventKind::Confirmed); + assert!(emitted.insert(txid, OnchainTxEventKind::Confirmed)); + } + #[test] fn wallet_sync_outcome_preserves_events_on_failure() { let block = bitcoin::BlockHash::all_zeros(); @@ -455,23 +551,34 @@ mod sync_tests { } } +async fn emit_onchain_sync_completed( + wallet: &Wallet, event_queue: &EventQueue, +) -> Result<(), Error> +where + L2::Target: LdkLogger, +{ + event_queue + .add_event(Event::SyncCompleted { + sync_type: SyncType::OnchainWallet, + synced_block_height: wallet.current_best_block().height, + }) + .await +} + // Process BDK wallet events and emit corresponding ldk-node events via the event queue. // When a transaction touches multiple wallet accounts, each wallet emits its own -// BdkWalletEvent, so we deduplicate by txid before forwarding to the event queue. +// BdkWalletEvent, so we deduplicate by txid and event type before forwarding to the event queue. +// Per event type, so that two wallets with different prior state can each contribute their event +// type for the same txid without suppressing the other. async fn process_wallet_events( wallet_events: Vec, wallet: &crate::wallet::Wallet, event_queue: &EventQueue, logger: &Arc, channel_manager: Option<&Arc>, _chain_monitor: Option<&Arc>, + emitted_tx_events: &mut EmittedTxEvents, ) -> Result<(), Error> where L2::Target: LdkLogger, { - // Use per-type sets so that two wallets with different prior state can each contribute - // their event type for the same txid without suppressing the other. - let mut seen_received_txids = std::collections::HashSet::new(); - let mut seen_confirmed_txids = std::collections::HashSet::new(); - let mut seen_reorged_txids = std::collections::HashSet::new(); - let mut seen_replaced_txids = std::collections::HashSet::new(); let transaction_confirmations = wallet.transaction_confirmations(); for wallet_event in wallet_events { @@ -485,9 +592,10 @@ where ); continue; }; - if !seen_confirmed_txids.insert(txid) { + if !emitted_tx_events.insert(txid, OnchainTxEventKind::Confirmed) { continue; } + emitted_tx_events.remove(txid, OnchainTxEventKind::Reorged); let details = get_transaction_details(&txid, wallet, channel_manager) .unwrap_or_else(|| { log_error!(logger, "Transaction {} not found in wallet", txid); @@ -520,9 +628,10 @@ where BdkWalletEvent::TxUnconfirmed { txid, old_block_time, .. } => { match old_block_time { Some(_) => { - if !seen_reorged_txids.insert(txid) { + if !emitted_tx_events.insert(txid, OnchainTxEventKind::Reorged) { continue; } + emitted_tx_events.remove(txid, OnchainTxEventKind::Confirmed); // Transaction was previously confirmed but is now unconfirmed (reorg) log_info!( logger, @@ -536,7 +645,7 @@ where })?; }, None => { - if !seen_received_txids.insert(txid) { + if !emitted_tx_events.insert(txid, OnchainTxEventKind::Received) { continue; } // New unconfirmed transaction detected in mempool @@ -577,7 +686,7 @@ where // We don't emit an event for chain tip changes as this is too noisy }, BdkWalletEvent::TxReplaced { txid, conflicts, .. } => { - if !seen_replaced_txids.insert(txid) { + if !emitted_tx_events.insert(txid, OnchainTxEventKind::Replaced) { continue; } let conflict_txids: Vec = @@ -636,7 +745,7 @@ impl ChainSource { onchain_wallet: Arc::new(Mutex::new(None)), event_queue: Arc::new(Mutex::new(None)), sync_config_sender, - sync_events_lock: tokio::sync::Mutex::new(()), + sync_events: tokio::sync::Mutex::new(SyncEventsState::default()), }, None, ) @@ -674,7 +783,7 @@ impl ChainSource { onchain_wallet: Arc::new(Mutex::new(None)), event_queue: Arc::new(Mutex::new(None)), sync_config_sender, - sync_events_lock: tokio::sync::Mutex::new(()), + sync_events: tokio::sync::Mutex::new(SyncEventsState::default()), }, None, ) @@ -707,7 +816,7 @@ impl ChainSource { onchain_wallet: Arc::new(Mutex::new(None)), event_queue: Arc::new(Mutex::new(None)), sync_config_sender: None, - sync_events_lock: tokio::sync::Mutex::new(()), + sync_events: tokio::sync::Mutex::new(SyncEventsState::default()), }, best_block, ) @@ -741,7 +850,7 @@ impl ChainSource { onchain_wallet: Arc::new(Mutex::new(None)), event_queue: Arc::new(Mutex::new(None)), sync_config_sender: None, - sync_events_lock: tokio::sync::Mutex::new(()), + sync_events: tokio::sync::Mutex::new(SyncEventsState::default()), }, best_block, ) @@ -904,6 +1013,7 @@ impl ChainSource { chain_monitor.as_ref(), self.config(), scope, + false, ) .await } else { @@ -927,7 +1037,12 @@ impl ChainSource { sync_scope(OnchainSyncScope::Primary), sync_scope(OnchainSyncScope::Additional) ); - primary.and(additional) + primary.and(additional)?; + // One `SyncCompleted` per call, once both passes succeeded. + if let Some(event_queue) = event_queue { + emit_onchain_sync_completed(&wallet, &event_queue).await?; + } + Ok(()) } fn config(&self) -> Option<&Arc> { @@ -1001,6 +1116,7 @@ impl ChainSource { Some(chain_monitor), self.config(), OnchainSyncScope::Additional, + true, ).await; } } @@ -1095,6 +1211,7 @@ impl ChainSource { Some(&chain_monitor), self.config(), OnchainSyncScope::Primary, + true, ).await; } _ = fee_rate_update_interval.tick() => { @@ -1141,16 +1258,28 @@ impl ChainSource { async fn sync_onchain_wallet_with_events( &self, event_queue: Option<&Arc>>>, channel_manager: Option<&Arc>, chain_monitor: Option<&Arc>, - config: Option<&Arc>, scope: OnchainSyncScope, + config: Option<&Arc>, scope: OnchainSyncScope, emit_sync_completed: bool, ) -> Result<(), Error> { let wallet = self.onchain_wallet.lock().unwrap().clone(); let wallet = wallet.ok_or(Error::WalletOperationFailed)?; match &self.kind { ChainSourceKind::Esplora(esplora_chain_source) => { - let WalletSyncOutcome { events: wallet_events, evicted_txids, error: sync_error } = - esplora_chain_source.sync_onchain_wallet(Arc::clone(&wallet), scope).await; - let _events_guard = self.sync_events_lock.lock().await; + let WalletSyncOutcome { + events: wallet_events, + evicted_txids, + error: sync_error, + skipped, + } = esplora_chain_source.sync_onchain_wallet(Arc::clone(&wallet), scope).await; + let mut events_state = self.sync_events.lock().await; + if skipped { + if events_state.record_synced(scope, true) && emit_sync_completed { + if let Some(event_queue) = event_queue { + emit_onchain_sync_completed(&wallet, event_queue).await?; + } + } + return Ok(()); + } // Process wallet events if event queue is provided if let Some(event_queue) = event_queue { @@ -1161,24 +1290,28 @@ impl ChainSource { &self.logger, channel_manager, chain_monitor, + &mut events_state.emitted_tx_events, ) .await?; // Applied even when another wallet in the pass failed. - emit_evicted_transactions(evicted_txids, event_queue, &self.logger).await; + emit_evicted_transactions( + evicted_txids, + event_queue, + &self.logger, + &mut events_state.emitted_tx_events, + ) + .await; } if let Some(error) = sync_error { return Err(error); } + let sync_completed = events_state.record_synced(scope, false); if let Some(event_queue) = event_queue { - let synced_height = wallet.current_best_block().height; - event_queue - .add_event(Event::SyncCompleted { - sync_type: SyncType::OnchainWallet, - synced_block_height: synced_height, - }) - .await?; + if sync_completed && emit_sync_completed { + emit_onchain_sync_completed(&wallet, event_queue).await?; + } // Check for balance changes and emit BalanceChanged event if needed if let (Some(cm), Some(chain_mon), Some(cfg)) = (channel_manager, chain_monitor, config) @@ -1234,9 +1367,21 @@ impl ChainSource { Ok(()) }, ChainSourceKind::Electrum(electrum_chain_source) => { - let WalletSyncOutcome { events: wallet_events, evicted_txids, error: sync_error } = - electrum_chain_source.sync_onchain_wallet(Arc::clone(&wallet), scope).await; - let _events_guard = self.sync_events_lock.lock().await; + let WalletSyncOutcome { + events: wallet_events, + evicted_txids, + error: sync_error, + skipped, + } = electrum_chain_source.sync_onchain_wallet(Arc::clone(&wallet), scope).await; + let mut events_state = self.sync_events.lock().await; + if skipped { + if events_state.record_synced(scope, true) && emit_sync_completed { + if let Some(event_queue) = event_queue { + emit_onchain_sync_completed(&wallet, event_queue).await?; + } + } + return Ok(()); + } // Process wallet events if event queue is provided if let Some(event_queue) = event_queue { @@ -1247,24 +1392,28 @@ impl ChainSource { &self.logger, channel_manager, chain_monitor, + &mut events_state.emitted_tx_events, ) .await?; // Applied even when another wallet in the pass failed. - emit_evicted_transactions(evicted_txids, event_queue, &self.logger).await; + emit_evicted_transactions( + evicted_txids, + event_queue, + &self.logger, + &mut events_state.emitted_tx_events, + ) + .await; } if let Some(error) = sync_error { return Err(error); } + let sync_completed = events_state.record_synced(scope, false); if let Some(event_queue) = event_queue { - let synced_height = wallet.current_best_block().height; - event_queue - .add_event(Event::SyncCompleted { - sync_type: SyncType::OnchainWallet, - synced_block_height: synced_height, - }) - .await?; + if sync_completed && emit_sync_completed { + emit_onchain_sync_completed(&wallet, event_queue).await?; + } // Check for balance changes and emit BalanceChanged event if needed if let (Some(cm), Some(chain_mon), Some(cfg)) = From 2e517db161143f535713eea0abdc4a8be5e7957a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 17:33:52 +0100 Subject: [PATCH 04/16] fix: hold SyncCompleted for runtime-added wallets and report re-confirmations in a new block --- src/chain/electrum.rs | 5 +- src/chain/esplora.rs | 5 +- src/chain/mod.rs | 115 ++++++++++++++++++++++++++++++------------ 3 files changed, 90 insertions(+), 35 deletions(-) diff --git a/src/chain/electrum.rs b/src/chain/electrum.rs index f022036a06..15c6b69345 100644 --- a/src/chain/electrum.rs +++ b/src/chain/electrum.rs @@ -222,7 +222,7 @@ pub(super) struct ElectrumChainSource { fee_estimator: Arc, pub(super) kv_store: Arc, pub(super) config: Arc, - address_type_runtime_config: Arc>, + pub(super) address_type_runtime_config: Arc>, logger: Arc, pub(super) node_metrics: Arc>, } @@ -295,7 +295,8 @@ impl ElectrumChainSource { if let Some(mut sync_receiver) = receiver_res { log_info!(self.logger, "Sync in progress, skipping."); match sync_receiver.recv().await { - Ok(Ok(())) => return super::WalletSyncOutcome::new(Vec::new(), None), + // The pass it waited on emitted the events. + Ok(Ok(())) => return super::WalletSyncOutcome::skipped(), Ok(Err(e)) => return super::WalletSyncOutcome::failed(e), Err(e) => { debug_assert!(false, "Failed to receive wallet sync result: {:?}", e); diff --git a/src/chain/esplora.rs b/src/chain/esplora.rs index bea60a657b..5e99b50fad 100644 --- a/src/chain/esplora.rs +++ b/src/chain/esplora.rs @@ -46,7 +46,7 @@ pub(super) struct EsploraChainSource { fee_estimator: Arc, pub(super) kv_store: Arc, pub(super) config: Arc, - address_type_runtime_config: Arc>, + pub(super) address_type_runtime_config: Arc>, logger: Arc, pub(super) node_metrics: Arc>, } @@ -130,7 +130,8 @@ impl EsploraChainSource { if let Some(mut sync_receiver) = receiver_res { log_info!(self.logger, "Sync in progress, skipping."); match sync_receiver.recv().await { - Ok(Ok(())) => return super::WalletSyncOutcome::new(Vec::new(), None), + // The pass it waited on emitted the events. + Ok(Ok(())) => return super::WalletSyncOutcome::skipped(), Ok(Err(e)) => return super::WalletSyncOutcome::failed(e), Err(e) => { debug_assert!(false, "Failed to receive wallet sync result: {:?}", e); diff --git a/src/chain/mod.rs b/src/chain/mod.rs index feda11112b..e71e88e208 100644 --- a/src/chain/mod.rs +++ b/src/chain/mod.rs @@ -55,7 +55,8 @@ pub(crate) enum OnchainSyncScope { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum OnchainTxEventKind { Received, - Confirmed, + // Per block, so a confirmation in another block after a reorg is reported again. + Confirmed(bitcoin::BlockHash), Reorged, Replaced, } @@ -85,11 +86,11 @@ impl EmittedTxEvents { true } - // Lets the event be emitted again, e.g. a confirmation after a reorg. - fn remove(&mut self, txid: Txid, kind: OnchainTxEventKind) { - if self.seen.remove(&(txid, kind)) { - self.order.retain(|entry| *entry != (txid, kind)); - } + // Lets the transaction's events matching `kind` be emitted again, e.g. a confirmation after + // a reorg. + fn remove(&mut self, txid: Txid, kind: impl Fn(&OnchainTxEventKind) -> bool) { + self.seen.retain(|(t, k)| *t != txid || !kind(k)); + self.order.retain(|(t, k)| *t != txid || !kind(k)); } } @@ -98,22 +99,26 @@ impl EmittedTxEvents { struct SyncEventsState { primary_synced: bool, additional_synced: bool, + complete: bool, emitted_tx_events: EmittedTxEvents, } impl SyncEventsState { // Records a successful pass and returns whether it should emit `SyncCompleted`. It is only - // emitted once both the primary and the additional wallets have synced since start, so it - // always means every wallet has synced. A pass with no additional wallets emits it only when - // it is the one that completes the pair. - fn record_synced(&mut self, scope: OnchainSyncScope, skipped: bool) -> bool { - let was_complete = self.primary_synced && self.additional_synced; + // emitted once both the primary and the additional passes have succeeded since start and + // every current additional wallet has synced (one added at runtime may not have yet), so it + // always means every wallet has synced. A pass that synced nothing emits it only when it is + // the one that completes the set. + fn record_synced( + &mut self, scope: OnchainSyncScope, skipped: bool, additional_wallets_synced: bool, + ) -> bool { match scope { OnchainSyncScope::Primary => self.primary_synced = true, OnchainSyncScope::Additional => self.additional_synced = true, } - let complete = self.primary_synced && self.additional_synced; - complete && (!skipped || !was_complete) + let was_complete = self.complete; + self.complete = self.primary_synced && self.additional_synced && additional_wallets_synced; + self.complete && (!skipped || !was_complete) } } @@ -245,7 +250,7 @@ async fn emit_evicted_transactions( { for txid in evicted_txids { // A rebroadcast of an evicted transaction is reported as received again. - emitted_tx_events.remove(txid, OnchainTxEventKind::Received); + emitted_tx_events.remove(txid, |kind| *kind == OnchainTxEventKind::Received); if let Err(e) = event_queue.add_event(Event::OnchainTransactionEvicted { txid }).await { log_error!(logger, "Failed to push evicted transaction event to queue: {}", e); } @@ -311,7 +316,8 @@ pub(super) struct WalletSyncOutcome { pub(super) events: Vec, pub(super) evicted_txids: Vec, pub(super) error: Option, - // An additional pass with no additional wallets to sync. + // Nothing synced in this call: an additional pass with no additional wallets, or a call that + // waited on a pass already in flight. pub(super) skipped: bool, } @@ -484,12 +490,14 @@ mod sync_tests { #[test] fn sync_completed_waits_for_both_scopes() { let mut state = SyncEventsState::default(); - assert!(!state.record_synced(OnchainSyncScope::Primary, false)); - // No additional wallets: the skipped pass completes the pair. - assert!(state.record_synced(OnchainSyncScope::Additional, true)); - assert!(!state.record_synced(OnchainSyncScope::Additional, true)); - assert!(state.record_synced(OnchainSyncScope::Primary, false)); - assert!(state.record_synced(OnchainSyncScope::Additional, false)); + assert!(!state.record_synced(OnchainSyncScope::Primary, false, true)); + // No additional wallets: the skipped pass completes the set. + assert!(state.record_synced(OnchainSyncScope::Additional, true, true)); + assert!(!state.record_synced(OnchainSyncScope::Additional, true, true)); + assert!(state.record_synced(OnchainSyncScope::Primary, false, true)); + // A wallet added at runtime holds the event back until it has synced. + assert!(!state.record_synced(OnchainSyncScope::Primary, false, false)); + assert!(state.record_synced(OnchainSyncScope::Additional, false, true)); } #[test] @@ -498,9 +506,15 @@ mod sync_tests { let mut emitted = EmittedTxEvents::default(); assert!(emitted.insert(txid, OnchainTxEventKind::Received)); assert!(!emitted.insert(txid, OnchainTxEventKind::Received)); - assert!(emitted.insert(txid, OnchainTxEventKind::Confirmed)); - emitted.remove(txid, OnchainTxEventKind::Confirmed); - assert!(emitted.insert(txid, OnchainTxEventKind::Confirmed)); + let block = bitcoin::BlockHash::all_zeros(); + let confirmed = OnchainTxEventKind::Confirmed(block); + assert!(emitted.insert(txid, confirmed)); + assert!(!emitted.insert(txid, confirmed)); + emitted.remove(txid, |kind| matches!(kind, OnchainTxEventKind::Confirmed(_))); + assert!(emitted.insert(txid, confirmed)); + // A confirmation in another block is reported without an unconfirmed event in between. + let other_block = bitcoin::BlockHash::from_byte_array([1; 32]); + assert!(emitted.insert(txid, OnchainTxEventKind::Confirmed(other_block))); } #[test] @@ -592,10 +606,11 @@ where ); continue; }; - if !emitted_tx_events.insert(txid, OnchainTxEventKind::Confirmed) { + let confirmed = OnchainTxEventKind::Confirmed(block_time.block_id.hash); + if !emitted_tx_events.insert(txid, confirmed) { continue; } - emitted_tx_events.remove(txid, OnchainTxEventKind::Reorged); + emitted_tx_events.remove(txid, |kind| *kind == OnchainTxEventKind::Reorged); let details = get_transaction_details(&txid, wallet, channel_manager) .unwrap_or_else(|| { log_error!(logger, "Transaction {} not found in wallet", txid); @@ -631,7 +646,8 @@ where if !emitted_tx_events.insert(txid, OnchainTxEventKind::Reorged) { continue; } - emitted_tx_events.remove(txid, OnchainTxEventKind::Confirmed); + emitted_tx_events + .remove(txid, |kind| matches!(kind, OnchainTxEventKind::Confirmed(_))); // Transaction was previously confirmed but is now unconfirmed (reorg) log_info!( logger, @@ -1045,6 +1061,25 @@ impl ChainSource { Ok(()) } + // Whether every current additional wallet has synced: account-`0` types since their last + // persisted sync, derived accounts since registration. + fn additional_wallets_synced(&self, wallet: &Wallet) -> bool { + let (runtime_config, node_metrics) = match &self.kind { + ChainSourceKind::Esplora(es) => (&es.address_type_runtime_config, &es.node_metrics), + ChainSourceKind::Electrum(el) => (&el.address_type_runtime_config, &el.node_metrics), + ChainSourceKind::Bitcoind(_) => return true, + }; + let accounts = runtime_config.read().unwrap().additional_wallet_accounts(); + let node_metrics = node_metrics.read().unwrap(); + accounts.into_iter().all(|account| { + if account.account_index == 0 { + node_metrics.get_wallet_sync_timestamp(account).is_some() + } else { + wallet.has_synced_derived_account(account) + } + }) + } + fn config(&self) -> Option<&Arc> { match &self.kind { ChainSourceKind::Esplora(esplora_chain_source) => Some(&esplora_chain_source.config), @@ -1273,7 +1308,12 @@ impl ChainSource { } = esplora_chain_source.sync_onchain_wallet(Arc::clone(&wallet), scope).await; let mut events_state = self.sync_events.lock().await; if skipped { - if events_state.record_synced(scope, true) && emit_sync_completed { + if events_state.record_synced( + scope, + true, + self.additional_wallets_synced(&wallet), + ) && emit_sync_completed + { if let Some(event_queue) = event_queue { emit_onchain_sync_completed(&wallet, event_queue).await?; } @@ -1307,7 +1347,11 @@ impl ChainSource { return Err(error); } - let sync_completed = events_state.record_synced(scope, false); + let sync_completed = events_state.record_synced( + scope, + false, + self.additional_wallets_synced(&wallet), + ); if let Some(event_queue) = event_queue { if sync_completed && emit_sync_completed { emit_onchain_sync_completed(&wallet, event_queue).await?; @@ -1375,7 +1419,12 @@ impl ChainSource { } = electrum_chain_source.sync_onchain_wallet(Arc::clone(&wallet), scope).await; let mut events_state = self.sync_events.lock().await; if skipped { - if events_state.record_synced(scope, true) && emit_sync_completed { + if events_state.record_synced( + scope, + true, + self.additional_wallets_synced(&wallet), + ) && emit_sync_completed + { if let Some(event_queue) = event_queue { emit_onchain_sync_completed(&wallet, event_queue).await?; } @@ -1409,7 +1458,11 @@ impl ChainSource { return Err(error); } - let sync_completed = events_state.record_synced(scope, false); + let sync_completed = events_state.record_synced( + scope, + false, + self.additional_wallets_synced(&wallet), + ); if let Some(event_queue) = event_queue { if sync_completed && emit_sync_completed { emit_onchain_sync_completed(&wallet, event_queue).await?; From b39917a62b42b16b2900090e0db1dc7b6a47bd61 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 17:47:57 +0100 Subject: [PATCH 05/16] chore: release 0.7.0-rc.86 Verified: ./bindgen.sh regenerated the bindings and the Swift xcframework; swift package compute-checksum of LDKNodeFFI.xcframework.zip matches Package.swift --- CHANGELOG.md | 4 +-- Cargo.lock | 2 +- Cargo.toml | 2 +- Package.swift | 4 +-- .../kotlin/ldk-node-android/gradle.properties | 2 +- .../ldknode/ldk_node.android.kt | 10 +++++-- .../ldknode/ldk_node.common.kt | 6 ++-- .../kotlin/ldk-node-jvm/gradle.properties | 2 +- bindings/python/pyproject.toml | 2 +- bindings/python/src/ldk_node/ldk_node.py | 28 ++++++++++++++++--- bindings/swift/Sources/LDKNode/LDKNode.swift | 24 +++++++++++++--- 11 files changed, 65 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a418962f7..e35629c845 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,4 @@ -# 0.7.0-rc.85 (Synonym Fork) +# 0.7.0-rc.86 (Synonym Fork) ## Bug Fixes @@ -87,7 +87,7 @@ ## Synonym Fork Additions -- Additional on-chain wallets (monitored address types and derived accounts) sync in the background on their own `additional_wallet_sync_interval_secs` interval, apart from the primary wallet, and over their own Electrum connection, so their sync no longer delays or times out the primary wallet's. +- Additional on-chain wallets (monitored address types and derived accounts) sync in the background on their own `additional_wallet_sync_interval_secs` interval, apart from the primary wallet, and over their own Electrum connection, so their sync no longer delays or times out the primary wallet's. `SyncCompleted { OnchainWallet }` is emitted only once both the primary and the additional wallets have synced, and once per `sync_wallets()` call. - Added `build_with_vss_store_and_lnurl_auth_key_domain`, which signs VSS LNURL-auth for a fixed key domain while calling the auth server on a subdomain of it, so wallets keep their VSS identity when the auth server moves to that subdomain. - Accept incoming payments up to the full channel value, instead of 10% of it, on nodes that cannot announce channels (no node alias or listening addresses), for channels opened after the update. - Expose the exact prepared transaction fee so applications can validate the approved total before broadcast. diff --git a/Cargo.lock b/Cargo.lock index 8815be2e7e..106bf3df5e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1901,7 +1901,7 @@ dependencies = [ [[package]] name = "ldk-node" -version = "0.7.0-rc.85" +version = "0.7.0-rc.86" dependencies = [ "async-trait", "base64 0.22.1", diff --git a/Cargo.toml b/Cargo.toml index 0927e76824..856e5eafa3 100755 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ exclude = ["bindings/uniffi-bindgen"] [package] name = "ldk-node" -version = "0.7.0-rc.85" +version = "0.7.0-rc.86" authors = ["Elias Rohrer "] homepage = "https://lightningdevkit.org/" license = "MIT OR Apache-2.0" diff --git a/Package.swift b/Package.swift index 8cfc7fb442..9d5f9b2ef8 100644 --- a/Package.swift +++ b/Package.swift @@ -3,8 +3,8 @@ import PackageDescription -let tag = "v0.7.0-rc.85" -let checksum = "7837d164dc39310d6a5597c0e5598126c5fa4daa72ba63fb9cb0c4f92a0c1e24" +let tag = "v0.7.0-rc.86" +let checksum = "fb4f8bbf8786f07a741d28f40c3a58ba546b0bfdf8d68300097421eba7cbf1ec" let url = "https://github.com/synonymdev/ldk-node/releases/download/\(tag)/LDKNodeFFI.xcframework.zip" let package = Package( diff --git a/bindings/kotlin/ldk-node-android/gradle.properties b/bindings/kotlin/ldk-node-android/gradle.properties index 7fc999f175..87265a48b0 100644 --- a/bindings/kotlin/ldk-node-android/gradle.properties +++ b/bindings/kotlin/ldk-node-android/gradle.properties @@ -3,4 +3,4 @@ android.useAndroidX=true android.enableJetifier=true kotlin.code.style=official group=com.synonym -version=0.7.0-rc.85 +version=0.7.0-rc.86 diff --git a/bindings/kotlin/ldk-node-android/lib/src/main/kotlin/org/lightningdevkit/ldknode/ldk_node.android.kt b/bindings/kotlin/ldk-node-android/lib/src/main/kotlin/org/lightningdevkit/ldknode/ldk_node.android.kt index 7b94734624..d9b6b85a5b 100644 --- a/bindings/kotlin/ldk-node-android/lib/src/main/kotlin/org/lightningdevkit/ldknode/ldk_node.android.kt +++ b/bindings/kotlin/ldk-node-android/lib/src/main/kotlin/org/lightningdevkit/ldknode/ldk_node.android.kt @@ -9966,19 +9966,22 @@ object FfiConverterTypeBackgroundSyncConfig: FfiConverterRustBuffer Date: Thu, 3 Dec 2026 18:35:04 +0100 Subject: [PATCH 06/16] fix: report full cross-wallet amounts, settle payments on their wallets' tip and release cancelled sync waiters Verified: cargo test --lib, cargo test -p bdk-wallet-aggregate --- crates/bdk-wallet-aggregate/src/lib.rs | 11 +++---- src/chain/electrum.rs | 7 ++--- src/chain/esplora.rs | 7 ++--- src/chain/mod.rs | 41 ++++++++++++++++++++++++++ src/wallet/mod.rs | 9 ++++++ 5 files changed, 60 insertions(+), 15 deletions(-) diff --git a/crates/bdk-wallet-aggregate/src/lib.rs b/crates/bdk-wallet-aggregate/src/lib.rs index 29b58586a4..3051813e78 100644 --- a/crates/bdk-wallet-aggregate/src/lib.rs +++ b/crates/bdk-wallet-aggregate/src/lib.rs @@ -382,16 +382,17 @@ where } /// Aggregated sent and received amounts for a transaction across all wallets. + /// + /// Counts every wallet whose outputs the transaction pays or spends, including one that has + /// not synced the transaction yet, so the amount is complete while wallets sync apart. pub fn sent_and_received(&self, txid: Txid) -> Option<(u64, u64)> { let tx = self.find_tx(txid)?; let mut total_sent = 0u64; let mut total_received = 0u64; for wallet in self.wallets.values() { - if wallet.get_tx(txid).is_some() { - let (sent, received) = wallet.sent_and_received(&tx); - total_sent += sent.to_sat(); - total_received += received.to_sat(); - } + let (sent, received) = wallet.sent_and_received(&tx); + total_sent += sent.to_sat(); + total_received += received.to_sat(); } Some((total_sent, total_received)) } diff --git a/src/chain/electrum.rs b/src/chain/electrum.rs index 15c6b69345..ec7cc23193 100644 --- a/src/chain/electrum.rs +++ b/src/chain/electrum.rs @@ -306,15 +306,12 @@ impl ElectrumChainSource { } } + let sync_guard = super::WalletSyncGuard::new(self.wallet_sync_status(scope)); let outcome = self .sync_onchain_wallet_inner(onchain_wallet, scope) .await .unwrap_or_else(super::WalletSyncOutcome::failed); - - self.wallet_sync_status(scope) - .lock() - .unwrap() - .propagate_result_to_subscribers(outcome.result()); + sync_guard.finish(outcome.result()); outcome } diff --git a/src/chain/esplora.rs b/src/chain/esplora.rs index 5e99b50fad..23e8f1ec98 100644 --- a/src/chain/esplora.rs +++ b/src/chain/esplora.rs @@ -141,15 +141,12 @@ impl EsploraChainSource { } } + let sync_guard = super::WalletSyncGuard::new(self.wallet_sync_status(scope)); let outcome = self .sync_onchain_wallet_inner(onchain_wallet, scope) .await .unwrap_or_else(super::WalletSyncOutcome::failed); - - self.wallet_sync_status(scope) - .lock() - .unwrap() - .propagate_result_to_subscribers(outcome.result()); + sync_guard.finish(outcome.result()); outcome } diff --git a/src/chain/mod.rs b/src/chain/mod.rs index e71e88e208..8535305c5a 100644 --- a/src/chain/mod.rs +++ b/src/chain/mod.rs @@ -122,6 +122,35 @@ impl SyncEventsState { } } +// Fails a pass's waiters when the pass is dropped before it finishes (e.g. cancelled while the +// node stops), so the next pass starts instead of waiting on a result that never comes. +pub(super) struct WalletSyncGuard<'a> { + status: &'a Mutex, + finished: bool, +} + +impl<'a> WalletSyncGuard<'a> { + pub(super) fn new(status: &'a Mutex) -> Self { + Self { status, finished: false } + } + + pub(super) fn finish(mut self, result: Result<(), Error>) { + self.finished = true; + self.status.lock().unwrap().propagate_result_to_subscribers(result); + } +} + +impl Drop for WalletSyncGuard<'_> { + fn drop(&mut self) { + if !self.finished { + self.status + .lock() + .unwrap() + .propagate_result_to_subscribers(Err(Error::WalletOperationFailed)); + } + } +} + pub(crate) enum WalletSyncStatus { Completed, InProgress { subscribers: tokio::sync::broadcast::Sender> }, @@ -487,6 +516,18 @@ mod sync_tests { assert!(node.node_metrics.read().unwrap().latest_onchain_wallet_sync_timestamp.is_some()); } + #[test] + fn dropped_sync_pass_fails_its_waiters() { + let status = Mutex::new(WalletSyncStatus::Completed); + assert!(status.lock().unwrap().register_or_subscribe_pending_sync().is_none()); + let guard = WalletSyncGuard::new(&status); + let mut waiter = status.lock().unwrap().register_or_subscribe_pending_sync().unwrap(); + drop(guard); + assert_eq!(waiter.try_recv().unwrap(), Err(Error::WalletOperationFailed)); + // The next pass starts instead of waiting. + assert!(status.lock().unwrap().register_or_subscribe_pending_sync().is_none()); + } + #[test] fn sync_completed_waits_for_both_scopes() { let mut state = SyncEventsState::default(); diff --git a/src/wallet/mod.rs b/src/wallet/mod.rs index 1f78a397b0..253c226e3d 100644 --- a/src/wallet/mod.rs +++ b/src/wallet/mod.rs @@ -1102,6 +1102,15 @@ impl Wallet { let (payment_status, confirmation_status) = if let Some(anchor) = transaction_confirmations.get(&txid).copied() { let confirmation_height = anchor.block_id.height; + // Depth on the wallets tracking the transaction: the others may sync on + // a longer interval, and their older tip must not hold its payment back. + let cur_height = locked_wallet + .wallets() + .values() + .filter(|wallet| wallet.get_tx(txid).is_some()) + .map(|wallet| wallet.latest_checkpoint().height()) + .min() + .unwrap_or(cur_height); let payment_status = if cur_height >= confirmation_height + ANTI_REORG_DELAY - 1 { PaymentStatus::Succeeded From 4e86a454d70b8eb158f67ce4001e7ca5295998a5 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 19:06:42 +0100 Subject: [PATCH 07/16] chore: ship the review fixes in 0.7.0-rc.86 Verified: ./bindgen.sh rebuilt the Swift xcframework; swift package compute-checksum of LDKNodeFFI.xcframework.zip matches Package.swift --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 9d5f9b2ef8..e0d019adc8 100644 --- a/Package.swift +++ b/Package.swift @@ -4,7 +4,7 @@ import PackageDescription let tag = "v0.7.0-rc.86" -let checksum = "fb4f8bbf8786f07a741d28f40c3a58ba546b0bfdf8d68300097421eba7cbf1ec" +let checksum = "b7851f2b11ee2f8e92de9722c2600d7b8e9863e96283f5260fc04451cfdd816d" let url = "https://github.com/synonymdev/ldk-node/releases/download/\(tag)/LDKNodeFFI.xcframework.zip" let package = Package( From c7422feef963d82e511762cab38a6aebb2ea199c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 19:53:09 +0100 Subject: [PATCH 08/16] fix: report additional wallets' sync apart and reconnect a failed idle connection Verified: cargo test --lib, cargo test -p bdk-wallet-aggregate --- CHANGELOG.md | 2 +- bindings/ldk_node.udl | 1 + crates/bdk-wallet-aggregate/src/lib.rs | 61 ++++++++ src/chain/electrum.rs | 120 ++++++++++++++- src/chain/esplora.rs | 5 +- src/chain/mod.rs | 194 +++++++++++-------------- src/event.rs | 12 +- src/wallet/mod.rs | 57 ++++---- tests/integration_tests_rust.rs | 54 ++++--- 9 files changed, 330 insertions(+), 176 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e35629c845..72104f5f4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -87,7 +87,7 @@ ## Synonym Fork Additions -- Additional on-chain wallets (monitored address types and derived accounts) sync in the background on their own `additional_wallet_sync_interval_secs` interval, apart from the primary wallet, and over their own Electrum connection, so their sync no longer delays or times out the primary wallet's. `SyncCompleted { OnchainWallet }` is emitted only once both the primary and the additional wallets have synced, and once per `sync_wallets()` call. +- Additional on-chain wallets (monitored address types and derived accounts) sync in the background on their own `additional_wallet_sync_interval_secs` interval, apart from the primary wallet, and over their own Electrum connection, so their sync no longer delays or times out the primary wallet's. Their pass reports `SyncCompleted` with the new `SyncType::AdditionalOnchainWallets`, while `SyncType::OnchainWallet` now covers the primary wallet only. - Added `build_with_vss_store_and_lnurl_auth_key_domain`, which signs VSS LNURL-auth for a fixed key domain while calling the auth server on a subdomain of it, so wallets keep their VSS identity when the auth server moves to that subdomain. - Accept incoming payments up to the full channel value, instead of 10% of it, on nodes that cannot announce channels (no node alias or listening addresses), for channels opened after the update. - Expose the exact prepared transaction fee so applications can validate the approved total before broadcast. diff --git a/bindings/ldk_node.udl b/bindings/ldk_node.udl index 47112cd7df..5e8705cfc2 100644 --- a/bindings/ldk_node.udl +++ b/bindings/ldk_node.udl @@ -604,6 +604,7 @@ enum SyncType { "OnchainWallet", "LightningWallet", "FeeRateCache", + "AdditionalOnchainWallets", }; [Enum] diff --git a/crates/bdk-wallet-aggregate/src/lib.rs b/crates/bdk-wallet-aggregate/src/lib.rs index 3051813e78..5762287111 100644 --- a/crates/bdk-wallet-aggregate/src/lib.rs +++ b/crates/bdk-wallet-aggregate/src/lib.rs @@ -506,6 +506,16 @@ where Ok(wallet.transactions().map(|wtx| wtx.tx_node.txid).collect()) } + /// The oldest tip height across the wallets tracking a transaction, for its confirmation + /// depth: wallets that may sync on a longer interval, and do not track it, never hold it back. + pub fn tip_height_for_tx(&self, txid: Txid) -> Option { + self.wallets + .values() + .filter(|wallet| wallet.get_tx(txid).is_some()) + .map(|wallet| wallet.latest_checkpoint().height()) + .min() + } + /// A Listen-oriented aggregate tip: the oldest height across wallets. /// /// When multiple wallets share that minimum height but disagree on the hash (fork), pick the @@ -1862,6 +1872,57 @@ mod tests { ScriptBuf::new_witness_program(&program) } + #[test] + fn sent_and_received_counts_wallets_that_have_not_synced_the_tx() { + let mut primary = create_empty_wallet(&mut NoopPersister); + let mut secondary = + create_empty_wallet_from_xprv(&mut NoopPersister, test_xprv_from_byte(7)); + let primary_script = primary.reveal_next_address(KeychainKind::External).script_pubkey(); + let secondary_script = + secondary.reveal_next_address(KeychainKind::External).script_pubkey(); + let tx = Transaction { + version: bitcoin::transaction::Version::TWO, + lock_time: bitcoin::blockdata::locktime::absolute::LockTime::ZERO, + input: vec![TxIn { + previous_output: OutPoint { txid: Txid::from_byte_array([9; 32]), vout: 0 }, + ..Default::default() + }], + output: vec![ + TxOut { value: Amount::from_sat(100_000), script_pubkey: primary_script }, + TxOut { value: Amount::from_sat(50_000), script_pubkey: secondary_script }, + ], + }; + // Only the primary has synced the transaction so far. + primary.apply_unconfirmed_txs([(tx.clone(), 0)]); + let aggregate = + AggregateWallet::new(primary, NoopPersister, 0u8, vec![(1, secondary, NoopPersister)]); + + assert_eq!(aggregate.sent_and_received(tx.compute_txid()), Some((0, 150_000))); + } + + #[test] + fn tx_tip_height_ignores_wallets_not_tracking_it() { + let mut primary = create_empty_wallet(&mut NoopPersister); + let funding_tx = fund_wallet(&mut primary, Amount::from_sat(10_000), 0x01); + let tip = primary + .latest_checkpoint() + .push(bdk_chain::BlockId { + height: 10, + hash: bitcoin::BlockHash::from_byte_array([10; 32]), + }) + .unwrap(); + primary + .apply_update(bdk_wallet::Update { chain: Some(tip), ..Default::default() }) + .unwrap(); + let secondary = create_empty_wallet_from_xprv(&mut NoopPersister, test_xprv_from_byte(7)); + let aggregate = + AggregateWallet::new(primary, NoopPersister, 0u8, vec![(1, secondary, NoopPersister)]); + + assert_eq!(aggregate.current_best_block().1, 0); + assert_eq!(aggregate.tip_height_for_tx(funding_tx.compute_txid()), Some(10)); + assert_eq!(aggregate.tip_height_for_tx(Txid::from_byte_array([3; 32])), None); + } + #[test] fn persistence_fails_when_a_wallet_has_no_persister() { let mut persister = NoopPersister; diff --git a/src/chain/electrum.rs b/src/chain/electrum.rs index ec7cc23193..3a454a952d 100644 --- a/src/chain/electrum.rs +++ b/src/chain/electrum.rs @@ -295,8 +295,7 @@ impl ElectrumChainSource { if let Some(mut sync_receiver) = receiver_res { log_info!(self.logger, "Sync in progress, skipping."); match sync_receiver.recv().await { - // The pass it waited on emitted the events. - Ok(Ok(())) => return super::WalletSyncOutcome::skipped(), + Ok(Ok(())) => return super::WalletSyncOutcome::waited(), Ok(Err(e)) => return super::WalletSyncOutcome::failed(e), Err(e) => { debug_assert!(false, "Failed to receive wallet sync result: {:?}", e); @@ -549,7 +548,9 @@ impl ElectrumChainSource { events: outcome.events, evicted_txids: outcome.evicted_txids, error: outcome.error, + synced_accounts: outcome.synced_accounts, skipped: false, + waited: false, }) } @@ -911,11 +912,26 @@ impl ElectrumRuntimeClient { // NAT may have dropped it meanwhile. Find out before the pass, and reconnect if so. let client = Arc::clone(&connection.read().unwrap()); let electrum_client = Arc::clone(&client.electrum_client); - let ping = self.runtime_handle.spawn_blocking(move || electrum_client.ping()).await; - if let Ok(Err(e)) = ping { - if electrum_connection_broken(&e) { - log_info!(self.logger, "Additional wallets' Electrum connection was closed: {}", e); - let _ = self.reconnect_client(connection, &client).await; + // Bounded like a sync request: electrum-client retries a hung ping at its socket timeout. + let deadline = Duration::from_secs(BDK_WALLET_SYNC_TIMEOUT_SECS); + let ping = tokio::time::timeout( + deadline, + self.runtime_handle.spawn_blocking(move || electrum_client.ping()), + ) + .await; + // Any failure counts: a ping that timed out on an idle connection means a hung one. + let failure = match ping { + Ok(Ok(Ok(_))) => None, + Ok(Ok(Err(e))) => Some(e.to_string()), + Ok(Err(e)) => Some(e.to_string()), + Err(_) => Some("timed out".to_owned()), + }; + if let Some(e) = failure { + log_info!(self.logger, "Additional wallets' Electrum connection failed a ping: {}", e); + let reconnect = + tokio::time::timeout(deadline, self.reconnect_client(connection, &client)); + if !matches!(reconnect.await, Ok(Ok(true))) { + return Err(Error::ConnectionFailed); } } Ok(Arc::clone(connection)) @@ -1406,7 +1422,7 @@ mod tests { use std::net::TcpListener; use std::panic::{catch_unwind, AssertUnwindSafe}; use std::process::Command; - use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering}; use std::sync::mpsc::{self, sync_channel}; use std::thread; use std::time::Instant; @@ -1785,6 +1801,94 @@ mod tests { assert!(Arc::ptr_eq(&additional, &again)); } + const ANSWER_PINGS: u8 = 0; + const DROP_PINGS: u8 = 1; + const IGNORE_PINGS: u8 = 2; + + // Answers every request, but drops the connection on a ping or leaves it unanswered as + // `ping_mode` says. + fn start_ping_server(ping_mode: Arc) -> String { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("tcp://{}", listener.local_addr().unwrap()); + thread::spawn(move || { + for stream in listener.incoming() { + let Ok(stream) = stream else { return }; + let ping_mode = Arc::clone(&ping_mode); + thread::spawn(move || { + let mut writer = stream.try_clone().unwrap(); + let mut reader = BufReader::new(stream); + let mut line = String::new(); + while reader.read_line(&mut line).unwrap_or(0) > 0 { + let request: serde_json::Value = serde_json::from_str(&line).unwrap(); + line.clear(); + if request["method"] == "server.ping" { + match ping_mode.load(Ordering::SeqCst) { + DROP_PINGS => return, + IGNORE_PINGS => continue, + _ => {}, + } + } + let response = serde_json::json!({ "jsonrpc": "2.0", "id": request["id"], "result": null }); + if writeln!(writer, "{}", response).is_err() { + return; + } + } + }); + } + }); + url + } + + fn ping_server_client(url: String, runtime: &Runtime) -> ElectrumRuntimeClient { + let logger = Arc::new(Logger::new_log_facade()); + ElectrumRuntimeClient::new( + url, + runtime.handle().clone(), + Arc::new(Config::default()), + logger, + 2, + ) + .unwrap() + } + + #[test] + fn additional_connection_reconnects_after_a_failed_ping() { + let ping_mode = Arc::new(AtomicU8::new(ANSWER_PINGS)); + let runtime = Runtime::new(Arc::new(Logger::new_log_facade())).unwrap(); + let client = ping_server_client(start_ping_server(Arc::clone(&ping_mode)), &runtime); + let connection = runtime.block_on(client.additional_connection()).unwrap(); + + // A dropped connection, then a hung one whose ping times out: both get replaced, + // electrum-client's own retries failing too. + for failure in [DROP_PINGS, IGNORE_PINGS] { + let before = Arc::clone(&connection.read().unwrap()); + ping_mode.store(failure, Ordering::SeqCst); + let again = runtime.block_on(client.additional_connection()).unwrap(); + ping_mode.store(ANSWER_PINGS, Ordering::SeqCst); + + assert!(Arc::ptr_eq(&connection, &again)); + let replaced = Arc::clone(&again.read().unwrap()); + assert!(!Arc::ptr_eq(&before, &replaced)); + assert!(replaced.electrum_client.ping().is_ok()); + } + } + + #[test] + fn additional_pass_fails_when_its_connection_cannot_be_replaced() { + let ping_mode = Arc::new(AtomicU8::new(ANSWER_PINGS)); + let runtime = Runtime::new(Arc::new(Logger::new_log_facade())).unwrap(); + let mut client = ping_server_client(start_ping_server(Arc::clone(&ping_mode)), &runtime); + runtime.block_on(client.additional_connection()).unwrap(); + + ping_mode.store(DROP_PINGS, Ordering::SeqCst); + client.connect_main = + Arc::new(|| Err(ElectrumError::IOError(std::io::ErrorKind::ConnectionRefused.into()))); + assert_eq!( + runtime.block_on(client.additional_connection()).err(), + Some(Error::ConnectionFailed) + ); + } + #[test] fn electrum_connection_counts_as_broken_only_after_it_was_closed_or_reset() { let pipe = || ElectrumError::IOError(std::io::ErrorKind::BrokenPipe.into()); diff --git a/src/chain/esplora.rs b/src/chain/esplora.rs index 23e8f1ec98..d3196608c5 100644 --- a/src/chain/esplora.rs +++ b/src/chain/esplora.rs @@ -130,8 +130,7 @@ impl EsploraChainSource { if let Some(mut sync_receiver) = receiver_res { log_info!(self.logger, "Sync in progress, skipping."); match sync_receiver.recv().await { - // The pass it waited on emitted the events. - Ok(Ok(())) => return super::WalletSyncOutcome::skipped(), + Ok(Ok(())) => return super::WalletSyncOutcome::waited(), Ok(Err(e)) => return super::WalletSyncOutcome::failed(e), Err(e) => { debug_assert!(false, "Failed to receive wallet sync result: {:?}", e); @@ -379,7 +378,9 @@ impl EsploraChainSource { events: outcome.events, evicted_txids: outcome.evicted_txids, error: outcome.error, + synced_accounts: outcome.synced_accounts, skipped: false, + waited: false, }) } diff --git a/src/chain/mod.rs b/src/chain/mod.rs index 8535305c5a..2c6d7d165a 100644 --- a/src/chain/mod.rs +++ b/src/chain/mod.rs @@ -94,34 +94,12 @@ impl EmittedTxEvents { } } -// State shared by the primary and additional passes' event emission. +// Event emission state shared by the primary and additional passes. #[derive(Default)] struct SyncEventsState { - primary_synced: bool, - additional_synced: bool, - complete: bool, emitted_tx_events: EmittedTxEvents, } -impl SyncEventsState { - // Records a successful pass and returns whether it should emit `SyncCompleted`. It is only - // emitted once both the primary and the additional passes have succeeded since start and - // every current additional wallet has synced (one added at runtime may not have yet), so it - // always means every wallet has synced. A pass that synced nothing emits it only when it is - // the one that completes the set. - fn record_synced( - &mut self, scope: OnchainSyncScope, skipped: bool, additional_wallets_synced: bool, - ) -> bool { - match scope { - OnchainSyncScope::Primary => self.primary_synced = true, - OnchainSyncScope::Additional => self.additional_synced = true, - } - let was_complete = self.complete; - self.complete = self.primary_synced && self.additional_synced && additional_wallets_synced; - self.complete && (!skipped || !was_complete) - } -} - // Fails a pass's waiters when the pass is dropped before it finishes (e.g. cancelled while the // node stops), so the next pass starts instead of waiting on a result that never comes. pub(super) struct WalletSyncGuard<'a> { @@ -338,6 +316,7 @@ fn should_use_incremental_sync( pub(super) struct AdditionalSyncOutcome { pub(super) events: Vec, pub(super) any_applied: bool, + pub(super) synced_accounts: Vec, pub(super) error: Option, } @@ -345,14 +324,24 @@ pub(super) struct WalletSyncOutcome { pub(super) events: Vec, pub(super) evicted_txids: Vec, pub(super) error: Option, - // Nothing synced in this call: an additional pass with no additional wallets, or a call that - // waited on a pass already in flight. + // The additional wallets this pass synced. + pub(super) synced_accounts: Vec, + // An additional pass with no additional wallets to sync. pub(super) skipped: bool, + // A call that waited on a pass already in flight: that pass reports the events. + pub(super) waited: bool, } impl WalletSyncOutcome { pub(super) fn new(events: Vec, error: Option) -> Self { - Self { events, evicted_txids: Vec::new(), error, skipped: false } + Self { + events, + evicted_txids: Vec::new(), + error, + synced_accounts: Vec::new(), + skipped: false, + waited: false, + } } pub(super) fn failed(error: Error) -> Self { @@ -363,6 +352,10 @@ impl WalletSyncOutcome { Self { skipped: true, ..Self::new(Vec::new(), None) } } + pub(super) fn waited() -> Self { + Self { waited: true, ..Self::new(Vec::new(), None) } + } + pub(super) fn result(&self) -> Result<(), Error> { self.error.map_or(Ok(()), Err) } @@ -373,6 +366,7 @@ pub(super) struct AppliedWalletSyncOutcome { pub(super) evicted_txids: Vec, pub(super) any_applied: bool, pub(super) primary_applied: bool, + pub(super) synced_accounts: Vec, pub(super) error: Option, } @@ -382,6 +376,7 @@ pub(super) fn apply_additional_sync_results( ) -> AdditionalSyncOutcome { let mut events = Vec::new(); let mut any_applied = false; + let mut synced_accounts = Vec::new(); let mut error = None; for (wallet_account, result) in results { let update = match result { @@ -396,6 +391,7 @@ pub(super) fn apply_additional_sync_results( match onchain_wallet.apply_update_for_wallet_account(wallet_account, update) { Ok(Some(wallet_events)) => { any_applied = true; + synced_accounts.push(wallet_account); if let Some(ts) = SystemTime::now().duration_since(UNIX_EPOCH).ok().map(|d| d.as_secs()) { @@ -416,7 +412,7 @@ pub(super) fn apply_additional_sync_results( } } - AdditionalSyncOutcome { events, any_applied, error } + AdditionalSyncOutcome { events, any_applied, synced_accounts, error } } /// Applies a pass's results. `apply_lock` serializes passes that overlap (primary and additional), @@ -459,6 +455,7 @@ pub(super) fn apply_wallet_sync_results( events, evicted_txids, any_applied: primary_applied || additional_outcome.any_applied, + synced_accounts: additional_outcome.synced_accounts, primary_applied, error, } @@ -529,16 +526,27 @@ mod sync_tests { } #[test] - fn sync_completed_waits_for_both_scopes() { - let mut state = SyncEventsState::default(); - assert!(!state.record_synced(OnchainSyncScope::Primary, false, true)); - // No additional wallets: the skipped pass completes the set. - assert!(state.record_synced(OnchainSyncScope::Additional, true, true)); - assert!(!state.record_synced(OnchainSyncScope::Additional, true, true)); - assert!(state.record_synced(OnchainSyncScope::Primary, false, true)); - // A wallet added at runtime holds the event back until it has synced. - assert!(!state.record_synced(OnchainSyncScope::Primary, false, false)); - assert!(state.record_synced(OnchainSyncScope::Additional, false, true)); + fn sync_completed_reports_the_synced_scope_tip() { + let mut config = Config::default(); + config.network = Network::Regtest; + let mut builder = NodeBuilder::from_config(config); + builder.set_chain_source_esplora("http://127.0.0.1:1".to_string(), None); + builder.set_entropy_seed_bytes([42u8; 64]); + builder.set_log_facade_logger(); + let store: Arc = Arc::new(InMemoryStore::new()); + let node = builder.build_with_store(store).unwrap(); + assert_eq!(node.wallet.scope_tip_height(false), None); + let xpub = node.export_onchain_wallet_account_xpub(AddressType::NativeSegwit, 1).unwrap(); + node.add_onchain_wallet_account(AddressType::NativeSegwit, 1, xpub).unwrap(); + + let genesis = node.wallet.current_best_block(); + let tip = CheckPoint::new(BlockId { height: genesis.height, hash: genesis.block_hash }) + .push(BlockId { height: 10, hash: bitcoin::BlockHash::from_byte_array([10; 32]) }) + .unwrap(); + node.wallet.apply_update(BdkUpdate { chain: Some(tip), ..Default::default() }).unwrap(); + + assert_eq!(node.wallet.scope_tip_height(true), Some(10)); + assert_eq!(node.wallet.scope_tip_height(false), Some(genesis.height)); } #[test] @@ -597,6 +605,8 @@ mod sync_tests { ); assert!(!outcome.any_applied); + // So the pass reports no `AdditionalOnchainWallets` sync for it. + assert!(outcome.synced_accounts.is_empty()); assert!(outcome.events.is_empty()); assert_eq!(outcome.error, None); assert_eq!( @@ -607,17 +617,16 @@ mod sync_tests { } async fn emit_onchain_sync_completed( - wallet: &Wallet, event_queue: &EventQueue, + wallet: &Wallet, event_queue: &EventQueue, sync_type: SyncType, ) -> Result<(), Error> where L2::Target: LdkLogger, { - event_queue - .add_event(Event::SyncCompleted { - sync_type: SyncType::OnchainWallet, - synced_block_height: wallet.current_best_block().height, - }) - .await + // The height of the wallets this pass synced, not of the others, which sync apart. + let synced_block_height = wallet + .scope_tip_height(sync_type == SyncType::OnchainWallet) + .unwrap_or_else(|| wallet.current_best_block().height); + event_queue.add_event(Event::SyncCompleted { sync_type, synced_block_height }).await } // Process BDK wallet events and emit corresponding ldk-node events via the event queue. @@ -1070,7 +1079,6 @@ impl ChainSource { chain_monitor.as_ref(), self.config(), scope, - false, ) .await } else { @@ -1094,31 +1102,7 @@ impl ChainSource { sync_scope(OnchainSyncScope::Primary), sync_scope(OnchainSyncScope::Additional) ); - primary.and(additional)?; - // One `SyncCompleted` per call, once both passes succeeded. - if let Some(event_queue) = event_queue { - emit_onchain_sync_completed(&wallet, &event_queue).await?; - } - Ok(()) - } - - // Whether every current additional wallet has synced: account-`0` types since their last - // persisted sync, derived accounts since registration. - fn additional_wallets_synced(&self, wallet: &Wallet) -> bool { - let (runtime_config, node_metrics) = match &self.kind { - ChainSourceKind::Esplora(es) => (&es.address_type_runtime_config, &es.node_metrics), - ChainSourceKind::Electrum(el) => (&el.address_type_runtime_config, &el.node_metrics), - ChainSourceKind::Bitcoind(_) => return true, - }; - let accounts = runtime_config.read().unwrap().additional_wallet_accounts(); - let node_metrics = node_metrics.read().unwrap(); - accounts.into_iter().all(|account| { - if account.account_index == 0 { - node_metrics.get_wallet_sync_timestamp(account).is_some() - } else { - wallet.has_synced_derived_account(account) - } - }) + primary.and(additional) } fn config(&self) -> Option<&Arc> { @@ -1192,7 +1176,6 @@ impl ChainSource { Some(chain_monitor), self.config(), OnchainSyncScope::Additional, - true, ).await; } } @@ -1287,7 +1270,6 @@ impl ChainSource { Some(&chain_monitor), self.config(), OnchainSyncScope::Primary, - true, ).await; } _ = fee_rate_update_interval.tick() => { @@ -1334,7 +1316,7 @@ impl ChainSource { async fn sync_onchain_wallet_with_events( &self, event_queue: Option<&Arc>>>, channel_manager: Option<&Arc>, chain_monitor: Option<&Arc>, - config: Option<&Arc>, scope: OnchainSyncScope, emit_sync_completed: bool, + config: Option<&Arc>, scope: OnchainSyncScope, ) -> Result<(), Error> { let wallet = self.onchain_wallet.lock().unwrap().clone(); let wallet = wallet.ok_or(Error::WalletOperationFailed)?; @@ -1345,22 +1327,19 @@ impl ChainSource { events: wallet_events, evicted_txids, error: sync_error, + synced_accounts, skipped, + waited, } = esplora_chain_source.sync_onchain_wallet(Arc::clone(&wallet), scope).await; - let mut events_state = self.sync_events.lock().await; + // The pass it waited on reports the events. + if waited { + return Ok(()); + } + // No additional wallets: nothing synced, and nothing to report. if skipped { - if events_state.record_synced( - scope, - true, - self.additional_wallets_synced(&wallet), - ) && emit_sync_completed - { - if let Some(event_queue) = event_queue { - emit_onchain_sync_completed(&wallet, event_queue).await?; - } - } return Ok(()); } + let mut events_state = self.sync_events.lock().await; // Process wallet events if event queue is provided if let Some(event_queue) = event_queue { @@ -1388,14 +1367,14 @@ impl ChainSource { return Err(error); } - let sync_completed = events_state.record_synced( - scope, - false, - self.additional_wallets_synced(&wallet), - ); if let Some(event_queue) = event_queue { - if sync_completed && emit_sync_completed { - emit_onchain_sync_completed(&wallet, event_queue).await?; + let sync_type = match scope { + OnchainSyncScope::Primary => Some(SyncType::OnchainWallet), + OnchainSyncScope::Additional => (!synced_accounts.is_empty()) + .then_some(SyncType::AdditionalOnchainWallets), + }; + if let Some(sync_type) = sync_type { + emit_onchain_sync_completed(&wallet, event_queue, sync_type).await?; } // Check for balance changes and emit BalanceChanged event if needed if let (Some(cm), Some(chain_mon), Some(cfg)) = @@ -1456,22 +1435,19 @@ impl ChainSource { events: wallet_events, evicted_txids, error: sync_error, + synced_accounts, skipped, + waited, } = electrum_chain_source.sync_onchain_wallet(Arc::clone(&wallet), scope).await; - let mut events_state = self.sync_events.lock().await; + // The pass it waited on reports the events. + if waited { + return Ok(()); + } + // No additional wallets: nothing synced, and nothing to report. if skipped { - if events_state.record_synced( - scope, - true, - self.additional_wallets_synced(&wallet), - ) && emit_sync_completed - { - if let Some(event_queue) = event_queue { - emit_onchain_sync_completed(&wallet, event_queue).await?; - } - } return Ok(()); } + let mut events_state = self.sync_events.lock().await; // Process wallet events if event queue is provided if let Some(event_queue) = event_queue { @@ -1499,14 +1475,14 @@ impl ChainSource { return Err(error); } - let sync_completed = events_state.record_synced( - scope, - false, - self.additional_wallets_synced(&wallet), - ); if let Some(event_queue) = event_queue { - if sync_completed && emit_sync_completed { - emit_onchain_sync_completed(&wallet, event_queue).await?; + let sync_type = match scope { + OnchainSyncScope::Primary => Some(SyncType::OnchainWallet), + OnchainSyncScope::Additional => (!synced_accounts.is_empty()) + .then_some(SyncType::AdditionalOnchainWallets), + }; + if let Some(sync_type) = sync_type { + emit_onchain_sync_completed(&wallet, event_queue, sync_type).await?; } // Check for balance changes and emit BalanceChanged event if needed diff --git a/src/event.rs b/src/event.rs index d6d5a9ad7f..d16fa12e83 100644 --- a/src/event.rs +++ b/src/event.rs @@ -174,11 +174,11 @@ impl TxOutput { /// Describes what component is being synchronized. /// -/// Note: Currently, only `OnchainWallet` sync completion events are emitted. -/// `LightningWallet` and `FeeRateCache` variants are reserved for future use. +/// Note: Currently, only `OnchainWallet` and `AdditionalOnchainWallets` sync completion events are +/// emitted. `LightningWallet` and `FeeRateCache` variants are reserved for future use. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SyncType { - /// Synchronizing the onchain wallet (checking for new transactions and confirmations). + /// Synchronizing the primary onchain wallet (checking for new transactions and confirmations). OnchainWallet, /// Synchronizing the Lightning wallet (updating channel states and commitments). /// @@ -188,12 +188,18 @@ pub enum SyncType { /// /// Reserved for future use - not currently emitted. FeeRateCache, + /// Synchronizing the additional onchain wallets: monitored address types and derived accounts. + /// + /// They sync apart from the primary wallet, on their own interval. Emitted only for a pass that + /// synced at least one of them, so a node without additional wallets never emits it. + AdditionalOnchainWallets, } impl_writeable_tlv_based_enum!(SyncType, (0, OnchainWallet) => {}, (1, LightningWallet) => {}, (2, FeeRateCache) => {}, + (3, AdditionalOnchainWallets) => {}, ); /// An event emitted by [`Node`], which should be handled by the user. diff --git a/src/wallet/mod.rs b/src/wallet/mod.rs index 253c226e3d..a5eb46290b 100644 --- a/src/wallet/mod.rs +++ b/src/wallet/mod.rs @@ -314,6 +314,18 @@ impl Wallet { self.inner.lock().unwrap().transaction_confirmations() } + /// The oldest tip among the primary wallet (`primary`) or among the additional wallets. + pub(crate) fn scope_tip_height(&self, primary: bool) -> Option { + let locked_wallet = self.inner.lock().unwrap(); + let primary_key = locked_wallet.primary_key(); + locked_wallet + .chain_tips_by_key() + .into_iter() + .filter(|(key, _, _)| (*key == primary_key) == primary) + .map(|(_, _, height)| height) + .min() + } + pub(crate) fn current_best_block(&self) -> BestBlock { let (block_hash, height) = self.inner.lock().unwrap().current_best_block(); BestBlock { block_hash, height } @@ -1099,33 +1111,28 @@ impl Wallet { } let id = PaymentId(txid.to_byte_array()); - let (payment_status, confirmation_status) = - if let Some(anchor) = transaction_confirmations.get(&txid).copied() { - let confirmation_height = anchor.block_id.height; - // Depth on the wallets tracking the transaction: the others may sync on - // a longer interval, and their older tip must not hold its payment back. - let cur_height = locked_wallet - .wallets() - .values() - .filter(|wallet| wallet.get_tx(txid).is_some()) - .map(|wallet| wallet.latest_checkpoint().height()) - .min() - .unwrap_or(cur_height); - let payment_status = - if cur_height >= confirmation_height + ANTI_REORG_DELAY - 1 { - PaymentStatus::Succeeded - } else { - PaymentStatus::Pending - }; - let confirmation_status = ConfirmationStatus::Confirmed { - block_hash: anchor.block_id.hash, - height: confirmation_height, - timestamp: anchor.confirmation_time, - }; - (payment_status, confirmation_status) + let (payment_status, confirmation_status) = if let Some(anchor) = + transaction_confirmations.get(&txid).copied() + { + let confirmation_height = anchor.block_id.height; + // Depth on the wallets tracking the transaction: the others may sync on + // a longer interval, and their older tip must not hold its payment back. + let cur_height = locked_wallet.tip_height_for_tx(txid).unwrap_or(cur_height); + let payment_status = if cur_height >= confirmation_height + ANTI_REORG_DELAY - 1 + { + PaymentStatus::Succeeded } else { - (PaymentStatus::Pending, ConfirmationStatus::Unconfirmed) + PaymentStatus::Pending + }; + let confirmation_status = ConfirmationStatus::Confirmed { + block_hash: anchor.block_id.hash, + height: confirmation_height, + timestamp: anchor.confirmation_time, }; + (payment_status, confirmation_status) + } else { + (PaymentStatus::Pending, ConfirmationStatus::Unconfirmed) + }; // TODO: It would be great to introduce additional variants for // `ChannelFunding` and `ChannelClosing`. For the former, we could just // take a reference to `ChannelManager` here and check against diff --git a/tests/integration_tests_rust.rs b/tests/integration_tests_rust.rs index 72f9e5e242..bfec4272d4 100644 --- a/tests/integration_tests_rust.rs +++ b/tests/integration_tests_rust.rs @@ -33,8 +33,7 @@ use ldk_node::payment::{ ConfirmationStatus, PaymentDetails, PaymentDirection, PaymentKind, PaymentStatus, QrPaymentResult, }; -use ldk_node::{Builder, DynStore, Event, NodeError, OnchainSendResult}; - +use ldk_node::{Builder, DynStore, Event, NodeError, OnchainSendResult, SyncType}; use lightning::ln::channelmanager::PaymentId; use lightning::routing::gossip::{NodeAlias, NodeId}; use lightning::routing::router::RouteParametersConfig; @@ -2998,35 +2997,34 @@ fn sync_completed_event() { let config = random_config(false); let node = setup_node(&chain_source, config, None); - while node.next_event().is_some() { - node.event_handled().unwrap(); - } - - node.sync_wallets().unwrap(); - - let mut found_sync_completed = false; - for _ in 0..10 { - if let Some(event) = node.next_event() { - match event { - Event::SyncCompleted { sync_type, synced_block_height } => { - println!( - "Received SyncCompleted event: type={:?}, height={}", - sync_type, synced_block_height - ); - found_sync_completed = true; - node.event_handled().unwrap(); - break; - }, - other_event => { - println!("Got other event: {:?}", other_event); - node.event_handled().unwrap(); - }, + let completed_sync_types = || { + let mut sync_types = Vec::new(); + for _ in 0..10 { + while let Some(event) = node.next_event() { + if let Event::SyncCompleted { sync_type, .. } = event { + sync_types.push(sync_type); + } + node.event_handled().unwrap(); } + std::thread::sleep(Duration::from_millis(100)); } - std::thread::sleep(Duration::from_millis(100)); - } + sync_types + }; + completed_sync_types(); - assert!(found_sync_completed, "Should have received SyncCompleted event"); + // Without additional wallets only the primary reports. + node.sync_wallets().unwrap(); + let sync_types = completed_sync_types(); + assert!(sync_types.contains(&SyncType::OnchainWallet), "{:?}", sync_types); + assert!(!sync_types.contains(&SyncType::AdditionalOnchainWallets), "{:?}", sync_types); + + // With one, its pass reports too. + let xpub = node.export_onchain_wallet_account_xpub(AddressType::NativeSegwit, 1).unwrap(); + node.add_onchain_wallet_account(AddressType::NativeSegwit, 1, xpub).unwrap(); + node.sync_wallets().unwrap(); + let sync_types = completed_sync_types(); + assert!(sync_types.contains(&SyncType::OnchainWallet), "{:?}", sync_types); + assert!(sync_types.contains(&SyncType::AdditionalOnchainWallets), "{:?}", sync_types); node.stop().unwrap(); } From 627b31e619ef575616fcb0e2c65d687e9a3edcee Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 20:59:10 +0100 Subject: [PATCH 09/16] chore: ship the additional wallets sync type in 0.7.0-rc.86 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Verified: swift package compute-checksum matches Package.swift (44db2715…) --- Package.swift | 2 +- .../kotlin/org/lightningdevkit/ldknode/ldk_node.common.kt | 3 ++- bindings/python/src/ldk_node/ldk_node.py | 8 ++++++++ bindings/swift/Sources/LDKNode/LDKNode.swift | 6 ++++++ 4 files changed, 17 insertions(+), 2 deletions(-) diff --git a/Package.swift b/Package.swift index e0d019adc8..f71ca47848 100644 --- a/Package.swift +++ b/Package.swift @@ -4,7 +4,7 @@ import PackageDescription let tag = "v0.7.0-rc.86" -let checksum = "b7851f2b11ee2f8e92de9722c2600d7b8e9863e96283f5260fc04451cfdd816d" +let checksum = "44db27159f11fad86940a9d0679e1eb80646748f2c9d9efa4073f0ba98c1c62a" let url = "https://github.com/synonymdev/ldk-node/releases/download/\(tag)/LDKNodeFFI.xcframework.zip" let package = Package( diff --git a/bindings/kotlin/ldk-node-android/lib/src/main/kotlin/org/lightningdevkit/ldknode/ldk_node.common.kt b/bindings/kotlin/ldk-node-android/lib/src/main/kotlin/org/lightningdevkit/ldknode/ldk_node.common.kt index 60b19bc69b..33366607c9 100644 --- a/bindings/kotlin/ldk-node-android/lib/src/main/kotlin/org/lightningdevkit/ldknode/ldk_node.common.kt +++ b/bindings/kotlin/ldk-node-android/lib/src/main/kotlin/org/lightningdevkit/ldknode/ldk_node.common.kt @@ -2291,7 +2291,8 @@ enum class SyncType { ONCHAIN_WALLET, LIGHTNING_WALLET, - FEE_RATE_CACHE; + FEE_RATE_CACHE, + ADDITIONAL_ONCHAIN_WALLETS; companion object } diff --git a/bindings/python/src/ldk_node/ldk_node.py b/bindings/python/src/ldk_node/ldk_node.py index fc5a14c3a8..f329bca5a2 100644 --- a/bindings/python/src/ldk_node/ldk_node.py +++ b/bindings/python/src/ldk_node/ldk_node.py @@ -15561,6 +15561,8 @@ class SyncType(enum.Enum): FEE_RATE_CACHE = 2 + ADDITIONAL_ONCHAIN_WALLETS = 3 + class _UniffiConverterTypeSyncType(_UniffiConverterRustBuffer): @@ -15573,6 +15575,8 @@ def read(buf): return SyncType.LIGHTNING_WALLET if variant == 3: return SyncType.FEE_RATE_CACHE + if variant == 4: + return SyncType.ADDITIONAL_ONCHAIN_WALLETS raise InternalError("Raw enum value doesn't match any cases") @staticmethod @@ -15583,6 +15587,8 @@ def check_lower(value): return if value == SyncType.FEE_RATE_CACHE: return + if value == SyncType.ADDITIONAL_ONCHAIN_WALLETS: + return raise ValueError(value) @staticmethod @@ -15593,6 +15599,8 @@ def write(value, buf): buf.write_i32(2) if value == SyncType.FEE_RATE_CACHE: buf.write_i32(3) + if value == SyncType.ADDITIONAL_ONCHAIN_WALLETS: + buf.write_i32(4) diff --git a/bindings/swift/Sources/LDKNode/LDKNode.swift b/bindings/swift/Sources/LDKNode/LDKNode.swift index 9e867cd7ee..79bfe5244a 100644 --- a/bindings/swift/Sources/LDKNode/LDKNode.swift +++ b/bindings/swift/Sources/LDKNode/LDKNode.swift @@ -10539,6 +10539,7 @@ public enum SyncType { case onchainWallet case lightningWallet case feeRateCache + case additionalOnchainWallets } #if swift(>=5.8) @@ -10556,6 +10557,8 @@ public struct FfiConverterTypeSyncType: FfiConverterRustBuffer { case 3: return .feeRateCache + case 4: return .additionalOnchainWallets + default: throw UniffiInternalError.unexpectedEnumCase } } @@ -10570,6 +10573,9 @@ public struct FfiConverterTypeSyncType: FfiConverterRustBuffer { case .feeRateCache: writeInt(&buf, Int32(3)) + + case .additionalOnchainWallets: + writeInt(&buf, Int32(4)) } } } From 24accc977a54a6eadb6856e444506929055b302d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 21:11:08 +0100 Subject: [PATCH 10/16] test: send funds after the additional wallets' startup pass Verified: cargo test --test multi_address_types_tests test_background_sync_keeps_additional_wallets_on_their_own_interval --- tests/multi_address_types_tests.rs | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/tests/multi_address_types_tests.rs b/tests/multi_address_types_tests.rs index 1eab11bc16..c8eecf1be4 100644 --- a/tests/multi_address_types_tests.rs +++ b/tests/multi_address_types_tests.rs @@ -3702,7 +3702,7 @@ mod derived_accounts { OnchainWalletAccountConfig, }; use ldk_node::payment::KeychainKind; - use ldk_node::{Builder, NodeError, RuntimeSyncIntervals}; + use ldk_node::{Builder, Event, NodeError, RuntimeSyncIntervals, SyncType}; use crate::common::{ distribute_funds_unconfirmed, generate_blocks_and_wait, invalidate_blocks, open_channel, @@ -4167,11 +4167,32 @@ mod derived_accounts { } builder.set_log_facade_logger(); let node = builder.build().unwrap(); - node.start().unwrap(); - let xpub = node.export_onchain_wallet_account_xpub(AddressType::NativeSegwit, 1).unwrap(); node.add_onchain_wallet_account(AddressType::NativeSegwit, 1, xpub).unwrap(); + node.start().unwrap(); + + // Funds go out only after the derived account's startup pass, so it stays empty + // until its next interval. + let mut startup_pass_done = false; + for _ in 0..60 { + while let Some(event) = node.next_event() { + node.event_handled().unwrap(); + if let Event::SyncCompleted { + sync_type: SyncType::AdditionalOnchainWallets, + .. + } = event + { + startup_pass_done = true; + } + } + if startup_pass_done { + break; + } + tokio::time::sleep(Duration::from_millis(500)).await; + } + assert!(startup_pass_done, "no startup pass for the derived account"); + let primary_address = node.onchain_payment().new_address().unwrap(); let derived_address = node .onchain_payment() From cf62335f62ab2cb3af0725e6796ca3cc3e605b16 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 21:26:11 +0100 Subject: [PATCH 11/16] fix: return waited syncs after their pass's events and skip wallets removed mid-pass A pass now finishes, waking calls that joined it, only after it queued its events. Requests skip additional wallets removed while the pass connects, and the pass deadline adds up every additional wallet's own deadline. Verified: cargo test --lib --- src/chain/electrum.rs | 62 ++++-- src/chain/esplora.rs | 13 +- src/chain/mod.rs | 486 +++++++++++++++++++++++------------------- 3 files changed, 320 insertions(+), 241 deletions(-) diff --git a/src/chain/electrum.rs b/src/chain/electrum.rs index 3a454a952d..20b2d003bb 100644 --- a/src/chain/electrum.rs +++ b/src/chain/electrum.rs @@ -211,6 +211,12 @@ fn additional_wallet_sync_timeout( } } +/// The additional wallets share one connection, which the server answers in order, so each gets +/// the deadline of the whole pass: every wallet's own deadline added up. +fn additional_pass_timeout(wallet_timeouts: impl Iterator) -> Duration { + wallet_timeouts.fold(Duration::ZERO, Duration::saturating_add) +} + pub(super) struct ElectrumChainSource { server_url: String, pub(super) sync_config: ElectrumSyncConfig, @@ -287,7 +293,7 @@ impl ElectrumChainSource { pub(crate) async fn sync_onchain_wallet( &self, onchain_wallet: Arc, scope: OnchainSyncScope, - ) -> super::WalletSyncOutcome { + ) -> (super::WalletSyncOutcome, Option>) { let receiver_res = { let mut status_lock = self.wallet_sync_status(scope).lock().unwrap(); status_lock.register_or_subscribe_pending_sync() @@ -295,12 +301,12 @@ impl ElectrumChainSource { if let Some(mut sync_receiver) = receiver_res { log_info!(self.logger, "Sync in progress, skipping."); match sync_receiver.recv().await { - Ok(Ok(())) => return super::WalletSyncOutcome::waited(), - Ok(Err(e)) => return super::WalletSyncOutcome::failed(e), + Ok(Ok(())) => return (super::WalletSyncOutcome::waited(), None), + Ok(Err(e)) => return (super::WalletSyncOutcome::failed(e), None), Err(e) => { debug_assert!(false, "Failed to receive wallet sync result: {:?}", e); log_error!(self.logger, "Failed to receive wallet sync result: {:?}", e); - return super::WalletSyncOutcome::failed(Error::WalletOperationFailed); + return (super::WalletSyncOutcome::failed(Error::WalletOperationFailed), None); }, } } @@ -310,9 +316,8 @@ impl ElectrumChainSource { .sync_onchain_wallet_inner(onchain_wallet, scope) .await .unwrap_or_else(super::WalletSyncOutcome::failed); - sync_guard.finish(outcome.result()); - - outcome + // The caller finishes the pass once it has reported the pass's events. + (outcome, Some(sync_guard)) } async fn sync_onchain_wallet_inner( @@ -417,15 +422,10 @@ impl ElectrumChainSource { } } - // The additional wallets share one connection, which the server answers in order, so each - // gets the deadline of the whole pass: the base timeout plus every wallet's request share. - let base_timeout = Duration::from_secs(BDK_WALLET_SYNC_TIMEOUT_SECS); let pass_timeout = - additional_sync_requests.iter().fold(base_timeout, |total, (account, req)| { - let timeout = - additional_wallet_sync_timeout(*account, req, additional_full_scan_settings); - total.saturating_add(timeout.saturating_sub(base_timeout)) - }); + additional_pass_timeout(additional_sync_requests.iter().map(|(account, req)| { + additional_wallet_sync_timeout(*account, req, additional_full_scan_settings) + })); for (wallet_account, sync_req) in additional_sync_requests { let client = Arc::clone(&electrum_client); @@ -2219,6 +2219,38 @@ mod tests { assert_eq!(additional_wallet_incremental_batch_size(1, settings), 100); } + #[test] + fn additional_pass_gets_every_wallets_deadline() { + let settings = FullScanSettings { stop_gap: 20, batch_size: 5 }; + let account = |account_index| crate::config::OnchainWalletAccount { + address_type: crate::config::AddressType::NativeSegwit, + account_index, + }; + let incremental = + || super::super::WalletSyncRequest::Incremental(BdkSyncRequest::builder().build()); + let full_scan = super::super::WalletSyncRequest::FullScan( + BdkFullScanRequest::builder() + .spks_for_keychain(BdkKeyChainKind::External, Vec::new()) + .spks_for_keychain(BdkKeyChainKind::Internal, Vec::new()) + .build(), + ); + let base = Duration::from_secs(BDK_WALLET_SYNC_TIMEOUT_SECS); + + assert_eq!(additional_wallet_sync_timeout(account(0), &incremental(), settings), base); + assert_eq!(additional_wallet_sync_timeout(account(1), &incremental(), settings), base); + assert_eq!( + additional_wallet_sync_timeout(account(1), &full_scan, settings), + Duration::from_secs(28) + ); + // Two monitored wallets and one derived wallet scanning in full, served in turn. + let timeouts = [ + additional_wallet_sync_timeout(account(0), &incremental(), settings), + additional_wallet_sync_timeout(account(0), &incremental(), settings), + additional_wallet_sync_timeout(account(1), &full_scan, settings), + ]; + assert_eq!(additional_pass_timeout(timeouts.into_iter()), Duration::from_secs(68)); + } + #[test] fn derived_incremental_timeout_scales_with_request_batches() { let settings = FullScanSettings { stop_gap: 1_000, batch_size: 100 }; diff --git a/src/chain/esplora.rs b/src/chain/esplora.rs index d3196608c5..af32babd3c 100644 --- a/src/chain/esplora.rs +++ b/src/chain/esplora.rs @@ -122,7 +122,7 @@ impl EsploraChainSource { pub(super) async fn sync_onchain_wallet( &self, onchain_wallet: Arc, scope: OnchainSyncScope, - ) -> super::WalletSyncOutcome { + ) -> (super::WalletSyncOutcome, Option>) { let receiver_res = { let mut status_lock = self.wallet_sync_status(scope).lock().unwrap(); status_lock.register_or_subscribe_pending_sync() @@ -130,12 +130,12 @@ impl EsploraChainSource { if let Some(mut sync_receiver) = receiver_res { log_info!(self.logger, "Sync in progress, skipping."); match sync_receiver.recv().await { - Ok(Ok(())) => return super::WalletSyncOutcome::waited(), - Ok(Err(e)) => return super::WalletSyncOutcome::failed(e), + Ok(Ok(())) => return (super::WalletSyncOutcome::waited(), None), + Ok(Err(e)) => return (super::WalletSyncOutcome::failed(e), None), Err(e) => { debug_assert!(false, "Failed to receive wallet sync result: {:?}", e); log_error!(self.logger, "Failed to receive wallet sync result: {:?}", e); - return super::WalletSyncOutcome::failed(Error::WalletOperationFailed); + return (super::WalletSyncOutcome::failed(Error::WalletOperationFailed), None); }, } } @@ -145,9 +145,8 @@ impl EsploraChainSource { .sync_onchain_wallet_inner(onchain_wallet, scope) .await .unwrap_or_else(super::WalletSyncOutcome::failed); - sync_guard.finish(outcome.result()); - - outcome + // The caller finishes the pass once it has reported the pass's events. + (outcome, Some(sync_guard)) } async fn sync_onchain_wallet_inner( diff --git a/src/chain/mod.rs b/src/chain/mod.rs index 2c6d7d165a..a9fc32f9bb 100644 --- a/src/chain/mod.rs +++ b/src/chain/mod.rs @@ -282,7 +282,7 @@ pub(super) fn collect_additional_sync_requests( additional_accounts .iter() .copied() - .map(|wallet_account| { + .filter_map(|wallet_account| { let do_incremental = should_use_incremental_sync(wallet_account, onchain_wallet, node_metrics); let request = if do_incremental { @@ -294,10 +294,20 @@ pub(super) fn collect_additional_sync_requests( .get_wallet_full_scan_request(wallet_account) .map(WalletSyncRequest::FullScan) }; - request.map(|request| (wallet_account, request)).map_err(|e| { - log_warn!(logger, "Failed to build sync request for {:?}: {}", wallet_account, e); - Error::WalletOperationFailed - }) + match request { + Ok(request) => Some(Ok((wallet_account, request))), + // Removed since the pass read its accounts: nothing to sync. + Err(bdk_wallet_aggregate::Error::WalletNotFound) => None, + Err(e) => { + log_warn!( + logger, + "Failed to build sync request for {:?}: {}", + wallet_account, + e + ); + Some(Err(Error::WalletOperationFailed)) + }, + } }) .collect() } @@ -549,6 +559,82 @@ mod sync_tests { assert_eq!(node.wallet.scope_tip_height(false), Some(genesis.height)); } + fn test_node() -> crate::Node { + let mut config = Config::default(); + config.network = Network::Regtest; + let mut builder = NodeBuilder::from_config(config); + builder.set_chain_source_esplora("http://127.0.0.1:1".to_string(), None); + builder.set_entropy_seed_bytes([42u8; 64]); + builder.set_log_facade_logger(); + let store: Arc = Arc::new(InMemoryStore::new()); + builder.build_with_store(store).unwrap() + } + + #[test] + fn sync_requests_skip_wallets_removed_mid_pass() { + let node = test_node(); + let account = + OnchainWalletAccount { address_type: AddressType::NativeSegwit, account_index: 1 }; + let xpub = node.export_onchain_wallet_account_xpub(AddressType::NativeSegwit, 1).unwrap(); + node.add_onchain_wallet_account(AddressType::NativeSegwit, 1, xpub).unwrap(); + node.remove_onchain_wallet_account(AddressType::NativeSegwit, 1).unwrap(); + + let requests = collect_additional_sync_requests( + &[account], + &node.wallet, + &node.node_metrics, + &node.logger, + ) + .unwrap(); + + assert!(requests.is_empty()); + } + + #[tokio::test(flavor = "multi_thread")] + async fn pass_waiters_return_once_its_events_are_queued() { + let node = test_node(); + let account = + OnchainWalletAccount { address_type: AddressType::NativeSegwit, account_index: 1 }; + let report = |synced_accounts: Vec| { + let status = Mutex::new(WalletSyncStatus::Completed); + assert!(status.lock().unwrap().register_or_subscribe_pending_sync().is_none()); + let mut waiter = status.lock().unwrap().register_or_subscribe_pending_sync().unwrap(); + let outcome = + WalletSyncOutcome { synced_accounts, ..WalletSyncOutcome::new(Vec::new(), None) }; + let (node, event_queue) = (&node, Arc::clone(&node.event_queue)); + async move { + let pass = WalletSyncGuard::new(&status); + let result = node + .chain_source + .report_pass( + outcome, + Some(pass), + &node.wallet, + Some(&event_queue), + None, + None, + None, + OnchainSyncScope::Additional, + ) + .await; + assert_eq!(result, Ok(())); + assert_eq!(waiter.try_recv().unwrap(), Ok(())); + } + }; + + // The waiter is told only after the pass queued its `SyncCompleted`. + report(vec![account]).await; + assert!(matches!( + node.event_queue.next_event(), + Some(Event::SyncCompleted { sync_type: SyncType::AdditionalOnchainWallets, .. }) + )); + node.event_queue.event_handled().await.unwrap(); + + // A pass whose wallets were all removed reports no sync. + report(Vec::new()).await; + assert!(node.event_queue.next_event().is_none()); + } + #[test] fn tx_events_dedupe_across_passes_until_reorg() { let txid = Txid::all_zeros(); @@ -1085,10 +1171,22 @@ impl ChainSource { // Simple sync without events (event_queue not set) match &self.kind { ChainSourceKind::Esplora(esplora_chain_source) => { - esplora_chain_source.sync_onchain_wallet(wallet, scope).await.result() + let (outcome, pass) = + esplora_chain_source.sync_onchain_wallet(wallet, scope).await; + let result = outcome.result(); + if let Some(pass) = pass { + pass.finish(result.clone()); + } + result }, ChainSourceKind::Electrum(electrum_chain_source) => { - electrum_chain_source.sync_onchain_wallet(wallet, scope).await.result() + let (outcome, pass) = + electrum_chain_source.sync_onchain_wallet(wallet, scope).await; + let result = outcome.result(); + if let Some(pass) = pass { + pass.finish(result.clone()); + } + result }, ChainSourceKind::Bitcoind(_) => { // Bitcoind sync is handled differently @@ -1323,228 +1421,178 @@ impl ChainSource { match &self.kind { ChainSourceKind::Esplora(esplora_chain_source) => { - let WalletSyncOutcome { - events: wallet_events, - evicted_txids, - error: sync_error, - synced_accounts, - skipped, - waited, - } = esplora_chain_source.sync_onchain_wallet(Arc::clone(&wallet), scope).await; - // The pass it waited on reports the events. - if waited { - return Ok(()); - } - // No additional wallets: nothing synced, and nothing to report. - if skipped { - return Ok(()); - } - let mut events_state = self.sync_events.lock().await; - - // Process wallet events if event queue is provided - if let Some(event_queue) = event_queue { - process_wallet_events( - wallet_events, - &wallet, - event_queue, - &self.logger, - channel_manager, - chain_monitor, - &mut events_state.emitted_tx_events, - ) - .await?; - // Applied even when another wallet in the pass failed. - emit_evicted_transactions( - evicted_txids, - event_queue, - &self.logger, - &mut events_state.emitted_tx_events, - ) - .await; - } - - if let Some(error) = sync_error { - return Err(error); - } - - if let Some(event_queue) = event_queue { - let sync_type = match scope { - OnchainSyncScope::Primary => Some(SyncType::OnchainWallet), - OnchainSyncScope::Additional => (!synced_accounts.is_empty()) - .then_some(SyncType::AdditionalOnchainWallets), - }; - if let Some(sync_type) = sync_type { - emit_onchain_sync_completed(&wallet, event_queue, sync_type).await?; - } - // Check for balance changes and emit BalanceChanged event if needed - if let (Some(cm), Some(chain_mon), Some(cfg)) = - (channel_manager, chain_monitor, config) - { - let cur_anchor_reserve_sats = - crate::total_anchor_channels_reserve_sats(cm, cfg); - let (total_onchain_balance_sats, spendable_onchain_balance_sats) = - wallet.get_balances(cur_anchor_reserve_sats).unwrap_or((0, 0)); - - let mut total_lightning_balance_sats = 0; - for channel_id in chain_mon.list_monitors() { - if let Ok(monitor) = chain_mon.get_monitor(channel_id) { - for ldk_balance in monitor.get_claimable_balances() { - total_lightning_balance_sats += - ldk_balance.claimable_amount_satoshis(); - } - } - } - - let balance_details = crate::BalanceDetails { - total_onchain_balance_sats, - spendable_onchain_balance_sats, - total_anchor_channels_reserve_sats: std::cmp::min( - cur_anchor_reserve_sats, - total_onchain_balance_sats, - ), - total_lightning_balance_sats, - lightning_balances: Vec::new(), - pending_balances_from_channel_closures: Vec::new(), - }; - - let node_metrics = match &self.kind { - ChainSourceKind::Esplora(es) => Arc::clone(&es.node_metrics), - ChainSourceKind::Electrum(el) => Arc::clone(&el.node_metrics), - ChainSourceKind::Bitcoind(bd) => Arc::clone(&bd.node_metrics), - }; - let kv_store = match &self.kind { - ChainSourceKind::Esplora(es) => Arc::clone(&es.kv_store), - ChainSourceKind::Electrum(el) => Arc::clone(&el.kv_store), - ChainSourceKind::Bitcoind(bd) => Arc::clone(&bd.kv_store), - }; - - check_and_emit_balance_update( - &node_metrics, - &balance_details, - event_queue, - &kv_store, - &self.logger, - ) - .await?; - } - } - Ok(()) + let (outcome, pass) = + esplora_chain_source.sync_onchain_wallet(Arc::clone(&wallet), scope).await; + self.report_pass( + outcome, + pass, + &wallet, + event_queue, + channel_manager, + chain_monitor, + config, + scope, + ) + .await }, ChainSourceKind::Electrum(electrum_chain_source) => { - let WalletSyncOutcome { - events: wallet_events, - evicted_txids, - error: sync_error, - synced_accounts, - skipped, - waited, - } = electrum_chain_source.sync_onchain_wallet(Arc::clone(&wallet), scope).await; - // The pass it waited on reports the events. - if waited { - return Ok(()); - } - // No additional wallets: nothing synced, and nothing to report. - if skipped { - return Ok(()); - } - let mut events_state = self.sync_events.lock().await; + let (outcome, pass) = + electrum_chain_source.sync_onchain_wallet(Arc::clone(&wallet), scope).await; + self.report_pass( + outcome, + pass, + &wallet, + event_queue, + channel_manager, + chain_monitor, + config, + scope, + ) + .await + }, + ChainSourceKind::Bitcoind { .. } => { + // In BitcoindRpc mode we sync lightning and onchain wallet in one go via + // `ChainPoller`. So nothing to do here. + unreachable!("Onchain wallet will be synced via chain polling") + }, + } + } - // Process wallet events if event queue is provided - if let Some(event_queue) = event_queue { - process_wallet_events( - wallet_events, - &wallet, - event_queue, - &self.logger, - channel_manager, - chain_monitor, - &mut events_state.emitted_tx_events, - ) - .await?; - // Applied even when another wallet in the pass failed. - emit_evicted_transactions( - evicted_txids, - event_queue, - &self.logger, - &mut events_state.emitted_tx_events, - ) - .await; - } + // Reports a pass's events, then finishes the pass, so a call that waited on it returns only + // once its events are queued. + async fn report_pass( + &self, outcome: WalletSyncOutcome, pass: Option>, wallet: &Arc, + event_queue: Option<&Arc>>>, + channel_manager: Option<&Arc>, chain_monitor: Option<&Arc>, + config: Option<&Arc>, scope: OnchainSyncScope, + ) -> Result<(), Error> { + let result = self + .emit_pass_events( + outcome, + wallet, + event_queue, + channel_manager, + chain_monitor, + config, + scope, + ) + .await; + if let Some(pass) = pass { + pass.finish(result.clone()); + } + result + } - if let Some(error) = sync_error { - return Err(error); - } + async fn emit_pass_events( + &self, outcome: WalletSyncOutcome, wallet: &Arc, + event_queue: Option<&Arc>>>, + channel_manager: Option<&Arc>, chain_monitor: Option<&Arc>, + config: Option<&Arc>, scope: OnchainSyncScope, + ) -> Result<(), Error> { + let WalletSyncOutcome { + events: wallet_events, + evicted_txids, + error: sync_error, + synced_accounts, + skipped, + waited, + } = outcome; + // The pass it waited on reports the events and returned once they were queued. + if waited { + return Ok(()); + } + // No additional wallets: nothing synced, and nothing to report. + if skipped { + return Ok(()); + } + let mut events_state = self.sync_events.lock().await; + + // Process wallet events if event queue is provided + if let Some(event_queue) = event_queue { + process_wallet_events( + wallet_events, + &wallet, + event_queue, + &self.logger, + channel_manager, + chain_monitor, + &mut events_state.emitted_tx_events, + ) + .await?; + // Applied even when another wallet in the pass failed. + emit_evicted_transactions( + evicted_txids, + event_queue, + &self.logger, + &mut events_state.emitted_tx_events, + ) + .await; + } - if let Some(event_queue) = event_queue { - let sync_type = match scope { - OnchainSyncScope::Primary => Some(SyncType::OnchainWallet), - OnchainSyncScope::Additional => (!synced_accounts.is_empty()) - .then_some(SyncType::AdditionalOnchainWallets), - }; - if let Some(sync_type) = sync_type { - emit_onchain_sync_completed(&wallet, event_queue, sync_type).await?; - } + if let Some(error) = sync_error { + return Err(error); + } - // Check for balance changes and emit BalanceChanged event if needed - if let (Some(cm), Some(chain_mon), Some(cfg)) = - (channel_manager, chain_monitor, config) - { - let cur_anchor_reserve_sats = - crate::total_anchor_channels_reserve_sats(cm, cfg); - let (total_onchain_balance_sats, spendable_onchain_balance_sats) = - wallet.get_balances(cur_anchor_reserve_sats).unwrap_or((0, 0)); - - let mut total_lightning_balance_sats = 0; - for channel_id in chain_mon.list_monitors() { - if let Ok(monitor) = chain_mon.get_monitor(channel_id) { - for ldk_balance in monitor.get_claimable_balances() { - total_lightning_balance_sats += - ldk_balance.claimable_amount_satoshis(); - } - } + if let Some(event_queue) = event_queue { + let sync_type = match scope { + OnchainSyncScope::Primary => Some(SyncType::OnchainWallet), + OnchainSyncScope::Additional => { + (!synced_accounts.is_empty()).then_some(SyncType::AdditionalOnchainWallets) + }, + }; + if let Some(sync_type) = sync_type { + emit_onchain_sync_completed(&wallet, event_queue, sync_type).await?; + } + // Check for balance changes and emit BalanceChanged event if needed + if let (Some(cm), Some(chain_mon), Some(cfg)) = (channel_manager, chain_monitor, config) + { + let cur_anchor_reserve_sats = crate::total_anchor_channels_reserve_sats(cm, cfg); + let (total_onchain_balance_sats, spendable_onchain_balance_sats) = + wallet.get_balances(cur_anchor_reserve_sats).unwrap_or((0, 0)); + + let mut total_lightning_balance_sats = 0; + for channel_id in chain_mon.list_monitors() { + if let Ok(monitor) = chain_mon.get_monitor(channel_id) { + for ldk_balance in monitor.get_claimable_balances() { + total_lightning_balance_sats += ldk_balance.claimable_amount_satoshis(); } - - let balance_details = crate::BalanceDetails { - total_onchain_balance_sats, - spendable_onchain_balance_sats, - total_anchor_channels_reserve_sats: std::cmp::min( - cur_anchor_reserve_sats, - total_onchain_balance_sats, - ), - total_lightning_balance_sats, - lightning_balances: Vec::new(), - pending_balances_from_channel_closures: Vec::new(), - }; - - let node_metrics = match &self.kind { - ChainSourceKind::Esplora(es) => Arc::clone(&es.node_metrics), - ChainSourceKind::Electrum(el) => Arc::clone(&el.node_metrics), - ChainSourceKind::Bitcoind(bd) => Arc::clone(&bd.node_metrics), - }; - let kv_store = match &self.kind { - ChainSourceKind::Esplora(es) => Arc::clone(&es.kv_store), - ChainSourceKind::Electrum(el) => Arc::clone(&el.kv_store), - ChainSourceKind::Bitcoind(bd) => Arc::clone(&bd.kv_store), - }; - - check_and_emit_balance_update( - &node_metrics, - &balance_details, - event_queue, - &kv_store, - &self.logger, - ) - .await?; } } - Ok(()) - }, - ChainSourceKind::Bitcoind { .. } => { - // In BitcoindRpc mode we sync lightning and onchain wallet in one go via - // `ChainPoller`. So nothing to do here. - unreachable!("Onchain wallet will be synced via chain polling") - }, + + let balance_details = crate::BalanceDetails { + total_onchain_balance_sats, + spendable_onchain_balance_sats, + total_anchor_channels_reserve_sats: std::cmp::min( + cur_anchor_reserve_sats, + total_onchain_balance_sats, + ), + total_lightning_balance_sats, + lightning_balances: Vec::new(), + pending_balances_from_channel_closures: Vec::new(), + }; + + let node_metrics = match &self.kind { + ChainSourceKind::Esplora(es) => Arc::clone(&es.node_metrics), + ChainSourceKind::Electrum(el) => Arc::clone(&el.node_metrics), + ChainSourceKind::Bitcoind(bd) => Arc::clone(&bd.node_metrics), + }; + let kv_store = match &self.kind { + ChainSourceKind::Esplora(es) => Arc::clone(&es.kv_store), + ChainSourceKind::Electrum(el) => Arc::clone(&el.kv_store), + ChainSourceKind::Bitcoind(bd) => Arc::clone(&bd.kv_store), + }; + + check_and_emit_balance_update( + &node_metrics, + &balance_details, + event_queue, + &kv_store, + &self.logger, + ) + .await?; + } } + Ok(()) } // Synchronize the Lightning wallet via transaction-based protocols (i.e., Esplora, Electrum, From 049cac0aa37f28fb72c282e579b066aaa77dcfc3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 21:36:24 +0100 Subject: [PATCH 12/16] docs: cover the additional wallets sync type in the mobile guide Verified: none (docs only) --- MOBILE_DEVELOPER_GUIDE.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/MOBILE_DEVELOPER_GUIDE.md b/MOBILE_DEVELOPER_GUIDE.md index 800a01bad1..7723fb693a 100644 --- a/MOBILE_DEVELOPER_GUIDE.md +++ b/MOBILE_DEVELOPER_GUIDE.md @@ -360,6 +360,8 @@ class SyncProgressView: UIView { self.statusLabel.text = "Syncing Lightning: \(percent)%" case .feeRateCache: self.statusLabel.text = "Updating fee rates: \(percent)%" + case .additionalOnchainWallets: + self.statusLabel.text = "Syncing other wallets: \(percent)%" } self.progressBar.isHidden = false @@ -669,6 +671,7 @@ class SyncProgressFragment : Fragment() { SyncType.ONCHAIN_WALLET -> "Syncing wallet..." SyncType.LIGHTNING_WALLET -> "Syncing Lightning..." SyncType.FEE_RATE_CACHE -> "Updating fee rates..." + SyncType.ADDITIONAL_ONCHAIN_WALLETS -> "Syncing other wallets..." } binding.progressContainer.visibility = View.VISIBLE From 12e9048fbf33c835a8dac6b4cbb240cd895b0242 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 21:42:38 +0100 Subject: [PATCH 13/16] chore: ship the waited sync fix in 0.7.0-rc.86 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Verified: swift package compute-checksum matches Package.swift (19760142…) --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index f71ca47848..e269abbbe4 100644 --- a/Package.swift +++ b/Package.swift @@ -4,7 +4,7 @@ import PackageDescription let tag = "v0.7.0-rc.86" -let checksum = "44db27159f11fad86940a9d0679e1eb80646748f2c9d9efa4073f0ba98c1c62a" +let checksum = "1976014269774886356919d2b3bf749c51c487cbba15925dbe8a513f11ab4b52" let url = "https://github.com/synonymdev/ldk-node/releases/download/\(tag)/LDKNodeFFI.xcframework.zip" let package = Package( From bbb1acebd890bf5f259329d02a95b24e4ec73607 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 22:27:05 +0100 Subject: [PATCH 14/16] fix: report the synced wallets' height and rerun a joined pass for new wallets SyncCompleted reports the lowest tip of the wallets the pass synced. A call that joined an additional pass runs another when that pass did not sync every additional wallet registered when the call started. Verified: cargo test --lib --- src/chain/mod.rs | 114 +++++++++++++++++++++++++++++----------------- src/wallet/mod.rs | 19 ++++++-- 2 files changed, 85 insertions(+), 48 deletions(-) diff --git a/src/chain/mod.rs b/src/chain/mod.rs index a9fc32f9bb..40a902df30 100644 --- a/src/chain/mod.rs +++ b/src/chain/mod.rs @@ -98,6 +98,8 @@ impl EmittedTxEvents { #[derive(Default)] struct SyncEventsState { emitted_tx_events: EmittedTxEvents, + // The additional wallets the last additional pass synced. + additional_pass_synced: Vec, } // Fails a pass's waiters when the pass is dropped before it finishes (e.g. cancelled while the @@ -545,7 +547,10 @@ mod sync_tests { builder.set_log_facade_logger(); let store: Arc = Arc::new(InMemoryStore::new()); let node = builder.build_with_store(store).unwrap(); - assert_eq!(node.wallet.scope_tip_height(false), None); + let primary = node.wallet.primary_account(); + let derived = + OnchainWalletAccount { address_type: AddressType::NativeSegwit, account_index: 1 }; + assert_eq!(node.wallet.tip_height_of(&[derived]), None); let xpub = node.export_onchain_wallet_account_xpub(AddressType::NativeSegwit, 1).unwrap(); node.add_onchain_wallet_account(AddressType::NativeSegwit, 1, xpub).unwrap(); @@ -555,8 +560,10 @@ mod sync_tests { .unwrap(); node.wallet.apply_update(BdkUpdate { chain: Some(tip), ..Default::default() }).unwrap(); - assert_eq!(node.wallet.scope_tip_height(true), Some(10)); - assert_eq!(node.wallet.scope_tip_height(false), Some(genesis.height)); + // A wallet the pass did not sync, such as one registered mid-pass, does not lower it. + assert_eq!(node.wallet.tip_height_of(&[primary]), Some(10)); + assert_eq!(node.wallet.tip_height_of(&[derived]), Some(genesis.height)); + assert_eq!(node.wallet.tip_height_of(&[primary, derived]), Some(genesis.height)); } fn test_node() -> crate::Node { @@ -633,6 +640,13 @@ mod sync_tests { // A pass whose wallets were all removed reports no sync. report(Vec::new()).await; assert!(node.event_queue.next_event().is_none()); + + // A call that joined that pass runs another for a wallet the pass did not sync. + let other = + OnchainWalletAccount { address_type: AddressType::NativeSegwit, account_index: 2 }; + report(vec![account]).await; + assert!(node.chain_source.last_pass_synced(&[account]).await); + assert!(!node.chain_source.last_pass_synced(&[account, other]).await); } #[test] @@ -704,14 +718,14 @@ mod sync_tests { async fn emit_onchain_sync_completed( wallet: &Wallet, event_queue: &EventQueue, sync_type: SyncType, + synced_accounts: &[OnchainWalletAccount], ) -> Result<(), Error> where L2::Target: LdkLogger, { // The height of the wallets this pass synced, not of the others, which sync apart. - let synced_block_height = wallet - .scope_tip_height(sync_type == SyncType::OnchainWallet) - .unwrap_or_else(|| wallet.current_best_block().height); + let synced_block_height = + wallet.tip_height_of(synced_accounts).unwrap_or_else(|| wallet.current_best_block().height); event_queue.add_event(Event::SyncCompleted { sync_type, synced_block_height }).await } @@ -1418,44 +1432,50 @@ impl ChainSource { ) -> Result<(), Error> { let wallet = self.onchain_wallet.lock().unwrap().clone(); let wallet = wallet.ok_or(Error::WalletOperationFailed)?; + // A call that joins a pass in flight may have registered additional wallets that pass did + // not read, so it runs another pass for them. + let wanted = match scope { + OnchainSyncScope::Primary => Vec::new(), + OnchainSyncScope::Additional => wallet.additional_wallet_accounts(), + }; - match &self.kind { - ChainSourceKind::Esplora(esplora_chain_source) => { - let (outcome, pass) = - esplora_chain_source.sync_onchain_wallet(Arc::clone(&wallet), scope).await; - self.report_pass( - outcome, - pass, - &wallet, - event_queue, - channel_manager, - chain_monitor, - config, - scope, - ) - .await - }, - ChainSourceKind::Electrum(electrum_chain_source) => { - let (outcome, pass) = - electrum_chain_source.sync_onchain_wallet(Arc::clone(&wallet), scope).await; - self.report_pass( - outcome, - pass, - &wallet, - event_queue, - channel_manager, - chain_monitor, - config, - scope, - ) - .await - }, - ChainSourceKind::Bitcoind { .. } => { - // In BitcoindRpc mode we sync lightning and onchain wallet in one go via - // `ChainPoller`. So nothing to do here. - unreachable!("Onchain wallet will be synced via chain polling") - }, + for _ in 0..2 { + let (outcome, pass) = match &self.kind { + ChainSourceKind::Esplora(esplora_chain_source) => { + esplora_chain_source.sync_onchain_wallet(Arc::clone(&wallet), scope).await + }, + ChainSourceKind::Electrum(electrum_chain_source) => { + electrum_chain_source.sync_onchain_wallet(Arc::clone(&wallet), scope).await + }, + ChainSourceKind::Bitcoind { .. } => { + // In BitcoindRpc mode we sync lightning and onchain wallet in one go via + // `ChainPoller`. So nothing to do here. + unreachable!("Onchain wallet will be synced via chain polling") + }, + }; + let waited = outcome.waited; + self.report_pass( + outcome, + pass, + &wallet, + event_queue, + channel_manager, + chain_monitor, + config, + scope, + ) + .await?; + if !waited || self.last_pass_synced(&wanted).await { + return Ok(()); + } } + Ok(()) + } + + // Whether the last additional pass synced every one of `accounts`. + async fn last_pass_synced(&self, accounts: &[OnchainWalletAccount]) -> bool { + let events_state = self.sync_events.lock().await; + accounts.iter().all(|account| events_state.additional_pass_synced.contains(account)) } // Reports a pass's events, then finishes the pass, so a call that waited on it returns only @@ -1506,6 +1526,9 @@ impl ChainSource { return Ok(()); } let mut events_state = self.sync_events.lock().await; + if scope == OnchainSyncScope::Additional { + events_state.additional_pass_synced = synced_accounts.clone(); + } // Process wallet events if event queue is provided if let Some(event_queue) = event_queue { @@ -1541,7 +1564,12 @@ impl ChainSource { }, }; if let Some(sync_type) = sync_type { - emit_onchain_sync_completed(&wallet, event_queue, sync_type).await?; + let primary = [wallet.primary_account()]; + let accounts = match scope { + OnchainSyncScope::Primary => &primary[..], + OnchainSyncScope::Additional => &synced_accounts[..], + }; + emit_onchain_sync_completed(&wallet, event_queue, sync_type, accounts).await?; } // Check for balance changes and emit BalanceChanged event if needed if let (Some(cm), Some(chain_mon), Some(cfg)) = (channel_manager, chain_monitor, config) diff --git a/src/wallet/mod.rs b/src/wallet/mod.rs index a5eb46290b..c1d0ae2950 100644 --- a/src/wallet/mod.rs +++ b/src/wallet/mod.rs @@ -315,17 +315,26 @@ impl Wallet { } /// The oldest tip among the primary wallet (`primary`) or among the additional wallets. - pub(crate) fn scope_tip_height(&self, primary: bool) -> Option { - let locked_wallet = self.inner.lock().unwrap(); - let primary_key = locked_wallet.primary_key(); - locked_wallet + /// The lowest chain tip among `accounts`' wallets. + pub(crate) fn tip_height_of(&self, accounts: &[OnchainWalletAccount]) -> Option { + self.inner + .lock() + .unwrap() .chain_tips_by_key() .into_iter() - .filter(|(key, _, _)| (*key == primary_key) == primary) + .filter(|(account, _, _)| accounts.contains(account)) .map(|(_, _, height)| height) .min() } + pub(crate) fn primary_account(&self) -> OnchainWalletAccount { + self.inner.lock().unwrap().primary_key() + } + + pub(crate) fn additional_wallet_accounts(&self) -> Vec { + self.address_type_runtime_config.read().unwrap().additional_wallet_accounts() + } + pub(crate) fn current_best_block(&self) -> BestBlock { let (block_hash, height) = self.inner.lock().unwrap().current_best_block(); BestBlock { block_hash, height } From fd9cab01725ca37b343cb5e7b1ad0742d683918b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 22:37:04 +0100 Subject: [PATCH 15/16] fix: record only a run pass's synced wallets Verified: cargo test --lib --- src/chain/mod.rs | 25 ++++++++++++++++++++++--- src/wallet/mod.rs | 1 - 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/chain/mod.rs b/src/chain/mod.rs index 40a902df30..e7827884f9 100644 --- a/src/chain/mod.rs +++ b/src/chain/mod.rs @@ -647,6 +647,23 @@ mod sync_tests { report(vec![account]).await; assert!(node.chain_source.last_pass_synced(&[account]).await); assert!(!node.chain_source.last_pass_synced(&[account, other]).await); + + // A call that only joined a pass leaves the record of the pass that ran. + let joined = node + .chain_source + .report_pass( + WalletSyncOutcome::failed(Error::WalletOperationFailed), + None, + &node.wallet, + Some(&node.event_queue), + None, + None, + None, + OnchainSyncScope::Additional, + ) + .await; + assert_eq!(joined, Err(Error::WalletOperationFailed)); + assert!(node.chain_source.last_pass_synced(&[account]).await); } #[test] @@ -1486,6 +1503,7 @@ impl ChainSource { channel_manager: Option<&Arc>, chain_monitor: Option<&Arc>, config: Option<&Arc>, scope: OnchainSyncScope, ) -> Result<(), Error> { + let synced_accounts = outcome.synced_accounts.clone(); let result = self .emit_pass_events( outcome, @@ -1498,6 +1516,10 @@ impl ChainSource { ) .await; if let Some(pass) = pass { + // Only a pass that ran records what it synced; a call that joined one does not. + if scope == OnchainSyncScope::Additional { + self.sync_events.lock().await.additional_pass_synced = synced_accounts; + } pass.finish(result.clone()); } result @@ -1526,9 +1548,6 @@ impl ChainSource { return Ok(()); } let mut events_state = self.sync_events.lock().await; - if scope == OnchainSyncScope::Additional { - events_state.additional_pass_synced = synced_accounts.clone(); - } // Process wallet events if event queue is provided if let Some(event_queue) = event_queue { diff --git a/src/wallet/mod.rs b/src/wallet/mod.rs index c1d0ae2950..6ce7f4f9fb 100644 --- a/src/wallet/mod.rs +++ b/src/wallet/mod.rs @@ -314,7 +314,6 @@ impl Wallet { self.inner.lock().unwrap().transaction_confirmations() } - /// The oldest tip among the primary wallet (`primary`) or among the additional wallets. /// The lowest chain tip among `accounts`' wallets. pub(crate) fn tip_height_of(&self, accounts: &[OnchainWalletAccount]) -> Option { self.inner From 9ec6e1495e17dbecaeaf8634e808cccb775ab25b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 22:50:14 +0100 Subject: [PATCH 16/16] chore: ship the synced height fix in 0.7.0-rc.86 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Verified: swift package compute-checksum matches Package.swift (4f4f2b0f…) --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index e269abbbe4..b5b5a7fc0e 100644 --- a/Package.swift +++ b/Package.swift @@ -4,7 +4,7 @@ import PackageDescription let tag = "v0.7.0-rc.86" -let checksum = "1976014269774886356919d2b3bf749c51c487cbba15925dbe8a513f11ab4b52" +let checksum = "4f4f2b0fc81b24f24faf5061b69e739cae2f02fc5303d6cb4f60b162aeed9eb4" let url = "https://github.com/synonymdev/ldk-node/releases/download/\(tag)/LDKNodeFFI.xcframework.zip" let package = Package(