Don't immediately exit BP if `ChannelManager` is persistable
[rust-lightning] / lightning-background-processor / src / lib.rs
1 //! Utilities that take care of tasks that (1) need to happen periodically to keep Rust-Lightning
2 //! running properly, and (2) either can or should be run in the background. See docs for
3 //! [`BackgroundProcessor`] for more details on the nitty-gritty.
4
5 // Prefix these with `rustdoc::` when we update our MSRV to be >= 1.52 to remove warnings.
6 #![deny(broken_intra_doc_links)]
7 #![deny(private_intra_doc_links)]
8
9 #![deny(missing_docs)]
10 #![cfg_attr(not(feature = "futures"), deny(unsafe_code))]
11
12 #![cfg_attr(docsrs, feature(doc_auto_cfg))]
13
14 #![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
15
16 #[cfg(any(test, feature = "std"))]
17 extern crate core;
18
19 #[cfg(not(feature = "std"))]
20 extern crate alloc;
21
22 #[macro_use] extern crate lightning;
23 extern crate lightning_rapid_gossip_sync;
24
25 use lightning::chain;
26 use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
27 use lightning::chain::chainmonitor::{ChainMonitor, Persist};
28 use lightning::chain::keysinterface::{EntropySource, NodeSigner, SignerProvider};
29 use lightning::events::{Event, PathFailure};
30 #[cfg(feature = "std")]
31 use lightning::events::{EventHandler, EventsProvider};
32 use lightning::ln::channelmanager::ChannelManager;
33 use lightning::ln::msgs::{ChannelMessageHandler, OnionMessageHandler, RoutingMessageHandler};
34 use lightning::ln::peer_handler::{CustomMessageHandler, PeerManager, SocketDescriptor};
35 use lightning::routing::gossip::{NetworkGraph, P2PGossipSync};
36 use lightning::routing::utxo::UtxoLookup;
37 use lightning::routing::router::Router;
38 use lightning::routing::scoring::{Score, WriteableScore};
39 use lightning::util::logger::Logger;
40 use lightning::util::persist::Persister;
41 #[cfg(feature = "std")]
42 use lightning::util::wakers::Sleeper;
43 use lightning_rapid_gossip_sync::RapidGossipSync;
44
45 use core::ops::Deref;
46 use core::time::Duration;
47
48 #[cfg(feature = "std")]
49 use std::sync::Arc;
50 #[cfg(feature = "std")]
51 use core::sync::atomic::{AtomicBool, Ordering};
52 #[cfg(feature = "std")]
53 use std::thread::{self, JoinHandle};
54 #[cfg(feature = "std")]
55 use std::time::Instant;
56
57 #[cfg(not(feature = "std"))]
58 use alloc::vec::Vec;
59
60 /// `BackgroundProcessor` takes care of tasks that (1) need to happen periodically to keep
61 /// Rust-Lightning running properly, and (2) either can or should be run in the background. Its
62 /// responsibilities are:
63 /// * Processing [`Event`]s with a user-provided [`EventHandler`].
64 /// * Monitoring whether the [`ChannelManager`] needs to be re-persisted to disk, and if so,
65 ///   writing it to disk/backups by invoking the callback given to it at startup.
66 ///   [`ChannelManager`] persistence should be done in the background.
67 /// * Calling [`ChannelManager::timer_tick_occurred`] and [`PeerManager::timer_tick_occurred`]
68 ///   at the appropriate intervals.
69 /// * Calling [`NetworkGraph::remove_stale_channels_and_tracking`] (if a [`GossipSync`] with a
70 ///   [`NetworkGraph`] is provided to [`BackgroundProcessor::start`]).
71 ///
72 /// It will also call [`PeerManager::process_events`] periodically though this shouldn't be relied
73 /// upon as doing so may result in high latency.
74 ///
75 /// # Note
76 ///
77 /// If [`ChannelManager`] persistence fails and the persisted manager becomes out-of-date, then
78 /// there is a risk of channels force-closing on startup when the manager realizes it's outdated.
79 /// However, as long as [`ChannelMonitor`] backups are sound, no funds besides those used for
80 /// unilateral chain closure fees are at risk.
81 ///
82 /// [`ChannelMonitor`]: lightning::chain::channelmonitor::ChannelMonitor
83 /// [`Event`]: lightning::events::Event
84 #[cfg(feature = "std")]
85 #[must_use = "BackgroundProcessor will immediately stop on drop. It should be stored until shutdown."]
86 pub struct BackgroundProcessor {
87         stop_thread: Arc<AtomicBool>,
88         thread_handle: Option<JoinHandle<Result<(), std::io::Error>>>,
89 }
90
91 #[cfg(not(test))]
92 const FRESHNESS_TIMER: u64 = 60;
93 #[cfg(test)]
94 const FRESHNESS_TIMER: u64 = 1;
95
96 #[cfg(all(not(test), not(debug_assertions)))]
97 const PING_TIMER: u64 = 10;
98 /// Signature operations take a lot longer without compiler optimisations.
99 /// Increasing the ping timer allows for this but slower devices will be disconnected if the
100 /// timeout is reached.
101 #[cfg(all(not(test), debug_assertions))]
102 const PING_TIMER: u64 = 30;
103 #[cfg(test)]
104 const PING_TIMER: u64 = 1;
105
106 /// Prune the network graph of stale entries hourly.
107 const NETWORK_PRUNE_TIMER: u64 = 60 * 60;
108
109 #[cfg(not(test))]
110 const SCORER_PERSIST_TIMER: u64 = 30;
111 #[cfg(test)]
112 const SCORER_PERSIST_TIMER: u64 = 1;
113
114 #[cfg(not(test))]
115 const FIRST_NETWORK_PRUNE_TIMER: u64 = 60;
116 #[cfg(test)]
117 const FIRST_NETWORK_PRUNE_TIMER: u64 = 1;
118
119 #[cfg(feature = "futures")]
120 /// core::cmp::min is not currently const, so we define a trivial (and equivalent) replacement
121 const fn min_u64(a: u64, b: u64) -> u64 { if a < b { a } else { b } }
122 #[cfg(feature = "futures")]
123 const FASTEST_TIMER: u64 = min_u64(min_u64(FRESHNESS_TIMER, PING_TIMER),
124         min_u64(SCORER_PERSIST_TIMER, FIRST_NETWORK_PRUNE_TIMER));
125
126 /// Either [`P2PGossipSync`] or [`RapidGossipSync`].
127 pub enum GossipSync<
128         P: Deref<Target = P2PGossipSync<G, U, L>>,
129         R: Deref<Target = RapidGossipSync<G, L>>,
130         G: Deref<Target = NetworkGraph<L>>,
131         U: Deref,
132         L: Deref,
133 >
134 where U::Target: UtxoLookup, L::Target: Logger {
135         /// Gossip sync via the lightning peer-to-peer network as defined by BOLT 7.
136         P2P(P),
137         /// Rapid gossip sync from a trusted server.
138         Rapid(R),
139         /// No gossip sync.
140         None,
141 }
142
143 impl<
144         P: Deref<Target = P2PGossipSync<G, U, L>>,
145         R: Deref<Target = RapidGossipSync<G, L>>,
146         G: Deref<Target = NetworkGraph<L>>,
147         U: Deref,
148         L: Deref,
149 > GossipSync<P, R, G, U, L>
150 where U::Target: UtxoLookup, L::Target: Logger {
151         fn network_graph(&self) -> Option<&G> {
152                 match self {
153                         GossipSync::P2P(gossip_sync) => Some(gossip_sync.network_graph()),
154                         GossipSync::Rapid(gossip_sync) => Some(gossip_sync.network_graph()),
155                         GossipSync::None => None,
156                 }
157         }
158
159         fn prunable_network_graph(&self) -> Option<&G> {
160                 match self {
161                         GossipSync::P2P(gossip_sync) => Some(gossip_sync.network_graph()),
162                         GossipSync::Rapid(gossip_sync) => {
163                                 if gossip_sync.is_initial_sync_complete() {
164                                         Some(gossip_sync.network_graph())
165                                 } else {
166                                         None
167                                 }
168                         },
169                         GossipSync::None => None,
170                 }
171         }
172 }
173
174 /// This is not exported to bindings users as the bindings concretize everything and have constructors for us
175 impl<P: Deref<Target = P2PGossipSync<G, U, L>>, G: Deref<Target = NetworkGraph<L>>, U: Deref, L: Deref>
176         GossipSync<P, &RapidGossipSync<G, L>, G, U, L>
177 where
178         U::Target: UtxoLookup,
179         L::Target: Logger,
180 {
181         /// Initializes a new [`GossipSync::P2P`] variant.
182         pub fn p2p(gossip_sync: P) -> Self {
183                 GossipSync::P2P(gossip_sync)
184         }
185 }
186
187 /// This is not exported to bindings users as the bindings concretize everything and have constructors for us
188 impl<'a, R: Deref<Target = RapidGossipSync<G, L>>, G: Deref<Target = NetworkGraph<L>>, L: Deref>
189         GossipSync<
190                 &P2PGossipSync<G, &'a (dyn UtxoLookup + Send + Sync), L>,
191                 R,
192                 G,
193                 &'a (dyn UtxoLookup + Send + Sync),
194                 L,
195         >
196 where
197         L::Target: Logger,
198 {
199         /// Initializes a new [`GossipSync::Rapid`] variant.
200         pub fn rapid(gossip_sync: R) -> Self {
201                 GossipSync::Rapid(gossip_sync)
202         }
203 }
204
205 /// This is not exported to bindings users as the bindings concretize everything and have constructors for us
206 impl<'a, L: Deref>
207         GossipSync<
208                 &P2PGossipSync<&'a NetworkGraph<L>, &'a (dyn UtxoLookup + Send + Sync), L>,
209                 &RapidGossipSync<&'a NetworkGraph<L>, L>,
210                 &'a NetworkGraph<L>,
211                 &'a (dyn UtxoLookup + Send + Sync),
212                 L,
213         >
214 where
215         L::Target: Logger,
216 {
217         /// Initializes a new [`GossipSync::None`] variant.
218         pub fn none() -> Self {
219                 GossipSync::None
220         }
221 }
222
223 fn handle_network_graph_update<L: Deref>(
224         network_graph: &NetworkGraph<L>, event: &Event
225 ) where L::Target: Logger {
226         if let Event::PaymentPathFailed {
227                 failure: PathFailure::OnPath { network_update: Some(ref upd) }, .. } = event
228         {
229                 network_graph.handle_network_update(upd);
230         }
231 }
232
233 fn update_scorer<'a, S: 'static + Deref<Target = SC> + Send + Sync, SC: 'a + WriteableScore<'a>>(
234         scorer: &'a S, event: &Event
235 ) {
236         let mut score = scorer.lock();
237         match event {
238                 Event::PaymentPathFailed { ref path, short_channel_id: Some(scid), .. } => {
239                         let path = path.iter().collect::<Vec<_>>();
240                         score.payment_path_failed(&path, *scid);
241                 },
242                 Event::PaymentPathFailed { ref path, payment_failed_permanently: true, .. } => {
243                         // Reached if the destination explicitly failed it back. We treat this as a successful probe
244                         // because the payment made it all the way to the destination with sufficient liquidity.
245                         let path = path.iter().collect::<Vec<_>>();
246                         score.probe_successful(&path);
247                 },
248                 Event::PaymentPathSuccessful { path, .. } => {
249                         let path = path.iter().collect::<Vec<_>>();
250                         score.payment_path_successful(&path);
251                 },
252                 Event::ProbeSuccessful { path, .. } => {
253                         let path = path.iter().collect::<Vec<_>>();
254                         score.probe_successful(&path);
255                 },
256                 Event::ProbeFailed { path, short_channel_id: Some(scid), .. } => {
257                         let path = path.iter().collect::<Vec<_>>();
258                         score.probe_failed(&path, *scid);
259                 },
260                 _ => {},
261         }
262 }
263
264 macro_rules! define_run_body {
265         ($persister: ident, $chain_monitor: ident, $process_chain_monitor_events: expr,
266          $channel_manager: ident, $process_channel_manager_events: expr,
267          $gossip_sync: ident, $peer_manager: ident, $logger: ident, $scorer: ident,
268          $loop_exit_check: expr, $await: expr, $get_timer: expr, $timer_elapsed: expr,
269          $check_slow_await: expr)
270         => { {
271                 log_trace!($logger, "Calling ChannelManager's timer_tick_occurred on startup");
272                 $channel_manager.timer_tick_occurred();
273
274                 let mut last_freshness_call = $get_timer(FRESHNESS_TIMER);
275                 let mut last_ping_call = $get_timer(PING_TIMER);
276                 let mut last_prune_call = $get_timer(FIRST_NETWORK_PRUNE_TIMER);
277                 let mut last_scorer_persist_call = $get_timer(SCORER_PERSIST_TIMER);
278                 let mut have_pruned = false;
279
280                 loop {
281                         $process_channel_manager_events;
282                         $process_chain_monitor_events;
283
284                         // Note that the PeerManager::process_events may block on ChannelManager's locks,
285                         // hence it comes last here. When the ChannelManager finishes whatever it's doing,
286                         // we want to ensure we get into `persist_manager` as quickly as we can, especially
287                         // without running the normal event processing above and handing events to users.
288                         //
289                         // Specifically, on an *extremely* slow machine, we may see ChannelManager start
290                         // processing a message effectively at any point during this loop. In order to
291                         // minimize the time between such processing completing and persisting the updated
292                         // ChannelManager, we want to minimize methods blocking on a ChannelManager
293                         // generally, and as a fallback place such blocking only immediately before
294                         // persistence.
295                         $peer_manager.process_events();
296
297                         // We wait up to 100ms, but track how long it takes to detect being put to sleep,
298                         // see `await_start`'s use below.
299                         let mut await_start = None;
300                         if $check_slow_await { await_start = Some($get_timer(1)); }
301                         let updates_available = $await;
302                         let await_slow = if $check_slow_await { $timer_elapsed(&mut await_start.unwrap(), 1) } else { false };
303
304                         if updates_available {
305                                 log_trace!($logger, "Persisting ChannelManager...");
306                                 $persister.persist_manager(&*$channel_manager)?;
307                                 log_trace!($logger, "Done persisting ChannelManager.");
308                         }
309                         // Exit the loop if the background processor was requested to stop.
310                         if $loop_exit_check {
311                                 log_trace!($logger, "Terminating background processor.");
312                                 break;
313                         }
314                         if $timer_elapsed(&mut last_freshness_call, FRESHNESS_TIMER) {
315                                 log_trace!($logger, "Calling ChannelManager's timer_tick_occurred");
316                                 $channel_manager.timer_tick_occurred();
317                                 last_freshness_call = $get_timer(FRESHNESS_TIMER);
318                         }
319                         if await_slow {
320                                 // On various platforms, we may be starved of CPU cycles for several reasons.
321                                 // E.g. on iOS, if we've been in the background, we will be entirely paused.
322                                 // Similarly, if we're on a desktop platform and the device has been asleep, we
323                                 // may not get any cycles.
324                                 // We detect this by checking if our max-100ms-sleep, above, ran longer than a
325                                 // full second, at which point we assume sockets may have been killed (they
326                                 // appear to be at least on some platforms, even if it has only been a second).
327                                 // Note that we have to take care to not get here just because user event
328                                 // processing was slow at the top of the loop. For example, the sample client
329                                 // may call Bitcoin Core RPCs during event handling, which very often takes
330                                 // more than a handful of seconds to complete, and shouldn't disconnect all our
331                                 // peers.
332                                 log_trace!($logger, "100ms sleep took more than a second, disconnecting peers.");
333                                 $peer_manager.disconnect_all_peers();
334                                 last_ping_call = $get_timer(PING_TIMER);
335                         } else if $timer_elapsed(&mut last_ping_call, PING_TIMER) {
336                                 log_trace!($logger, "Calling PeerManager's timer_tick_occurred");
337                                 $peer_manager.timer_tick_occurred();
338                                 last_ping_call = $get_timer(PING_TIMER);
339                         }
340
341                         // Note that we want to run a graph prune once not long after startup before
342                         // falling back to our usual hourly prunes. This avoids short-lived clients never
343                         // pruning their network graph. We run once 60 seconds after startup before
344                         // continuing our normal cadence.
345                         if $timer_elapsed(&mut last_prune_call, if have_pruned { NETWORK_PRUNE_TIMER } else { FIRST_NETWORK_PRUNE_TIMER }) {
346                                 // The network graph must not be pruned while rapid sync completion is pending
347                                 if let Some(network_graph) = $gossip_sync.prunable_network_graph() {
348                                         #[cfg(feature = "std")] {
349                                                 log_trace!($logger, "Pruning and persisting network graph.");
350                                                 network_graph.remove_stale_channels_and_tracking();
351                                         }
352                                         #[cfg(not(feature = "std"))] {
353                                                 log_warn!($logger, "Not pruning network graph, consider enabling `std` or doing so manually with remove_stale_channels_and_tracking_with_time.");
354                                                 log_trace!($logger, "Persisting network graph.");
355                                         }
356
357                                         if let Err(e) = $persister.persist_graph(network_graph) {
358                                                 log_error!($logger, "Error: Failed to persist network graph, check your disk and permissions {}", e)
359                                         }
360
361                                         have_pruned = true;
362                                 }
363                                 last_prune_call = $get_timer(NETWORK_PRUNE_TIMER);
364                         }
365
366                         if $timer_elapsed(&mut last_scorer_persist_call, SCORER_PERSIST_TIMER) {
367                                 if let Some(ref scorer) = $scorer {
368                                         log_trace!($logger, "Persisting scorer");
369                                         if let Err(e) = $persister.persist_scorer(&scorer) {
370                                                 log_error!($logger, "Error: Failed to persist scorer, check your disk and permissions {}", e)
371                                         }
372                                 }
373                                 last_scorer_persist_call = $get_timer(SCORER_PERSIST_TIMER);
374                         }
375                 }
376
377                 // After we exit, ensure we persist the ChannelManager one final time - this avoids
378                 // some races where users quit while channel updates were in-flight, with
379                 // ChannelMonitor update(s) persisted without a corresponding ChannelManager update.
380                 $persister.persist_manager(&*$channel_manager)?;
381
382                 // Persist Scorer on exit
383                 if let Some(ref scorer) = $scorer {
384                         $persister.persist_scorer(&scorer)?;
385                 }
386
387                 // Persist NetworkGraph on exit
388                 if let Some(network_graph) = $gossip_sync.network_graph() {
389                         $persister.persist_graph(network_graph)?;
390                 }
391
392                 Ok(())
393         } }
394 }
395
396 #[cfg(feature = "futures")]
397 pub(crate) mod futures_util {
398         use core::future::Future;
399         use core::task::{Poll, Waker, RawWaker, RawWakerVTable};
400         use core::pin::Pin;
401         use core::marker::Unpin;
402         pub(crate) struct Selector<
403                 A: Future<Output=()> + Unpin, B: Future<Output=()> + Unpin, C: Future<Output=bool> + Unpin
404         > {
405                 pub a: A,
406                 pub b: B,
407                 pub c: C,
408         }
409         pub(crate) enum SelectorOutput {
410                 A, B, C(bool),
411         }
412
413         impl<
414                 A: Future<Output=()> + Unpin, B: Future<Output=()> + Unpin, C: Future<Output=bool> + Unpin
415         > Future for Selector<A, B, C> {
416                 type Output = SelectorOutput;
417                 fn poll(mut self: Pin<&mut Self>, ctx: &mut core::task::Context<'_>) -> Poll<SelectorOutput> {
418                         match Pin::new(&mut self.a).poll(ctx) {
419                                 Poll::Ready(()) => { return Poll::Ready(SelectorOutput::A); },
420                                 Poll::Pending => {},
421                         }
422                         match Pin::new(&mut self.b).poll(ctx) {
423                                 Poll::Ready(()) => { return Poll::Ready(SelectorOutput::B); },
424                                 Poll::Pending => {},
425                         }
426                         match Pin::new(&mut self.c).poll(ctx) {
427                                 Poll::Ready(res) => { return Poll::Ready(SelectorOutput::C(res)); },
428                                 Poll::Pending => {},
429                         }
430                         Poll::Pending
431                 }
432         }
433
434         // If we want to poll a future without an async context to figure out if it has completed or
435         // not without awaiting, we need a Waker, which needs a vtable...we fill it with dummy values
436         // but sadly there's a good bit of boilerplate here.
437         fn dummy_waker_clone(_: *const ()) -> RawWaker { RawWaker::new(core::ptr::null(), &DUMMY_WAKER_VTABLE) }
438         fn dummy_waker_action(_: *const ()) { }
439
440         const DUMMY_WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new(
441                 dummy_waker_clone, dummy_waker_action, dummy_waker_action, dummy_waker_action);
442         pub(crate) fn dummy_waker() -> Waker { unsafe { Waker::from_raw(RawWaker::new(core::ptr::null(), &DUMMY_WAKER_VTABLE)) } }
443 }
444 #[cfg(feature = "futures")]
445 use futures_util::{Selector, SelectorOutput, dummy_waker};
446 #[cfg(feature = "futures")]
447 use core::task;
448
449 /// Processes background events in a future.
450 ///
451 /// `sleeper` should return a future which completes in the given amount of time and returns a
452 /// boolean indicating whether the background processing should exit. Once `sleeper` returns a
453 /// future which outputs true, the loop will exit and this function's future will complete.
454 ///
455 /// See [`BackgroundProcessor::start`] for information on which actions this handles.
456 ///
457 /// Requires the `futures` feature. Note that while this method is available without the `std`
458 /// feature, doing so will skip calling [`NetworkGraph::remove_stale_channels_and_tracking`],
459 /// you should call [`NetworkGraph::remove_stale_channels_and_tracking_with_time`] regularly
460 /// manually instead.
461 ///
462 /// The `mobile_interruptable_platform` flag should be set if we're currently running on a
463 /// mobile device, where we may need to check for interruption of the application regularly. If you
464 /// are unsure, you should set the flag, as the performance impact of it is minimal unless there
465 /// are hundreds or thousands of simultaneous process calls running.
466 #[cfg(feature = "futures")]
467 pub async fn process_events_async<
468         'a,
469         UL: 'static + Deref + Send + Sync,
470         CF: 'static + Deref + Send + Sync,
471         CW: 'static + Deref + Send + Sync,
472         T: 'static + Deref + Send + Sync,
473         ES: 'static + Deref + Send + Sync,
474         NS: 'static + Deref + Send + Sync,
475         SP: 'static + Deref + Send + Sync,
476         F: 'static + Deref + Send + Sync,
477         R: 'static + Deref + Send + Sync,
478         G: 'static + Deref<Target = NetworkGraph<L>> + Send + Sync,
479         L: 'static + Deref + Send + Sync,
480         P: 'static + Deref + Send + Sync,
481         Descriptor: 'static + SocketDescriptor + Send + Sync,
482         CMH: 'static + Deref + Send + Sync,
483         RMH: 'static + Deref + Send + Sync,
484         OMH: 'static + Deref + Send + Sync,
485         EventHandlerFuture: core::future::Future<Output = ()>,
486         EventHandler: Fn(Event) -> EventHandlerFuture,
487         PS: 'static + Deref + Send,
488         M: 'static + Deref<Target = ChainMonitor<<SP::Target as SignerProvider>::Signer, CF, T, F, L, P>> + Send + Sync,
489         CM: 'static + Deref<Target = ChannelManager<CW, T, ES, NS, SP, F, R, L>> + Send + Sync,
490         PGS: 'static + Deref<Target = P2PGossipSync<G, UL, L>> + Send + Sync,
491         RGS: 'static + Deref<Target = RapidGossipSync<G, L>> + Send,
492         UMH: 'static + Deref + Send + Sync,
493         PM: 'static + Deref<Target = PeerManager<Descriptor, CMH, RMH, OMH, L, UMH, NS>> + Send + Sync,
494         S: 'static + Deref<Target = SC> + Send + Sync,
495         SC: for<'b> WriteableScore<'b>,
496         SleepFuture: core::future::Future<Output = bool> + core::marker::Unpin,
497         Sleeper: Fn(Duration) -> SleepFuture
498 >(
499         persister: PS, event_handler: EventHandler, chain_monitor: M, channel_manager: CM,
500         gossip_sync: GossipSync<PGS, RGS, G, UL, L>, peer_manager: PM, logger: L, scorer: Option<S>,
501         sleeper: Sleeper, mobile_interruptable_platform: bool,
502 ) -> Result<(), lightning::io::Error>
503 where
504         UL::Target: 'static + UtxoLookup,
505         CF::Target: 'static + chain::Filter,
506         CW::Target: 'static + chain::Watch<<SP::Target as SignerProvider>::Signer>,
507         T::Target: 'static + BroadcasterInterface,
508         ES::Target: 'static + EntropySource,
509         NS::Target: 'static + NodeSigner,
510         SP::Target: 'static + SignerProvider,
511         F::Target: 'static + FeeEstimator,
512         R::Target: 'static + Router,
513         L::Target: 'static + Logger,
514         P::Target: 'static + Persist<<SP::Target as SignerProvider>::Signer>,
515         CMH::Target: 'static + ChannelMessageHandler,
516         OMH::Target: 'static + OnionMessageHandler,
517         RMH::Target: 'static + RoutingMessageHandler,
518         UMH::Target: 'static + CustomMessageHandler,
519         PS::Target: 'static + Persister<'a, CW, T, ES, NS, SP, F, R, L, SC>,
520 {
521         let mut should_break = false;
522         let async_event_handler = |event| {
523                 let network_graph = gossip_sync.network_graph();
524                 let event_handler = &event_handler;
525                 let scorer = &scorer;
526                 async move {
527                         if let Some(network_graph) = network_graph {
528                                 handle_network_graph_update(network_graph, &event)
529                         }
530                         if let Some(ref scorer) = scorer {
531                                 update_scorer(scorer, &event);
532                         }
533                         event_handler(event).await;
534                 }
535         };
536         define_run_body!(persister,
537                 chain_monitor, chain_monitor.process_pending_events_async(async_event_handler).await,
538                 channel_manager, channel_manager.process_pending_events_async(async_event_handler).await,
539                 gossip_sync, peer_manager, logger, scorer, should_break, {
540                         let fut = Selector {
541                                 a: channel_manager.get_persistable_update_future(),
542                                 b: chain_monitor.get_update_future(),
543                                 c: sleeper(if mobile_interruptable_platform { Duration::from_millis(100) } else { Duration::from_secs(FASTEST_TIMER) }),
544                         };
545                         match fut.await {
546                                 SelectorOutput::A => true,
547                                 SelectorOutput::B => false,
548                                 SelectorOutput::C(exit) => {
549                                         should_break = exit;
550                                         false
551                                 }
552                         }
553                 }, |t| sleeper(Duration::from_secs(t)),
554                 |fut: &mut SleepFuture, _| {
555                         let mut waker = dummy_waker();
556                         let mut ctx = task::Context::from_waker(&mut waker);
557                         core::pin::Pin::new(fut).poll(&mut ctx).is_ready()
558                 }, mobile_interruptable_platform)
559 }
560
561 #[cfg(feature = "std")]
562 impl BackgroundProcessor {
563         /// Start a background thread that takes care of responsibilities enumerated in the [top-level
564         /// documentation].
565         ///
566         /// The thread runs indefinitely unless the object is dropped, [`stop`] is called, or
567         /// [`Persister::persist_manager`] returns an error. In case of an error, the error is retrieved by calling
568         /// either [`join`] or [`stop`].
569         ///
570         /// # Data Persistence
571         ///
572         /// [`Persister::persist_manager`] is responsible for writing out the [`ChannelManager`] to disk, and/or
573         /// uploading to one or more backup services. See [`ChannelManager::write`] for writing out a
574         /// [`ChannelManager`]. See the `lightning-persister` crate for LDK's
575         /// provided implementation.
576         ///
577         /// [`Persister::persist_graph`] is responsible for writing out the [`NetworkGraph`] to disk, if
578         /// [`GossipSync`] is supplied. See [`NetworkGraph::write`] for writing out a [`NetworkGraph`].
579         /// See the `lightning-persister` crate for LDK's provided implementation.
580         ///
581         /// Typically, users should either implement [`Persister::persist_manager`] to never return an
582         /// error or call [`join`] and handle any error that may arise. For the latter case,
583         /// `BackgroundProcessor` must be restarted by calling `start` again after handling the error.
584         ///
585         /// # Event Handling
586         ///
587         /// `event_handler` is responsible for handling events that users should be notified of (e.g.,
588         /// payment failed). [`BackgroundProcessor`] may decorate the given [`EventHandler`] with common
589         /// functionality implemented by other handlers.
590         /// * [`P2PGossipSync`] if given will update the [`NetworkGraph`] based on payment failures.
591         ///
592         /// # Rapid Gossip Sync
593         ///
594         /// If rapid gossip sync is meant to run at startup, pass [`RapidGossipSync`] via `gossip_sync`
595         /// to indicate that the [`BackgroundProcessor`] should not prune the [`NetworkGraph`] instance
596         /// until the [`RapidGossipSync`] instance completes its first sync.
597         ///
598         /// [top-level documentation]: BackgroundProcessor
599         /// [`join`]: Self::join
600         /// [`stop`]: Self::stop
601         /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
602         /// [`ChannelManager::write`]: lightning::ln::channelmanager::ChannelManager#impl-Writeable
603         /// [`Persister::persist_manager`]: lightning::util::persist::Persister::persist_manager
604         /// [`Persister::persist_graph`]: lightning::util::persist::Persister::persist_graph
605         /// [`NetworkGraph`]: lightning::routing::gossip::NetworkGraph
606         /// [`NetworkGraph::write`]: lightning::routing::gossip::NetworkGraph#impl-Writeable
607         pub fn start<
608                 'a,
609                 UL: 'static + Deref + Send + Sync,
610                 CF: 'static + Deref + Send + Sync,
611                 CW: 'static + Deref + Send + Sync,
612                 T: 'static + Deref + Send + Sync,
613                 ES: 'static + Deref + Send + Sync,
614                 NS: 'static + Deref + Send + Sync,
615                 SP: 'static + Deref + Send + Sync,
616                 F: 'static + Deref + Send + Sync,
617                 R: 'static + Deref + Send + Sync,
618                 G: 'static + Deref<Target = NetworkGraph<L>> + Send + Sync,
619                 L: 'static + Deref + Send + Sync,
620                 P: 'static + Deref + Send + Sync,
621                 Descriptor: 'static + SocketDescriptor + Send + Sync,
622                 CMH: 'static + Deref + Send + Sync,
623                 OMH: 'static + Deref + Send + Sync,
624                 RMH: 'static + Deref + Send + Sync,
625                 EH: 'static + EventHandler + Send,
626                 PS: 'static + Deref + Send,
627                 M: 'static + Deref<Target = ChainMonitor<<SP::Target as SignerProvider>::Signer, CF, T, F, L, P>> + Send + Sync,
628                 CM: 'static + Deref<Target = ChannelManager<CW, T, ES, NS, SP, F, R, L>> + Send + Sync,
629                 PGS: 'static + Deref<Target = P2PGossipSync<G, UL, L>> + Send + Sync,
630                 RGS: 'static + Deref<Target = RapidGossipSync<G, L>> + Send,
631                 UMH: 'static + Deref + Send + Sync,
632                 PM: 'static + Deref<Target = PeerManager<Descriptor, CMH, RMH, OMH, L, UMH, NS>> + Send + Sync,
633                 S: 'static + Deref<Target = SC> + Send + Sync,
634                 SC: for <'b> WriteableScore<'b>,
635         >(
636                 persister: PS, event_handler: EH, chain_monitor: M, channel_manager: CM,
637                 gossip_sync: GossipSync<PGS, RGS, G, UL, L>, peer_manager: PM, logger: L, scorer: Option<S>,
638         ) -> Self
639         where
640                 UL::Target: 'static + UtxoLookup,
641                 CF::Target: 'static + chain::Filter,
642                 CW::Target: 'static + chain::Watch<<SP::Target as SignerProvider>::Signer>,
643                 T::Target: 'static + BroadcasterInterface,
644                 ES::Target: 'static + EntropySource,
645                 NS::Target: 'static + NodeSigner,
646                 SP::Target: 'static + SignerProvider,
647                 F::Target: 'static + FeeEstimator,
648                 R::Target: 'static + Router,
649                 L::Target: 'static + Logger,
650                 P::Target: 'static + Persist<<SP::Target as SignerProvider>::Signer>,
651                 CMH::Target: 'static + ChannelMessageHandler,
652                 OMH::Target: 'static + OnionMessageHandler,
653                 RMH::Target: 'static + RoutingMessageHandler,
654                 UMH::Target: 'static + CustomMessageHandler,
655                 PS::Target: 'static + Persister<'a, CW, T, ES, NS, SP, F, R, L, SC>,
656         {
657                 let stop_thread = Arc::new(AtomicBool::new(false));
658                 let stop_thread_clone = stop_thread.clone();
659                 let handle = thread::spawn(move || -> Result<(), std::io::Error> {
660                         let event_handler = |event| {
661                                 let network_graph = gossip_sync.network_graph();
662                                 if let Some(network_graph) = network_graph {
663                                         handle_network_graph_update(network_graph, &event)
664                                 }
665                                 if let Some(ref scorer) = scorer {
666                                         update_scorer(scorer, &event);
667                                 }
668                                 event_handler.handle_event(event);
669                         };
670                         define_run_body!(persister, chain_monitor, chain_monitor.process_pending_events(&event_handler),
671                                 channel_manager, channel_manager.process_pending_events(&event_handler),
672                                 gossip_sync, peer_manager, logger, scorer, stop_thread.load(Ordering::Acquire),
673                                 Sleeper::from_two_futures(
674                                         channel_manager.get_persistable_update_future(),
675                                         chain_monitor.get_update_future()
676                                 ).wait_timeout(Duration::from_millis(100)),
677                                 |_| Instant::now(), |time: &Instant, dur| time.elapsed().as_secs() > dur, false)
678                 });
679                 Self { stop_thread: stop_thread_clone, thread_handle: Some(handle) }
680         }
681
682         /// Join `BackgroundProcessor`'s thread, returning any error that occurred while persisting
683         /// [`ChannelManager`].
684         ///
685         /// # Panics
686         ///
687         /// This function panics if the background thread has panicked such as while persisting or
688         /// handling events.
689         ///
690         /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
691         pub fn join(mut self) -> Result<(), std::io::Error> {
692                 assert!(self.thread_handle.is_some());
693                 self.join_thread()
694         }
695
696         /// Stop `BackgroundProcessor`'s thread, returning any error that occurred while persisting
697         /// [`ChannelManager`].
698         ///
699         /// # Panics
700         ///
701         /// This function panics if the background thread has panicked such as while persisting or
702         /// handling events.
703         ///
704         /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
705         pub fn stop(mut self) -> Result<(), std::io::Error> {
706                 assert!(self.thread_handle.is_some());
707                 self.stop_and_join_thread()
708         }
709
710         fn stop_and_join_thread(&mut self) -> Result<(), std::io::Error> {
711                 self.stop_thread.store(true, Ordering::Release);
712                 self.join_thread()
713         }
714
715         fn join_thread(&mut self) -> Result<(), std::io::Error> {
716                 match self.thread_handle.take() {
717                         Some(handle) => handle.join().unwrap(),
718                         None => Ok(()),
719                 }
720         }
721 }
722
723 #[cfg(feature = "std")]
724 impl Drop for BackgroundProcessor {
725         fn drop(&mut self) {
726                 self.stop_and_join_thread().unwrap();
727         }
728 }
729
730 #[cfg(all(feature = "std", test))]
731 mod tests {
732         use bitcoin::blockdata::block::BlockHeader;
733         use bitcoin::blockdata::constants::genesis_block;
734         use bitcoin::blockdata::locktime::PackedLockTime;
735         use bitcoin::blockdata::transaction::{Transaction, TxOut};
736         use bitcoin::network::constants::Network;
737         use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1};
738         use lightning::chain::{BestBlock, Confirm, chainmonitor};
739         use lightning::chain::channelmonitor::ANTI_REORG_DELAY;
740         use lightning::chain::keysinterface::{InMemorySigner, KeysManager};
741         use lightning::chain::transaction::OutPoint;
742         use lightning::events::{Event, PathFailure, MessageSendEventsProvider, MessageSendEvent};
743         use lightning::{get_event_msg, get_event};
744         use lightning::ln::PaymentHash;
745         use lightning::ln::channelmanager;
746         use lightning::ln::channelmanager::{BREAKDOWN_TIMEOUT, ChainParameters, MIN_CLTV_EXPIRY_DELTA, PaymentId};
747         use lightning::ln::features::{ChannelFeatures, NodeFeatures};
748         use lightning::ln::msgs::{ChannelMessageHandler, Init};
749         use lightning::ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler};
750         use lightning::routing::gossip::{NetworkGraph, NodeId, P2PGossipSync};
751         use lightning::routing::router::{DefaultRouter, RouteHop};
752         use lightning::routing::scoring::{ChannelUsage, Score};
753         use lightning::util::config::UserConfig;
754         use lightning::util::ser::Writeable;
755         use lightning::util::test_utils;
756         use lightning::util::persist::KVStorePersister;
757         use lightning_persister::FilesystemPersister;
758         use std::collections::VecDeque;
759         use std::fs;
760         use std::path::PathBuf;
761         use std::sync::{Arc, Mutex};
762         use std::sync::mpsc::SyncSender;
763         use std::time::Duration;
764         use bitcoin::hashes::Hash;
765         use bitcoin::TxMerkleNode;
766         use lightning_rapid_gossip_sync::RapidGossipSync;
767         use super::{BackgroundProcessor, GossipSync, FRESHNESS_TIMER};
768
769         const EVENT_DEADLINE: u64 = 5 * FRESHNESS_TIMER;
770
771         #[derive(Clone, Hash, PartialEq, Eq)]
772         struct TestDescriptor{}
773         impl SocketDescriptor for TestDescriptor {
774                 fn send_data(&mut self, _data: &[u8], _resume_read: bool) -> usize {
775                         0
776                 }
777
778                 fn disconnect_socket(&mut self) {}
779         }
780
781         type ChannelManager = channelmanager::ChannelManager<Arc<ChainMonitor>, Arc<test_utils::TestBroadcaster>, Arc<KeysManager>, Arc<KeysManager>, Arc<KeysManager>, Arc<test_utils::TestFeeEstimator>, Arc<DefaultRouter< Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, Arc<test_utils::TestLogger>, Arc<Mutex<TestScorer>>>>, Arc<test_utils::TestLogger>>;
782
783         type ChainMonitor = chainmonitor::ChainMonitor<InMemorySigner, Arc<test_utils::TestChainSource>, Arc<test_utils::TestBroadcaster>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>, Arc<FilesystemPersister>>;
784
785         type PGS = Arc<P2PGossipSync<Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>>;
786         type RGS = Arc<RapidGossipSync<Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, Arc<test_utils::TestLogger>>>;
787
788         struct Node {
789                 node: Arc<ChannelManager>,
790                 p2p_gossip_sync: PGS,
791                 rapid_gossip_sync: RGS,
792                 peer_manager: Arc<PeerManager<TestDescriptor, Arc<test_utils::TestChannelMessageHandler>, Arc<test_utils::TestRoutingMessageHandler>, IgnoringMessageHandler, Arc<test_utils::TestLogger>, IgnoringMessageHandler, Arc<KeysManager>>>,
793                 chain_monitor: Arc<ChainMonitor>,
794                 persister: Arc<FilesystemPersister>,
795                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
796                 network_graph: Arc<NetworkGraph<Arc<test_utils::TestLogger>>>,
797                 logger: Arc<test_utils::TestLogger>,
798                 best_block: BestBlock,
799                 scorer: Arc<Mutex<TestScorer>>,
800         }
801
802         impl Node {
803                 fn p2p_gossip_sync(&self) -> GossipSync<PGS, RGS, Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>> {
804                         GossipSync::P2P(self.p2p_gossip_sync.clone())
805                 }
806
807                 fn rapid_gossip_sync(&self) -> GossipSync<PGS, RGS, Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>> {
808                         GossipSync::Rapid(self.rapid_gossip_sync.clone())
809                 }
810
811                 fn no_gossip_sync(&self) -> GossipSync<PGS, RGS, Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>> {
812                         GossipSync::None
813                 }
814         }
815
816         impl Drop for Node {
817                 fn drop(&mut self) {
818                         let data_dir = self.persister.get_data_dir();
819                         match fs::remove_dir_all(data_dir.clone()) {
820                                 Err(e) => println!("Failed to remove test persister directory {}: {}", data_dir, e),
821                                 _ => {}
822                         }
823                 }
824         }
825
826         struct Persister {
827                 graph_error: Option<(std::io::ErrorKind, &'static str)>,
828                 graph_persistence_notifier: Option<SyncSender<()>>,
829                 manager_error: Option<(std::io::ErrorKind, &'static str)>,
830                 scorer_error: Option<(std::io::ErrorKind, &'static str)>,
831                 filesystem_persister: FilesystemPersister,
832         }
833
834         impl Persister {
835                 fn new(data_dir: String) -> Self {
836                         let filesystem_persister = FilesystemPersister::new(data_dir);
837                         Self { graph_error: None, graph_persistence_notifier: None, manager_error: None, scorer_error: None, filesystem_persister }
838                 }
839
840                 fn with_graph_error(self, error: std::io::ErrorKind, message: &'static str) -> Self {
841                         Self { graph_error: Some((error, message)), ..self }
842                 }
843
844                 fn with_graph_persistence_notifier(self, sender: SyncSender<()>) -> Self {
845                         Self { graph_persistence_notifier: Some(sender), ..self }
846                 }
847
848                 fn with_manager_error(self, error: std::io::ErrorKind, message: &'static str) -> Self {
849                         Self { manager_error: Some((error, message)), ..self }
850                 }
851
852                 fn with_scorer_error(self, error: std::io::ErrorKind, message: &'static str) -> Self {
853                         Self { scorer_error: Some((error, message)), ..self }
854                 }
855         }
856
857         impl KVStorePersister for Persister {
858                 fn persist<W: Writeable>(&self, key: &str, object: &W) -> std::io::Result<()> {
859                         if key == "manager" {
860                                 if let Some((error, message)) = self.manager_error {
861                                         return Err(std::io::Error::new(error, message))
862                                 }
863                         }
864
865                         if key == "network_graph" {
866                                 if let Some(sender) = &self.graph_persistence_notifier {
867                                         sender.send(()).unwrap();
868                                 };
869
870                                 if let Some((error, message)) = self.graph_error {
871                                         return Err(std::io::Error::new(error, message))
872                                 }
873                         }
874
875                         if key == "scorer" {
876                                 if let Some((error, message)) = self.scorer_error {
877                                         return Err(std::io::Error::new(error, message))
878                                 }
879                         }
880
881                         self.filesystem_persister.persist(key, object)
882                 }
883         }
884
885         struct TestScorer {
886                 event_expectations: Option<VecDeque<TestResult>>,
887         }
888
889         #[derive(Debug)]
890         enum TestResult {
891                 PaymentFailure { path: Vec<RouteHop>, short_channel_id: u64 },
892                 PaymentSuccess { path: Vec<RouteHop> },
893                 ProbeFailure { path: Vec<RouteHop> },
894                 ProbeSuccess { path: Vec<RouteHop> },
895         }
896
897         impl TestScorer {
898                 fn new() -> Self {
899                         Self { event_expectations: None }
900                 }
901
902                 fn expect(&mut self, expectation: TestResult) {
903                         self.event_expectations.get_or_insert_with(VecDeque::new).push_back(expectation);
904                 }
905         }
906
907         impl lightning::util::ser::Writeable for TestScorer {
908                 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), lightning::io::Error> { Ok(()) }
909         }
910
911         impl Score for TestScorer {
912                 fn channel_penalty_msat(
913                         &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, _usage: ChannelUsage
914                 ) -> u64 { unimplemented!(); }
915
916                 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
917                         if let Some(expectations) = &mut self.event_expectations {
918                                 match expectations.pop_front().unwrap() {
919                                         TestResult::PaymentFailure { path, short_channel_id } => {
920                                                 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
921                                                 assert_eq!(actual_short_channel_id, short_channel_id);
922                                         },
923                                         TestResult::PaymentSuccess { path } => {
924                                                 panic!("Unexpected successful payment path: {:?}", path)
925                                         },
926                                         TestResult::ProbeFailure { path } => {
927                                                 panic!("Unexpected probe failure: {:?}", path)
928                                         },
929                                         TestResult::ProbeSuccess { path } => {
930                                                 panic!("Unexpected probe success: {:?}", path)
931                                         }
932                                 }
933                         }
934                 }
935
936                 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
937                         if let Some(expectations) = &mut self.event_expectations {
938                                 match expectations.pop_front().unwrap() {
939                                         TestResult::PaymentFailure { path, .. } => {
940                                                 panic!("Unexpected payment path failure: {:?}", path)
941                                         },
942                                         TestResult::PaymentSuccess { path } => {
943                                                 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
944                                         },
945                                         TestResult::ProbeFailure { path } => {
946                                                 panic!("Unexpected probe failure: {:?}", path)
947                                         },
948                                         TestResult::ProbeSuccess { path } => {
949                                                 panic!("Unexpected probe success: {:?}", path)
950                                         }
951                                 }
952                         }
953                 }
954
955                 fn probe_failed(&mut self, actual_path: &[&RouteHop], _: u64) {
956                         if let Some(expectations) = &mut self.event_expectations {
957                                 match expectations.pop_front().unwrap() {
958                                         TestResult::PaymentFailure { path, .. } => {
959                                                 panic!("Unexpected payment path failure: {:?}", path)
960                                         },
961                                         TestResult::PaymentSuccess { path } => {
962                                                 panic!("Unexpected payment path success: {:?}", path)
963                                         },
964                                         TestResult::ProbeFailure { path } => {
965                                                 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
966                                         },
967                                         TestResult::ProbeSuccess { path } => {
968                                                 panic!("Unexpected probe success: {:?}", path)
969                                         }
970                                 }
971                         }
972                 }
973                 fn probe_successful(&mut self, actual_path: &[&RouteHop]) {
974                         if let Some(expectations) = &mut self.event_expectations {
975                                 match expectations.pop_front().unwrap() {
976                                         TestResult::PaymentFailure { path, .. } => {
977                                                 panic!("Unexpected payment path failure: {:?}", path)
978                                         },
979                                         TestResult::PaymentSuccess { path } => {
980                                                 panic!("Unexpected payment path success: {:?}", path)
981                                         },
982                                         TestResult::ProbeFailure { path } => {
983                                                 panic!("Unexpected probe failure: {:?}", path)
984                                         },
985                                         TestResult::ProbeSuccess { path } => {
986                                                 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
987                                         }
988                                 }
989                         }
990                 }
991         }
992
993         impl Drop for TestScorer {
994                 fn drop(&mut self) {
995                         if std::thread::panicking() {
996                                 return;
997                         }
998
999                         if let Some(event_expectations) = &self.event_expectations {
1000                                 if !event_expectations.is_empty() {
1001                                         panic!("Unsatisfied event expectations: {:?}", event_expectations);
1002                                 }
1003                         }
1004                 }
1005         }
1006
1007         fn get_full_filepath(filepath: String, filename: String) -> String {
1008                 let mut path = PathBuf::from(filepath);
1009                 path.push(filename);
1010                 path.to_str().unwrap().to_string()
1011         }
1012
1013         fn create_nodes(num_nodes: usize, persist_dir: String) -> Vec<Node> {
1014                 let mut nodes = Vec::new();
1015                 for i in 0..num_nodes {
1016                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))});
1017                         let fee_estimator = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) });
1018                         let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
1019                         let network = Network::Testnet;
1020                         let genesis_block = genesis_block(network);
1021                         let network_graph = Arc::new(NetworkGraph::new(network, logger.clone()));
1022                         let scorer = Arc::new(Mutex::new(TestScorer::new()));
1023                         let seed = [i as u8; 32];
1024                         let router = Arc::new(DefaultRouter::new(network_graph.clone(), logger.clone(), seed, scorer.clone()));
1025                         let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1026                         let persister = Arc::new(FilesystemPersister::new(format!("{}_persister_{}", persist_dir, i)));
1027                         let now = Duration::from_secs(genesis_block.header.time as u64);
1028                         let keys_manager = Arc::new(KeysManager::new(&seed, now.as_secs(), now.subsec_nanos()));
1029                         let chain_monitor = Arc::new(chainmonitor::ChainMonitor::new(Some(chain_source.clone()), tx_broadcaster.clone(), logger.clone(), fee_estimator.clone(), persister.clone()));
1030                         let best_block = BestBlock::from_network(network);
1031                         let params = ChainParameters { network, best_block };
1032                         let manager = Arc::new(ChannelManager::new(fee_estimator.clone(), chain_monitor.clone(), tx_broadcaster.clone(), router.clone(), logger.clone(), keys_manager.clone(), keys_manager.clone(), keys_manager.clone(), UserConfig::default(), params));
1033                         let p2p_gossip_sync = Arc::new(P2PGossipSync::new(network_graph.clone(), Some(chain_source.clone()), logger.clone()));
1034                         let rapid_gossip_sync = Arc::new(RapidGossipSync::new(network_graph.clone(), logger.clone()));
1035                         let msg_handler = MessageHandler { chan_handler: Arc::new(test_utils::TestChannelMessageHandler::new()), route_handler: Arc::new(test_utils::TestRoutingMessageHandler::new()), onion_message_handler: IgnoringMessageHandler{}};
1036                         let peer_manager = Arc::new(PeerManager::new(msg_handler, 0, &seed, logger.clone(), IgnoringMessageHandler{}, keys_manager.clone()));
1037                         let node = Node { node: manager, p2p_gossip_sync, rapid_gossip_sync, peer_manager, chain_monitor, persister, tx_broadcaster, network_graph, logger, best_block, scorer };
1038                         nodes.push(node);
1039                 }
1040
1041                 for i in 0..num_nodes {
1042                         for j in (i+1)..num_nodes {
1043                                 nodes[i].node.peer_connected(&nodes[j].node.get_our_node_id(), &Init { features: nodes[j].node.init_features(), remote_network_address: None }, true).unwrap();
1044                                 nodes[j].node.peer_connected(&nodes[i].node.get_our_node_id(), &Init { features: nodes[i].node.init_features(), remote_network_address: None }, false).unwrap();
1045                         }
1046                 }
1047
1048                 nodes
1049         }
1050
1051         macro_rules! open_channel {
1052                 ($node_a: expr, $node_b: expr, $channel_value: expr) => {{
1053                         begin_open_channel!($node_a, $node_b, $channel_value);
1054                         let events = $node_a.node.get_and_clear_pending_events();
1055                         assert_eq!(events.len(), 1);
1056                         let (temporary_channel_id, tx) = handle_funding_generation_ready!(events[0], $channel_value);
1057                         end_open_channel!($node_a, $node_b, temporary_channel_id, tx);
1058                         tx
1059                 }}
1060         }
1061
1062         macro_rules! begin_open_channel {
1063                 ($node_a: expr, $node_b: expr, $channel_value: expr) => {{
1064                         $node_a.node.create_channel($node_b.node.get_our_node_id(), $channel_value, 100, 42, None).unwrap();
1065                         $node_b.node.handle_open_channel(&$node_a.node.get_our_node_id(), &get_event_msg!($node_a, MessageSendEvent::SendOpenChannel, $node_b.node.get_our_node_id()));
1066                         $node_a.node.handle_accept_channel(&$node_b.node.get_our_node_id(), &get_event_msg!($node_b, MessageSendEvent::SendAcceptChannel, $node_a.node.get_our_node_id()));
1067                 }}
1068         }
1069
1070         macro_rules! handle_funding_generation_ready {
1071                 ($event: expr, $channel_value: expr) => {{
1072                         match $event {
1073                                 Event::FundingGenerationReady { temporary_channel_id, channel_value_satoshis, ref output_script, user_channel_id, .. } => {
1074                                         assert_eq!(channel_value_satoshis, $channel_value);
1075                                         assert_eq!(user_channel_id, 42);
1076
1077                                         let tx = Transaction { version: 1 as i32, lock_time: PackedLockTime(0), input: Vec::new(), output: vec![TxOut {
1078                                                 value: channel_value_satoshis, script_pubkey: output_script.clone(),
1079                                         }]};
1080                                         (temporary_channel_id, tx)
1081                                 },
1082                                 _ => panic!("Unexpected event"),
1083                         }
1084                 }}
1085         }
1086
1087         macro_rules! end_open_channel {
1088                 ($node_a: expr, $node_b: expr, $temporary_channel_id: expr, $tx: expr) => {{
1089                         $node_a.node.funding_transaction_generated(&$temporary_channel_id, &$node_b.node.get_our_node_id(), $tx.clone()).unwrap();
1090                         $node_b.node.handle_funding_created(&$node_a.node.get_our_node_id(), &get_event_msg!($node_a, MessageSendEvent::SendFundingCreated, $node_b.node.get_our_node_id()));
1091                         get_event!($node_b, Event::ChannelPending);
1092
1093                         $node_a.node.handle_funding_signed(&$node_b.node.get_our_node_id(), &get_event_msg!($node_b, MessageSendEvent::SendFundingSigned, $node_a.node.get_our_node_id()));
1094                         get_event!($node_a, Event::ChannelPending);
1095                 }}
1096         }
1097
1098         fn confirm_transaction_depth(node: &mut Node, tx: &Transaction, depth: u32) {
1099                 for i in 1..=depth {
1100                         let prev_blockhash = node.best_block.block_hash();
1101                         let height = node.best_block.height() + 1;
1102                         let header = BlockHeader { version: 0x20000000, prev_blockhash, merkle_root: TxMerkleNode::all_zeros(), time: height, bits: 42, nonce: 42 };
1103                         let txdata = vec![(0, tx)];
1104                         node.best_block = BestBlock::new(header.block_hash(), height);
1105                         match i {
1106                                 1 => {
1107                                         node.node.transactions_confirmed(&header, &txdata, height);
1108                                         node.chain_monitor.transactions_confirmed(&header, &txdata, height);
1109                                 },
1110                                 x if x == depth => {
1111                                         node.node.best_block_updated(&header, height);
1112                                         node.chain_monitor.best_block_updated(&header, height);
1113                                 },
1114                                 _ => {},
1115                         }
1116                 }
1117         }
1118         fn confirm_transaction(node: &mut Node, tx: &Transaction) {
1119                 confirm_transaction_depth(node, tx, ANTI_REORG_DELAY);
1120         }
1121
1122         #[test]
1123         fn test_background_processor() {
1124                 // Test that when a new channel is created, the ChannelManager needs to be re-persisted with
1125                 // updates. Also test that when new updates are available, the manager signals that it needs
1126                 // re-persistence and is successfully re-persisted.
1127                 let nodes = create_nodes(2, "test_background_processor".to_string());
1128
1129                 // Go through the channel creation process so that each node has something to persist. Since
1130                 // open_channel consumes events, it must complete before starting BackgroundProcessor to
1131                 // avoid a race with processing events.
1132                 let tx = open_channel!(nodes[0], nodes[1], 100000);
1133
1134                 // Initiate the background processors to watch each node.
1135                 let data_dir = nodes[0].persister.get_data_dir();
1136                 let persister = Arc::new(Persister::new(data_dir));
1137                 let event_handler = |_: _| {};
1138                 let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].p2p_gossip_sync(), nodes[0].peer_manager.clone(), nodes[0].logger.clone(), Some(nodes[0].scorer.clone()));
1139
1140                 macro_rules! check_persisted_data {
1141                         ($node: expr, $filepath: expr) => {
1142                                 let mut expected_bytes = Vec::new();
1143                                 loop {
1144                                         expected_bytes.clear();
1145                                         match $node.write(&mut expected_bytes) {
1146                                                 Ok(()) => {
1147                                                         match std::fs::read($filepath) {
1148                                                                 Ok(bytes) => {
1149                                                                         if bytes == expected_bytes {
1150                                                                                 break
1151                                                                         } else {
1152                                                                                 continue
1153                                                                         }
1154                                                                 },
1155                                                                 Err(_) => continue
1156                                                         }
1157                                                 },
1158                                                 Err(e) => panic!("Unexpected error: {}", e)
1159                                         }
1160                                 }
1161                         }
1162                 }
1163
1164                 // Check that the initial channel manager data is persisted as expected.
1165                 let filepath = get_full_filepath("test_background_processor_persister_0".to_string(), "manager".to_string());
1166                 check_persisted_data!(nodes[0].node, filepath.clone());
1167
1168                 loop {
1169                         if !nodes[0].node.get_persistence_condvar_value() { break }
1170                 }
1171
1172                 // Force-close the channel.
1173                 nodes[0].node.force_close_broadcasting_latest_txn(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id(), &nodes[1].node.get_our_node_id()).unwrap();
1174
1175                 // Check that the force-close updates are persisted.
1176                 check_persisted_data!(nodes[0].node, filepath.clone());
1177                 loop {
1178                         if !nodes[0].node.get_persistence_condvar_value() { break }
1179                 }
1180
1181                 // Check network graph is persisted
1182                 let filepath = get_full_filepath("test_background_processor_persister_0".to_string(), "network_graph".to_string());
1183                 check_persisted_data!(nodes[0].network_graph, filepath.clone());
1184
1185                 // Check scorer is persisted
1186                 let filepath = get_full_filepath("test_background_processor_persister_0".to_string(), "scorer".to_string());
1187                 check_persisted_data!(nodes[0].scorer, filepath.clone());
1188
1189                 if !std::thread::panicking() {
1190                         bg_processor.stop().unwrap();
1191                 }
1192         }
1193
1194         #[test]
1195         fn test_timer_tick_called() {
1196                 // Test that ChannelManager's and PeerManager's `timer_tick_occurred` is called every
1197                 // `FRESHNESS_TIMER`.
1198                 let nodes = create_nodes(1, "test_timer_tick_called".to_string());
1199                 let data_dir = nodes[0].persister.get_data_dir();
1200                 let persister = Arc::new(Persister::new(data_dir));
1201                 let event_handler = |_: _| {};
1202                 let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].no_gossip_sync(), nodes[0].peer_manager.clone(), nodes[0].logger.clone(), Some(nodes[0].scorer.clone()));
1203                 loop {
1204                         let log_entries = nodes[0].logger.lines.lock().unwrap();
1205                         let desired_log = "Calling ChannelManager's timer_tick_occurred".to_string();
1206                         let second_desired_log = "Calling PeerManager's timer_tick_occurred".to_string();
1207                         if log_entries.get(&("lightning_background_processor".to_string(), desired_log)).is_some() &&
1208                                         log_entries.get(&("lightning_background_processor".to_string(), second_desired_log)).is_some() {
1209                                 break
1210                         }
1211                 }
1212
1213                 if !std::thread::panicking() {
1214                         bg_processor.stop().unwrap();
1215                 }
1216         }
1217
1218         #[test]
1219         fn test_channel_manager_persist_error() {
1220                 // Test that if we encounter an error during manager persistence, the thread panics.
1221                 let nodes = create_nodes(2, "test_persist_error".to_string());
1222                 open_channel!(nodes[0], nodes[1], 100000);
1223
1224                 let data_dir = nodes[0].persister.get_data_dir();
1225                 let persister = Arc::new(Persister::new(data_dir).with_manager_error(std::io::ErrorKind::Other, "test"));
1226                 let event_handler = |_: _| {};
1227                 let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].no_gossip_sync(), nodes[0].peer_manager.clone(), nodes[0].logger.clone(), Some(nodes[0].scorer.clone()));
1228                 match bg_processor.join() {
1229                         Ok(_) => panic!("Expected error persisting manager"),
1230                         Err(e) => {
1231                                 assert_eq!(e.kind(), std::io::ErrorKind::Other);
1232                                 assert_eq!(e.get_ref().unwrap().to_string(), "test");
1233                         },
1234                 }
1235         }
1236
1237         #[test]
1238         fn test_network_graph_persist_error() {
1239                 // Test that if we encounter an error during network graph persistence, an error gets returned.
1240                 let nodes = create_nodes(2, "test_persist_network_graph_error".to_string());
1241                 let data_dir = nodes[0].persister.get_data_dir();
1242                 let persister = Arc::new(Persister::new(data_dir).with_graph_error(std::io::ErrorKind::Other, "test"));
1243                 let event_handler = |_: _| {};
1244                 let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].p2p_gossip_sync(), nodes[0].peer_manager.clone(), nodes[0].logger.clone(), Some(nodes[0].scorer.clone()));
1245
1246                 match bg_processor.stop() {
1247                         Ok(_) => panic!("Expected error persisting network graph"),
1248                         Err(e) => {
1249                                 assert_eq!(e.kind(), std::io::ErrorKind::Other);
1250                                 assert_eq!(e.get_ref().unwrap().to_string(), "test");
1251                         },
1252                 }
1253         }
1254
1255         #[test]
1256         fn test_scorer_persist_error() {
1257                 // Test that if we encounter an error during scorer persistence, an error gets returned.
1258                 let nodes = create_nodes(2, "test_persist_scorer_error".to_string());
1259                 let data_dir = nodes[0].persister.get_data_dir();
1260                 let persister = Arc::new(Persister::new(data_dir).with_scorer_error(std::io::ErrorKind::Other, "test"));
1261                 let event_handler = |_: _| {};
1262                 let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].no_gossip_sync(), nodes[0].peer_manager.clone(),  nodes[0].logger.clone(), Some(nodes[0].scorer.clone()));
1263
1264                 match bg_processor.stop() {
1265                         Ok(_) => panic!("Expected error persisting scorer"),
1266                         Err(e) => {
1267                                 assert_eq!(e.kind(), std::io::ErrorKind::Other);
1268                                 assert_eq!(e.get_ref().unwrap().to_string(), "test");
1269                         },
1270                 }
1271         }
1272
1273         #[test]
1274         fn test_background_event_handling() {
1275                 let mut nodes = create_nodes(2, "test_background_event_handling".to_string());
1276                 let channel_value = 100000;
1277                 let data_dir = nodes[0].persister.get_data_dir();
1278                 let persister = Arc::new(Persister::new(data_dir.clone()));
1279
1280                 // Set up a background event handler for FundingGenerationReady events.
1281                 let (sender, receiver) = std::sync::mpsc::sync_channel(1);
1282                 let event_handler = move |event: Event| match event {
1283                         Event::FundingGenerationReady { .. } => sender.send(handle_funding_generation_ready!(event, channel_value)).unwrap(),
1284                         Event::ChannelReady { .. } => {},
1285                         _ => panic!("Unexpected event: {:?}", event),
1286                 };
1287
1288                 let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].no_gossip_sync(), nodes[0].peer_manager.clone(), nodes[0].logger.clone(), Some(nodes[0].scorer.clone()));
1289
1290                 // Open a channel and check that the FundingGenerationReady event was handled.
1291                 begin_open_channel!(nodes[0], nodes[1], channel_value);
1292                 let (temporary_channel_id, funding_tx) = receiver
1293                         .recv_timeout(Duration::from_secs(EVENT_DEADLINE))
1294                         .expect("FundingGenerationReady not handled within deadline");
1295                 end_open_channel!(nodes[0], nodes[1], temporary_channel_id, funding_tx);
1296
1297                 // Confirm the funding transaction.
1298                 confirm_transaction(&mut nodes[0], &funding_tx);
1299                 let as_funding = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
1300                 confirm_transaction(&mut nodes[1], &funding_tx);
1301                 let bs_funding = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReady, nodes[0].node.get_our_node_id());
1302                 nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_funding);
1303                 let _as_channel_update = get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
1304                 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_funding);
1305                 let _bs_channel_update = get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
1306
1307                 if !std::thread::panicking() {
1308                         bg_processor.stop().unwrap();
1309                 }
1310
1311                 // Set up a background event handler for SpendableOutputs events.
1312                 let (sender, receiver) = std::sync::mpsc::sync_channel(1);
1313                 let event_handler = move |event: Event| match event {
1314                         Event::SpendableOutputs { .. } => sender.send(event).unwrap(),
1315                         Event::ChannelReady { .. } => {},
1316                         Event::ChannelClosed { .. } => {},
1317                         _ => panic!("Unexpected event: {:?}", event),
1318                 };
1319                 let persister = Arc::new(Persister::new(data_dir));
1320                 let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].no_gossip_sync(), nodes[0].peer_manager.clone(), nodes[0].logger.clone(), Some(nodes[0].scorer.clone()));
1321
1322                 // Force close the channel and check that the SpendableOutputs event was handled.
1323                 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
1324                 let commitment_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().pop().unwrap();
1325                 confirm_transaction_depth(&mut nodes[0], &commitment_tx, BREAKDOWN_TIMEOUT as u32);
1326
1327                 let event = receiver
1328                         .recv_timeout(Duration::from_secs(EVENT_DEADLINE))
1329                         .expect("Events not handled within deadline");
1330                 match event {
1331                         Event::SpendableOutputs { .. } => {},
1332                         _ => panic!("Unexpected event: {:?}", event),
1333                 }
1334
1335                 if !std::thread::panicking() {
1336                         bg_processor.stop().unwrap();
1337                 }
1338         }
1339
1340         #[test]
1341         fn test_scorer_persistence() {
1342                 let nodes = create_nodes(2, "test_scorer_persistence".to_string());
1343                 let data_dir = nodes[0].persister.get_data_dir();
1344                 let persister = Arc::new(Persister::new(data_dir));
1345                 let event_handler = |_: _| {};
1346                 let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].no_gossip_sync(), nodes[0].peer_manager.clone(), nodes[0].logger.clone(), Some(nodes[0].scorer.clone()));
1347
1348                 loop {
1349                         let log_entries = nodes[0].logger.lines.lock().unwrap();
1350                         let expected_log = "Persisting scorer".to_string();
1351                         if log_entries.get(&("lightning_background_processor".to_string(), expected_log)).is_some() {
1352                                 break
1353                         }
1354                 }
1355
1356                 if !std::thread::panicking() {
1357                         bg_processor.stop().unwrap();
1358                 }
1359         }
1360
1361         #[test]
1362         fn test_not_pruning_network_graph_until_graph_sync_completion() {
1363                 let nodes = create_nodes(2, "test_not_pruning_network_graph_until_graph_sync_completion".to_string());
1364                 let data_dir = nodes[0].persister.get_data_dir();
1365                 let (sender, receiver) = std::sync::mpsc::sync_channel(1);
1366                 let persister = Arc::new(Persister::new(data_dir).with_graph_persistence_notifier(sender));
1367                 let network_graph = nodes[0].network_graph.clone();
1368                 let features = ChannelFeatures::empty();
1369                 network_graph.add_channel_from_partial_announcement(42, 53, features, nodes[0].node.get_our_node_id(), nodes[1].node.get_our_node_id())
1370                         .expect("Failed to update channel from partial announcement");
1371                 let original_graph_description = network_graph.to_string();
1372                 assert!(original_graph_description.contains("42: features: 0000, node_one:"));
1373                 assert_eq!(network_graph.read_only().channels().len(), 1);
1374
1375                 let event_handler = |_: _| {};
1376                 let background_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].rapid_gossip_sync(), nodes[0].peer_manager.clone(), nodes[0].logger.clone(), Some(nodes[0].scorer.clone()));
1377
1378                 loop {
1379                         let log_entries = nodes[0].logger.lines.lock().unwrap();
1380                         let loop_counter = "Calling ChannelManager's timer_tick_occurred".to_string();
1381                         if *log_entries.get(&("lightning_background_processor".to_string(), loop_counter))
1382                                 .unwrap_or(&0) > 1
1383                         {
1384                                 // Wait until the loop has gone around at least twice.
1385                                 break
1386                         }
1387                 }
1388
1389                 let initialization_input = vec![
1390                         76, 68, 75, 1, 111, 226, 140, 10, 182, 241, 179, 114, 193, 166, 162, 70, 174, 99, 247,
1391                         79, 147, 30, 131, 101, 225, 90, 8, 156, 104, 214, 25, 0, 0, 0, 0, 0, 97, 227, 98, 218,
1392                         0, 0, 0, 4, 2, 22, 7, 207, 206, 25, 164, 197, 231, 230, 231, 56, 102, 61, 250, 251,
1393                         187, 172, 38, 46, 79, 247, 108, 44, 155, 48, 219, 238, 252, 53, 192, 6, 67, 2, 36, 125,
1394                         157, 176, 223, 175, 234, 116, 94, 248, 201, 225, 97, 235, 50, 47, 115, 172, 63, 136,
1395                         88, 216, 115, 11, 111, 217, 114, 84, 116, 124, 231, 107, 2, 158, 1, 242, 121, 152, 106,
1396                         204, 131, 186, 35, 93, 70, 216, 10, 237, 224, 183, 89, 95, 65, 3, 83, 185, 58, 138,
1397                         181, 64, 187, 103, 127, 68, 50, 2, 201, 19, 17, 138, 136, 149, 185, 226, 156, 137, 175,
1398                         110, 32, 237, 0, 217, 90, 31, 100, 228, 149, 46, 219, 175, 168, 77, 4, 143, 38, 128,
1399                         76, 97, 0, 0, 0, 2, 0, 0, 255, 8, 153, 192, 0, 2, 27, 0, 0, 0, 1, 0, 0, 255, 2, 68,
1400                         226, 0, 6, 11, 0, 1, 2, 3, 0, 0, 0, 2, 0, 40, 0, 0, 0, 0, 0, 0, 3, 232, 0, 0, 3, 232,
1401                         0, 0, 0, 1, 0, 0, 0, 0, 58, 85, 116, 216, 255, 8, 153, 192, 0, 2, 27, 0, 0, 25, 0, 0,
1402                         0, 1, 0, 0, 0, 125, 255, 2, 68, 226, 0, 6, 11, 0, 1, 5, 0, 0, 0, 0, 29, 129, 25, 192,
1403                 ];
1404                 nodes[0].rapid_gossip_sync.update_network_graph_no_std(&initialization_input[..], Some(1642291930)).unwrap();
1405
1406                 // this should have added two channels
1407                 assert_eq!(network_graph.read_only().channels().len(), 3);
1408
1409                 receiver
1410                         .recv_timeout(Duration::from_secs(super::FIRST_NETWORK_PRUNE_TIMER * 5))
1411                         .expect("Network graph not pruned within deadline");
1412
1413                 background_processor.stop().unwrap();
1414
1415                 // all channels should now be pruned
1416                 assert_eq!(network_graph.read_only().channels().len(), 0);
1417         }
1418
1419         #[test]
1420         fn test_payment_path_scoring() {
1421                 // Ensure that we update the scorer when relevant events are processed. In this case, we ensure
1422                 // that we update the scorer upon a payment path succeeding (note that the channel must be
1423                 // public or else we won't score it).
1424                 // Set up a background event handler for FundingGenerationReady events.
1425                 let (sender, receiver) = std::sync::mpsc::sync_channel(1);
1426                 let event_handler = move |event: Event| match event {
1427                         Event::PaymentPathFailed { .. } => sender.send(event).unwrap(),
1428                         Event::PaymentPathSuccessful { .. } => sender.send(event).unwrap(),
1429                         Event::ProbeSuccessful { .. } => sender.send(event).unwrap(),
1430                         Event::ProbeFailed { .. } => sender.send(event).unwrap(),
1431                         _ => panic!("Unexpected event: {:?}", event),
1432                 };
1433
1434                 let nodes = create_nodes(1, "test_payment_path_scoring".to_string());
1435                 let data_dir = nodes[0].persister.get_data_dir();
1436                 let persister = Arc::new(Persister::new(data_dir));
1437                 let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].no_gossip_sync(), nodes[0].peer_manager.clone(), nodes[0].logger.clone(), Some(nodes[0].scorer.clone()));
1438
1439                 let scored_scid = 4242;
1440                 let secp_ctx = Secp256k1::new();
1441                 let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
1442                 let node_1_id = PublicKey::from_secret_key(&secp_ctx, &node_1_privkey);
1443
1444                 let path = vec![RouteHop {
1445                         pubkey: node_1_id,
1446                         node_features: NodeFeatures::empty(),
1447                         short_channel_id: scored_scid,
1448                         channel_features: ChannelFeatures::empty(),
1449                         fee_msat: 0,
1450                         cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA as u32,
1451                 }];
1452
1453                 nodes[0].scorer.lock().unwrap().expect(TestResult::PaymentFailure { path: path.clone(), short_channel_id: scored_scid });
1454                 nodes[0].node.push_pending_event(Event::PaymentPathFailed {
1455                         payment_id: None,
1456                         payment_hash: PaymentHash([42; 32]),
1457                         payment_failed_permanently: false,
1458                         failure: PathFailure::OnPath { network_update: None },
1459                         path: path.clone(),
1460                         short_channel_id: Some(scored_scid),
1461                 });
1462                 let event = receiver
1463                         .recv_timeout(Duration::from_secs(EVENT_DEADLINE))
1464                         .expect("PaymentPathFailed not handled within deadline");
1465                 match event {
1466                         Event::PaymentPathFailed { .. } => {},
1467                         _ => panic!("Unexpected event"),
1468                 }
1469
1470                 // Ensure we'll score payments that were explicitly failed back by the destination as
1471                 // ProbeSuccess.
1472                 nodes[0].scorer.lock().unwrap().expect(TestResult::ProbeSuccess { path: path.clone() });
1473                 nodes[0].node.push_pending_event(Event::PaymentPathFailed {
1474                         payment_id: None,
1475                         payment_hash: PaymentHash([42; 32]),
1476                         payment_failed_permanently: true,
1477                         failure: PathFailure::OnPath { network_update: None },
1478                         path: path.clone(),
1479                         short_channel_id: None,
1480                 });
1481                 let event = receiver
1482                         .recv_timeout(Duration::from_secs(EVENT_DEADLINE))
1483                         .expect("PaymentPathFailed not handled within deadline");
1484                 match event {
1485                         Event::PaymentPathFailed { .. } => {},
1486                         _ => panic!("Unexpected event"),
1487                 }
1488
1489                 nodes[0].scorer.lock().unwrap().expect(TestResult::PaymentSuccess { path: path.clone() });
1490                 nodes[0].node.push_pending_event(Event::PaymentPathSuccessful {
1491                         payment_id: PaymentId([42; 32]),
1492                         payment_hash: None,
1493                         path: path.clone(),
1494                 });
1495                 let event = receiver
1496                         .recv_timeout(Duration::from_secs(EVENT_DEADLINE))
1497                         .expect("PaymentPathSuccessful not handled within deadline");
1498                 match event {
1499                         Event::PaymentPathSuccessful { .. } => {},
1500                         _ => panic!("Unexpected event"),
1501                 }
1502
1503                 nodes[0].scorer.lock().unwrap().expect(TestResult::ProbeSuccess { path: path.clone() });
1504                 nodes[0].node.push_pending_event(Event::ProbeSuccessful {
1505                         payment_id: PaymentId([42; 32]),
1506                         payment_hash: PaymentHash([42; 32]),
1507                         path: path.clone(),
1508                 });
1509                 let event = receiver
1510                         .recv_timeout(Duration::from_secs(EVENT_DEADLINE))
1511                         .expect("ProbeSuccessful not handled within deadline");
1512                 match event {
1513                         Event::ProbeSuccessful  { .. } => {},
1514                         _ => panic!("Unexpected event"),
1515                 }
1516
1517                 nodes[0].scorer.lock().unwrap().expect(TestResult::ProbeFailure { path: path.clone() });
1518                 nodes[0].node.push_pending_event(Event::ProbeFailed {
1519                         payment_id: PaymentId([42; 32]),
1520                         payment_hash: PaymentHash([42; 32]),
1521                         path,
1522                         short_channel_id: Some(scored_scid),
1523                 });
1524                 let event = receiver
1525                         .recv_timeout(Duration::from_secs(EVENT_DEADLINE))
1526                         .expect("ProbeFailure not handled within deadline");
1527                 match event {
1528                         Event::ProbeFailed { .. } => {},
1529                         _ => panic!("Unexpected event"),
1530                 }
1531
1532                 if !std::thread::panicking() {
1533                         bg_processor.stop().unwrap();
1534                 }
1535         }
1536 }