Skip to main content

lightning_background_processor/
lib.rs

1// This file is Copyright its original authors, visible in version control
2// history.
3//
4// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7// You may not use this file except in accordance with one or both of these
8// licenses.
9
10//! Utilities that take care of tasks that (1) need to happen periodically to keep Rust-Lightning
11//! running properly, and (2) either can or should be run in the background.
12#![cfg_attr(feature = "std", doc = "See docs for [`BackgroundProcessor`] for more details.")]
13#![deny(rustdoc::broken_intra_doc_links)]
14#![deny(rustdoc::private_intra_doc_links)]
15#![deny(missing_docs)]
16#![cfg_attr(docsrs, feature(doc_cfg))]
17#![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
18
19#[cfg(any(test, feature = "std"))]
20extern crate core;
21
22#[cfg(not(feature = "std"))]
23extern crate alloc;
24
25#[macro_use]
26extern crate lightning;
27extern crate lightning_rapid_gossip_sync;
28
29mod fwd_batch;
30
31use fwd_batch::BatchDelay;
32
33#[cfg(not(c_bindings))]
34use lightning::chain;
35#[cfg(not(c_bindings))]
36use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
37use lightning::chain::chainmonitor::AChainMonitor;
38#[cfg(feature = "std")]
39use lightning::events::EventHandler;
40#[cfg(feature = "std")]
41use lightning::events::EventsProvider;
42use lightning::events::ReplayEvent;
43use lightning::events::{Event, PathFailure};
44use lightning::util::ser::Writeable;
45
46#[cfg(not(c_bindings))]
47use lightning::io::Error;
48use lightning::ln::channelmanager::AChannelManager;
49use lightning::ln::msgs::OnionMessageHandler;
50use lightning::ln::peer_handler::APeerManager;
51use lightning::onion_message::messenger::AOnionMessenger;
52use lightning::routing::gossip::{NetworkGraph, P2PGossipSync};
53use lightning::routing::scoring::{ScoreUpdate, WriteableScore};
54use lightning::routing::utxo::UtxoLookup;
55#[cfg(not(c_bindings))]
56use lightning::sign::EntropySource;
57use lightning::sign::{ChangeDestinationSource, ChangeDestinationSourceSync, OutputSpender};
58use lightning::util::logger::Logger;
59#[cfg(not(c_bindings))]
60use lightning::util::native_async::MaybeSend;
61use lightning::util::persist::{
62	KVStore, KVStoreSync, KVStoreSyncWrapper, CHANNEL_MANAGER_PERSISTENCE_KEY,
63	CHANNEL_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE, CHANNEL_MANAGER_PERSISTENCE_SECONDARY_NAMESPACE,
64	NETWORK_GRAPH_PERSISTENCE_KEY, NETWORK_GRAPH_PERSISTENCE_PRIMARY_NAMESPACE,
65	NETWORK_GRAPH_PERSISTENCE_SECONDARY_NAMESPACE, SCORER_PERSISTENCE_KEY,
66	SCORER_PERSISTENCE_PRIMARY_NAMESPACE, SCORER_PERSISTENCE_SECONDARY_NAMESPACE,
67};
68use lightning::util::sweep::{OutputSweeper, OutputSweeperSync};
69use lightning::util::wakers::Future;
70#[cfg(feature = "std")]
71use lightning::util::wakers::Sleeper;
72use lightning_rapid_gossip_sync::RapidGossipSync;
73
74use lightning_liquidity::ALiquidityManager;
75#[cfg(feature = "std")]
76use lightning_liquidity::ALiquidityManagerSync;
77
78use core::ops::Deref;
79use core::time::Duration;
80
81#[cfg(feature = "std")]
82use core::sync::atomic::{AtomicBool, Ordering};
83#[cfg(feature = "std")]
84use std::sync::Arc;
85#[cfg(feature = "std")]
86use std::thread::{self, JoinHandle};
87#[cfg(feature = "std")]
88use std::time::Instant;
89
90#[cfg(not(feature = "std"))]
91use alloc::boxed::Box;
92#[cfg(all(not(c_bindings), not(feature = "std")))]
93use alloc::string::String;
94#[cfg(all(not(c_bindings), not(feature = "std")))]
95use alloc::sync::Arc;
96#[cfg(all(not(c_bindings), not(feature = "std")))]
97use alloc::vec::Vec;
98
99/// `BackgroundProcessor` takes care of tasks that (1) need to happen periodically to keep
100/// Rust-Lightning running properly, and (2) either can or should be run in the background. Its
101/// responsibilities are:
102/// * Processing [`Event`]s with a user-provided [`EventHandler`].
103/// * Monitoring whether the [`ChannelManager`] needs to be re-persisted to disk, and if so,
104///   writing it to disk/backups by invoking the callback given to it at startup.
105///   [`ChannelManager`] persistence should be done in the background.
106/// * Calling [`ChannelManager::timer_tick_occurred`], [`ChainMonitor::rebroadcast_pending_claims`]
107///   and [`PeerManager::timer_tick_occurred`] at the appropriate intervals.
108/// * Calling [`NetworkGraph::remove_stale_channels_and_tracking`] (if a [`GossipSync`] with a
109///   [`NetworkGraph`] is provided to [`BackgroundProcessor::start`]).
110///
111/// It will also call [`PeerManager::process_events`] periodically though this shouldn't be relied
112/// upon as doing so may result in high latency.
113///
114/// # Note
115///
116/// If [`ChannelManager`] persistence fails and the persisted manager becomes out-of-date, then
117/// there is a risk of channels force-closing on startup when the manager realizes it's outdated.
118/// However, as long as [`ChannelMonitor`] backups are sound, no funds besides those used for
119/// unilateral chain closure fees are at risk.
120///
121/// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
122/// [`ChannelManager::timer_tick_occurred`]: lightning::ln::channelmanager::ChannelManager::timer_tick_occurred
123/// [`ChainMonitor::rebroadcast_pending_claims`]: lightning::chain::chainmonitor::ChainMonitor::rebroadcast_pending_claims
124/// [`ChannelMonitor`]: lightning::chain::channelmonitor::ChannelMonitor
125/// [`Event`]: lightning::events::Event
126/// [`PeerManager::timer_tick_occurred`]: lightning::ln::peer_handler::PeerManager::timer_tick_occurred
127/// [`PeerManager::process_events`]: lightning::ln::peer_handler::PeerManager::process_events
128#[cfg(feature = "std")]
129#[must_use = "BackgroundProcessor will immediately stop on drop. It should be stored until shutdown."]
130pub struct BackgroundProcessor {
131	stop_thread: Arc<AtomicBool>,
132	thread_handle: Option<JoinHandle<Result<(), std::io::Error>>>,
133}
134
135#[cfg(not(test))]
136const FRESHNESS_TIMER: Duration = Duration::from_secs(60);
137#[cfg(test)]
138const FRESHNESS_TIMER: Duration = Duration::from_secs(1);
139
140#[cfg(all(not(test), not(debug_assertions)))]
141const PING_TIMER: Duration = Duration::from_secs(10);
142/// Signature operations take a lot longer without compiler optimisations.
143/// Increasing the ping timer allows for this but slower devices will be disconnected if the
144/// timeout is reached.
145#[cfg(all(not(test), debug_assertions))]
146const PING_TIMER: Duration = Duration::from_secs(30);
147#[cfg(test)]
148const PING_TIMER: Duration = Duration::from_secs(1);
149
150#[cfg(not(test))]
151const ONION_MESSAGE_HANDLER_TIMER: Duration = Duration::from_secs(10);
152#[cfg(test)]
153const ONION_MESSAGE_HANDLER_TIMER: Duration = Duration::from_secs(1);
154
155/// Prune the network graph of stale entries hourly.
156const NETWORK_PRUNE_TIMER: Duration = Duration::from_secs(60 * 60);
157
158#[cfg(not(test))]
159const SCORER_PERSIST_TIMER: Duration = Duration::from_secs(60 * 5);
160#[cfg(test)]
161const SCORER_PERSIST_TIMER: Duration = Duration::from_secs(1);
162
163#[cfg(not(test))]
164const FIRST_NETWORK_PRUNE_TIMER: Duration = Duration::from_secs(60);
165#[cfg(test)]
166const FIRST_NETWORK_PRUNE_TIMER: Duration = Duration::from_secs(1);
167
168#[cfg(not(test))]
169const REBROADCAST_TIMER: Duration = Duration::from_secs(30);
170#[cfg(test)]
171const REBROADCAST_TIMER: Duration = Duration::from_secs(1);
172
173#[cfg(not(test))]
174const SWEEPER_TIMER: Duration = Duration::from_secs(30);
175#[cfg(test)]
176const SWEEPER_TIMER: Duration = Duration::from_secs(1);
177
178#[cfg(not(test))]
179const FIRST_ARCHIVE_STALE_MONITORS_TIMER: Duration = Duration::from_secs(15);
180#[cfg(test)]
181const FIRST_ARCHIVE_STALE_MONITORS_TIMER: Duration = Duration::ZERO;
182
183#[cfg(not(test))]
184const ARCHIVE_STALE_MONITORS_TIMER: Duration = Duration::from_secs(60 * 10);
185#[cfg(test)]
186const ARCHIVE_STALE_MONITORS_TIMER: Duration = Duration::from_secs(1);
187
188/// core::cmp::min is not currently const, so we define a trivial (and equivalent) replacement
189const fn min_duration(a: Duration, b: Duration) -> Duration {
190	if a.as_nanos() < b.as_nanos() {
191		a
192	} else {
193		b
194	}
195}
196const FASTEST_TIMER: Duration = min_duration(
197	min_duration(FRESHNESS_TIMER, PING_TIMER),
198	min_duration(SCORER_PERSIST_TIMER, min_duration(FIRST_NETWORK_PRUNE_TIMER, REBROADCAST_TIMER)),
199);
200
201/// Either [`P2PGossipSync`] or [`RapidGossipSync`].
202pub enum GossipSync<
203	P: Deref<Target = P2PGossipSync<G, U, L>>,
204	R: Deref<Target = RapidGossipSync<G, L>>,
205	G: Deref<Target = NetworkGraph<L>>,
206	U: UtxoLookup,
207	L: Logger,
208> {
209	/// Gossip sync via the lightning peer-to-peer network as defined by BOLT 7.
210	P2P(P),
211	/// Rapid gossip sync from a trusted server.
212	Rapid(R),
213	/// No gossip sync.
214	None,
215}
216
217impl<
218		P: Deref<Target = P2PGossipSync<G, U, L>>,
219		R: Deref<Target = RapidGossipSync<G, L>>,
220		G: Deref<Target = NetworkGraph<L>>,
221		U: UtxoLookup,
222		L: Logger,
223	> GossipSync<P, R, G, U, L>
224{
225	fn network_graph(&self) -> Option<&G> {
226		match self {
227			GossipSync::P2P(gossip_sync) => Some(gossip_sync.network_graph()),
228			GossipSync::Rapid(gossip_sync) => Some(gossip_sync.network_graph()),
229			GossipSync::None => None,
230		}
231	}
232
233	fn prunable_network_graph(&self) -> Option<&G> {
234		match self {
235			GossipSync::P2P(gossip_sync) => Some(gossip_sync.network_graph()),
236			GossipSync::Rapid(gossip_sync) => {
237				if gossip_sync.is_initial_sync_complete() {
238					Some(gossip_sync.network_graph())
239				} else {
240					None
241				}
242			},
243			GossipSync::None => None,
244		}
245	}
246
247	fn validation_completion_future(&self) -> Option<Future> {
248		match self {
249			GossipSync::P2P(gossip_sync) => Some(gossip_sync.validation_completion_future()),
250			GossipSync::Rapid(_) => None,
251			GossipSync::None => None,
252		}
253	}
254}
255
256/// This is not exported to bindings users as the bindings concretize everything and have constructors for us
257impl<
258		P: Deref<Target = P2PGossipSync<G, U, L>>,
259		G: Deref<Target = NetworkGraph<L>>,
260		U: UtxoLookup,
261		L: Logger,
262	> GossipSync<P, &RapidGossipSync<G, L>, G, U, L>
263{
264	/// Initializes a new [`GossipSync::P2P`] variant.
265	pub fn p2p(gossip_sync: P) -> Self {
266		GossipSync::P2P(gossip_sync)
267	}
268}
269
270/// This is not exported to bindings users as the bindings concretize everything and have constructors for us
271impl<
272		'a,
273		R: Deref<Target = RapidGossipSync<G, L>>,
274		G: Deref<Target = NetworkGraph<L>>,
275		L: Logger,
276	>
277	GossipSync<
278		&P2PGossipSync<G, &'a (dyn UtxoLookup + Send + Sync), L>,
279		R,
280		G,
281		&'a (dyn UtxoLookup + Send + Sync),
282		L,
283	>
284{
285	/// Initializes a new [`GossipSync::Rapid`] variant.
286	pub fn rapid(gossip_sync: R) -> Self {
287		GossipSync::Rapid(gossip_sync)
288	}
289}
290
291/// This is not exported to bindings users as the bindings concretize everything and have constructors for us
292impl<'a, L: Logger>
293	GossipSync<
294		&P2PGossipSync<&'a NetworkGraph<L>, &'a (dyn UtxoLookup + Send + Sync), L>,
295		&RapidGossipSync<&'a NetworkGraph<L>, L>,
296		&'a NetworkGraph<L>,
297		&'a (dyn UtxoLookup + Send + Sync),
298		L,
299	>
300{
301	/// Initializes a new [`GossipSync::None`] variant.
302	pub fn none() -> Self {
303		GossipSync::None
304	}
305}
306
307fn handle_network_graph_update<L: Logger>(network_graph: &NetworkGraph<L>, event: &Event) {
308	if let Event::PaymentPathFailed {
309		failure: PathFailure::OnPath { network_update: Some(ref upd) },
310		..
311	} = event
312	{
313		network_graph.handle_network_update(upd);
314	}
315}
316
317/// Updates scorer based on event and returns whether an update occurred so we can decide whether
318/// to persist.
319fn update_scorer<'a, S: Deref<Target = SC>, SC: 'a + WriteableScore<'a>>(
320	scorer: &'a S, event: &Event, duration_since_epoch: Duration,
321) -> bool {
322	match event {
323		Event::PaymentPathFailed { ref path, short_channel_id: Some(scid), .. } => {
324			let mut score = scorer.write_lock();
325			score.payment_path_failed(path, *scid, duration_since_epoch);
326		},
327		Event::PaymentPathFailed { ref path, payment_failed_permanently: true, .. } => {
328			// Reached if the destination explicitly failed it back. We treat this as a successful probe
329			// because the payment made it all the way to the destination with sufficient liquidity.
330			let mut score = scorer.write_lock();
331			score.probe_successful(path, duration_since_epoch);
332		},
333		Event::PaymentPathSuccessful { path, .. } => {
334			let mut score = scorer.write_lock();
335			score.payment_path_successful(path, duration_since_epoch);
336		},
337		Event::ProbeSuccessful { path, .. } => {
338			let mut score = scorer.write_lock();
339			score.probe_successful(path, duration_since_epoch);
340		},
341		Event::ProbeFailed { path, short_channel_id: Some(scid), .. } => {
342			let mut score = scorer.write_lock();
343			score.probe_failed(path, *scid, duration_since_epoch);
344		},
345		_ => return false,
346	}
347	true
348}
349
350#[cfg(all(not(c_bindings), feature = "std"))]
351type ScorerWrapper<T> = std::sync::RwLock<T>;
352
353#[cfg(all(not(c_bindings), not(feature = "std")))]
354type ScorerWrapper<T> = core::cell::RefCell<T>;
355
356#[cfg(not(c_bindings))]
357type DynRouter = lightning::routing::router::DefaultRouter<
358	&'static NetworkGraph<&'static (dyn Logger + Send + Sync)>,
359	&'static (dyn Logger + Send + Sync),
360	&'static (dyn EntropySource + Send + Sync),
361	&'static ScorerWrapper<
362		lightning::routing::scoring::ProbabilisticScorer<
363			&'static NetworkGraph<&'static (dyn Logger + Send + Sync)>,
364			&'static (dyn Logger + Send + Sync),
365		>,
366	>,
367	lightning::routing::scoring::ProbabilisticScoringFeeParameters,
368	lightning::routing::scoring::ProbabilisticScorer<
369		&'static NetworkGraph<&'static (dyn Logger + Send + Sync)>,
370		&'static (dyn Logger + Send + Sync),
371	>,
372>;
373
374#[cfg(not(c_bindings))]
375type DynMessageRouter = lightning::onion_message::messenger::DefaultMessageRouter<
376	&'static NetworkGraph<&'static (dyn Logger + Send + Sync)>,
377	&'static (dyn Logger + Send + Sync),
378	&'static (dyn EntropySource + Send + Sync),
379>;
380
381#[cfg(not(c_bindings))]
382type DynSignerProvider = dyn lightning::sign::SignerProvider<EcdsaSigner = lightning::sign::InMemorySigner>
383	+ Send
384	+ Sync;
385
386#[cfg(not(c_bindings))]
387type DynChannelManager = lightning::ln::channelmanager::ChannelManager<
388	&'static (dyn chain::Watch<lightning::sign::InMemorySigner> + Send + Sync),
389	&'static (dyn BroadcasterInterface + Send + Sync),
390	&'static (dyn EntropySource + Send + Sync),
391	&'static (dyn lightning::sign::NodeSigner + Send + Sync),
392	&'static DynSignerProvider,
393	&'static (dyn FeeEstimator + Send + Sync),
394	&'static DynRouter,
395	&'static DynMessageRouter,
396	&'static (dyn Logger + Send + Sync),
397>;
398
399/// When initializing a background processor without an onion messenger, this can be used to avoid
400/// specifying a concrete `OnionMessenger` type.
401#[cfg(not(c_bindings))]
402pub const NO_ONION_MESSENGER: Option<
403	Arc<
404		dyn AOnionMessenger<
405				EntropySource = &(dyn EntropySource + Send + Sync),
406				NodeSigner = &(dyn lightning::sign::NodeSigner + Send + Sync),
407				Logger = &'static (dyn Logger + Send + Sync),
408				NL = &'static DynChannelManager,
409				MessageRouter = &'static DynMessageRouter,
410				OMH = lightning::ln::peer_handler::IgnoringMessageHandler,
411				APH = lightning::ln::peer_handler::IgnoringMessageHandler,
412				DRH = lightning::ln::peer_handler::IgnoringMessageHandler,
413				CMH = lightning::ln::peer_handler::IgnoringMessageHandler,
414			> + Send
415			+ Sync,
416	>,
417> = None;
418
419#[cfg(not(c_bindings))]
420/// A panicking implementation of [`KVStore`] that is used in [`NO_LIQUIDITY_MANAGER`].
421pub struct DummyKVStore;
422
423#[cfg(not(c_bindings))]
424impl KVStore for DummyKVStore {
425	fn read(
426		&self, _: &str, _: &str, _: &str,
427	) -> impl core::future::Future<Output = Result<Vec<u8>, Error>> + MaybeSend + 'static {
428		async { unimplemented!() }
429	}
430
431	fn write(
432		&self, _: &str, _: &str, _: &str, _: Vec<u8>,
433	) -> impl core::future::Future<Output = Result<(), Error>> + MaybeSend + 'static {
434		async { unimplemented!() }
435	}
436
437	fn remove(
438		&self, _: &str, _: &str, _: &str, _: bool,
439	) -> impl core::future::Future<Output = Result<(), Error>> + MaybeSend + 'static {
440		async { unimplemented!() }
441	}
442
443	fn list(
444		&self, _: &str, _: &str,
445	) -> impl core::future::Future<Output = Result<Vec<String>, Error>> + MaybeSend + 'static {
446		async { unimplemented!() }
447	}
448}
449
450/// When initializing a background processor without a liquidity manager, this can be used to avoid
451/// specifying a concrete `LiquidityManager` type.
452#[cfg(not(c_bindings))]
453pub const NO_LIQUIDITY_MANAGER: Option<
454	Arc<
455		dyn ALiquidityManager<
456				EntropySource = &(dyn EntropySource + Send + Sync),
457				NodeSigner = &(dyn lightning::sign::NodeSigner + Send + Sync),
458				AChannelManager = DynChannelManager,
459				CM = &DynChannelManager,
460				K = &DummyKVStore,
461				TimeProvider = dyn lightning_liquidity::utils::time::TimeProvider + Send + Sync,
462				TP = &(dyn lightning_liquidity::utils::time::TimeProvider + Send + Sync),
463				BroadcasterInterface = &(dyn lightning::chain::chaininterface::BroadcasterInterface
464					+ Send
465					+ Sync),
466			> + Send
467			+ Sync,
468	>,
469> = None;
470
471/// When initializing a background processor without a liquidity manager, this can be used to avoid
472/// specifying a concrete `LiquidityManagerSync` type.
473#[cfg(all(not(c_bindings), feature = "std"))]
474pub const NO_LIQUIDITY_MANAGER_SYNC: Option<
475	Arc<
476		dyn ALiquidityManagerSync<
477				EntropySource = &(dyn EntropySource + Send + Sync),
478				NodeSigner = &(dyn lightning::sign::NodeSigner + Send + Sync),
479				AChannelManager = DynChannelManager,
480				CM = &DynChannelManager,
481				KVStoreSync = dyn lightning::util::persist::KVStoreSync + Send + Sync,
482				KS = &(dyn lightning::util::persist::KVStoreSync + Send + Sync),
483				TimeProvider = dyn lightning_liquidity::utils::time::TimeProvider + Send + Sync,
484				TP = &(dyn lightning_liquidity::utils::time::TimeProvider + Send + Sync),
485				BroadcasterInterface = &(dyn lightning::chain::chaininterface::BroadcasterInterface
486					+ Send
487					+ Sync),
488			> + Send
489			+ Sync,
490	>,
491> = None;
492
493pub(crate) mod futures_util {
494	use core::future::Future;
495	use core::marker::Unpin;
496	use core::pin::Pin;
497	use core::task::{Poll, RawWaker, RawWakerVTable, Waker};
498	pub(crate) struct Selector<
499		A: Future<Output = bool> + Unpin,
500		B: Future<Output = ()> + Unpin,
501		C: Future<Output = ()> + Unpin,
502		D: Future<Output = ()> + Unpin,
503		E: Future<Output = ()> + Unpin,
504		F: Future<Output = ()> + Unpin,
505	> {
506		pub a: A,
507		pub b: B,
508		pub c: C,
509		pub d: D,
510		pub e: E,
511		pub f: F,
512	}
513
514	pub(crate) enum SelectorOutput {
515		A(bool),
516		B,
517		C,
518		D,
519		E,
520		F,
521	}
522
523	impl<
524			A: Future<Output = bool> + Unpin,
525			B: Future<Output = ()> + Unpin,
526			C: Future<Output = ()> + Unpin,
527			D: Future<Output = ()> + Unpin,
528			E: Future<Output = ()> + Unpin,
529			F: Future<Output = ()> + Unpin,
530		> Future for Selector<A, B, C, D, E, F>
531	{
532		type Output = SelectorOutput;
533		fn poll(
534			mut self: Pin<&mut Self>, ctx: &mut core::task::Context<'_>,
535		) -> Poll<SelectorOutput> {
536			// Bias the selector so it first polls the sleeper future, allowing to exit immediately
537			// if the flag is set.
538			match Pin::new(&mut self.a).poll(ctx) {
539				Poll::Ready(res) => {
540					return Poll::Ready(SelectorOutput::A(res));
541				},
542				Poll::Pending => {},
543			}
544			match Pin::new(&mut self.b).poll(ctx) {
545				Poll::Ready(()) => {
546					return Poll::Ready(SelectorOutput::B);
547				},
548				Poll::Pending => {},
549			}
550			match Pin::new(&mut self.c).poll(ctx) {
551				Poll::Ready(()) => {
552					return Poll::Ready(SelectorOutput::C);
553				},
554				Poll::Pending => {},
555			}
556			match Pin::new(&mut self.d).poll(ctx) {
557				Poll::Ready(()) => {
558					return Poll::Ready(SelectorOutput::D);
559				},
560				Poll::Pending => {},
561			}
562			match Pin::new(&mut self.e).poll(ctx) {
563				Poll::Ready(()) => {
564					return Poll::Ready(SelectorOutput::E);
565				},
566				Poll::Pending => {},
567			}
568			match Pin::new(&mut self.f).poll(ctx) {
569				Poll::Ready(()) => {
570					return Poll::Ready(SelectorOutput::F);
571				},
572				Poll::Pending => {},
573			}
574			Poll::Pending
575		}
576	}
577
578	/// A selector that takes a future wrapped in an option that will be polled if it is `Some` and
579	/// will always be pending otherwise.
580	pub(crate) struct OptionalSelector<F: Future<Output = ()> + Unpin> {
581		pub optional_future: Option<F>,
582	}
583
584	impl<F: Future<Output = ()> + Unpin> Future for OptionalSelector<F> {
585		type Output = ();
586		fn poll(mut self: Pin<&mut Self>, ctx: &mut core::task::Context<'_>) -> Poll<Self::Output> {
587			match self.optional_future.as_mut() {
588				Some(f) => match Pin::new(f).poll(ctx) {
589					Poll::Ready(()) => {
590						self.optional_future.take();
591						Poll::Ready(())
592					},
593					Poll::Pending => Poll::Pending,
594				},
595				None => Poll::Pending,
596			}
597		}
598	}
599
600	impl<F: Future<Output = ()> + Unpin> From<Option<F>> for OptionalSelector<F> {
601		fn from(optional_future: Option<F>) -> Self {
602			Self { optional_future }
603		}
604	}
605
606	// If we want to poll a future without an async context to figure out if it has completed or
607	// not without awaiting, we need a Waker, which needs a vtable...we fill it with dummy values
608	// but sadly there's a good bit of boilerplate here.
609	fn dummy_waker_clone(_: *const ()) -> RawWaker {
610		RawWaker::new(core::ptr::null(), &DUMMY_WAKER_VTABLE)
611	}
612	fn dummy_waker_action(_: *const ()) {}
613
614	const DUMMY_WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new(
615		dummy_waker_clone,
616		dummy_waker_action,
617		dummy_waker_action,
618		dummy_waker_action,
619	);
620	pub(crate) fn dummy_waker() -> Waker {
621		unsafe { Waker::from_raw(RawWaker::new(core::ptr::null(), &DUMMY_WAKER_VTABLE)) }
622	}
623
624	enum JoinerResult<ERR, F: Future<Output = Result<(), ERR>> + Unpin> {
625		Pending(Option<F>),
626		Ready(Result<(), ERR>),
627	}
628
629	pub(crate) struct Joiner<
630		ERR,
631		A: Future<Output = Result<(), ERR>> + Unpin,
632		B: Future<Output = Result<(), ERR>> + Unpin,
633		C: Future<Output = Result<(), ERR>> + Unpin,
634		D: Future<Output = Result<(), ERR>> + Unpin,
635		E: Future<Output = Result<(), ERR>> + Unpin,
636	> {
637		a: JoinerResult<ERR, A>,
638		b: JoinerResult<ERR, B>,
639		c: JoinerResult<ERR, C>,
640		d: JoinerResult<ERR, D>,
641		e: JoinerResult<ERR, E>,
642	}
643
644	impl<
645			ERR,
646			A: Future<Output = Result<(), ERR>> + Unpin,
647			B: Future<Output = Result<(), ERR>> + Unpin,
648			C: Future<Output = Result<(), ERR>> + Unpin,
649			D: Future<Output = Result<(), ERR>> + Unpin,
650			E: Future<Output = Result<(), ERR>> + Unpin,
651		> Joiner<ERR, A, B, C, D, E>
652	{
653		pub(crate) fn new() -> Self {
654			Self {
655				a: JoinerResult::Pending(None),
656				b: JoinerResult::Pending(None),
657				c: JoinerResult::Pending(None),
658				d: JoinerResult::Pending(None),
659				e: JoinerResult::Pending(None),
660			}
661		}
662
663		pub(crate) fn set_a(&mut self, fut: A) {
664			self.a = JoinerResult::Pending(Some(fut));
665		}
666		pub(crate) fn set_a_res(&mut self, res: Result<(), ERR>) {
667			self.a = JoinerResult::Ready(res);
668		}
669		pub(crate) fn set_b(&mut self, fut: B) {
670			self.b = JoinerResult::Pending(Some(fut));
671		}
672		pub(crate) fn set_c(&mut self, fut: C) {
673			self.c = JoinerResult::Pending(Some(fut));
674		}
675		pub(crate) fn set_d(&mut self, fut: D) {
676			self.d = JoinerResult::Pending(Some(fut));
677		}
678		pub(crate) fn set_e(&mut self, fut: E) {
679			self.e = JoinerResult::Pending(Some(fut));
680		}
681	}
682
683	impl<
684			ERR,
685			A: Future<Output = Result<(), ERR>> + Unpin,
686			B: Future<Output = Result<(), ERR>> + Unpin,
687			C: Future<Output = Result<(), ERR>> + Unpin,
688			D: Future<Output = Result<(), ERR>> + Unpin,
689			E: Future<Output = Result<(), ERR>> + Unpin,
690		> Future for Joiner<ERR, A, B, C, D, E>
691	where
692		Joiner<ERR, A, B, C, D, E>: Unpin,
693	{
694		type Output = [Result<(), ERR>; 5];
695		fn poll(mut self: Pin<&mut Self>, ctx: &mut core::task::Context<'_>) -> Poll<Self::Output> {
696			let mut all_complete = true;
697			macro_rules! handle {
698				($val: ident) => {
699					match &mut (self.$val) {
700						JoinerResult::Pending(None) => {
701							self.$val = JoinerResult::Ready(Ok(()));
702						},
703						JoinerResult::<ERR, _>::Pending(Some(ref mut val)) => {
704							match Pin::new(val).poll(ctx) {
705								Poll::Ready(res) => {
706									self.$val = JoinerResult::Ready(res);
707								},
708								Poll::Pending => {
709									all_complete = false;
710								},
711							}
712						},
713						JoinerResult::Ready(_) => {},
714					}
715				};
716			}
717			handle!(a);
718			handle!(b);
719			handle!(c);
720			handle!(d);
721			handle!(e);
722
723			if all_complete {
724				let mut res = [Ok(()), Ok(()), Ok(()), Ok(()), Ok(())];
725				if let JoinerResult::Ready(ref mut val) = &mut self.a {
726					core::mem::swap(&mut res[0], val);
727				}
728				if let JoinerResult::Ready(ref mut val) = &mut self.b {
729					core::mem::swap(&mut res[1], val);
730				}
731				if let JoinerResult::Ready(ref mut val) = &mut self.c {
732					core::mem::swap(&mut res[2], val);
733				}
734				if let JoinerResult::Ready(ref mut val) = &mut self.d {
735					core::mem::swap(&mut res[3], val);
736				}
737				if let JoinerResult::Ready(ref mut val) = &mut self.e {
738					core::mem::swap(&mut res[4], val);
739				}
740				Poll::Ready(res)
741			} else {
742				Poll::Pending
743			}
744		}
745	}
746}
747use core::task;
748use futures_util::{dummy_waker, Joiner, OptionalSelector, Selector, SelectorOutput};
749
750/// Processes background events in a future.
751///
752/// `sleeper` should return a future which completes in the given amount of time and returns a
753/// boolean indicating whether the background processing should exit. Once `sleeper` returns a
754/// future which outputs `true`, the loop will exit and this function's future will complete.
755/// The `sleeper` future is free to return early after it has triggered the exit condition.
756///
757#[cfg_attr(
758	feature = "std",
759	doc = " See [`BackgroundProcessor::start`] for information on which actions this handles.\n"
760)]
761/// The `mobile_interruptable_platform` flag should be set if we're currently running on a
762/// mobile device, where we may need to check for interruption of the application regularly. If you
763/// are unsure, you should set the flag, as the performance impact of it is minimal unless there
764/// are hundreds or thousands of simultaneous process calls running.
765///
766/// The `fetch_time` parameter should return the current wall clock time, if one is available. If
767/// no time is available, some features may be disabled, however the node will still operate fine.
768///
769/// Note that when deferred monitor writes are enabled on [`ChainMonitor`], this function flushes
770/// pending writes after persisting the [`ChannelManager`]. If the [`Persist`] implementation
771/// performs blocking I/O and returns [`Completed`] synchronously rather than returning
772/// [`InProgress`], this will block the async executor.
773///
774/// [`ChainMonitor`]: lightning::chain::chainmonitor::ChainMonitor
775/// [`Persist`]: lightning::chain::chainmonitor::Persist
776/// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
777/// [`Completed`]: lightning::chain::ChannelMonitorUpdateStatus::Completed
778/// [`InProgress`]: lightning::chain::ChannelMonitorUpdateStatus::InProgress
779///
780/// For example, in order to process background events in a [Tokio](https://tokio.rs/) task, you
781/// could setup `process_events_async` like this:
782/// ```
783/// # use lightning::io;
784/// # use lightning::events::ReplayEvent;
785/// # use std::sync::{Arc, RwLock};
786/// # use std::sync::atomic::{AtomicBool, Ordering};
787/// # use std::time::SystemTime;
788/// # use lightning_background_processor::{process_events_async, GossipSync};
789/// # use core::future::Future;
790/// # use core::pin::Pin;
791/// # use lightning_liquidity::utils::time::TimeProvider;
792/// # struct Logger {}
793/// # impl lightning::util::logger::Logger for Logger {
794/// #     fn log(&self, _record: lightning::util::logger::Record) {}
795/// # }
796/// # struct StoreSync {}
797/// # impl lightning::util::persist::KVStoreSync for StoreSync {
798/// #     fn read(&self, primary_namespace: &str, secondary_namespace: &str, key: &str) -> io::Result<Vec<u8>> { Ok(Vec::new()) }
799/// #     fn write(&self, primary_namespace: &str, secondary_namespace: &str, key: &str, buf: Vec<u8>) -> io::Result<()> { Ok(()) }
800/// #     fn remove(&self, primary_namespace: &str, secondary_namespace: &str, key: &str, lazy: bool) -> io::Result<()> { Ok(()) }
801/// #     fn list(&self, primary_namespace: &str, secondary_namespace: &str) -> io::Result<Vec<String>> { Ok(Vec::new()) }
802/// # }
803/// # struct Store {}
804/// # impl lightning::util::persist::KVStore for Store {
805/// #     fn read(&self, primary_namespace: &str, secondary_namespace: &str, key: &str) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, io::Error>> + 'static + Send>> { todo!() }
806/// #     fn write(&self, primary_namespace: &str, secondary_namespace: &str, key: &str, buf: Vec<u8>) -> Pin<Box<dyn Future<Output = Result<(), io::Error>> + 'static + Send>> { todo!() }
807/// #     fn remove(&self, primary_namespace: &str, secondary_namespace: &str, key: &str, lazy: bool) -> Pin<Box<dyn Future<Output = Result<(), io::Error>> + 'static + Send>> { todo!() }
808/// #     fn list(&self, primary_namespace: &str, secondary_namespace: &str) -> Pin<Box<dyn Future<Output = Result<Vec<String>, io::Error>> + 'static + Send>> { todo!() }
809/// # }
810/// # use core::time::Duration;
811/// # struct DefaultTimeProvider;
812/// #
813/// # impl TimeProvider for DefaultTimeProvider {
814/// #    fn duration_since_epoch(&self) -> Duration {
815/// #        use std::time::{SystemTime, UNIX_EPOCH};
816/// #        SystemTime::now().duration_since(UNIX_EPOCH).expect("system time before Unix epoch")
817/// #    }
818/// # }
819/// # struct EventHandler {}
820/// # impl EventHandler {
821/// #     async fn handle_event(&self, _: lightning::events::Event) -> Result<(), ReplayEvent> { Ok(()) }
822/// # }
823/// # #[derive(Eq, PartialEq, Clone, Hash)]
824/// # struct SocketDescriptor {}
825/// # impl lightning::ln::peer_handler::SocketDescriptor for SocketDescriptor {
826/// #     fn send_data(&mut self, _data: &[u8], _continue_read: bool) -> usize { 0 }
827/// #     fn disconnect_socket(&mut self) {}
828/// # }
829/// # type ChainMonitor<B, F, FE> = lightning::chain::chainmonitor::ChainMonitor<lightning::sign::InMemorySigner, Arc<F>, Arc<B>, Arc<FE>, Arc<Logger>, Arc<StoreSync>, Arc<lightning::sign::KeysManager>>;
830/// # type NetworkGraph = lightning::routing::gossip::NetworkGraph<Arc<Logger>>;
831/// # type P2PGossipSync<UL> = lightning::routing::gossip::P2PGossipSync<Arc<NetworkGraph>, Arc<UL>, Arc<Logger>>;
832/// # type ChannelManager<B, F, FE> = lightning::ln::channelmanager::SimpleArcChannelManager<ChainMonitor<B, F, FE>, B, FE, Logger>;
833/// # type OnionMessenger<B, F, FE> = lightning::onion_message::messenger::OnionMessenger<Arc<lightning::sign::KeysManager>, Arc<lightning::sign::KeysManager>, Arc<Logger>, Arc<ChannelManager<B, F, FE>>, Arc<lightning::onion_message::messenger::DefaultMessageRouter<Arc<NetworkGraph>, Arc<Logger>, Arc<lightning::sign::KeysManager>>>, Arc<ChannelManager<B, F, FE>>, lightning::ln::peer_handler::IgnoringMessageHandler, lightning::ln::peer_handler::IgnoringMessageHandler, lightning::ln::peer_handler::IgnoringMessageHandler>;
834/// # type LiquidityManager<B, F, FE> = lightning_liquidity::LiquidityManager<Arc<lightning::sign::KeysManager>, Arc<lightning::sign::KeysManager>, Arc<ChannelManager<B, F, FE>>, Arc<Store>, Arc<DefaultTimeProvider>, Arc<B>>;
835/// # type Scorer = RwLock<lightning::routing::scoring::ProbabilisticScorer<Arc<NetworkGraph>, Arc<Logger>>>;
836/// # type PeerManager<B, F, FE, UL> = lightning::ln::peer_handler::SimpleArcPeerManager<SocketDescriptor, ChainMonitor<B, F, FE>, B, FE, Arc<UL>, Logger, F, StoreSync>;
837/// # type OutputSweeper<B, D, FE, F, O> = lightning::util::sweep::OutputSweeper<Arc<B>, Arc<D>, Arc<FE>, Arc<F>, Arc<Store>, Arc<Logger>, Arc<O>>;
838///
839/// # struct Node<
840/// #     B: lightning::chain::chaininterface::BroadcasterInterface + Send + Sync + 'static,
841/// #     F: lightning::chain::Filter + Send + Sync + 'static,
842/// #     FE: lightning::chain::chaininterface::FeeEstimator + Send + Sync + 'static,
843/// #     UL: lightning::routing::utxo::UtxoLookup + Send + Sync + 'static,
844/// #     D: lightning::sign::ChangeDestinationSource + Send + Sync + 'static,
845/// #     O: lightning::sign::OutputSpender + Send + Sync + 'static,
846/// # > {
847/// #     peer_manager: Arc<PeerManager<B, F, FE, UL>>,
848/// #     event_handler: Arc<EventHandler>,
849/// #     channel_manager: Arc<ChannelManager<B, F, FE>>,
850/// #     onion_messenger: Arc<OnionMessenger<B, F, FE>>,
851/// #     liquidity_manager: Arc<LiquidityManager<B, F, FE>>,
852/// #     chain_monitor: Arc<ChainMonitor<B, F, FE>>,
853/// #     gossip_sync: Arc<P2PGossipSync<UL>>,
854/// #     persister: Arc<Store>,
855/// #     logger: Arc<Logger>,
856/// #     scorer: Arc<Scorer>,
857/// #     sweeper: Arc<OutputSweeper<B, D, FE, F, O>>,
858/// # }
859/// #
860/// # async fn setup_background_processing<
861/// #     B: lightning::chain::chaininterface::BroadcasterInterface + Send + Sync + 'static,
862/// #     F: lightning::chain::Filter + Send + Sync + 'static,
863/// #     FE: lightning::chain::chaininterface::FeeEstimator + Send + Sync + 'static,
864/// #     UL: lightning::routing::utxo::UtxoLookup + Send + Sync + 'static,
865/// #     D: lightning::sign::ChangeDestinationSource + Send + Sync + 'static,
866/// #     O: lightning::sign::OutputSpender + Send + Sync + 'static,
867/// # >(node: Node<B, F, FE, UL, D, O>) {
868///	let background_persister = Arc::clone(&node.persister);
869///	let background_event_handler = Arc::clone(&node.event_handler);
870///	let background_chain_mon = Arc::clone(&node.chain_monitor);
871///	let background_chan_man = Arc::clone(&node.channel_manager);
872///	let background_gossip_sync = GossipSync::p2p(Arc::clone(&node.gossip_sync));
873///	let background_peer_man = Arc::clone(&node.peer_manager);
874///	let background_onion_messenger = Arc::clone(&node.onion_messenger);
875///	let background_liquidity_manager = Arc::clone(&node.liquidity_manager);
876///	let background_logger = Arc::clone(&node.logger);
877///	let background_scorer = Arc::clone(&node.scorer);
878///	let background_sweeper = Arc::clone(&node.sweeper);
879///	// Setup the sleeper.
880#[cfg_attr(
881	feature = "std",
882	doc = "	let (stop_sender, stop_receiver) = tokio::sync::watch::channel(());"
883)]
884#[cfg_attr(feature = "std", doc = "")]
885///	let sleeper = move |d| {
886#[cfg_attr(feature = "std", doc = "		let mut receiver = stop_receiver.clone();")]
887///		Box::pin(async move {
888///			tokio::select!{
889///				_ = tokio::time::sleep(d) => false,
890#[cfg_attr(feature = "std", doc = "				_ = receiver.changed() => true,")]
891///			}
892///		})
893///	};
894///
895///	let mobile_interruptable_platform = false;
896///
897#[cfg_attr(feature = "std", doc = "	let handle = tokio::spawn(async move {")]
898#[cfg_attr(
899	not(feature = "std"),
900	doc = "	let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();"
901)]
902#[cfg_attr(not(feature = "std"), doc = "	rt.block_on(async move {")]
903///		process_events_async(
904///			background_persister,
905///			|e| background_event_handler.handle_event(e),
906///			background_chain_mon,
907///			background_chan_man,
908///			Some(background_onion_messenger),
909///			background_gossip_sync,
910///			background_peer_man,
911///			Some(background_liquidity_manager),
912///			Some(background_sweeper),
913///			background_logger,
914///			Some(background_scorer),
915///			sleeper,
916///			mobile_interruptable_platform,
917///			|| Some(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap())
918///		)
919///		.await
920///		.expect("Failed to process events");
921///	});
922///
923///	// Stop the background processing.
924#[cfg_attr(feature = "std", doc = "	stop_sender.send(()).unwrap();")]
925#[cfg_attr(feature = "std", doc = "	handle.await.unwrap()")]
926///	# }
927///```
928pub async fn process_events_async<
929	'a,
930	UL: UtxoLookup,
931	G: Deref<Target = NetworkGraph<L>>,
932	L: Logger,
933	EventHandlerFuture: core::future::Future<Output = Result<(), ReplayEvent>>,
934	EventHandler: Fn(Event) -> EventHandlerFuture,
935	M: Deref,
936	CM: Deref,
937	OM: Deref,
938	PGS: Deref<Target = P2PGossipSync<G, UL, L>>,
939	RGS: Deref<Target = RapidGossipSync<G, L>>,
940	PM: Deref,
941	LM: Deref,
942	D: Deref,
943	O: OutputSpender,
944	K: KVStore,
945	OS: Deref<
946		Target = OutputSweeper<
947			<M::Target as AChainMonitor>::Broadcaster,
948			D,
949			<M::Target as AChainMonitor>::FeeEstimator,
950			<M::Target as AChainMonitor>::Filter,
951			K,
952			L,
953			O,
954		>,
955	>,
956	S: Deref<Target = SC>,
957	SC: for<'b> WriteableScore<'b>,
958	SleepFuture: core::future::Future<Output = bool> + core::marker::Unpin,
959	Sleeper: Fn(Duration) -> SleepFuture,
960	FetchTime: Fn() -> Option<Duration>,
961>(
962	kv_store: K, event_handler: EventHandler, chain_monitor: M, channel_manager: CM,
963	onion_messenger: Option<OM>, gossip_sync: GossipSync<PGS, RGS, G, UL, L>, peer_manager: PM,
964	liquidity_manager: Option<LM>, sweeper: Option<OS>, logger: L, scorer: Option<S>,
965	sleeper: Sleeper, mobile_interruptable_platform: bool, fetch_time: FetchTime,
966) -> Result<(), lightning::io::Error>
967where
968	M::Target: AChainMonitor<Signer = <CM::Target as AChannelManager>::Signer, Logger = L>,
969	CM::Target: AChannelManager,
970	OM::Target: AOnionMessenger,
971	PM::Target: APeerManager,
972	LM::Target: ALiquidityManager,
973	D::Target: ChangeDestinationSource,
974{
975	let async_event_handler = |event| {
976		let network_graph = gossip_sync.network_graph();
977		let event_handler = &event_handler;
978		let scorer = &scorer;
979		let logger = &logger;
980		let kv_store = &kv_store;
981		let fetch_time = &fetch_time;
982		// We should be able to drop the Box once our MSRV is 1.68
983		Box::pin(async move {
984			if let Some(network_graph) = network_graph {
985				handle_network_graph_update(network_graph, &event)
986			}
987			if let Some(ref scorer) = scorer {
988				if let Some(duration_since_epoch) = fetch_time() {
989					if update_scorer(scorer, &event, duration_since_epoch) {
990						log_trace!(logger, "Persisting scorer after update");
991						if let Err(e) = kv_store
992							.write(
993								SCORER_PERSISTENCE_PRIMARY_NAMESPACE,
994								SCORER_PERSISTENCE_SECONDARY_NAMESPACE,
995								SCORER_PERSISTENCE_KEY,
996								scorer.encode(),
997							)
998							.await
999						{
1000							log_error!(logger, "Error: Failed to persist scorer, check your disk and permissions {}", e);
1001							// We opt not to abort early on persistence failure here as persisting
1002							// the scorer is non-critical and we still hope that it will have
1003							// resolved itself when it is potentially critical in event handling
1004							// below.
1005						}
1006					}
1007				}
1008			}
1009			event_handler(event).await
1010		})
1011	};
1012	let mut batch_delay = BatchDelay::new();
1013
1014	log_trace!(logger, "Calling ChannelManager's timer_tick_occurred on startup");
1015	channel_manager.get_cm().timer_tick_occurred();
1016	log_trace!(logger, "Rebroadcasting monitor's pending claims on startup");
1017	chain_monitor.get_cm().rebroadcast_pending_claims();
1018
1019	let mut last_freshness_call = sleeper(FRESHNESS_TIMER);
1020	let mut last_onion_message_handler_call = sleeper(ONION_MESSAGE_HANDLER_TIMER);
1021	let mut last_ping_call = sleeper(PING_TIMER);
1022	let mut last_prune_call = sleeper(FIRST_NETWORK_PRUNE_TIMER);
1023	let mut last_scorer_persist_call = sleeper(SCORER_PERSIST_TIMER);
1024	let mut last_rebroadcast_call = sleeper(REBROADCAST_TIMER);
1025	let mut last_sweeper_call = sleeper(SWEEPER_TIMER);
1026	let mut last_archive_call = sleeper(FIRST_ARCHIVE_STALE_MONITORS_TIMER);
1027	let mut have_pruned = false;
1028	let mut have_decayed_scorer = false;
1029	let mut have_archived = false;
1030
1031	let mut last_forwards_processing_call = sleeper(batch_delay.get());
1032
1033	loop {
1034		channel_manager.get_cm().process_pending_events_async(async_event_handler).await;
1035		chain_monitor.get_cm().process_pending_events_async(async_event_handler).await;
1036		if let Some(om) = &onion_messenger {
1037			om.get_om().process_pending_events_async(async_event_handler).await
1038		}
1039
1040		// Note that the PeerManager::process_events may block on ChannelManager's locks,
1041		// hence it comes last here. When the ChannelManager finishes whatever it's doing,
1042		// we want to ensure we get into `persist_manager` as quickly as we can, especially
1043		// without running the normal event processing above and handing events to users.
1044		//
1045		// Specifically, on an *extremely* slow machine, we may see ChannelManager start
1046		// processing a message effectively at any point during this loop. In order to
1047		// minimize the time between such processing completing and persisting the updated
1048		// ChannelManager, we want to minimize methods blocking on a ChannelManager
1049		// generally, and as a fallback place such blocking only immediately before
1050		// persistence.
1051		peer_manager.as_ref().process_events();
1052		match check_and_reset_sleeper(&mut last_forwards_processing_call, || {
1053			sleeper(batch_delay.next())
1054		}) {
1055			Some(false) => {
1056				channel_manager.get_cm().process_pending_htlc_forwards();
1057			},
1058			Some(true) => break,
1059			None => {},
1060		}
1061
1062		// We wait up to 100ms, but track how long it takes to detect being put to sleep,
1063		// see `await_start`'s use below.
1064		let mut await_start = None;
1065		if mobile_interruptable_platform {
1066			await_start = Some(sleeper(Duration::from_secs(1)));
1067		}
1068		let om_fut: OptionalSelector<_> =
1069			onion_messenger.as_ref().map(|om| om.get_om().get_update_future()).into();
1070		let lm_fut: OptionalSelector<_> = liquidity_manager
1071			.as_ref()
1072			.map(|lm| lm.get_lm().get_pending_msgs_or_needs_persist_future())
1073			.into();
1074		let gv_fut: OptionalSelector<_> = gossip_sync.validation_completion_future().into();
1075		let needs_processing = channel_manager.get_cm().needs_pending_htlc_processing();
1076		let sleep_delay = match (needs_processing, mobile_interruptable_platform) {
1077			(true, true) => batch_delay.get().min(Duration::from_millis(100)),
1078			(true, false) => batch_delay.get().min(FASTEST_TIMER),
1079			(false, true) => Duration::from_millis(100),
1080			(false, false) => FASTEST_TIMER,
1081		};
1082		let fut = Selector {
1083			a: sleeper(sleep_delay),
1084			b: channel_manager.get_cm().get_event_or_persistence_needed_future(),
1085			c: chain_monitor.get_cm().get_update_future(),
1086			d: om_fut,
1087			e: lm_fut,
1088			f: gv_fut,
1089		};
1090		match fut.await {
1091			SelectorOutput::B
1092			| SelectorOutput::C
1093			| SelectorOutput::D
1094			| SelectorOutput::E
1095			| SelectorOutput::F => {},
1096			SelectorOutput::A(exit) => {
1097				if exit {
1098					break;
1099				}
1100			},
1101		}
1102
1103		let await_slow = if mobile_interruptable_platform {
1104			// Specify a zero new sleeper timeout because we won't use the new sleeper. It is re-initialized in the next
1105			// loop iteration.
1106			match check_and_reset_sleeper(&mut await_start.unwrap(), || sleeper(Duration::ZERO)) {
1107				Some(true) => break,
1108				Some(false) => true,
1109				None => false,
1110			}
1111		} else {
1112			false
1113		};
1114		match check_and_reset_sleeper(&mut last_freshness_call, || sleeper(FRESHNESS_TIMER)) {
1115			Some(false) => {
1116				log_trace!(logger, "Calling ChannelManager's timer_tick_occurred");
1117				channel_manager.get_cm().timer_tick_occurred();
1118			},
1119			Some(true) => break,
1120			None => {},
1121		}
1122
1123		// We capture pending_operation_count inside the persistence branch to
1124		// avoid a race: ChannelManager handlers queue deferred monitor ops
1125		// before the persistence flag is set. Capturing outside would let us
1126		// observe pending ops while the flag is still unset, causing us to
1127		// flush monitor writes without persisting the ChannelManager.
1128		// Declared before futures so it outlives the Joiner (drop order).
1129		let pending_monitor_writes;
1130
1131		let mut futures = Joiner::new();
1132
1133		if channel_manager.get_cm().get_and_clear_needs_persistence() {
1134			pending_monitor_writes = chain_monitor.get_cm().pending_operation_count();
1135			log_trace!(logger, "Persisting ChannelManager...");
1136
1137			let fut = async {
1138				kv_store
1139					.write(
1140						CHANNEL_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE,
1141						CHANNEL_MANAGER_PERSISTENCE_SECONDARY_NAMESPACE,
1142						CHANNEL_MANAGER_PERSISTENCE_KEY,
1143						channel_manager.get_cm().encode(),
1144					)
1145					.await?;
1146
1147				// Flush monitor operations that were pending before we persisted. New updates
1148				// that arrived after are left for the next iteration.
1149				chain_monitor.get_cm().flush(pending_monitor_writes, &logger);
1150				Ok(())
1151			};
1152			// TODO: Once our MSRV is 1.68 we should be able to drop the Box
1153			let mut fut = Box::pin(fut);
1154
1155			// Because persisting the ChannelManager is important to avoid accidental
1156			// force-closures, go ahead and poll the future once before we do slightly more
1157			// CPU-intensive tasks in the form of NetworkGraph pruning or scorer time-stepping
1158			// below. This will get it moving but won't block us for too long if the underlying
1159			// future is actually async.
1160			use core::future::Future;
1161			let mut waker = dummy_waker();
1162			let mut ctx = task::Context::from_waker(&mut waker);
1163			match core::pin::Pin::new(&mut fut).poll(&mut ctx) {
1164				task::Poll::Ready(res) => futures.set_a_res(res),
1165				task::Poll::Pending => futures.set_a(fut),
1166			}
1167
1168			log_trace!(logger, "Done persisting ChannelManager.");
1169		}
1170
1171		// Note that we want to archive stale ChannelMonitors and run a network graph prune once
1172		// not long after startup before falling back to their usual infrequent runs. This avoids
1173		// short-lived clients never archiving stale ChannelMonitors or pruning their network
1174		// graph. For network graph pruning, in the case of RGS sync, we run a prune immediately
1175		// after initial sync completes, otherwise we do so on a timer which should be long enough
1176		// to give us a chance to get most of the network graph from our peers.
1177		let archive_timer = if have_archived {
1178			ARCHIVE_STALE_MONITORS_TIMER
1179		} else {
1180			FIRST_ARCHIVE_STALE_MONITORS_TIMER
1181		};
1182		let archive_timer_elapsed = {
1183			match check_and_reset_sleeper(&mut last_archive_call, || sleeper(archive_timer)) {
1184				Some(false) => true,
1185				Some(true) => break,
1186				None => false,
1187			}
1188		};
1189		if archive_timer_elapsed {
1190			log_trace!(logger, "Archiving stale ChannelMonitors.");
1191			chain_monitor.get_cm().archive_fully_resolved_channel_monitors();
1192			have_archived = true;
1193			log_trace!(logger, "Archived stale ChannelMonitors.");
1194		}
1195
1196		let prune_timer = if gossip_sync.prunable_network_graph().is_some() {
1197			NETWORK_PRUNE_TIMER
1198		} else {
1199			FIRST_NETWORK_PRUNE_TIMER
1200		};
1201		let prune_timer_elapsed = {
1202			match check_and_reset_sleeper(&mut last_prune_call, || sleeper(prune_timer)) {
1203				Some(false) => true,
1204				Some(true) => break,
1205				None => false,
1206			}
1207		};
1208
1209		let should_prune = match gossip_sync {
1210			GossipSync::Rapid(_) => !have_pruned || prune_timer_elapsed,
1211			_ => prune_timer_elapsed,
1212		};
1213		if should_prune {
1214			// The network graph must not be pruned while rapid sync completion is pending
1215			if let Some(network_graph) = gossip_sync.prunable_network_graph() {
1216				if let Some(duration_since_epoch) = fetch_time() {
1217					log_trace!(logger, "Pruning and persisting network graph.");
1218					network_graph.remove_stale_channels_and_tracking_with_time(
1219						duration_since_epoch.as_secs(),
1220					);
1221				} else {
1222					log_warn!(logger, "Not pruning network graph, consider implementing the fetch_time argument or calling remove_stale_channels_and_tracking_with_time manually.");
1223					log_trace!(logger, "Persisting network graph.");
1224				}
1225				let fut = async {
1226					if let Err(e) = kv_store
1227						.write(
1228							NETWORK_GRAPH_PERSISTENCE_PRIMARY_NAMESPACE,
1229							NETWORK_GRAPH_PERSISTENCE_SECONDARY_NAMESPACE,
1230							NETWORK_GRAPH_PERSISTENCE_KEY,
1231							network_graph.encode(),
1232						)
1233						.await
1234					{
1235						log_error!(logger, "Error: Failed to persist network graph, check your disk and permissions {}",e);
1236					}
1237
1238					Ok(())
1239				};
1240
1241				// TODO: Once our MSRV is 1.68 we should be able to drop the Box
1242				futures.set_b(Box::pin(fut));
1243
1244				have_pruned = true;
1245			}
1246		}
1247		if !have_decayed_scorer {
1248			if let Some(ref scorer) = scorer {
1249				if let Some(duration_since_epoch) = fetch_time() {
1250					log_trace!(logger, "Calling time_passed on scorer at startup");
1251					scorer.write_lock().time_passed(duration_since_epoch);
1252				}
1253			}
1254			have_decayed_scorer = true;
1255		}
1256		match check_and_reset_sleeper(&mut last_scorer_persist_call, || {
1257			sleeper(SCORER_PERSIST_TIMER)
1258		}) {
1259			Some(false) => {
1260				if let Some(ref scorer) = scorer {
1261					if let Some(duration_since_epoch) = fetch_time() {
1262						log_trace!(logger, "Calling time_passed and persisting scorer");
1263						scorer.write_lock().time_passed(duration_since_epoch);
1264					} else {
1265						log_trace!(logger, "Persisting scorer");
1266					}
1267					let fut = async {
1268						if let Err(e) = kv_store
1269							.write(
1270								SCORER_PERSISTENCE_PRIMARY_NAMESPACE,
1271								SCORER_PERSISTENCE_SECONDARY_NAMESPACE,
1272								SCORER_PERSISTENCE_KEY,
1273								scorer.encode(),
1274							)
1275							.await
1276						{
1277							log_error!(
1278							logger,
1279							"Error: Failed to persist scorer, check your disk and permissions {}",
1280							e
1281						);
1282						}
1283
1284						Ok(())
1285					};
1286
1287					// TODO: Once our MSRV is 1.68 we should be able to drop the Box
1288					futures.set_c(Box::pin(fut));
1289				}
1290			},
1291			Some(true) => break,
1292			None => {},
1293		}
1294		match check_and_reset_sleeper(&mut last_sweeper_call, || sleeper(SWEEPER_TIMER)) {
1295			Some(false) => {
1296				log_trace!(logger, "Regenerating sweeper spends if necessary");
1297				if let Some(ref sweeper) = sweeper {
1298					let fut = async {
1299						let _ = sweeper.regenerate_and_broadcast_spend_if_necessary().await;
1300
1301						Ok(())
1302					};
1303
1304					// TODO: Once our MSRV is 1.68 we should be able to drop the Box
1305					futures.set_d(Box::pin(fut));
1306				}
1307			},
1308			Some(true) => break,
1309			None => {},
1310		}
1311
1312		if let Some(liquidity_manager) = liquidity_manager.as_ref() {
1313			let fut = async {
1314				liquidity_manager
1315					.get_lm()
1316					.persist()
1317					.await
1318					.map(|did_persist| {
1319						if did_persist {
1320							log_trace!(logger, "Persisted LiquidityManager.");
1321						}
1322					})
1323					.map_err(|e| {
1324						log_error!(logger, "Persisting LiquidityManager failed: {}", e);
1325						e
1326					})
1327			};
1328			futures.set_e(Box::pin(fut));
1329		}
1330
1331		// Run persistence tasks in parallel and exit if any of them returns an error.
1332		for res in futures.await {
1333			res?;
1334		}
1335
1336		match check_and_reset_sleeper(&mut last_onion_message_handler_call, || {
1337			sleeper(ONION_MESSAGE_HANDLER_TIMER)
1338		}) {
1339			Some(false) => {
1340				if let Some(om) = &onion_messenger {
1341					log_trace!(logger, "Calling OnionMessageHandler's timer_tick_occurred");
1342					om.get_om().timer_tick_occurred();
1343				}
1344			},
1345			Some(true) => break,
1346			None => {},
1347		}
1348
1349		// Peer manager timer tick. If we were interrupted on a mobile platform, we disconnect all peers.
1350		if await_slow {
1351			// On various platforms, we may be starved of CPU cycles for several reasons.
1352			// E.g. on iOS, if we've been in the background, we will be entirely paused.
1353			// Similarly, if we're on a desktop platform and the device has been asleep, we
1354			// may not get any cycles.
1355			// We detect this by checking if our max-100ms-sleep, above, ran longer than a
1356			// full second, at which point we assume sockets may have been killed (they
1357			// appear to be at least on some platforms, even if it has only been a second).
1358			// Note that we have to take care to not get here just because user event
1359			// processing was slow at the top of the loop. For example, the sample client
1360			// may call Bitcoin Core RPCs during event handling, which very often takes
1361			// more than a handful of seconds to complete, and shouldn't disconnect all our
1362			// peers.
1363			log_trace!(logger, "100ms sleep took more than a second, disconnecting peers.");
1364			peer_manager.as_ref().disconnect_all_peers();
1365			last_ping_call = sleeper(PING_TIMER);
1366		} else {
1367			match check_and_reset_sleeper(&mut last_ping_call, || sleeper(PING_TIMER)) {
1368				Some(false) => {
1369					log_trace!(logger, "Calling PeerManager's timer_tick_occurred");
1370					peer_manager.as_ref().timer_tick_occurred();
1371				},
1372				Some(true) => break,
1373				_ => {},
1374			}
1375		}
1376
1377		// Rebroadcast pending claims.
1378		match check_and_reset_sleeper(&mut last_rebroadcast_call, || sleeper(REBROADCAST_TIMER)) {
1379			Some(false) => {
1380				log_trace!(logger, "Rebroadcasting monitor's pending claims");
1381				chain_monitor.get_cm().rebroadcast_pending_claims();
1382			},
1383			Some(true) => break,
1384			None => {},
1385		}
1386	}
1387	log_trace!(logger, "Terminating background processor.");
1388
1389	// After we exit, ensure we persist the ChannelManager one final time - this avoids
1390	// some races where users quit while channel updates were in-flight, with
1391	// ChannelMonitor update(s) persisted without a corresponding ChannelManager update.
1392	let pending_monitor_writes = chain_monitor.get_cm().pending_operation_count();
1393	kv_store
1394		.write(
1395			CHANNEL_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE,
1396			CHANNEL_MANAGER_PERSISTENCE_SECONDARY_NAMESPACE,
1397			CHANNEL_MANAGER_PERSISTENCE_KEY,
1398			channel_manager.get_cm().encode(),
1399		)
1400		.await?;
1401
1402	// Flush monitor operations that were pending before final persistence.
1403	chain_monitor.get_cm().flush(pending_monitor_writes, &logger);
1404
1405	if let Some(ref scorer) = scorer {
1406		kv_store
1407			.write(
1408				SCORER_PERSISTENCE_PRIMARY_NAMESPACE,
1409				SCORER_PERSISTENCE_SECONDARY_NAMESPACE,
1410				SCORER_PERSISTENCE_KEY,
1411				scorer.encode(),
1412			)
1413			.await?;
1414	}
1415	if let Some(network_graph) = gossip_sync.network_graph() {
1416		kv_store
1417			.write(
1418				NETWORK_GRAPH_PERSISTENCE_PRIMARY_NAMESPACE,
1419				NETWORK_GRAPH_PERSISTENCE_SECONDARY_NAMESPACE,
1420				NETWORK_GRAPH_PERSISTENCE_KEY,
1421				network_graph.encode(),
1422			)
1423			.await?;
1424	}
1425	Ok(())
1426}
1427
1428fn check_and_reset_sleeper<
1429	SleepFuture: core::future::Future<Output = bool> + core::marker::Unpin,
1430>(
1431	fut: &mut SleepFuture, mut new_sleeper: impl FnMut() -> SleepFuture,
1432) -> Option<bool> {
1433	let mut waker = dummy_waker();
1434	let mut ctx = task::Context::from_waker(&mut waker);
1435	match core::pin::Pin::new(&mut *fut).poll(&mut ctx) {
1436		task::Poll::Ready(exit) => {
1437			*fut = new_sleeper();
1438			Some(exit)
1439		},
1440		task::Poll::Pending => None,
1441	}
1442}
1443
1444/// Async events processor that is based on [`process_events_async`] but allows for [`KVStoreSync`] to be used for
1445/// synchronous background persistence.
1446pub async fn process_events_async_with_kv_store_sync<
1447	UL: UtxoLookup,
1448	G: Deref<Target = NetworkGraph<L>>,
1449	L: Logger,
1450	EventHandlerFuture: core::future::Future<Output = Result<(), ReplayEvent>>,
1451	EventHandler: Fn(Event) -> EventHandlerFuture,
1452	M: Deref,
1453	CM: Deref,
1454	OM: Deref,
1455	PGS: Deref<Target = P2PGossipSync<G, UL, L>>,
1456	RGS: Deref<Target = RapidGossipSync<G, L>>,
1457	PM: Deref,
1458	LM: Deref,
1459	D: Deref,
1460	O: OutputSpender,
1461	K: Deref,
1462	OS: Deref<
1463		Target = OutputSweeperSync<
1464			<M::Target as AChainMonitor>::Broadcaster,
1465			D,
1466			<M::Target as AChainMonitor>::FeeEstimator,
1467			<M::Target as AChainMonitor>::Filter,
1468			K,
1469			L,
1470			O,
1471		>,
1472	>,
1473	S: Deref<Target = SC>,
1474	SC: for<'b> WriteableScore<'b>,
1475	SleepFuture: core::future::Future<Output = bool> + core::marker::Unpin,
1476	Sleeper: Fn(Duration) -> SleepFuture,
1477	FetchTime: Fn() -> Option<Duration>,
1478>(
1479	kv_store: K, event_handler: EventHandler, chain_monitor: M, channel_manager: CM,
1480	onion_messenger: Option<OM>, gossip_sync: GossipSync<PGS, RGS, G, UL, L>, peer_manager: PM,
1481	liquidity_manager: Option<LM>, sweeper: Option<OS>, logger: L, scorer: Option<S>,
1482	sleeper: Sleeper, mobile_interruptable_platform: bool, fetch_time: FetchTime,
1483) -> Result<(), lightning::io::Error>
1484where
1485	M::Target: AChainMonitor<Signer = <CM::Target as AChannelManager>::Signer, Logger = L>,
1486	CM::Target: AChannelManager,
1487	OM::Target: AOnionMessenger,
1488	PM::Target: APeerManager,
1489	LM::Target: ALiquidityManager,
1490	D::Target: ChangeDestinationSourceSync,
1491	K::Target: KVStoreSync,
1492{
1493	let kv_store = KVStoreSyncWrapper(kv_store);
1494	process_events_async(
1495		kv_store,
1496		event_handler,
1497		chain_monitor,
1498		channel_manager,
1499		onion_messenger,
1500		gossip_sync,
1501		peer_manager,
1502		liquidity_manager,
1503		sweeper.as_ref().map(|os| os.sweeper_async()),
1504		logger,
1505		scorer,
1506		sleeper,
1507		mobile_interruptable_platform,
1508		fetch_time,
1509	)
1510	.await
1511}
1512
1513#[cfg(feature = "std")]
1514impl BackgroundProcessor {
1515	/// Start a background thread that takes care of responsibilities enumerated in the [top-level
1516	/// documentation].
1517	///
1518	/// The thread runs indefinitely unless the object is dropped, [`stop`] is called, or
1519	/// [`KVStoreSync`] returns an error. In case of an error, the error is retrieved by calling
1520	/// either [`join`] or [`stop`].
1521	///
1522	/// # Data Persistence
1523	///
1524	/// [`KVStoreSync`] is responsible for writing out the [`ChannelManager`] to disk, and/or
1525	/// uploading to one or more backup services. See [`ChannelManager::write`] for writing out a
1526	/// [`ChannelManager`]. See the `lightning-persister` crate for LDK's
1527	/// provided implementation.
1528	///
1529	/// [`KVStoreSync`] is also responsible for writing out the [`NetworkGraph`] to disk, if
1530	/// [`GossipSync`] is supplied. See [`NetworkGraph::write`] for writing out a [`NetworkGraph`].
1531	/// See the `lightning-persister` crate for LDK's provided implementation.
1532	///
1533	/// Typically, users should either implement [`KVStoreSync`] to never return an
1534	/// error or call [`join`] and handle any error that may arise. For the latter case,
1535	/// `BackgroundProcessor` must be restarted by calling `start` again after handling the error.
1536	///
1537	/// # Event Handling
1538	///
1539	/// `event_handler` is responsible for handling events that users should be notified of (e.g.,
1540	/// payment failed). [`BackgroundProcessor`] may decorate the given [`EventHandler`] with common
1541	/// functionality implemented by other handlers.
1542	/// * [`P2PGossipSync`] if given will update the [`NetworkGraph`] based on payment failures.
1543	///
1544	/// # Rapid Gossip Sync
1545	///
1546	/// If rapid gossip sync is meant to run at startup, pass [`RapidGossipSync`] via `gossip_sync`
1547	/// to indicate that the [`BackgroundProcessor`] should not prune the [`NetworkGraph`] instance
1548	/// until the [`RapidGossipSync`] instance completes its first sync.
1549	///
1550	/// [top-level documentation]: BackgroundProcessor
1551	/// [`join`]: Self::join
1552	/// [`stop`]: Self::stop
1553	/// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
1554	/// [`ChannelManager::write`]: lightning::ln::channelmanager::ChannelManager#impl-Writeable
1555	/// [`NetworkGraph`]: lightning::routing::gossip::NetworkGraph
1556	/// [`NetworkGraph::write`]: lightning::routing::gossip::NetworkGraph#impl-Writeable
1557	pub fn start<
1558		'a,
1559		UL: 'static + UtxoLookup,
1560		G: 'static + Deref<Target = NetworkGraph<L>>,
1561		L: 'static + Deref + Send,
1562		EH: 'static + EventHandler + Send,
1563		M: 'static + Deref + Send + Sync,
1564		CM: 'static + Deref + Send,
1565		OM: 'static + Deref + Send,
1566		PGS: 'static + Deref<Target = P2PGossipSync<G, UL, L>> + Send,
1567		RGS: 'static + Deref<Target = RapidGossipSync<G, L>> + Send,
1568		PM: 'static + Deref + Send,
1569		LM: 'static + Deref + Send,
1570		S: 'static + Deref<Target = SC> + Send + Sync,
1571		SC: for<'b> WriteableScore<'b>,
1572		D: 'static + Deref,
1573		O: 'static + OutputSpender,
1574		K: 'static + Deref + Send,
1575		OS: 'static
1576			+ Deref<
1577				Target = OutputSweeperSync<
1578					<M::Target as AChainMonitor>::Broadcaster,
1579					D,
1580					<M::Target as AChainMonitor>::FeeEstimator,
1581					<M::Target as AChainMonitor>::Filter,
1582					K,
1583					L,
1584					O,
1585				>,
1586			>
1587			+ Send,
1588	>(
1589		kv_store: K, event_handler: EH, chain_monitor: M, channel_manager: CM,
1590		onion_messenger: Option<OM>, gossip_sync: GossipSync<PGS, RGS, G, UL, L>, peer_manager: PM,
1591		liquidity_manager: Option<LM>, sweeper: Option<OS>, logger: L, scorer: Option<S>,
1592	) -> Self
1593	where
1594		L::Target: 'static + Logger,
1595		M::Target: AChainMonitor<Signer = <CM::Target as AChannelManager>::Signer, Logger = L>,
1596		CM::Target: AChannelManager,
1597		OM::Target: AOnionMessenger,
1598		PM::Target: APeerManager,
1599		LM::Target: ALiquidityManagerSync,
1600		D::Target: ChangeDestinationSourceSync,
1601		K::Target: 'static + KVStoreSync,
1602	{
1603		let stop_thread = Arc::new(AtomicBool::new(false));
1604		let stop_thread_clone = Arc::clone(&stop_thread);
1605		let handle = thread::spawn(move || -> Result<(), std::io::Error> {
1606			let event_handler = |event| {
1607				let network_graph = gossip_sync.network_graph();
1608				if let Some(network_graph) = network_graph {
1609					handle_network_graph_update(network_graph, &event)
1610				}
1611				if let Some(ref scorer) = scorer {
1612					use std::time::SystemTime;
1613					let duration_since_epoch = SystemTime::now()
1614						.duration_since(SystemTime::UNIX_EPOCH)
1615						.expect("Time should be sometime after 1970");
1616					if update_scorer(scorer, &event, duration_since_epoch) {
1617						log_trace!(logger, "Persisting scorer after update");
1618						if let Err(e) = kv_store.write(
1619							SCORER_PERSISTENCE_PRIMARY_NAMESPACE,
1620							SCORER_PERSISTENCE_SECONDARY_NAMESPACE,
1621							SCORER_PERSISTENCE_KEY,
1622							scorer.encode(),
1623						) {
1624							log_error!(logger, "Error: Failed to persist scorer, check your disk and permissions {}", e)
1625						}
1626					}
1627				}
1628				event_handler.handle_event(event)
1629			};
1630			let mut batch_delay = BatchDelay::new();
1631
1632			log_trace!(logger, "Calling ChannelManager's timer_tick_occurred on startup");
1633			channel_manager.get_cm().timer_tick_occurred();
1634			log_trace!(logger, "Rebroadcasting monitor's pending claims on startup");
1635			chain_monitor.get_cm().rebroadcast_pending_claims();
1636
1637			let mut last_freshness_call = Instant::now();
1638			let mut last_onion_message_handler_call = Instant::now();
1639			let mut last_ping_call = Instant::now();
1640			let mut last_prune_call = Instant::now();
1641			let mut last_scorer_persist_call = Instant::now();
1642			let mut last_rebroadcast_call = Instant::now();
1643			let mut last_sweeper_call = Instant::now();
1644			let mut last_archive_call = Instant::now();
1645			let mut have_pruned = false;
1646			let mut have_decayed_scorer = false;
1647			let mut have_archived = false;
1648
1649			let mut cur_batch_delay = batch_delay.get();
1650			let mut last_forwards_processing_call = Instant::now();
1651
1652			loop {
1653				channel_manager.get_cm().process_pending_events(&event_handler);
1654				chain_monitor.get_cm().process_pending_events(&event_handler);
1655				if let Some(om) = &onion_messenger {
1656					om.get_om().process_pending_events(&event_handler)
1657				};
1658
1659				// Note that the PeerManager::process_events may block on ChannelManager's locks,
1660				// hence it comes last here. When the ChannelManager finishes whatever it's doing,
1661				// we want to ensure we get into `persist_manager` as quickly as we can, especially
1662				// without running the normal event processing above and handing events to users.
1663				//
1664				// Specifically, on an *extremely* slow machine, we may see ChannelManager start
1665				// processing a message effectively at any point during this loop. In order to
1666				// minimize the time between such processing completing and persisting the updated
1667				// ChannelManager, we want to minimize methods blocking on a ChannelManager
1668				// generally, and as a fallback place such blocking only immediately before
1669				// persistence.
1670				peer_manager.as_ref().process_events();
1671				if last_forwards_processing_call.elapsed() > cur_batch_delay {
1672					channel_manager.get_cm().process_pending_htlc_forwards();
1673					cur_batch_delay = batch_delay.next();
1674					last_forwards_processing_call = Instant::now();
1675				}
1676				if stop_thread.load(Ordering::Acquire) {
1677					log_trace!(logger, "Terminating background processor.");
1678					break;
1679				}
1680				let om_fut = onion_messenger.as_ref().map(|om| om.get_om().get_update_future());
1681				let lm_fut = liquidity_manager
1682					.as_ref()
1683					.map(|lm| lm.get_lm().get_pending_msgs_or_needs_persist_future());
1684				let gv_fut = gossip_sync.validation_completion_future();
1685				let always_futures = [
1686					channel_manager.get_cm().get_event_or_persistence_needed_future(),
1687					chain_monitor.get_cm().get_update_future(),
1688				];
1689				let futures = always_futures.into_iter().chain(om_fut).chain(lm_fut).chain(gv_fut);
1690				let sleeper = Sleeper::from_futures(futures);
1691
1692				let batch_delay = if channel_manager.get_cm().needs_pending_htlc_processing() {
1693					batch_delay.get()
1694				} else {
1695					Duration::MAX
1696				};
1697				let fastest_timeout = batch_delay.min(Duration::from_millis(100));
1698				sleeper.wait_timeout(fastest_timeout);
1699				if stop_thread.load(Ordering::Acquire) {
1700					log_trace!(logger, "Terminating background processor.");
1701					break;
1702				}
1703				if last_freshness_call.elapsed() > FRESHNESS_TIMER {
1704					log_trace!(logger, "Calling ChannelManager's timer_tick_occurred");
1705					channel_manager.get_cm().timer_tick_occurred();
1706					last_freshness_call = Instant::now();
1707				}
1708
1709				if channel_manager.get_cm().get_and_clear_needs_persistence() {
1710					// We capture pending_operation_count inside the persistence
1711					// branch to avoid a race: ChannelManager handlers queue
1712					// deferred monitor ops before the persistence flag is set.
1713					// Capturing outside would let us observe pending ops while
1714					// the flag is still unset, causing us to flush monitor
1715					// writes without persisting the ChannelManager.
1716					let pending_monitor_writes = chain_monitor.get_cm().pending_operation_count();
1717					log_trace!(logger, "Persisting ChannelManager...");
1718					(kv_store.write(
1719						CHANNEL_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE,
1720						CHANNEL_MANAGER_PERSISTENCE_SECONDARY_NAMESPACE,
1721						CHANNEL_MANAGER_PERSISTENCE_KEY,
1722						channel_manager.get_cm().encode(),
1723					))?;
1724					log_trace!(logger, "Done persisting ChannelManager.");
1725
1726					// Flush monitor operations that were pending before we persisted.
1727					// New updates that arrived after are left for the next iteration.
1728					chain_monitor.get_cm().flush(pending_monitor_writes, &logger);
1729				}
1730
1731				if let Some(liquidity_manager) = liquidity_manager.as_ref() {
1732					log_trace!(logger, "Persisting LiquidityManager...");
1733					let _ = liquidity_manager.get_lm().persist().map_err(|e| {
1734						log_error!(logger, "Persisting LiquidityManager failed: {}", e);
1735					});
1736				}
1737
1738				// Note that we want to archive stale ChannelMonitors and run a network graph prune once
1739				// not long after startup before falling back to their usual infrequent runs. This avoids
1740				// short-lived clients never archiving stale ChannelMonitors or pruning their network
1741				// graph. For network graph pruning, in the case of RGS sync, we run a prune immediately
1742				// after initial sync completes, otherwise we do so on a timer which should be long enough
1743				// to give us a chance to get most of the network graph from our peers.
1744				let archive_timer = if have_archived {
1745					ARCHIVE_STALE_MONITORS_TIMER
1746				} else {
1747					FIRST_ARCHIVE_STALE_MONITORS_TIMER
1748				};
1749				let archive_timer_elapsed = last_archive_call.elapsed() > archive_timer;
1750				if archive_timer_elapsed {
1751					log_trace!(logger, "Archiving stale ChannelMonitors.");
1752					chain_monitor.get_cm().archive_fully_resolved_channel_monitors();
1753					have_archived = true;
1754					last_archive_call = Instant::now();
1755					log_trace!(logger, "Archived stale ChannelMonitors.");
1756				}
1757
1758				let prune_timer =
1759					if have_pruned { NETWORK_PRUNE_TIMER } else { FIRST_NETWORK_PRUNE_TIMER };
1760				let prune_timer_elapsed = last_prune_call.elapsed() > prune_timer;
1761				let should_prune = match gossip_sync {
1762					GossipSync::Rapid(_) => !have_pruned || prune_timer_elapsed,
1763					_ => prune_timer_elapsed,
1764				};
1765				if should_prune {
1766					// The network graph must not be pruned while rapid sync completion is pending
1767					if let Some(network_graph) = gossip_sync.prunable_network_graph() {
1768						let duration_since_epoch = std::time::SystemTime::now()
1769							.duration_since(std::time::SystemTime::UNIX_EPOCH)
1770							.expect("Time should be sometime after 1970");
1771
1772						log_trace!(logger, "Pruning and persisting network graph.");
1773						network_graph.remove_stale_channels_and_tracking_with_time(
1774							duration_since_epoch.as_secs(),
1775						);
1776						if let Err(e) = kv_store.write(
1777							NETWORK_GRAPH_PERSISTENCE_PRIMARY_NAMESPACE,
1778							NETWORK_GRAPH_PERSISTENCE_SECONDARY_NAMESPACE,
1779							NETWORK_GRAPH_PERSISTENCE_KEY,
1780							network_graph.encode(),
1781						) {
1782							log_error!(logger, "Error: Failed to persist network graph, check your disk and permissions {}", e);
1783						}
1784						have_pruned = true;
1785					}
1786					last_prune_call = Instant::now();
1787				}
1788				if !have_decayed_scorer {
1789					if let Some(ref scorer) = scorer {
1790						let duration_since_epoch = std::time::SystemTime::now()
1791							.duration_since(std::time::SystemTime::UNIX_EPOCH)
1792							.expect("Time should be sometime after 1970");
1793						log_trace!(logger, "Calling time_passed on scorer at startup");
1794						scorer.write_lock().time_passed(duration_since_epoch);
1795					}
1796					have_decayed_scorer = true;
1797				}
1798				if last_scorer_persist_call.elapsed() > SCORER_PERSIST_TIMER {
1799					if let Some(ref scorer) = scorer {
1800						let duration_since_epoch = std::time::SystemTime::now()
1801							.duration_since(std::time::SystemTime::UNIX_EPOCH)
1802							.expect("Time should be sometime after 1970");
1803						log_trace!(logger, "Calling time_passed and persisting scorer");
1804						scorer.write_lock().time_passed(duration_since_epoch);
1805						if let Err(e) = kv_store.write(
1806							SCORER_PERSISTENCE_PRIMARY_NAMESPACE,
1807							SCORER_PERSISTENCE_SECONDARY_NAMESPACE,
1808							SCORER_PERSISTENCE_KEY,
1809							scorer.encode(),
1810						) {
1811							log_error!(logger, "Error: Failed to persist scorer, check your disk and permissions {}", e);
1812						}
1813					}
1814					last_scorer_persist_call = Instant::now();
1815				}
1816				if last_sweeper_call.elapsed() > SWEEPER_TIMER {
1817					log_trace!(logger, "Regenerating sweeper spends if necessary");
1818					if let Some(ref sweeper) = sweeper {
1819						let _ = sweeper.regenerate_and_broadcast_spend_if_necessary();
1820					}
1821					last_sweeper_call = Instant::now();
1822				}
1823				if last_onion_message_handler_call.elapsed() > ONION_MESSAGE_HANDLER_TIMER {
1824					if let Some(om) = &onion_messenger {
1825						log_trace!(logger, "Calling OnionMessageHandler's timer_tick_occurred");
1826						om.get_om().timer_tick_occurred();
1827					}
1828					last_onion_message_handler_call = Instant::now();
1829				}
1830				if last_ping_call.elapsed() > PING_TIMER {
1831					log_trace!(logger, "Calling PeerManager's timer_tick_occurred");
1832					peer_manager.as_ref().timer_tick_occurred();
1833					last_ping_call = Instant::now();
1834				}
1835				if last_rebroadcast_call.elapsed() > REBROADCAST_TIMER {
1836					log_trace!(logger, "Rebroadcasting monitor's pending claims");
1837					chain_monitor.get_cm().rebroadcast_pending_claims();
1838					last_rebroadcast_call = Instant::now();
1839				}
1840			}
1841
1842			// After we exit, ensure we persist the ChannelManager one final time - this avoids
1843			// some races where users quit while channel updates were in-flight, with
1844			// ChannelMonitor update(s) persisted without a corresponding ChannelManager update.
1845			let pending_monitor_writes = chain_monitor.get_cm().pending_operation_count();
1846			kv_store.write(
1847				CHANNEL_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE,
1848				CHANNEL_MANAGER_PERSISTENCE_SECONDARY_NAMESPACE,
1849				CHANNEL_MANAGER_PERSISTENCE_KEY,
1850				channel_manager.get_cm().encode(),
1851			)?;
1852
1853			// Flush monitor operations that were pending before final persistence.
1854			chain_monitor.get_cm().flush(pending_monitor_writes, &logger);
1855
1856			if let Some(ref scorer) = scorer {
1857				kv_store.write(
1858					SCORER_PERSISTENCE_PRIMARY_NAMESPACE,
1859					SCORER_PERSISTENCE_SECONDARY_NAMESPACE,
1860					SCORER_PERSISTENCE_KEY,
1861					scorer.encode(),
1862				)?;
1863			}
1864			if let Some(network_graph) = gossip_sync.network_graph() {
1865				kv_store.write(
1866					NETWORK_GRAPH_PERSISTENCE_PRIMARY_NAMESPACE,
1867					NETWORK_GRAPH_PERSISTENCE_SECONDARY_NAMESPACE,
1868					NETWORK_GRAPH_PERSISTENCE_KEY,
1869					network_graph.encode(),
1870				)?;
1871			}
1872			Ok(())
1873		});
1874		Self { stop_thread: stop_thread_clone, thread_handle: Some(handle) }
1875	}
1876
1877	/// Join `BackgroundProcessor`'s thread, returning any error that occurred while persisting
1878	/// [`ChannelManager`].
1879	///
1880	/// # Panics
1881	///
1882	/// This function panics if the background thread has panicked such as while persisting or
1883	/// handling events.
1884	///
1885	/// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
1886	pub fn join(mut self) -> Result<(), std::io::Error> {
1887		assert!(self.thread_handle.is_some());
1888		self.join_thread()
1889	}
1890
1891	/// Stop `BackgroundProcessor`'s thread, returning any error that occurred while persisting
1892	/// [`ChannelManager`].
1893	///
1894	/// # Panics
1895	///
1896	/// This function panics if the background thread has panicked such as while persisting or
1897	/// handling events.
1898	///
1899	/// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
1900	pub fn stop(mut self) -> Result<(), std::io::Error> {
1901		assert!(self.thread_handle.is_some());
1902		self.stop_and_join_thread()
1903	}
1904
1905	fn stop_and_join_thread(&mut self) -> Result<(), std::io::Error> {
1906		self.stop_thread.store(true, Ordering::Release);
1907		self.join_thread()
1908	}
1909
1910	fn join_thread(&mut self) -> Result<(), std::io::Error> {
1911		match self.thread_handle.take() {
1912			Some(handle) => handle.join().unwrap(),
1913			None => Ok(()),
1914		}
1915	}
1916}
1917
1918#[cfg(feature = "std")]
1919impl Drop for BackgroundProcessor {
1920	fn drop(&mut self) {
1921		self.stop_and_join_thread().unwrap();
1922	}
1923}
1924
1925#[cfg(all(feature = "std", test))]
1926mod tests {
1927	use super::{BackgroundProcessor, GossipSync, FRESHNESS_TIMER};
1928	use bitcoin::constants::{genesis_block, ChainHash};
1929	use bitcoin::hashes::Hash;
1930	use bitcoin::locktime::absolute::LockTime;
1931	use bitcoin::network::Network;
1932	use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1933	use bitcoin::transaction::Version;
1934	use bitcoin::transaction::{Transaction, TxOut};
1935	use bitcoin::{Amount, ScriptBuf, Txid};
1936	use core::sync::atomic::{AtomicBool, Ordering};
1937	use lightning::chain::chainmonitor;
1938	use lightning::chain::channelmonitor::ANTI_REORG_DELAY;
1939	use lightning::chain::transaction::OutPoint;
1940	use lightning::chain::{BlockLocator, Confirm};
1941	use lightning::events::{Event, PathFailure, ReplayEvent};
1942	use lightning::ln::channelmanager;
1943	use lightning::ln::channelmanager::{
1944		ChainParameters, PaymentId, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA,
1945	};
1946	use lightning::ln::functional_test_utils::*;
1947	use lightning::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, Init, MessageSendEvent};
1948	use lightning::ln::peer_handler::{
1949		IgnoringMessageHandler, MessageHandler, PeerManager, SocketDescriptor,
1950	};
1951	use lightning::ln::types::ChannelId;
1952	use lightning::onion_message::messenger::{DefaultMessageRouter, OnionMessenger};
1953	use lightning::routing::gossip::{NetworkGraph, P2PGossipSync};
1954	use lightning::routing::router::{CandidateRouteHop, DefaultRouter, Path, RouteHop};
1955	use lightning::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp, ScoreUpdate};
1956	use lightning::sign::{ChangeDestinationSourceSync, InMemorySigner, KeysManager, NodeSigner};
1957	use lightning::types::features::{ChannelFeatures, NodeFeatures};
1958	use lightning::types::payment::PaymentHash;
1959	use lightning::util::config::UserConfig;
1960	use lightning::util::persist::{
1961		KVStoreSync, KVStoreSyncWrapper, CHANNEL_MANAGER_PERSISTENCE_KEY,
1962		CHANNEL_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE,
1963		CHANNEL_MANAGER_PERSISTENCE_SECONDARY_NAMESPACE, NETWORK_GRAPH_PERSISTENCE_KEY,
1964		NETWORK_GRAPH_PERSISTENCE_PRIMARY_NAMESPACE, NETWORK_GRAPH_PERSISTENCE_SECONDARY_NAMESPACE,
1965		SCORER_PERSISTENCE_KEY, SCORER_PERSISTENCE_PRIMARY_NAMESPACE,
1966		SCORER_PERSISTENCE_SECONDARY_NAMESPACE,
1967	};
1968	use lightning::util::ser::Writeable;
1969	use lightning::util::sweep::{
1970		OutputSpendStatus, OutputSweeper, OutputSweeperSync, PRUNE_DELAY_BLOCKS,
1971	};
1972	use lightning::util::test_utils;
1973	use lightning::{get_event, get_event_msg};
1974	use lightning_liquidity::utils::time::DefaultTimeProvider;
1975	use lightning_liquidity::{ALiquidityManagerSync, LiquidityManager, LiquidityManagerSync};
1976	use lightning_persister::fs_store::v1::FilesystemStore;
1977	use lightning_rapid_gossip_sync::RapidGossipSync;
1978	use std::collections::VecDeque;
1979	use std::path::PathBuf;
1980	use std::sync::mpsc::SyncSender;
1981	use std::sync::Arc;
1982	use std::time::Duration;
1983	use std::{env, fs};
1984
1985	const EVENT_DEADLINE: Duration =
1986		Duration::from_millis(5 * (FRESHNESS_TIMER.as_millis() as u64));
1987
1988	/// Reads a directory and returns only non-`.tmp` files.
1989	/// The file system may return files in any order, and during persistence
1990	/// operations there may be temporary `.tmp` files present.
1991	fn list_monitor_files(dir: &str) -> Vec<std::fs::DirEntry> {
1992		std::fs::read_dir(dir)
1993			.unwrap()
1994			.filter_map(|entry| {
1995				let entry = entry.unwrap();
1996				let path_str = entry.path().to_str().unwrap().to_lowercase();
1997				// Skip any .tmp files that may exist during persistence.
1998				// On Windows, ReplaceFileW creates backup files with .TMP (uppercase).
1999				if path_str.ends_with(".tmp") {
2000					None
2001				} else {
2002					Some(entry)
2003				}
2004			})
2005			.collect()
2006	}
2007
2008	#[derive(Clone, Hash, PartialEq, Eq)]
2009	struct TestDescriptor {}
2010	impl SocketDescriptor for TestDescriptor {
2011		fn send_data(&mut self, _data: &[u8], _continue_read: bool) -> usize {
2012			0
2013		}
2014
2015		fn disconnect_socket(&mut self) {}
2016	}
2017
2018	#[cfg(c_bindings)]
2019	type LockingWrapper<T> = lightning::routing::scoring::MultiThreadedLockableScore<T>;
2020	#[cfg(not(c_bindings))]
2021	type LockingWrapper<T> = std::sync::Mutex<T>;
2022
2023	type ChannelManager = channelmanager::ChannelManager<
2024		Arc<ChainMonitor>,
2025		Arc<test_utils::TestBroadcaster>,
2026		Arc<KeysManager>,
2027		Arc<KeysManager>,
2028		Arc<KeysManager>,
2029		Arc<test_utils::TestFeeEstimator>,
2030		Arc<
2031			DefaultRouter<
2032				Arc<NetworkGraph<Arc<test_utils::TestLogger>>>,
2033				Arc<test_utils::TestLogger>,
2034				Arc<KeysManager>,
2035				Arc<LockingWrapper<TestScorer>>,
2036				(),
2037				TestScorer,
2038			>,
2039		>,
2040		Arc<
2041			DefaultMessageRouter<
2042				Arc<NetworkGraph<Arc<test_utils::TestLogger>>>,
2043				Arc<test_utils::TestLogger>,
2044				Arc<KeysManager>,
2045			>,
2046		>,
2047		Arc<test_utils::TestLogger>,
2048	>;
2049
2050	type ChainMonitor = chainmonitor::ChainMonitor<
2051		InMemorySigner,
2052		Arc<test_utils::TestChainSource>,
2053		Arc<test_utils::TestBroadcaster>,
2054		Arc<test_utils::TestFeeEstimator>,
2055		Arc<test_utils::TestLogger>,
2056		Arc<Persister>,
2057		Arc<KeysManager>,
2058	>;
2059
2060	type PGS = Arc<
2061		P2PGossipSync<
2062			Arc<NetworkGraph<Arc<test_utils::TestLogger>>>,
2063			Arc<test_utils::TestChainSource>,
2064			Arc<test_utils::TestLogger>,
2065		>,
2066	>;
2067	type RGS = Arc<
2068		RapidGossipSync<
2069			Arc<NetworkGraph<Arc<test_utils::TestLogger>>>,
2070			Arc<test_utils::TestLogger>,
2071		>,
2072	>;
2073
2074	type OM = OnionMessenger<
2075		Arc<KeysManager>,
2076		Arc<KeysManager>,
2077		Arc<test_utils::TestLogger>,
2078		Arc<ChannelManager>,
2079		Arc<
2080			DefaultMessageRouter<
2081				Arc<NetworkGraph<Arc<test_utils::TestLogger>>>,
2082				Arc<test_utils::TestLogger>,
2083				Arc<KeysManager>,
2084			>,
2085		>,
2086		IgnoringMessageHandler,
2087		Arc<ChannelManager>,
2088		IgnoringMessageHandler,
2089		IgnoringMessageHandler,
2090	>;
2091
2092	type LM = LiquidityManagerSync<
2093		Arc<KeysManager>,
2094		Arc<KeysManager>,
2095		Arc<ChannelManager>,
2096		Arc<Persister>,
2097		DefaultTimeProvider,
2098		Arc<test_utils::TestBroadcaster>,
2099	>;
2100
2101	struct Node {
2102		node: Arc<ChannelManager>,
2103		messenger: Arc<OM>,
2104		p2p_gossip_sync: PGS,
2105		rapid_gossip_sync: RGS,
2106		peer_manager: Arc<
2107			PeerManager<
2108				TestDescriptor,
2109				Arc<test_utils::TestChannelMessageHandler>,
2110				Arc<test_utils::TestRoutingMessageHandler>,
2111				Arc<OM>,
2112				Arc<test_utils::TestLogger>,
2113				IgnoringMessageHandler,
2114				Arc<KeysManager>,
2115				IgnoringMessageHandler,
2116			>,
2117		>,
2118		liquidity_manager: Arc<LM>,
2119		chain_monitor: Arc<ChainMonitor>,
2120		kv_store: Arc<Persister>,
2121		tx_broadcaster: Arc<test_utils::TestBroadcaster>,
2122		network_graph: Arc<NetworkGraph<Arc<test_utils::TestLogger>>>,
2123		logger: Arc<test_utils::TestLogger>,
2124		best_block: BlockLocator,
2125		scorer: Arc<LockingWrapper<TestScorer>>,
2126		sweeper: Arc<
2127			OutputSweeperSync<
2128				Arc<test_utils::TestBroadcaster>,
2129				Arc<TestWallet>,
2130				Arc<test_utils::TestFeeEstimator>,
2131				Arc<test_utils::TestChainSource>,
2132				Arc<Persister>,
2133				Arc<test_utils::TestLogger>,
2134				Arc<KeysManager>,
2135			>,
2136		>,
2137	}
2138
2139	impl Node {
2140		fn p2p_gossip_sync(
2141			&self,
2142		) -> GossipSync<
2143			PGS,
2144			RGS,
2145			Arc<NetworkGraph<Arc<test_utils::TestLogger>>>,
2146			Arc<test_utils::TestChainSource>,
2147			Arc<test_utils::TestLogger>,
2148		> {
2149			GossipSync::P2P(Arc::clone(&self.p2p_gossip_sync))
2150		}
2151
2152		fn rapid_gossip_sync(
2153			&self,
2154		) -> GossipSync<
2155			PGS,
2156			RGS,
2157			Arc<NetworkGraph<Arc<test_utils::TestLogger>>>,
2158			Arc<test_utils::TestChainSource>,
2159			Arc<test_utils::TestLogger>,
2160		> {
2161			GossipSync::Rapid(Arc::clone(&self.rapid_gossip_sync))
2162		}
2163
2164		fn no_gossip_sync(
2165			&self,
2166		) -> GossipSync<
2167			PGS,
2168			RGS,
2169			Arc<NetworkGraph<Arc<test_utils::TestLogger>>>,
2170			Arc<test_utils::TestChainSource>,
2171			Arc<test_utils::TestLogger>,
2172		> {
2173			GossipSync::None
2174		}
2175	}
2176
2177	impl Drop for Node {
2178		fn drop(&mut self) {
2179			let data_dir = self.kv_store.get_data_dir();
2180			match fs::remove_dir_all(data_dir.clone()) {
2181				Err(e) => {
2182					println!("Failed to remove test store directory {}: {}", data_dir.display(), e)
2183				},
2184				_ => {},
2185			}
2186		}
2187	}
2188
2189	struct Persister {
2190		graph_error: Option<(std::io::ErrorKind, &'static str)>,
2191		graph_persistence_notifier: Option<SyncSender<()>>,
2192		manager_error: Option<(std::io::ErrorKind, &'static str)>,
2193		scorer_error: Option<(std::io::ErrorKind, &'static str)>,
2194		kv_store: FilesystemStore,
2195	}
2196
2197	impl Persister {
2198		fn new(data_dir: PathBuf) -> Self {
2199			let kv_store = FilesystemStore::new(data_dir);
2200			Self {
2201				graph_error: None,
2202				graph_persistence_notifier: None,
2203				manager_error: None,
2204				scorer_error: None,
2205				kv_store,
2206			}
2207		}
2208
2209		fn with_graph_error(self, error: std::io::ErrorKind, message: &'static str) -> Self {
2210			Self { graph_error: Some((error, message)), ..self }
2211		}
2212
2213		fn with_graph_persistence_notifier(self, sender: SyncSender<()>) -> Self {
2214			Self { graph_persistence_notifier: Some(sender), ..self }
2215		}
2216
2217		fn with_manager_error(self, error: std::io::ErrorKind, message: &'static str) -> Self {
2218			Self { manager_error: Some((error, message)), ..self }
2219		}
2220
2221		fn with_scorer_error(self, error: std::io::ErrorKind, message: &'static str) -> Self {
2222			Self { scorer_error: Some((error, message)), ..self }
2223		}
2224
2225		pub fn get_data_dir(&self) -> PathBuf {
2226			self.kv_store.get_data_dir()
2227		}
2228	}
2229
2230	impl KVStoreSync for Persister {
2231		fn read(
2232			&self, primary_namespace: &str, secondary_namespace: &str, key: &str,
2233		) -> lightning::io::Result<Vec<u8>> {
2234			self.kv_store.read(primary_namespace, secondary_namespace, key)
2235		}
2236
2237		fn write(
2238			&self, primary_namespace: &str, secondary_namespace: &str, key: &str, buf: Vec<u8>,
2239		) -> lightning::io::Result<()> {
2240			if primary_namespace == CHANNEL_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE
2241				&& secondary_namespace == CHANNEL_MANAGER_PERSISTENCE_SECONDARY_NAMESPACE
2242				&& key == CHANNEL_MANAGER_PERSISTENCE_KEY
2243			{
2244				if let Some((error, message)) = self.manager_error {
2245					return Err(std::io::Error::new(error, message).into());
2246				}
2247			}
2248
2249			if primary_namespace == NETWORK_GRAPH_PERSISTENCE_PRIMARY_NAMESPACE
2250				&& secondary_namespace == NETWORK_GRAPH_PERSISTENCE_SECONDARY_NAMESPACE
2251				&& key == NETWORK_GRAPH_PERSISTENCE_KEY
2252			{
2253				if let Some(sender) = &self.graph_persistence_notifier {
2254					match sender.send(()) {
2255						Ok(()) => {},
2256						Err(std::sync::mpsc::SendError(())) => {
2257							println!("Persister failed to notify as receiver went away.")
2258						},
2259					}
2260				};
2261
2262				if let Some((error, message)) = self.graph_error {
2263					return Err(std::io::Error::new(error, message).into());
2264				}
2265			}
2266
2267			if primary_namespace == SCORER_PERSISTENCE_PRIMARY_NAMESPACE
2268				&& secondary_namespace == SCORER_PERSISTENCE_SECONDARY_NAMESPACE
2269				&& key == SCORER_PERSISTENCE_KEY
2270			{
2271				if let Some((error, message)) = self.scorer_error {
2272					return Err(std::io::Error::new(error, message).into());
2273				}
2274			}
2275
2276			self.kv_store.write(primary_namespace, secondary_namespace, key, buf)
2277		}
2278
2279		fn remove(
2280			&self, primary_namespace: &str, secondary_namespace: &str, key: &str, lazy: bool,
2281		) -> lightning::io::Result<()> {
2282			self.kv_store.remove(primary_namespace, secondary_namespace, key, lazy)
2283		}
2284
2285		fn list(
2286			&self, primary_namespace: &str, secondary_namespace: &str,
2287		) -> lightning::io::Result<Vec<String>> {
2288			self.kv_store.list(primary_namespace, secondary_namespace)
2289		}
2290	}
2291
2292	struct TestScorer {
2293		event_expectations: Option<VecDeque<TestResult>>,
2294	}
2295
2296	#[derive(Debug)]
2297	enum TestResult {
2298		PaymentFailure { path: Path, short_channel_id: u64 },
2299		PaymentSuccess { path: Path },
2300		ProbeFailure { path: Path },
2301		ProbeSuccess { path: Path },
2302	}
2303
2304	impl TestScorer {
2305		fn new() -> Self {
2306			Self { event_expectations: None }
2307		}
2308
2309		fn expect(&mut self, expectation: TestResult) {
2310			self.event_expectations.get_or_insert_with(VecDeque::new).push_back(expectation);
2311		}
2312	}
2313
2314	impl lightning::util::ser::Writeable for TestScorer {
2315		fn write<W: lightning::util::ser::Writer>(
2316			&self, _: &mut W,
2317		) -> Result<(), lightning::io::Error> {
2318			Ok(())
2319		}
2320	}
2321
2322	impl ScoreLookUp for TestScorer {
2323		type ScoreParams = ();
2324		fn channel_penalty_msat(
2325			&self, _candidate: &CandidateRouteHop, _usage: ChannelUsage,
2326			_score_params: &Self::ScoreParams,
2327		) -> u64 {
2328			unimplemented!();
2329		}
2330	}
2331
2332	impl ScoreUpdate for TestScorer {
2333		fn payment_path_failed(
2334			&mut self, actual_path: &Path, actual_short_channel_id: u64, _: Duration,
2335		) {
2336			if let Some(expectations) = &mut self.event_expectations {
2337				match expectations.pop_front().unwrap() {
2338					TestResult::PaymentFailure { path, short_channel_id } => {
2339						assert_eq!(actual_path, &path);
2340						assert_eq!(actual_short_channel_id, short_channel_id);
2341					},
2342					TestResult::PaymentSuccess { path } => {
2343						panic!("Unexpected successful payment path: {:?}", path)
2344					},
2345					TestResult::ProbeFailure { path } => {
2346						panic!("Unexpected probe failure: {:?}", path)
2347					},
2348					TestResult::ProbeSuccess { path } => {
2349						panic!("Unexpected probe success: {:?}", path)
2350					},
2351				}
2352			}
2353		}
2354
2355		fn payment_path_successful(&mut self, actual_path: &Path, _: Duration) {
2356			if let Some(expectations) = &mut self.event_expectations {
2357				match expectations.pop_front().unwrap() {
2358					TestResult::PaymentFailure { path, .. } => {
2359						panic!("Unexpected payment path failure: {:?}", path)
2360					},
2361					TestResult::PaymentSuccess { path } => {
2362						assert_eq!(actual_path, &path);
2363					},
2364					TestResult::ProbeFailure { path } => {
2365						panic!("Unexpected probe failure: {:?}", path)
2366					},
2367					TestResult::ProbeSuccess { path } => {
2368						panic!("Unexpected probe success: {:?}", path)
2369					},
2370				}
2371			}
2372		}
2373
2374		fn probe_failed(&mut self, actual_path: &Path, _: u64, _: Duration) {
2375			if let Some(expectations) = &mut self.event_expectations {
2376				match expectations.pop_front().unwrap() {
2377					TestResult::PaymentFailure { path, .. } => {
2378						panic!("Unexpected payment path failure: {:?}", path)
2379					},
2380					TestResult::PaymentSuccess { path } => {
2381						panic!("Unexpected payment path success: {:?}", path)
2382					},
2383					TestResult::ProbeFailure { path } => {
2384						assert_eq!(actual_path, &path);
2385					},
2386					TestResult::ProbeSuccess { path } => {
2387						panic!("Unexpected probe success: {:?}", path)
2388					},
2389				}
2390			}
2391		}
2392		fn probe_successful(&mut self, actual_path: &Path, _: Duration) {
2393			if let Some(expectations) = &mut self.event_expectations {
2394				match expectations.pop_front().unwrap() {
2395					TestResult::PaymentFailure { path, .. } => {
2396						panic!("Unexpected payment path failure: {:?}", path)
2397					},
2398					TestResult::PaymentSuccess { path } => {
2399						panic!("Unexpected payment path success: {:?}", path)
2400					},
2401					TestResult::ProbeFailure { path } => {
2402						panic!("Unexpected probe failure: {:?}", path)
2403					},
2404					TestResult::ProbeSuccess { path } => {
2405						assert_eq!(actual_path, &path);
2406					},
2407				}
2408			}
2409		}
2410		fn time_passed(&mut self, _: Duration) {}
2411	}
2412
2413	#[cfg(c_bindings)]
2414	impl lightning::routing::scoring::Score for TestScorer {}
2415
2416	impl Drop for TestScorer {
2417		fn drop(&mut self) {
2418			if std::thread::panicking() {
2419				return;
2420			}
2421
2422			if let Some(event_expectations) = &self.event_expectations {
2423				if !event_expectations.is_empty() {
2424					panic!("Unsatisfied event expectations: {:?}", event_expectations);
2425				}
2426			}
2427		}
2428	}
2429
2430	struct TestWallet {}
2431
2432	impl ChangeDestinationSourceSync for TestWallet {
2433		fn get_change_destination_script(&self) -> Result<ScriptBuf, ()> {
2434			Ok(ScriptBuf::new())
2435		}
2436	}
2437
2438	fn get_full_filepath(filepath: String, filename: String) -> String {
2439		let mut path = PathBuf::from(filepath);
2440		path.push(filename);
2441		path.to_str().unwrap().to_string()
2442	}
2443
2444	fn create_nodes(num_nodes: usize, persist_dir: &str) -> (String, Vec<Node>) {
2445		let persist_temp_path = env::temp_dir().join(persist_dir);
2446		let persist_dir = persist_temp_path.to_string_lossy().to_string();
2447		let network = Network::Bitcoin;
2448		let mut nodes = Vec::new();
2449		for i in 0..num_nodes {
2450			let tx_broadcaster = Arc::new(test_utils::TestBroadcaster::new(network));
2451			let fee_estimator = Arc::new(test_utils::TestFeeEstimator::new(253));
2452			let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
2453			let genesis_block = genesis_block(network);
2454			let network_graph = Arc::new(NetworkGraph::new(network, Arc::clone(&logger)));
2455			let scorer = Arc::new(LockingWrapper::new(TestScorer::new()));
2456			let now = Duration::from_secs(genesis_block.header.time as u64);
2457			let seed = [i as u8; 32];
2458			let keys_manager =
2459				Arc::new(KeysManager::new(&seed, now.as_secs(), now.subsec_nanos(), true));
2460			let router = Arc::new(DefaultRouter::new(
2461				Arc::clone(&network_graph),
2462				Arc::clone(&logger),
2463				Arc::clone(&keys_manager),
2464				Arc::clone(&scorer),
2465				Default::default(),
2466			));
2467			let msg_router = Arc::new(DefaultMessageRouter::new(
2468				Arc::clone(&network_graph),
2469				Arc::clone(&keys_manager),
2470			));
2471			let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Bitcoin));
2472			let kv_store =
2473				Arc::new(Persister::new(format!("{}_persister_{}", &persist_dir, i).into()));
2474			let now = Duration::from_secs(genesis_block.header.time as u64);
2475			let keys_manager =
2476				Arc::new(KeysManager::new(&seed, now.as_secs(), now.subsec_nanos(), true));
2477			let chain_monitor = Arc::new(chainmonitor::ChainMonitor::new(
2478				Some(Arc::clone(&chain_source)),
2479				Arc::clone(&tx_broadcaster),
2480				Arc::clone(&logger),
2481				Arc::clone(&fee_estimator),
2482				Arc::clone(&kv_store),
2483				Arc::clone(&keys_manager),
2484				keys_manager.get_peer_storage_key(),
2485				true,
2486			));
2487			let best_block = BlockLocator::from_network(network);
2488			let params = ChainParameters { network, best_block };
2489			let mut config = UserConfig::default();
2490			config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = false;
2491			let manager = Arc::new(ChannelManager::new(
2492				Arc::clone(&fee_estimator),
2493				Arc::clone(&chain_monitor),
2494				Arc::clone(&tx_broadcaster),
2495				Arc::clone(&router),
2496				Arc::clone(&msg_router),
2497				Arc::clone(&logger),
2498				Arc::clone(&keys_manager),
2499				Arc::clone(&keys_manager),
2500				Arc::clone(&keys_manager),
2501				config,
2502				params,
2503				genesis_block.header.time,
2504			));
2505			let messenger = Arc::new(OnionMessenger::new(
2506				Arc::clone(&keys_manager),
2507				Arc::clone(&keys_manager),
2508				Arc::clone(&logger),
2509				Arc::clone(&manager),
2510				Arc::clone(&msg_router),
2511				IgnoringMessageHandler {},
2512				Arc::clone(&manager),
2513				IgnoringMessageHandler {},
2514				IgnoringMessageHandler {},
2515			));
2516			let wallet = Arc::new(TestWallet {});
2517			let sweeper = Arc::new(OutputSweeperSync::new(
2518				best_block,
2519				Arc::clone(&tx_broadcaster),
2520				Arc::clone(&fee_estimator),
2521				None::<Arc<test_utils::TestChainSource>>,
2522				Arc::clone(&keys_manager),
2523				wallet,
2524				Arc::clone(&kv_store),
2525				Arc::clone(&logger),
2526			));
2527			let p2p_gossip_sync = Arc::new(P2PGossipSync::new(
2528				Arc::clone(&network_graph),
2529				Some(Arc::clone(&chain_source)),
2530				Arc::clone(&logger),
2531			));
2532			let rapid_gossip_sync =
2533				Arc::new(RapidGossipSync::new(Arc::clone(&network_graph), Arc::clone(&logger)));
2534			let msg_handler = MessageHandler {
2535				chan_handler: Arc::new(test_utils::TestChannelMessageHandler::new(
2536					ChainHash::using_genesis_block(Network::Testnet),
2537				)),
2538				route_handler: Arc::new(test_utils::TestRoutingMessageHandler::new()),
2539				onion_message_handler: Arc::clone(&messenger),
2540				custom_message_handler: IgnoringMessageHandler {},
2541				send_only_message_handler: IgnoringMessageHandler {},
2542			};
2543			let peer_manager = Arc::new(PeerManager::new(
2544				msg_handler,
2545				0,
2546				&seed,
2547				Arc::clone(&logger),
2548				Arc::clone(&keys_manager),
2549			));
2550			let liquidity_manager = Arc::new(
2551				LiquidityManagerSync::new(
2552					Arc::clone(&keys_manager),
2553					Arc::clone(&keys_manager),
2554					Arc::clone(&manager),
2555					Arc::clone(&kv_store),
2556					Arc::clone(&tx_broadcaster),
2557					None,
2558					None,
2559				)
2560				.unwrap(),
2561			);
2562			let node = Node {
2563				node: manager,
2564				p2p_gossip_sync,
2565				rapid_gossip_sync,
2566				peer_manager,
2567				liquidity_manager,
2568				chain_monitor,
2569				kv_store,
2570				tx_broadcaster,
2571				network_graph,
2572				logger,
2573				best_block,
2574				scorer,
2575				sweeper,
2576				messenger,
2577			};
2578			nodes.push(node);
2579		}
2580
2581		for i in 0..num_nodes {
2582			for j in (i + 1)..num_nodes {
2583				let init_i = Init {
2584					features: nodes[j].node.init_features(),
2585					networks: None,
2586					remote_network_address: None,
2587				};
2588				nodes[i]
2589					.node
2590					.peer_connected(nodes[j].node.get_our_node_id(), &init_i, true)
2591					.unwrap();
2592				let init_j = Init {
2593					features: nodes[i].node.init_features(),
2594					networks: None,
2595					remote_network_address: None,
2596				};
2597				nodes[j]
2598					.node
2599					.peer_connected(nodes[i].node.get_our_node_id(), &init_j, false)
2600					.unwrap();
2601			}
2602		}
2603
2604		(persist_dir, nodes)
2605	}
2606
2607	/// Opens a channel between two nodes without a running `BackgroundProcessor`,
2608	/// so deferred monitor operations are flushed manually at each step.
2609	macro_rules! open_channel {
2610		($node_a: expr, $node_b: expr, $channel_value: expr) => {{
2611			begin_open_channel!($node_a, $node_b, $channel_value);
2612			let events = $node_a.node.get_and_clear_pending_events();
2613			assert_eq!(events.len(), 1);
2614			let (temporary_channel_id, tx) =
2615				handle_funding_generation_ready!(events[0], $channel_value);
2616			$node_a
2617				.node
2618				.funding_transaction_generated(
2619					temporary_channel_id,
2620					$node_b.node.get_our_node_id(),
2621					tx.clone(),
2622				)
2623				.unwrap();
2624			// funding_transaction_generated does not call watch_channel, so no
2625			// deferred op is queued and FundingCreated is available immediately.
2626			let msg_a = get_event_msg!(
2627				$node_a,
2628				MessageSendEvent::SendFundingCreated,
2629				$node_b.node.get_our_node_id()
2630			);
2631			$node_b.node.handle_funding_created($node_a.node.get_our_node_id(), &msg_a);
2632			// Flush node_b's new monitor (watch_channel) so it releases the
2633			// FundingSigned message.
2634			$node_b
2635				.chain_monitor
2636				.flush($node_b.chain_monitor.pending_operation_count(), &$node_b.logger);
2637			get_event!($node_b, Event::ChannelPending);
2638			let msg_b = get_event_msg!(
2639				$node_b,
2640				MessageSendEvent::SendFundingSigned,
2641				$node_a.node.get_our_node_id()
2642			);
2643			$node_a.node.handle_funding_signed($node_b.node.get_our_node_id(), &msg_b);
2644			// Flush node_a's new monitor (watch_channel) queued by
2645			// handle_funding_signed.
2646			$node_a
2647				.chain_monitor
2648				.flush($node_a.chain_monitor.pending_operation_count(), &$node_a.logger);
2649			get_event!($node_a, Event::ChannelPending);
2650			tx
2651		}};
2652	}
2653
2654	macro_rules! begin_open_channel {
2655		($node_a: expr, $node_b: expr, $channel_value: expr) => {{
2656			$node_a
2657				.node
2658				.create_channel($node_b.node.get_our_node_id(), $channel_value, 100, 42, None, None)
2659				.unwrap();
2660			let msg_a = get_event_msg!(
2661				$node_a,
2662				MessageSendEvent::SendOpenChannel,
2663				$node_b.node.get_our_node_id()
2664			);
2665			$node_b.node.handle_open_channel($node_a.node.get_our_node_id(), &msg_a);
2666			let events = $node_b.node.get_and_clear_pending_events();
2667			assert_eq!(events.len(), 1);
2668			match &events[0] {
2669				Event::OpenChannelRequest {
2670					temporary_channel_id, counterparty_node_id, ..
2671				} => {
2672					$node_b
2673						.node
2674						.accept_inbound_channel(
2675							temporary_channel_id,
2676							counterparty_node_id,
2677							42,
2678							None,
2679						)
2680						.unwrap();
2681				},
2682				_ => panic!("Unexpected event"),
2683			};
2684
2685			let msg_b = get_event_msg!(
2686				$node_b,
2687				MessageSendEvent::SendAcceptChannel,
2688				$node_a.node.get_our_node_id()
2689			);
2690			$node_a.node.handle_accept_channel($node_b.node.get_our_node_id(), &msg_b);
2691		}};
2692	}
2693
2694	macro_rules! handle_funding_generation_ready {
2695		($event: expr, $channel_value: expr) => {{
2696			match $event {
2697				Event::FundingGenerationReady {
2698					temporary_channel_id,
2699					channel_value_satoshis,
2700					ref output_script,
2701					user_channel_id,
2702					..
2703				} => {
2704					assert_eq!(channel_value_satoshis, $channel_value);
2705					assert_eq!(user_channel_id, 42);
2706
2707					let tx = Transaction {
2708						version: Version::ONE,
2709						lock_time: LockTime::ZERO,
2710						input: Vec::new(),
2711						output: vec![TxOut {
2712							value: Amount::from_sat(channel_value_satoshis),
2713							script_pubkey: output_script.clone(),
2714						}],
2715					};
2716					(temporary_channel_id, tx)
2717				},
2718				_ => panic!("Unexpected event"),
2719			}
2720		}};
2721	}
2722
2723	fn confirm_transaction_depth(node: &mut Node, tx: &Transaction, depth: u32) {
2724		for i in 1..=depth {
2725			let prev_blockhash = node.best_block.block_hash;
2726			let height = node.best_block.height + 1;
2727			let header = create_dummy_header(prev_blockhash, height);
2728			let txdata = vec![(0, tx)];
2729			node.best_block = BlockLocator::new(header.block_hash(), height);
2730			match i {
2731				1 => {
2732					node.node.transactions_confirmed(&header, &txdata, height);
2733					node.chain_monitor.transactions_confirmed(&header, &txdata, height);
2734					node.sweeper.transactions_confirmed(&header, &txdata, height);
2735				},
2736				x if x == depth => {
2737					// We need the TestBroadcaster to know about the new height so that it doesn't think
2738					// we're violating the time lock requirements of transactions broadcasted at that
2739					// point.
2740					let block = (genesis_block(Network::Bitcoin), height);
2741					node.tx_broadcaster.blocks.lock().unwrap().push(block);
2742					node.node.best_block_updated(&header, height);
2743					node.chain_monitor.best_block_updated(&header, height);
2744					node.sweeper.best_block_updated(&header, height);
2745				},
2746				_ => {},
2747			}
2748		}
2749	}
2750
2751	fn advance_chain(node: &mut Node, num_blocks: u32) {
2752		for i in 1..=num_blocks {
2753			let prev_blockhash = node.best_block.block_hash;
2754			let height = node.best_block.height + 1;
2755			let header = create_dummy_header(prev_blockhash, height);
2756			node.best_block = BlockLocator::new(header.block_hash(), height);
2757			if i == num_blocks {
2758				// We need the TestBroadcaster to know about the new height so that it doesn't think
2759				// we're violating the time lock requirements of transactions broadcasted at that
2760				// point.
2761				let block = (genesis_block(Network::Bitcoin), height);
2762				node.tx_broadcaster.blocks.lock().unwrap().push(block);
2763				node.node.best_block_updated(&header, height);
2764				node.chain_monitor.best_block_updated(&header, height);
2765				node.sweeper.best_block_updated(&header, height);
2766			}
2767		}
2768	}
2769
2770	fn confirm_transaction(node: &mut Node, tx: &Transaction) {
2771		confirm_transaction_depth(node, tx, ANTI_REORG_DELAY);
2772	}
2773
2774	/// Waits until the background processor has flushed all pending deferred monitor
2775	/// operations for the given node. Panics if the pending count does not reach zero
2776	/// within `EVENT_DEADLINE`.
2777	fn wait_for_flushed(chain_monitor: &ChainMonitor) {
2778		let start = std::time::Instant::now();
2779		while chain_monitor.pending_operation_count() > 0 {
2780			assert!(
2781				start.elapsed() < EVENT_DEADLINE,
2782				"Pending monitor operations were not flushed within deadline"
2783			);
2784			std::thread::sleep(Duration::from_millis(10));
2785		}
2786	}
2787
2788	#[test]
2789	fn test_background_processor() {
2790		// Test that when a new channel is created, the ChannelManager needs to be re-persisted with
2791		// updates. Also test that when new updates are available, the manager signals that it needs
2792		// re-persistence and is successfully re-persisted.
2793		let (persist_dir, nodes) = create_nodes(2, "test_background_processor");
2794
2795		// Go through the channel creation process so that each node has something to persist. Since
2796		// open_channel consumes events, it must complete before starting BackgroundProcessor to
2797		// avoid a race with processing events.
2798		let tx = open_channel!(nodes[0], nodes[1], 100000);
2799
2800		// Initiate the background processors to watch each node.
2801		let data_dir = nodes[0].kv_store.get_data_dir();
2802		let persister = Arc::new(Persister::new(data_dir));
2803		let event_handler = |_: _| Ok(());
2804		let bg_processor = BackgroundProcessor::start(
2805			persister,
2806			event_handler,
2807			Arc::clone(&nodes[0].chain_monitor),
2808			Arc::clone(&nodes[0].node),
2809			Some(Arc::clone(&nodes[0].messenger)),
2810			nodes[0].p2p_gossip_sync(),
2811			Arc::clone(&nodes[0].peer_manager),
2812			Some(Arc::clone(&nodes[0].liquidity_manager)),
2813			Some(Arc::clone(&nodes[0].sweeper)),
2814			Arc::clone(&nodes[0].logger),
2815			Some(Arc::clone(&nodes[0].scorer)),
2816		);
2817
2818		macro_rules! check_persisted_data {
2819			($node: expr, $filepath: expr) => {
2820				let mut expected_bytes = Vec::new();
2821				loop {
2822					expected_bytes.clear();
2823					match $node.write(&mut expected_bytes) {
2824						Ok(()) => match std::fs::read($filepath) {
2825							Ok(bytes) => {
2826								if bytes == expected_bytes {
2827									break;
2828								} else {
2829									continue;
2830								}
2831							},
2832							Err(_) => continue,
2833						},
2834						Err(e) => panic!("Unexpected error: {}", e),
2835					}
2836				}
2837			};
2838		}
2839
2840		// Check that the initial channel manager data is persisted as expected.
2841		let filepath =
2842			get_full_filepath(format!("{}_persister_0", &persist_dir), "manager".to_string());
2843		check_persisted_data!(nodes[0].node, filepath.clone());
2844
2845		loop {
2846			if !nodes[0].node.get_event_or_persist_condvar_value() {
2847				break;
2848			}
2849		}
2850
2851		// Force-close the channel.
2852		let error_message = "Channel force-closed";
2853		nodes[0]
2854			.node
2855			.force_close_broadcasting_latest_txn(
2856				&ChannelId::v1_from_funding_outpoint(OutPoint {
2857					txid: tx.compute_txid(),
2858					index: 0,
2859				}),
2860				&nodes[1].node.get_our_node_id(),
2861				error_message.to_string(),
2862			)
2863			.unwrap();
2864
2865		// Check that the force-close updates are persisted.
2866		check_persisted_data!(nodes[0].node, filepath.clone());
2867		loop {
2868			if !nodes[0].node.get_event_or_persist_condvar_value() {
2869				break;
2870			}
2871		}
2872
2873		// Check network graph is persisted
2874		let filepath =
2875			get_full_filepath(format!("{}_persister_0", &persist_dir), "network_graph".to_string());
2876		check_persisted_data!(nodes[0].network_graph, filepath.clone());
2877
2878		// Check scorer is persisted
2879		let filepath =
2880			get_full_filepath(format!("{}_persister_0", &persist_dir), "scorer".to_string());
2881		check_persisted_data!(nodes[0].scorer, filepath.clone());
2882
2883		if !std::thread::panicking() {
2884			bg_processor.stop().unwrap();
2885		}
2886	}
2887
2888	#[test]
2889	fn test_timer_tick_called() {
2890		// Test that:
2891		// - `ChannelManager::timer_tick_occurred` is called every `FRESHNESS_TIMER`,
2892		// - `ChainMonitor::rebroadcast_pending_claims` is called every `REBROADCAST_TIMER`,
2893		// - `PeerManager::timer_tick_occurred` is called every `PING_TIMER`, and
2894		// - `OnionMessageHandler::timer_tick_occurred` is called every `ONION_MESSAGE_HANDLER_TIMER`.
2895		let (_, nodes) = create_nodes(1, "test_timer_tick_called");
2896		let data_dir = nodes[0].kv_store.get_data_dir();
2897		let persister = Arc::new(Persister::new(data_dir));
2898		let event_handler = |_: _| Ok(());
2899		let bg_processor = BackgroundProcessor::start(
2900			persister,
2901			event_handler,
2902			Arc::clone(&nodes[0].chain_monitor),
2903			Arc::clone(&nodes[0].node),
2904			Some(Arc::clone(&nodes[0].messenger)),
2905			nodes[0].no_gossip_sync(),
2906			Arc::clone(&nodes[0].peer_manager),
2907			Some(Arc::clone(&nodes[0].liquidity_manager)),
2908			Some(Arc::clone(&nodes[0].sweeper)),
2909			Arc::clone(&nodes[0].logger),
2910			Some(Arc::clone(&nodes[0].scorer)),
2911		);
2912		loop {
2913			let log_entries = nodes[0].logger.lines.lock().unwrap();
2914			let desired_log_1 = "Calling ChannelManager's timer_tick_occurred".to_string();
2915			let desired_log_2 = "Calling PeerManager's timer_tick_occurred".to_string();
2916			let desired_log_3 = "Rebroadcasting monitor's pending claims".to_string();
2917			let desired_log_4 = "Calling OnionMessageHandler's timer_tick_occurred".to_string();
2918			if log_entries.get(&("lightning_background_processor", desired_log_1)).is_some()
2919				&& log_entries.get(&("lightning_background_processor", desired_log_2)).is_some()
2920				&& log_entries.get(&("lightning_background_processor", desired_log_3)).is_some()
2921				&& log_entries.get(&("lightning_background_processor", desired_log_4)).is_some()
2922			{
2923				break;
2924			}
2925		}
2926
2927		if !std::thread::panicking() {
2928			bg_processor.stop().unwrap();
2929		}
2930	}
2931
2932	#[test]
2933	fn test_channel_manager_persist_error() {
2934		// Test that if we encounter an error during manager persistence, the thread panics.
2935		let (_, nodes) = create_nodes(2, "test_persist_error");
2936		open_channel!(nodes[0], nodes[1], 100000);
2937
2938		let data_dir = nodes[0].kv_store.get_data_dir();
2939		let persister = Arc::new(
2940			Persister::new(data_dir).with_manager_error(std::io::ErrorKind::Other, "test"),
2941		);
2942		let event_handler = |_: _| Ok(());
2943		let bg_processor = BackgroundProcessor::start(
2944			persister,
2945			event_handler,
2946			Arc::clone(&nodes[0].chain_monitor),
2947			Arc::clone(&nodes[0].node),
2948			Some(Arc::clone(&nodes[0].messenger)),
2949			nodes[0].no_gossip_sync(),
2950			Arc::clone(&nodes[0].peer_manager),
2951			Some(Arc::clone(&nodes[0].liquidity_manager)),
2952			Some(Arc::clone(&nodes[0].sweeper)),
2953			Arc::clone(&nodes[0].logger),
2954			Some(Arc::clone(&nodes[0].scorer)),
2955		);
2956		match bg_processor.join() {
2957			Ok(_) => panic!("Expected error persisting manager"),
2958			Err(e) => {
2959				assert_eq!(e.kind(), std::io::ErrorKind::Other);
2960				assert_eq!(e.get_ref().unwrap().to_string(), "test");
2961			},
2962		}
2963	}
2964
2965	#[tokio::test]
2966	async fn test_channel_manager_persist_error_async() {
2967		// Test that if we encounter an error during manager persistence, the thread panics.
2968		let (_, nodes) = create_nodes(2, "test_persist_error_sync");
2969		open_channel!(nodes[0], nodes[1], 100000);
2970
2971		let data_dir = nodes[0].kv_store.get_data_dir();
2972		let kv_store_sync = Arc::new(
2973			Persister::new(data_dir).with_manager_error(std::io::ErrorKind::Other, "test"),
2974		);
2975		let kv_store = KVStoreSyncWrapper(kv_store_sync);
2976
2977		// Yes, you can unsafe { turn off the borrow checker }
2978		let lm_async: &'static LiquidityManager<_, _, _, _, _, _> = unsafe {
2979			&*(nodes[0].liquidity_manager.get_lm_async()
2980				as *const LiquidityManager<_, _, _, _, _, _>)
2981				as &'static LiquidityManager<_, _, _, _, _, _>
2982		};
2983		let sweeper_async: &'static OutputSweeper<_, _, _, _, _, _, _> = unsafe {
2984			&*(nodes[0].sweeper.sweeper_async() as *const OutputSweeper<_, _, _, _, _, _, _>)
2985				as &'static OutputSweeper<_, _, _, _, _, _, _>
2986		};
2987
2988		let bp_future = super::process_events_async(
2989			kv_store,
2990			|_: _| async { Ok(()) },
2991			Arc::clone(&nodes[0].chain_monitor),
2992			Arc::clone(&nodes[0].node),
2993			Some(Arc::clone(&nodes[0].messenger)),
2994			nodes[0].rapid_gossip_sync(),
2995			Arc::clone(&nodes[0].peer_manager),
2996			Some(lm_async),
2997			Some(sweeper_async),
2998			Arc::clone(&nodes[0].logger),
2999			Some(Arc::clone(&nodes[0].scorer)),
3000			move |dur: Duration| {
3001				Box::pin(async move {
3002					tokio::time::sleep(dur).await;
3003					false // Never exit
3004				})
3005			},
3006			false,
3007			|| Some(Duration::ZERO),
3008		);
3009		match bp_future.await {
3010			Ok(_) => panic!("Expected error persisting manager"),
3011			Err(e) => {
3012				assert_eq!(e.kind(), lightning::io::ErrorKind::Other);
3013				assert_eq!(e.get_ref().unwrap().to_string(), "test");
3014			},
3015		}
3016	}
3017
3018	#[test]
3019	fn test_network_graph_persist_error() {
3020		// Test that if we encounter an error during network graph persistence, an error gets returned.
3021		let (_, nodes) = create_nodes(2, "test_persist_network_graph_error");
3022		let data_dir = nodes[0].kv_store.get_data_dir();
3023		let persister =
3024			Arc::new(Persister::new(data_dir).with_graph_error(std::io::ErrorKind::Other, "test"));
3025		let event_handler = |_: _| Ok(());
3026		let bg_processor = BackgroundProcessor::start(
3027			persister,
3028			event_handler,
3029			Arc::clone(&nodes[0].chain_monitor),
3030			Arc::clone(&nodes[0].node),
3031			Some(Arc::clone(&nodes[0].messenger)),
3032			nodes[0].p2p_gossip_sync(),
3033			Arc::clone(&nodes[0].peer_manager),
3034			Some(Arc::clone(&nodes[0].liquidity_manager)),
3035			Some(Arc::clone(&nodes[0].sweeper)),
3036			Arc::clone(&nodes[0].logger),
3037			Some(Arc::clone(&nodes[0].scorer)),
3038		);
3039
3040		match bg_processor.stop() {
3041			Ok(_) => panic!("Expected error persisting network graph"),
3042			Err(e) => {
3043				assert_eq!(e.kind(), std::io::ErrorKind::Other);
3044				assert_eq!(e.get_ref().unwrap().to_string(), "test");
3045			},
3046		}
3047	}
3048
3049	#[test]
3050	fn test_scorer_persist_error() {
3051		// Test that if we encounter an error during scorer persistence, an error gets returned.
3052		let (_, nodes) = create_nodes(2, "test_persist_scorer_error");
3053		let data_dir = nodes[0].kv_store.get_data_dir();
3054		let persister =
3055			Arc::new(Persister::new(data_dir).with_scorer_error(std::io::ErrorKind::Other, "test"));
3056		let event_handler = |_: _| Ok(());
3057		let bg_processor = BackgroundProcessor::start(
3058			persister,
3059			event_handler,
3060			Arc::clone(&nodes[0].chain_monitor),
3061			Arc::clone(&nodes[0].node),
3062			Some(Arc::clone(&nodes[0].messenger)),
3063			nodes[0].no_gossip_sync(),
3064			Arc::clone(&nodes[0].peer_manager),
3065			Some(Arc::clone(&nodes[0].liquidity_manager)),
3066			Some(Arc::clone(&nodes[0].sweeper)),
3067			Arc::clone(&nodes[0].logger),
3068			Some(Arc::clone(&nodes[0].scorer)),
3069		);
3070
3071		match bg_processor.stop() {
3072			Ok(_) => panic!("Expected error persisting scorer"),
3073			Err(e) => {
3074				assert_eq!(e.kind(), std::io::ErrorKind::Other);
3075				assert_eq!(e.get_ref().unwrap().to_string(), "test");
3076			},
3077		}
3078	}
3079
3080	#[test]
3081	fn test_background_event_handling() {
3082		let (_, mut nodes) = create_nodes(2, "test_background_event_handling");
3083		let node_0_id = nodes[0].node.get_our_node_id();
3084		let node_1_id = nodes[1].node.get_our_node_id();
3085
3086		let channel_value = 100000;
3087		let data_dir = nodes[0].kv_store.get_data_dir();
3088		let persister = Arc::new(Persister::new(data_dir.clone()));
3089
3090		// Set up a background event handler for FundingGenerationReady events.
3091		let (funding_generation_send, funding_generation_recv) = std::sync::mpsc::sync_channel(1);
3092		let (channel_pending_send, channel_pending_recv) = std::sync::mpsc::sync_channel(1);
3093		let event_handler = move |event: Event| {
3094			match event {
3095				Event::FundingGenerationReady { .. } => funding_generation_send
3096					.send(handle_funding_generation_ready!(event, channel_value))
3097					.unwrap(),
3098				Event::ChannelPending { .. } => channel_pending_send.send(()).unwrap(),
3099				Event::ChannelReady { .. } => {},
3100				_ => panic!("Unexpected event: {:?}", event),
3101			}
3102			Ok(())
3103		};
3104
3105		let bg_processor = BackgroundProcessor::start(
3106			persister,
3107			event_handler,
3108			Arc::clone(&nodes[0].chain_monitor),
3109			Arc::clone(&nodes[0].node),
3110			Some(Arc::clone(&nodes[0].messenger)),
3111			nodes[0].no_gossip_sync(),
3112			Arc::clone(&nodes[0].peer_manager),
3113			Some(Arc::clone(&nodes[0].liquidity_manager)),
3114			Some(Arc::clone(&nodes[0].sweeper)),
3115			Arc::clone(&nodes[0].logger),
3116			Some(Arc::clone(&nodes[0].scorer)),
3117		);
3118
3119		// Open a channel and check that the FundingGenerationReady event was handled.
3120		begin_open_channel!(nodes[0], nodes[1], channel_value);
3121		let (temporary_channel_id, funding_tx) = funding_generation_recv
3122			.recv_timeout(EVENT_DEADLINE)
3123			.expect("FundingGenerationReady not handled within deadline");
3124		nodes[0]
3125			.node
3126			.funding_transaction_generated(temporary_channel_id, node_1_id, funding_tx.clone())
3127			.unwrap();
3128		// funding_transaction_generated does not call watch_channel, so no deferred op is
3129		// queued and the FundingCreated message is available immediately.
3130		let msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, node_1_id);
3131		nodes[1].node.handle_funding_created(node_0_id, &msg_0);
3132		// Node 1 has no bg processor, flush its new monitor (watch_channel) manually so
3133		// events and FundingSigned are released.
3134		nodes[1]
3135			.chain_monitor
3136			.flush(nodes[1].chain_monitor.pending_operation_count(), &nodes[1].logger);
3137		get_event!(nodes[1], Event::ChannelPending);
3138		let msg_1 = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, node_0_id);
3139		nodes[0].node.handle_funding_signed(node_1_id, &msg_1);
3140		// Wait for the bg processor to flush the new monitor (watch_channel) queued by
3141		// handle_funding_signed.
3142		wait_for_flushed(&nodes[0].chain_monitor);
3143		channel_pending_recv
3144			.recv_timeout(EVENT_DEADLINE)
3145			.expect("ChannelPending not handled within deadline");
3146
3147		// Confirm the funding transaction.
3148		confirm_transaction(&mut nodes[0], &funding_tx);
3149		let as_funding = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, node_1_id);
3150		confirm_transaction(&mut nodes[1], &funding_tx);
3151		let bs_funding = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReady, node_0_id);
3152		nodes[0].node.handle_channel_ready(node_1_id, &bs_funding);
3153		let _as_channel_update =
3154			get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, node_1_id);
3155		nodes[1].node.handle_channel_ready(node_0_id, &as_funding);
3156		let _bs_channel_update =
3157			get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, node_0_id);
3158		let broadcast_funding =
3159			nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().pop().unwrap();
3160		assert_eq!(broadcast_funding.compute_txid(), funding_tx.compute_txid());
3161		assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
3162
3163		if !std::thread::panicking() {
3164			bg_processor.stop().unwrap();
3165		}
3166
3167		// Set up a background event handler for SpendableOutputs events.
3168		let (sender, receiver) = std::sync::mpsc::sync_channel(1);
3169		let event_handler = move |event: Event| {
3170			match event {
3171				Event::SpendableOutputs { .. } => sender.send(event).unwrap(),
3172				Event::ChannelReady { .. } => {},
3173				Event::ChannelClosed { .. } => {},
3174				_ => panic!("Unexpected event: {:?}", event),
3175			}
3176			Ok(())
3177		};
3178		let persister = Arc::new(Persister::new(data_dir));
3179		let bg_processor = BackgroundProcessor::start(
3180			persister,
3181			event_handler,
3182			Arc::clone(&nodes[0].chain_monitor),
3183			Arc::clone(&nodes[0].node),
3184			Some(Arc::clone(&nodes[0].messenger)),
3185			nodes[0].no_gossip_sync(),
3186			Arc::clone(&nodes[0].peer_manager),
3187			Some(Arc::clone(&nodes[0].liquidity_manager)),
3188			Some(Arc::clone(&nodes[0].sweeper)),
3189			Arc::clone(&nodes[0].logger),
3190			Some(Arc::clone(&nodes[0].scorer)),
3191		);
3192
3193		// Force close the channel and check that the SpendableOutputs event was handled.
3194		let error_message = "Channel force-closed";
3195		nodes[0]
3196			.node
3197			.force_close_broadcasting_latest_txn(
3198				&nodes[0].node.list_channels()[0].channel_id,
3199				&node_1_id,
3200				error_message.to_string(),
3201			)
3202			.unwrap();
3203		// Wait for the bg processor to flush the monitor update triggered by force close
3204		// so the commitment tx is broadcast.
3205		wait_for_flushed(&nodes[0].chain_monitor);
3206		let commitment_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().pop().unwrap();
3207		confirm_transaction_depth(&mut nodes[0], &commitment_tx, BREAKDOWN_TIMEOUT as u32);
3208
3209		let event =
3210			receiver.recv_timeout(EVENT_DEADLINE).expect("Events not handled within deadline");
3211		match event {
3212			Event::SpendableOutputs { outputs, channel_id, counterparty_node_id } => {
3213				nodes[0]
3214					.sweeper
3215					.track_spendable_outputs(
3216						outputs,
3217						channel_id,
3218						counterparty_node_id,
3219						false,
3220						Some(153),
3221					)
3222					.unwrap();
3223			},
3224			_ => panic!("Unexpected event: {:?}", event),
3225		}
3226
3227		// Check we don't generate an initial sweeping tx until we reach the required height.
3228		assert_eq!(nodes[0].sweeper.tracked_spendable_outputs().len(), 1);
3229		let tracked_output = nodes[0].sweeper.tracked_spendable_outputs().first().unwrap().clone();
3230		if let Some(sweep_tx_0) = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().pop() {
3231			assert!(!tracked_output.is_spent_in(&sweep_tx_0));
3232			match tracked_output.status {
3233				OutputSpendStatus::PendingInitialBroadcast { delayed_until_height } => {
3234					assert_eq!(delayed_until_height, Some(153));
3235				},
3236				_ => panic!("Unexpected status"),
3237			}
3238		}
3239
3240		advance_chain(&mut nodes[0], 3);
3241
3242		let tx_broadcaster = Arc::clone(&nodes[0].tx_broadcaster);
3243		let wait_for_sweep_tx = || -> Transaction {
3244			loop {
3245				let sweep_tx = tx_broadcaster.txn_broadcasted.lock().unwrap().pop();
3246				if let Some(sweep_tx) = sweep_tx {
3247					return sweep_tx;
3248				}
3249
3250				std::thread::sleep(Duration::from_millis(10));
3251			}
3252		};
3253
3254		// Check we generate an initial sweeping tx.
3255		assert_eq!(nodes[0].sweeper.tracked_spendable_outputs().len(), 1);
3256		let sweep_tx_0 = wait_for_sweep_tx();
3257		let tracked_output = nodes[0].sweeper.tracked_spendable_outputs().first().unwrap().clone();
3258		match tracked_output.status {
3259			OutputSpendStatus::PendingFirstConfirmation { latest_spending_tx, .. } => {
3260				assert_eq!(sweep_tx_0.compute_txid(), latest_spending_tx.compute_txid());
3261			},
3262			_ => panic!("Unexpected status"),
3263		}
3264
3265		// Check we regenerate and rebroadcast the sweeping tx each block.
3266		advance_chain(&mut nodes[0], 1);
3267		assert_eq!(nodes[0].sweeper.tracked_spendable_outputs().len(), 1);
3268		let sweep_tx_1 = wait_for_sweep_tx();
3269		let tracked_output = nodes[0].sweeper.tracked_spendable_outputs().first().unwrap().clone();
3270		match tracked_output.status {
3271			OutputSpendStatus::PendingFirstConfirmation { latest_spending_tx, .. } => {
3272				assert_eq!(sweep_tx_1.compute_txid(), latest_spending_tx.compute_txid());
3273			},
3274			_ => panic!("Unexpected status"),
3275		}
3276		assert_ne!(sweep_tx_0, sweep_tx_1);
3277
3278		advance_chain(&mut nodes[0], 1);
3279		assert_eq!(nodes[0].sweeper.tracked_spendable_outputs().len(), 1);
3280		let sweep_tx_2 = wait_for_sweep_tx();
3281		let tracked_output = nodes[0].sweeper.tracked_spendable_outputs().first().unwrap().clone();
3282		match tracked_output.status {
3283			OutputSpendStatus::PendingFirstConfirmation { latest_spending_tx, .. } => {
3284				assert_eq!(sweep_tx_2.compute_txid(), latest_spending_tx.compute_txid());
3285			},
3286			_ => panic!("Unexpected status"),
3287		}
3288		assert_ne!(sweep_tx_0, sweep_tx_2);
3289		assert_ne!(sweep_tx_1, sweep_tx_2);
3290
3291		// Check we still track the spendable outputs up to ANTI_REORG_DELAY confirmations.
3292		confirm_transaction_depth(&mut nodes[0], &sweep_tx_2, 5);
3293		assert_eq!(nodes[0].sweeper.tracked_spendable_outputs().len(), 1);
3294		let tracked_output = nodes[0].sweeper.tracked_spendable_outputs().first().unwrap().clone();
3295		match tracked_output.status {
3296			OutputSpendStatus::PendingThresholdConfirmations { latest_spending_tx, .. } => {
3297				assert_eq!(sweep_tx_2.compute_txid(), latest_spending_tx.compute_txid());
3298			},
3299			_ => panic!("Unexpected status"),
3300		}
3301
3302		// Check we still see the transaction as confirmed if we unconfirm any untracked
3303		// transaction. (We previously had a bug that would mark tracked transactions as
3304		// unconfirmed if any transaction at an unknown block height would be unconfirmed.)
3305		let unconf_txid = Txid::from_slice(&[0; 32]).unwrap();
3306		nodes[0].sweeper.transaction_unconfirmed(&unconf_txid);
3307
3308		assert_eq!(nodes[0].sweeper.tracked_spendable_outputs().len(), 1);
3309		let tracked_output = nodes[0].sweeper.tracked_spendable_outputs().first().unwrap().clone();
3310		match tracked_output.status {
3311			OutputSpendStatus::PendingThresholdConfirmations { latest_spending_tx, .. } => {
3312				assert_eq!(sweep_tx_2.compute_txid(), latest_spending_tx.compute_txid());
3313			},
3314			_ => panic!("Unexpected status"),
3315		}
3316
3317		// Check we stop tracking the spendable outputs when one of the txs reaches
3318		// PRUNE_DELAY_BLOCKS confirmations.
3319		confirm_transaction_depth(&mut nodes[0], &sweep_tx_0, PRUNE_DELAY_BLOCKS);
3320		assert_eq!(nodes[0].sweeper.tracked_spendable_outputs().len(), 0);
3321
3322		if !std::thread::panicking() {
3323			bg_processor.stop().unwrap();
3324		}
3325	}
3326
3327	#[test]
3328	fn test_event_handling_failures_are_replayed() {
3329		let (_, nodes) = create_nodes(2, "test_event_handling_failures_are_replayed");
3330		let channel_value = 100000;
3331		let data_dir = nodes[0].kv_store.get_data_dir();
3332		let persister = Arc::new(Persister::new(data_dir.clone()));
3333
3334		let (first_event_send, first_event_recv) = std::sync::mpsc::sync_channel(1);
3335		let (second_event_send, second_event_recv) = std::sync::mpsc::sync_channel(1);
3336		let should_fail_event_handling = Arc::new(AtomicBool::new(true));
3337		let event_handler = move |event: Event| {
3338			if let Ok(true) = should_fail_event_handling.compare_exchange(
3339				true,
3340				false,
3341				Ordering::Acquire,
3342				Ordering::Relaxed,
3343			) {
3344				first_event_send.send(event).unwrap();
3345				return Err(ReplayEvent());
3346			}
3347
3348			second_event_send.send(event).unwrap();
3349			Ok(())
3350		};
3351
3352		let bg_processor = BackgroundProcessor::start(
3353			persister,
3354			event_handler,
3355			Arc::clone(&nodes[0].chain_monitor),
3356			Arc::clone(&nodes[0].node),
3357			Some(Arc::clone(&nodes[0].messenger)),
3358			nodes[0].no_gossip_sync(),
3359			Arc::clone(&nodes[0].peer_manager),
3360			Some(Arc::clone(&nodes[0].liquidity_manager)),
3361			Some(Arc::clone(&nodes[0].sweeper)),
3362			Arc::clone(&nodes[0].logger),
3363			Some(Arc::clone(&nodes[0].scorer)),
3364		);
3365
3366		begin_open_channel!(nodes[0], nodes[1], channel_value);
3367		assert_eq!(
3368			first_event_recv.recv_timeout(EVENT_DEADLINE).unwrap(),
3369			second_event_recv.recv_timeout(EVENT_DEADLINE).unwrap()
3370		);
3371
3372		if !std::thread::panicking() {
3373			bg_processor.stop().unwrap();
3374		}
3375	}
3376
3377	#[test]
3378	fn test_scorer_persistence() {
3379		let (_, nodes) = create_nodes(2, "test_scorer_persistence");
3380		let data_dir = nodes[0].kv_store.get_data_dir();
3381		let persister = Arc::new(Persister::new(data_dir));
3382		let event_handler = |_: _| Ok(());
3383		let bg_processor = BackgroundProcessor::start(
3384			persister,
3385			event_handler,
3386			Arc::clone(&nodes[0].chain_monitor),
3387			Arc::clone(&nodes[0].node),
3388			Some(Arc::clone(&nodes[0].messenger)),
3389			nodes[0].no_gossip_sync(),
3390			Arc::clone(&nodes[0].peer_manager),
3391			Some(Arc::clone(&nodes[0].liquidity_manager)),
3392			Some(Arc::clone(&nodes[0].sweeper)),
3393			Arc::clone(&nodes[0].logger),
3394			Some(Arc::clone(&nodes[0].scorer)),
3395		);
3396
3397		loop {
3398			let log_entries = nodes[0].logger.lines.lock().unwrap();
3399			let expected_log = "Calling time_passed and persisting scorer".to_string();
3400			if log_entries.get(&("lightning_background_processor", expected_log)).is_some() {
3401				break;
3402			}
3403		}
3404
3405		if !std::thread::panicking() {
3406			bg_processor.stop().unwrap();
3407		}
3408	}
3409
3410	macro_rules! do_test_not_pruning_network_graph_until_graph_sync_completion {
3411		($nodes: expr, $receive: expr, $sleep: expr) => {
3412			let features = ChannelFeatures::empty();
3413			$nodes[0]
3414				.network_graph
3415				.add_channel_from_partial_announcement(
3416					42,
3417					None,
3418					53,
3419					features,
3420					$nodes[0].node.get_our_node_id().into(),
3421					$nodes[1].node.get_our_node_id().into(),
3422				)
3423				.expect("Failed to update channel from partial announcement");
3424			let original_graph_description = $nodes[0].network_graph.to_string();
3425			assert!(original_graph_description.contains("42: features: 0000, node_one:"));
3426			assert_eq!($nodes[0].network_graph.read_only().channels().len(), 1);
3427
3428			loop {
3429				$sleep;
3430				let log_entries = $nodes[0].logger.lines.lock().unwrap();
3431				let loop_counter = "Calling ChannelManager's timer_tick_occurred".to_string();
3432				if *log_entries.get(&("lightning_background_processor", loop_counter)).unwrap_or(&0)
3433					> 1
3434				{
3435					// Wait until the loop has gone around at least twice.
3436					break;
3437				}
3438			}
3439
3440			let initialization_input = vec![
3441				76, 68, 75, 1, 111, 226, 140, 10, 182, 241, 179, 114, 193, 166, 162, 70, 174, 99,
3442				247, 79, 147, 30, 131, 101, 225, 90, 8, 156, 104, 214, 25, 0, 0, 0, 0, 0, 97, 227,
3443				98, 218, 0, 0, 0, 4, 2, 22, 7, 207, 206, 25, 164, 197, 231, 230, 231, 56, 102, 61,
3444				250, 251, 187, 172, 38, 46, 79, 247, 108, 44, 155, 48, 219, 238, 252, 53, 192, 6,
3445				67, 2, 36, 125, 157, 176, 223, 175, 234, 116, 94, 248, 201, 225, 97, 235, 50, 47,
3446				115, 172, 63, 136, 88, 216, 115, 11, 111, 217, 114, 84, 116, 124, 231, 107, 2, 158,
3447				1, 242, 121, 152, 106, 204, 131, 186, 35, 93, 70, 216, 10, 237, 224, 183, 89, 95,
3448				65, 3, 83, 185, 58, 138, 181, 64, 187, 103, 127, 68, 50, 2, 201, 19, 17, 138, 136,
3449				149, 185, 226, 156, 137, 175, 110, 32, 237, 0, 217, 90, 31, 100, 228, 149, 46, 219,
3450				175, 168, 77, 4, 143, 38, 128, 76, 97, 0, 0, 0, 2, 0, 0, 255, 8, 153, 192, 0, 2,
3451				27, 0, 0, 0, 1, 0, 0, 255, 2, 68, 226, 0, 6, 11, 0, 1, 2, 3, 0, 0, 0, 2, 0, 40, 0,
3452				0, 0, 0, 0, 0, 3, 232, 0, 0, 3, 232, 0, 0, 0, 1, 0, 0, 0, 0, 58, 85, 116, 216, 255,
3453				8, 153, 192, 0, 2, 27, 0, 0, 25, 0, 0, 0, 1, 0, 0, 0, 125, 255, 2, 68, 226, 0, 6,
3454				11, 0, 1, 5, 0, 0, 0, 0, 29, 129, 25, 192,
3455			];
3456			$nodes[0]
3457				.rapid_gossip_sync
3458				.update_network_graph_no_std(&initialization_input[..], Some(1642291930))
3459				.unwrap();
3460
3461			// this should have added two channels and pruned the previous one.
3462			assert_eq!($nodes[0].network_graph.read_only().channels().len(), 2);
3463
3464			$receive.expect("Network graph not pruned within deadline");
3465
3466			// all channels should now be pruned
3467			assert_eq!($nodes[0].network_graph.read_only().channels().len(), 0);
3468		};
3469	}
3470
3471	#[test]
3472	fn test_not_pruning_network_graph_until_graph_sync_completion() {
3473		let (sender, receiver) = std::sync::mpsc::sync_channel(1);
3474
3475		let (_, nodes) =
3476			create_nodes(2, "test_not_pruning_network_graph_until_graph_sync_completion");
3477		let data_dir = nodes[0].kv_store.get_data_dir();
3478		let persister = Arc::new(Persister::new(data_dir).with_graph_persistence_notifier(sender));
3479
3480		let event_handler = |_: _| Ok(());
3481		let background_processor = BackgroundProcessor::start(
3482			persister,
3483			event_handler,
3484			Arc::clone(&nodes[0].chain_monitor),
3485			Arc::clone(&nodes[0].node),
3486			Some(Arc::clone(&nodes[0].messenger)),
3487			nodes[0].rapid_gossip_sync(),
3488			Arc::clone(&nodes[0].peer_manager),
3489			Some(Arc::clone(&nodes[0].liquidity_manager)),
3490			Some(Arc::clone(&nodes[0].sweeper)),
3491			Arc::clone(&nodes[0].logger),
3492			Some(Arc::clone(&nodes[0].scorer)),
3493		);
3494
3495		do_test_not_pruning_network_graph_until_graph_sync_completion!(
3496			nodes,
3497			receiver.recv_timeout(super::FIRST_NETWORK_PRUNE_TIMER * 5),
3498			std::thread::sleep(Duration::from_millis(1))
3499		);
3500
3501		background_processor.stop().unwrap();
3502	}
3503
3504	#[tokio::test]
3505	async fn test_not_pruning_network_graph_until_graph_sync_completion_async() {
3506		let (sender, receiver) = std::sync::mpsc::sync_channel(1);
3507
3508		let (_, nodes) =
3509			create_nodes(2, "test_not_pruning_network_graph_until_graph_sync_completion_async");
3510		let data_dir = nodes[0].kv_store.get_data_dir();
3511		let kv_store_sync =
3512			Arc::new(Persister::new(data_dir).with_graph_persistence_notifier(sender));
3513		let kv_store = KVStoreSyncWrapper(kv_store_sync);
3514
3515		// Yes, you can unsafe { turn off the borrow checker }
3516		let lm_async: &'static LiquidityManager<_, _, _, _, _, _> = unsafe {
3517			&*(nodes[0].liquidity_manager.get_lm_async()
3518				as *const LiquidityManager<_, _, _, _, _, _>)
3519				as &'static LiquidityManager<_, _, _, _, _, _>
3520		};
3521		let sweeper_async: &'static OutputSweeper<_, _, _, _, _, _, _> = unsafe {
3522			&*(nodes[0].sweeper.sweeper_async() as *const OutputSweeper<_, _, _, _, _, _, _>)
3523				as &'static OutputSweeper<_, _, _, _, _, _, _>
3524		};
3525
3526		let (exit_sender, exit_receiver) = tokio::sync::watch::channel(());
3527		let bp_future = super::process_events_async(
3528			kv_store,
3529			|_: _| async { Ok(()) },
3530			Arc::clone(&nodes[0].chain_monitor),
3531			Arc::clone(&nodes[0].node),
3532			Some(Arc::clone(&nodes[0].messenger)),
3533			nodes[0].rapid_gossip_sync(),
3534			Arc::clone(&nodes[0].peer_manager),
3535			Some(lm_async),
3536			Some(sweeper_async),
3537			Arc::clone(&nodes[0].logger),
3538			Some(Arc::clone(&nodes[0].scorer)),
3539			move |dur: Duration| {
3540				let mut exit_receiver = exit_receiver.clone();
3541				Box::pin(async move {
3542					tokio::select! {
3543						_ = tokio::time::sleep(dur) => false,
3544						_ = exit_receiver.changed() => true,
3545					}
3546				})
3547			},
3548			false,
3549			|| Some(Duration::from_secs(1696300000)),
3550		);
3551
3552		let t1 = tokio::spawn(bp_future);
3553		let t2 = tokio::spawn(async move {
3554			do_test_not_pruning_network_graph_until_graph_sync_completion!(
3555				nodes,
3556				{
3557					let mut i = 0;
3558					loop {
3559						tokio::time::sleep(super::FIRST_NETWORK_PRUNE_TIMER).await;
3560						if let Ok(()) = receiver.try_recv() {
3561							break Ok::<(), ()>(());
3562						}
3563						assert!(i < 5);
3564						i += 1;
3565					}
3566				},
3567				tokio::time::sleep(Duration::from_millis(1)).await
3568			);
3569			exit_sender.send(()).unwrap();
3570		});
3571		let (r1, r2) = tokio::join!(t1, t2);
3572		r1.unwrap().unwrap();
3573		r2.unwrap()
3574	}
3575
3576	macro_rules! do_test_payment_path_scoring {
3577		($nodes: expr, $receive: expr) => {
3578			// Ensure that we update the scorer when relevant events are processed. In this case, we ensure
3579			// that we update the scorer upon a payment path succeeding (note that the channel must be
3580			// public or else we won't score it).
3581			// A background event handler for FundingGenerationReady events must be hooked up to a
3582			// running background processor.
3583			let scored_scid = 4242;
3584			let secp_ctx = Secp256k1::new();
3585			let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
3586			let node_1_id = PublicKey::from_secret_key(&secp_ctx, &node_1_privkey);
3587
3588			let path = Path { hops: vec![RouteHop {
3589				pubkey: node_1_id,
3590				node_features: NodeFeatures::empty(),
3591				short_channel_id: scored_scid,
3592				channel_features: ChannelFeatures::empty(),
3593				fee_msat: 0,
3594				cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA as u32,
3595				maybe_announced_channel: true,
3596			}], blinded_tail: None };
3597
3598			$nodes[0].scorer.write_lock().expect(TestResult::PaymentFailure { path: path.clone(), short_channel_id: scored_scid });
3599			$nodes[0].node.push_pending_event(Event::PaymentPathFailed {
3600				payment_id: None,
3601				payment_hash: PaymentHash([42; 32]),
3602				payment_failed_permanently: false,
3603				failure: PathFailure::OnPath { network_update: None },
3604				path: path.clone(),
3605				short_channel_id: Some(scored_scid),
3606				error_code: None,
3607				error_data: None,
3608				hold_times: Vec::new(),
3609			});
3610			let event = $receive.expect("PaymentPathFailed not handled within deadline");
3611			match event {
3612				Event::PaymentPathFailed { .. } => {},
3613				_ => panic!("Unexpected event"),
3614			}
3615
3616			// Ensure we'll score payments that were explicitly failed back by the destination as
3617			// ProbeSuccess.
3618			$nodes[0].scorer.write_lock().expect(TestResult::ProbeSuccess { path: path.clone() });
3619			$nodes[0].node.push_pending_event(Event::PaymentPathFailed {
3620				payment_id: None,
3621				payment_hash: PaymentHash([42; 32]),
3622				payment_failed_permanently: true,
3623				failure: PathFailure::OnPath { network_update: None },
3624				path: path.clone(),
3625				short_channel_id: None,
3626				error_code: None,
3627				error_data: None,
3628				hold_times: Vec::new(),
3629			});
3630			let event = $receive.expect("PaymentPathFailed not handled within deadline");
3631			match event {
3632				Event::PaymentPathFailed { .. } => {},
3633				_ => panic!("Unexpected event"),
3634			}
3635
3636			$nodes[0].scorer.write_lock().expect(TestResult::PaymentSuccess { path: path.clone() });
3637			$nodes[0].node.push_pending_event(Event::PaymentPathSuccessful {
3638				payment_id: PaymentId([42; 32]),
3639				payment_hash: None,
3640				path: path.clone(),
3641				hold_times: Vec::new(),
3642			});
3643			let event = $receive.expect("PaymentPathSuccessful not handled within deadline");
3644			match event {
3645				Event::PaymentPathSuccessful { .. } => {},
3646				_ => panic!("Unexpected event"),
3647			}
3648
3649			$nodes[0].scorer.write_lock().expect(TestResult::ProbeSuccess { path: path.clone() });
3650			$nodes[0].node.push_pending_event(Event::ProbeSuccessful {
3651				payment_id: PaymentId([42; 32]),
3652				payment_hash: PaymentHash([42; 32]),
3653				path: path.clone(),
3654			});
3655			let event = $receive.expect("ProbeSuccessful not handled within deadline");
3656			match event {
3657				Event::ProbeSuccessful  { .. } => {},
3658				_ => panic!("Unexpected event"),
3659			}
3660
3661			$nodes[0].scorer.write_lock().expect(TestResult::ProbeFailure { path: path.clone() });
3662			$nodes[0].node.push_pending_event(Event::ProbeFailed {
3663				payment_id: PaymentId([42; 32]),
3664				payment_hash: PaymentHash([42; 32]),
3665				path,
3666				short_channel_id: Some(scored_scid),
3667			});
3668			let event = $receive.expect("ProbeFailure not handled within deadline");
3669			match event {
3670				Event::ProbeFailed { .. } => {},
3671				_ => panic!("Unexpected event"),
3672			}
3673		}
3674	}
3675
3676	#[test]
3677	fn test_payment_path_scoring() {
3678		let (sender, receiver) = std::sync::mpsc::sync_channel(1);
3679		let event_handler = move |event: Event| {
3680			match event {
3681				Event::PaymentPathFailed { .. } => sender.send(event).unwrap(),
3682				Event::PaymentPathSuccessful { .. } => sender.send(event).unwrap(),
3683				Event::ProbeSuccessful { .. } => sender.send(event).unwrap(),
3684				Event::ProbeFailed { .. } => sender.send(event).unwrap(),
3685				_ => panic!("Unexpected event: {:?}", event),
3686			}
3687			Ok(())
3688		};
3689
3690		let (_, nodes) = create_nodes(1, "test_payment_path_scoring");
3691		let data_dir = nodes[0].kv_store.get_data_dir();
3692		let persister = Arc::new(Persister::new(data_dir));
3693		let bg_processor = BackgroundProcessor::start(
3694			persister,
3695			event_handler,
3696			Arc::clone(&nodes[0].chain_monitor),
3697			Arc::clone(&nodes[0].node),
3698			Some(Arc::clone(&nodes[0].messenger)),
3699			nodes[0].no_gossip_sync(),
3700			Arc::clone(&nodes[0].peer_manager),
3701			Some(Arc::clone(&nodes[0].liquidity_manager)),
3702			Some(Arc::clone(&nodes[0].sweeper)),
3703			Arc::clone(&nodes[0].logger),
3704			Some(Arc::clone(&nodes[0].scorer)),
3705		);
3706
3707		do_test_payment_path_scoring!(nodes, receiver.recv_timeout(EVENT_DEADLINE));
3708
3709		if !std::thread::panicking() {
3710			bg_processor.stop().unwrap();
3711		}
3712
3713		let log_entries = nodes[0].logger.lines.lock().unwrap();
3714		let expected_log = "Persisting scorer after update".to_string();
3715		assert_eq!(*log_entries.get(&("lightning_background_processor", expected_log)).unwrap(), 5);
3716	}
3717
3718	#[tokio::test]
3719	async fn test_payment_path_scoring_async() {
3720		let (sender, mut receiver) = tokio::sync::mpsc::channel(1);
3721		let event_handler = move |event: Event| {
3722			let sender_ref = sender.clone();
3723			async move {
3724				match event {
3725					Event::PaymentPathFailed { .. } => sender_ref.send(event).await.unwrap(),
3726					Event::PaymentPathSuccessful { .. } => sender_ref.send(event).await.unwrap(),
3727					Event::ProbeSuccessful { .. } => sender_ref.send(event).await.unwrap(),
3728					Event::ProbeFailed { .. } => sender_ref.send(event).await.unwrap(),
3729					_ => panic!("Unexpected event: {:?}", event),
3730				}
3731				Ok(())
3732			}
3733		};
3734
3735		let (_, nodes) = create_nodes(1, "test_payment_path_scoring_async");
3736		let data_dir = nodes[0].kv_store.get_data_dir();
3737		let kv_store_sync = Arc::new(Persister::new(data_dir));
3738		let kv_store = KVStoreSyncWrapper(kv_store_sync);
3739
3740		let (exit_sender, exit_receiver) = tokio::sync::watch::channel(());
3741
3742		// Yes, you can unsafe { turn off the borrow checker }
3743		let lm_async: &'static LiquidityManager<_, _, _, _, _, _> = unsafe {
3744			&*(nodes[0].liquidity_manager.get_lm_async()
3745				as *const LiquidityManager<_, _, _, _, _, _>)
3746				as &'static LiquidityManager<_, _, _, _, _, _>
3747		};
3748		let sweeper_async: &'static OutputSweeper<_, _, _, _, _, _, _> = unsafe {
3749			&*(nodes[0].sweeper.sweeper_async() as *const OutputSweeper<_, _, _, _, _, _, _>)
3750				as &'static OutputSweeper<_, _, _, _, _, _, _>
3751		};
3752
3753		let bp_future = super::process_events_async(
3754			kv_store,
3755			event_handler,
3756			Arc::clone(&nodes[0].chain_monitor),
3757			Arc::clone(&nodes[0].node),
3758			Some(Arc::clone(&nodes[0].messenger)),
3759			nodes[0].no_gossip_sync(),
3760			Arc::clone(&nodes[0].peer_manager),
3761			Some(lm_async),
3762			Some(sweeper_async),
3763			Arc::clone(&nodes[0].logger),
3764			Some(Arc::clone(&nodes[0].scorer)),
3765			move |dur: Duration| {
3766				let mut exit_receiver = exit_receiver.clone();
3767				Box::pin(async move {
3768					tokio::select! {
3769						_ = tokio::time::sleep(dur) => false,
3770						_ = exit_receiver.changed() => true,
3771					}
3772				})
3773			},
3774			false,
3775			|| Some(Duration::ZERO),
3776		);
3777		let t1 = tokio::spawn(bp_future);
3778		let t2 = tokio::spawn(async move {
3779			do_test_payment_path_scoring!(nodes, receiver.recv().await);
3780			exit_sender.send(()).unwrap();
3781
3782			let log_entries = nodes[0].logger.lines.lock().unwrap();
3783			let expected_log = "Persisting scorer after update".to_string();
3784			assert_eq!(
3785				*log_entries.get(&("lightning_background_processor", expected_log)).unwrap(),
3786				5
3787			);
3788		});
3789
3790		let (r1, r2) = tokio::join!(t1, t2);
3791		r1.unwrap().unwrap();
3792		r2.unwrap()
3793	}
3794
3795	#[tokio::test]
3796	#[cfg(not(c_bindings))]
3797	async fn test_no_consts() {
3798		// Compile-test the NO_* constants can be used.
3799		let (_, nodes) = create_nodes(1, "test_no_consts");
3800		let bg_processor = BackgroundProcessor::start(
3801			Arc::clone(&nodes[0].kv_store),
3802			move |_: Event| Ok(()),
3803			Arc::clone(&nodes[0].chain_monitor),
3804			Arc::clone(&nodes[0].node),
3805			crate::NO_ONION_MESSENGER,
3806			nodes[0].no_gossip_sync(),
3807			Arc::clone(&nodes[0].peer_manager),
3808			crate::NO_LIQUIDITY_MANAGER_SYNC,
3809			Some(Arc::clone(&nodes[0].sweeper)),
3810			Arc::clone(&nodes[0].logger),
3811			Some(Arc::clone(&nodes[0].scorer)),
3812		);
3813
3814		if !std::thread::panicking() {
3815			bg_processor.stop().unwrap();
3816		}
3817
3818		let kv_store = KVStoreSyncWrapper(Arc::clone(&nodes[0].kv_store));
3819		let (exit_sender, exit_receiver) = tokio::sync::watch::channel(());
3820		let sweeper_async: &'static OutputSweeper<_, _, _, _, _, _, _> = unsafe {
3821			&*(nodes[0].sweeper.sweeper_async() as *const OutputSweeper<_, _, _, _, _, _, _>)
3822				as &'static OutputSweeper<_, _, _, _, _, _, _>
3823		};
3824		let bp_future = super::process_events_async(
3825			kv_store,
3826			move |_: Event| async move { Ok(()) },
3827			Arc::clone(&nodes[0].chain_monitor),
3828			Arc::clone(&nodes[0].node),
3829			crate::NO_ONION_MESSENGER,
3830			nodes[0].no_gossip_sync(),
3831			Arc::clone(&nodes[0].peer_manager),
3832			crate::NO_LIQUIDITY_MANAGER,
3833			Some(sweeper_async),
3834			Arc::clone(&nodes[0].logger),
3835			Some(Arc::clone(&nodes[0].scorer)),
3836			move |dur: Duration| {
3837				let mut exit_receiver = exit_receiver.clone();
3838				Box::pin(async move {
3839					tokio::select! {
3840						_ = tokio::time::sleep(dur) => false,
3841						_ = exit_receiver.changed() => true,
3842					}
3843				})
3844			},
3845			false,
3846			|| Some(Duration::ZERO),
3847		);
3848		let t1 = tokio::spawn(bp_future);
3849		exit_sender.send(()).unwrap();
3850		t1.await.unwrap().unwrap();
3851	}
3852
3853	#[test]
3854	fn test_monitor_archive() {
3855		let (persist_dir, nodes) = create_nodes(2, "test_monitor_archive");
3856		// Open a channel, but don't confirm it so that it prunes immediately on FC.
3857		open_channel!(nodes[0], nodes[1], 100000);
3858
3859		let data_dir = nodes[1].kv_store.get_data_dir();
3860		let persister = Arc::new(Persister::new(data_dir));
3861		let event_handler = |_: _| Ok(());
3862		let bp = BackgroundProcessor::start(
3863			persister,
3864			event_handler,
3865			Arc::clone(&nodes[1].chain_monitor),
3866			Arc::clone(&nodes[1].node),
3867			Some(Arc::clone(&nodes[1].messenger)),
3868			nodes[1].p2p_gossip_sync(),
3869			Arc::clone(&nodes[1].peer_manager),
3870			Some(Arc::clone(&nodes[1].liquidity_manager)),
3871			Some(Arc::clone(&nodes[1].sweeper)),
3872			Arc::clone(&nodes[1].logger),
3873			Some(Arc::clone(&nodes[1].scorer)),
3874		);
3875
3876		let dir = format!("{}_persister_1/monitors", &persist_dir);
3877		let mut mons = list_monitor_files(&dir);
3878		assert_eq!(mons.len(), 1);
3879		let mon = mons.pop().unwrap();
3880
3881		// Because the channel wasn't funded, we'll archive the ChannelMonitor immedaitely after
3882		// its force-closed (at least on node B, which didn't put their money into it).
3883		nodes[1].node.force_close_all_channels_broadcasting_latest_txn("".to_owned());
3884		loop {
3885			let mons = list_monitor_files(&dir);
3886			if mons.is_empty() {
3887				break;
3888			}
3889			assert_eq!(mons.len(), 1);
3890			assert_eq!(mons[0].path(), mon.path());
3891		}
3892
3893		bp.stop().unwrap();
3894	}
3895
3896	#[tokio::test]
3897	#[cfg(not(c_bindings))]
3898	async fn test_monitor_archive_async() {
3899		let (persist_dir, nodes) = create_nodes(2, "test_monitor_archive_async");
3900		// Open a channel, but don't confirm it so that it prunes immediately on FC.
3901		open_channel!(nodes[0], nodes[1], 100000);
3902
3903		let kv_store = KVStoreSyncWrapper(Arc::clone(&nodes[0].kv_store));
3904		let sweeper_async: &'static OutputSweeper<_, _, _, _, _, _, _> = unsafe {
3905			&*(nodes[0].sweeper.sweeper_async() as *const OutputSweeper<_, _, _, _, _, _, _>)
3906				as &'static OutputSweeper<_, _, _, _, _, _, _>
3907		};
3908		let (exit_sender, exit_receiver) = tokio::sync::watch::channel(());
3909		let bp_future = tokio::spawn(super::process_events_async(
3910			kv_store,
3911			move |_: Event| async move { Ok(()) },
3912			Arc::clone(&nodes[1].chain_monitor),
3913			Arc::clone(&nodes[1].node),
3914			crate::NO_ONION_MESSENGER,
3915			nodes[1].no_gossip_sync(),
3916			Arc::clone(&nodes[1].peer_manager),
3917			crate::NO_LIQUIDITY_MANAGER,
3918			Some(sweeper_async),
3919			Arc::clone(&nodes[1].logger),
3920			Some(Arc::clone(&nodes[1].scorer)),
3921			move |dur: Duration| {
3922				let mut exit_receiver = exit_receiver.clone();
3923				Box::pin(async move {
3924					tokio::select! {
3925						_ = tokio::time::sleep(dur) => false,
3926						_ = exit_receiver.changed() => true,
3927					}
3928				})
3929			},
3930			false,
3931			|| Some(Duration::ZERO),
3932		));
3933
3934		let dir = format!("{}_persister_1/monitors", &persist_dir);
3935		let mut mons = list_monitor_files(&dir);
3936		assert_eq!(mons.len(), 1);
3937		let mon = mons.pop().unwrap();
3938
3939		// Because the channel wasn't funded, we'll archive the ChannelMonitor immedaitely after
3940		// its force-closed (at least on node B, which didn't put their money into it).
3941		nodes[1].node.force_close_all_channels_broadcasting_latest_txn("".to_owned());
3942		loop {
3943			let mons = list_monitor_files(&dir);
3944			if mons.is_empty() {
3945				break;
3946			}
3947			assert_eq!(mons.len(), 1);
3948			assert_eq!(mons[0].path(), mon.path());
3949			tokio::task::yield_now().await;
3950		}
3951
3952		exit_sender.send(()).unwrap();
3953		bp_future.await.unwrap().unwrap();
3954	}
3955}