diff --git a/CHANGELOG.md b/CHANGELOG.md index ff7fb9169d..72104f5f4b 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,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. 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/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/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 diff --git a/Package.swift b/Package.swift index 8cfc7fb442..b5b5a7fc0e 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 = "4f4f2b0fc81b24f24faf5061b69e739cae2f02fc5303d6cb4f60b162aeed9eb4" 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=5.8) @@ -10540,6 +10557,8 @@ public struct FfiConverterTypeSyncType: FfiConverterRustBuffer { case 3: return .feeRateCache + case 4: return .additionalOnchainWallets + default: throw UniffiInternalError.unexpectedEnumCase } } @@ -10554,6 +10573,9 @@ public struct FfiConverterTypeSyncType: FfiConverterRustBuffer { case .feeRateCache: writeInt(&buf, Int32(3)) + + case .additionalOnchainWallets: + writeInt(&buf, Int32(4)) } } } diff --git a/crates/bdk-wallet-aggregate/src/lib.rs b/crates/bdk-wallet-aggregate/src/lib.rs index 29b58586a4..5762287111 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)) } @@ -505,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 @@ -1861,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 ba2dd35a4a..20b2d003bb 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, @@ -189,16 +189,46 @@ 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()) + }, + } +} + +/// 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, 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, pub(super) config: Arc, - address_type_runtime_config: Arc>, + pub(super) address_type_runtime_config: Arc>, logger: Arc, pub(super) node_metrics: Arc>, } @@ -218,6 +248,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,41 +284,44 @@ 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, - ) -> super::WalletSyncOutcome { + &self, onchain_wallet: Arc, scope: OnchainSyncScope, + ) -> (super::WalletSyncOutcome, Option>) { 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 { log_info!(self.logger, "Sync in progress, skipping."); match sync_receiver.recv().await { - Ok(Ok(())) => return super::WalletSyncOutcome::new(Vec::new(), None), - 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); }, } } + let sync_guard = super::WalletSyncGuard::new(self.wallet_sync_status(scope)); 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 - .lock() - .unwrap() - .propagate_result_to_subscribers(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( - &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 +337,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::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. + 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 +360,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 +385,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 +404,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, @@ -364,8 +422,14 @@ impl ElectrumChainSource { } } + let pass_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); + let connection = Arc::clone(&connection); let txs = Arc::clone(&cached_txs); let incremental_batch_size = additional_wallet_incremental_batch_size( wallet_account.account_index, @@ -373,21 +437,14 @@ 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( + &connection, req, txs.iter().cloned(), incremental_batch_size, - timeout, + pass_timeout, ) .await .map(|u| u.into()); @@ -395,17 +452,14 @@ 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( + &connection, req, txs.iter().cloned(), additional_full_scan_settings, - timeout, + pass_timeout, ) .await .map(|u| u.into()); @@ -442,7 +496,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 +509,7 @@ impl ElectrumChainSource { &onchain_wallet, &self.node_metrics, &self.logger, + &self.sync_apply_lock, ); if outcome.primary_applied { log_info!( @@ -463,6 +519,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 +544,14 @@ impl ElectrumChainSource { } } - Ok(super::WalletSyncOutcome::new(outcome.events, outcome.error)) + Ok(super::WalletSyncOutcome { + events: outcome.events, + evicted_txids: outcome.evicted_txids, + error: outcome.error, + synced_accounts: outcome.synced_accounts, + skipped: false, + waited: false, + }) } pub(crate) async fn sync_lightning_wallet( @@ -718,7 +789,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 +805,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 +864,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 +882,74 @@ 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?; + + // 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); + // 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)) + } + 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 +1052,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 +1080,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 +1088,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 +1116,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) }, @@ -1282,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; @@ -1648,6 +1788,107 @@ 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)); + } + + 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()); @@ -1978,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 e95c8d631d..af32babd3c 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,12 +39,14 @@ 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, 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>, } @@ -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,47 +113,57 @@ 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, - ) -> super::WalletSyncOutcome { + &self, onchain_wallet: Arc, scope: OnchainSyncScope, + ) -> (super::WalletSyncOutcome, Option>) { 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 { log_info!(self.logger, "Sync in progress, skipping."); match sync_receiver.recv().await { - Ok(Ok(())) => return super::WalletSyncOutcome::new(Vec::new(), None), - 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); }, } } + let sync_guard = super::WalletSyncGuard::new(self.wallet_sync_status(scope)); 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 - .lock() - .unwrap() - .propagate_result_to_subscribers(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( - &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::skipped()); + } let additional_sync_requests = super::collect_additional_sync_requests( &additional_accounts, &onchain_wallet, @@ -157,10 +171,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 +196,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 +208,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 +325,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 +338,7 @@ impl EsploraChainSource { &onchain_wallet, &self.node_metrics, &self.logger, + &self.sync_apply_lock, ); if outcome.primary_applied { log_info!( @@ -325,6 +348,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 +373,14 @@ impl EsploraChainSource { } } - Ok(super::WalletSyncOutcome::new(outcome.events, outcome.error)) + Ok(super::WalletSyncOutcome { + events: outcome.events, + evicted_txids: outcome.evicted_txids, + error: outcome.error, + synced_accounts: outcome.synced_accounts, + skipped: false, + waited: false, + }) } pub(super) async fn sync_lightning_wallet( @@ -643,11 +681,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..e7827884f9 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}; @@ -42,6 +42,95 @@ 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, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +enum OnchainTxEventKind { + Received, + // Per block, so a confirmation in another block after a reorg is reported again. + Confirmed(bitcoin::BlockHash), + 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 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)); + } +} + +// Event emission state shared by the primary and additional passes. +#[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 +// 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> }, @@ -102,6 +191,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: tokio::sync::Mutex, } enum ChainSourceKind { @@ -158,16 +250,16 @@ 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, + emitted_tx_events: &mut EmittedTxEvents, ) where L2::Target: LdkLogger, { - let evicted_txids = check_evicted_transactions(prev_unconfirmed_txids, wallet, logger); - for txid in evicted_txids { + // A rebroadcast of an evicted transaction is reported as received again. + 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); } @@ -192,7 +284,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 { @@ -204,10 +296,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() } @@ -226,21 +328,44 @@ 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, } pub(super) struct WalletSyncOutcome { pub(super) events: Vec, + pub(super) evicted_txids: Vec, pub(super) error: Option, + // 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, error } + Self { + events, + evicted_txids: Vec::new(), + error, + synced_accounts: Vec::new(), + skipped: false, + waited: false, + } } pub(super) fn failed(error: Error) -> Self { - Self { events: 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 waited() -> Self { + Self { waited: true, ..Self::new(Vec::new(), None) } } pub(super) fn result(&self) -> Result<(), Error> { @@ -250,8 +375,10 @@ 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) synced_accounts: Vec, pub(super) error: Option, } @@ -261,6 +388,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 { @@ -275,6 +403,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()) { @@ -295,14 +424,19 @@ 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), +/// 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,10 +461,13 @@ 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, + synced_accounts: additional_outcome.synced_accounts, primary_applied, error, } @@ -377,6 +514,7 @@ mod sync_tests { &node.wallet, &node.node_metrics, &node.logger, + &Mutex::new(()), ); assert!(outcome.primary_applied); @@ -387,6 +525,164 @@ 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_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(); + 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(); + + 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(); + + // 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 { + 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()); + + // 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); + + // 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] + 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)); + 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] fn wallet_sync_outcome_preserves_events_on_failure() { let block = bitcoin::BlockHash::all_zeros(); @@ -426,6 +722,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!( @@ -435,23 +733,33 @@ 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.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 +} + // 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 { @@ -465,9 +773,11 @@ where ); continue; }; - if !seen_confirmed_txids.insert(txid) { + let confirmed = OnchainTxEventKind::Confirmed(block_time.block_id.hash); + if !emitted_tx_events.insert(txid, confirmed) { continue; } + 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); @@ -500,9 +810,11 @@ 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, |kind| matches!(kind, OnchainTxEventKind::Confirmed(_))); // Transaction was previously confirmed but is now unconfirmed (reorg) log_info!( logger, @@ -516,7 +828,7 @@ where })?; }, None => { - if !seen_received_txids.insert(txid) { + if !emitted_tx_events.insert(txid, OnchainTxEventKind::Received) { continue; } // New unconfirmed transaction detected in mempool @@ -557,7 +869,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 = @@ -616,6 +928,7 @@ impl ChainSource { onchain_wallet: Arc::new(Mutex::new(None)), event_queue: Arc::new(Mutex::new(None)), sync_config_sender, + sync_events: tokio::sync::Mutex::new(SyncEventsState::default()), }, None, ) @@ -653,6 +966,7 @@ impl ChainSource { onchain_wallet: Arc::new(Mutex::new(None)), event_queue: Arc::new(Mutex::new(None)), sync_config_sender, + sync_events: tokio::sync::Mutex::new(SyncEventsState::default()), }, None, ) @@ -685,6 +999,7 @@ impl ChainSource { onchain_wallet: Arc::new(Mutex::new(None)), event_queue: Arc::new(Mutex::new(None)), sync_config_sender: None, + sync_events: tokio::sync::Mutex::new(SyncEventsState::default()), }, best_block, ) @@ -718,6 +1033,7 @@ impl ChainSource { onchain_wallet: Arc::new(Mutex::new(None)), event_queue: Arc::new(Mutex::new(None)), sync_config_sender: None, + sync_events: tokio::sync::Mutex::new(SyncEventsState::default()), }, best_block, ) @@ -865,31 +1181,57 @@ 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) => { + 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) => { + 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 + Ok(()) + }, + } + } } - } + }; + let (primary, additional) = tokio::join!( + sync_scope(OnchainSyncScope::Primary), + sync_scope(OnchainSyncScope::Additional) + ); + primary.and(additional) } fn config(&self) -> Option<&Arc> { @@ -901,6 +1243,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 +1358,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 +1398,7 @@ impl ChainSource { Some(&channel_manager), Some(&chain_monitor), self.config(), + OnchainSyncScope::Primary, ).await; } _ = fee_rate_update_interval.tick() => { @@ -1032,211 +1445,201 @@ 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)?; + // 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) => { - // Track unconfirmed transactions before sync to detect evictions - let prev_unconfirmed_txids = wallet.get_unconfirmed_txids(); + 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(()) + } - let WalletSyncOutcome { events: wallet_events, error: sync_error } = - esplora_chain_source.sync_onchain_wallet(Arc::clone(&wallet)).await; + // 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)) + } - // 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, - ) - .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 synced_accounts = outcome.synced_accounts.clone(); + let result = self + .emit_pass_events( + outcome, + wallet, + event_queue, + channel_manager, + chain_monitor, + config, + scope, + ) + .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 + } - 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; - 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; + // 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; + } - // 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?; - // 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(error) = sync_error { + return Err(error); + } - 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?; + 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 { + 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) + { + 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(); + } } } - 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; - - // 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, - ) - .await?; - } - if let Some(error) = sync_error { - return Err(error); - } - - 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; + 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(), + }; - // 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?; - - // 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 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), + }; - 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") - }, + 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, 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/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 1f78a397b0..6ce7f4f9fb 100644 --- a/src/wallet/mod.rs +++ b/src/wallet/mod.rs @@ -314,6 +314,26 @@ impl Wallet { self.inner.lock().unwrap().transaction_confirmations() } + /// 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(|(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 } @@ -1099,24 +1119,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; - 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(); } diff --git a/tests/multi_address_types_tests.rs b/tests/multi_address_types_tests.rs index 01aaf977fc..c8eecf1be4 100644 --- a/tests/multi_address_types_tests.rs +++ b/tests/multi_address_types_tests.rs @@ -3697,9 +3697,12 @@ 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, EsploraSyncConfig, + OnchainWalletAccountConfig, + }; use ldk_node::payment::KeychainKind; - use ldk_node::{Builder, NodeError}; + use ldk_node::{Builder, Event, NodeError, RuntimeSyncIntervals, SyncType}; use crate::common::{ distribute_funds_unconfirmed, generate_blocks_and_wait, invalidate_blocks, open_channel, @@ -4134,6 +4137,116 @@ mod derived_accounts { node.stop().unwrap(); } + #[tokio::test(flavor = "multi_thread", worker_threads = 1)] + 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 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, + }; + + 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(); + 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() + .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 (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(); + } + } + #[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();