3d26ec84a75cb0671c5fc6530c5bbc13241650ee
[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 #![deny(broken_intra_doc_links)]
6 #![deny(missing_docs)]
7 #![deny(unsafe_code)]
8
9 #[macro_use] extern crate lightning;
10
11 use lightning::chain;
12 use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
13 use lightning::chain::chainmonitor::{ChainMonitor, Persist};
14 use lightning::chain::keysinterface::{Sign, KeysInterface};
15 use lightning::ln::channelmanager::ChannelManager;
16 use lightning::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler};
17 use lightning::ln::peer_handler::{PeerManager, SocketDescriptor};
18 use lightning::ln::peer_handler::CustomMessageHandler;
19 use lightning::routing::network_graph::NetGraphMsgHandler;
20 use lightning::util::events::{Event, EventHandler, EventsProvider};
21 use lightning::util::logger::Logger;
22 use std::sync::Arc;
23 use std::sync::atomic::{AtomicBool, Ordering};
24 use std::thread;
25 use std::thread::JoinHandle;
26 use std::time::{Duration, Instant};
27 use std::ops::Deref;
28
29 /// `BackgroundProcessor` takes care of tasks that (1) need to happen periodically to keep
30 /// Rust-Lightning running properly, and (2) either can or should be run in the background. Its
31 /// responsibilities are:
32 /// * Processing [`Event`]s with a user-provided [`EventHandler`].
33 /// * Monitoring whether the [`ChannelManager`] needs to be re-persisted to disk, and if so,
34 ///   writing it to disk/backups by invoking the callback given to it at startup.
35 ///   [`ChannelManager`] persistence should be done in the background.
36 /// * Calling [`ChannelManager::timer_tick_occurred`] and [`PeerManager::timer_tick_occurred`]
37 ///   at the appropriate intervals.
38 ///
39 /// It will also call [`PeerManager::process_events`] periodically though this shouldn't be relied
40 /// upon as doing so may result in high latency.
41 ///
42 /// # Note
43 ///
44 /// If [`ChannelManager`] persistence fails and the persisted manager becomes out-of-date, then
45 /// there is a risk of channels force-closing on startup when the manager realizes it's outdated.
46 /// However, as long as [`ChannelMonitor`] backups are sound, no funds besides those used for
47 /// unilateral chain closure fees are at risk.
48 ///
49 /// [`ChannelMonitor`]: lightning::chain::channelmonitor::ChannelMonitor
50 /// [`Event`]: lightning::util::events::Event
51 #[must_use = "BackgroundProcessor will immediately stop on drop. It should be stored until shutdown."]
52 pub struct BackgroundProcessor {
53         stop_thread: Arc<AtomicBool>,
54         thread_handle: Option<JoinHandle<Result<(), std::io::Error>>>,
55 }
56
57 #[cfg(not(test))]
58 const FRESHNESS_TIMER: u64 = 60;
59 #[cfg(test)]
60 const FRESHNESS_TIMER: u64 = 1;
61
62 #[cfg(all(not(test), not(debug_assertions)))]
63 const PING_TIMER: u64 = 5;
64 /// Signature operations take a lot longer without compiler optimisations.
65 /// Increasing the ping timer allows for this but slower devices will be disconnected if the
66 /// timeout is reached.
67 #[cfg(all(not(test), debug_assertions))]
68 const PING_TIMER: u64 = 30;
69 #[cfg(test)]
70 const PING_TIMER: u64 = 1;
71
72 /// Trait which handles persisting a [`ChannelManager`] to disk.
73 ///
74 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
75 pub trait ChannelManagerPersister<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
76 where
77         M::Target: 'static + chain::Watch<Signer>,
78         T::Target: 'static + BroadcasterInterface,
79         K::Target: 'static + KeysInterface<Signer = Signer>,
80         F::Target: 'static + FeeEstimator,
81         L::Target: 'static + Logger,
82 {
83         /// Persist the given [`ChannelManager`] to disk, returning an error if persistence failed
84         /// (which will cause the [`BackgroundProcessor`] which called this method to exit.
85         ///
86         /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
87         fn persist_manager(&self, channel_manager: &ChannelManager<Signer, M, T, K, F, L>) -> Result<(), std::io::Error>;
88 }
89
90 impl<Fun, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
91 ChannelManagerPersister<Signer, M, T, K, F, L> for Fun where
92         M::Target: 'static + chain::Watch<Signer>,
93         T::Target: 'static + BroadcasterInterface,
94         K::Target: 'static + KeysInterface<Signer = Signer>,
95         F::Target: 'static + FeeEstimator,
96         L::Target: 'static + Logger,
97         Fun: Fn(&ChannelManager<Signer, M, T, K, F, L>) -> Result<(), std::io::Error>,
98 {
99         fn persist_manager(&self, channel_manager: &ChannelManager<Signer, M, T, K, F, L>) -> Result<(), std::io::Error> {
100                 self(channel_manager)
101         }
102 }
103
104 /// Decorates an [`EventHandler`] with common functionality provided by standard [`EventHandler`]s.
105 struct DecoratingEventHandler<
106         E: EventHandler,
107         N: Deref<Target = NetGraphMsgHandler<A, L>>,
108         A: Deref,
109         L: Deref,
110 >
111 where A::Target: chain::Access, L::Target: Logger {
112         event_handler: E,
113         net_graph_msg_handler: Option<N>,
114 }
115
116 impl<
117         E: EventHandler,
118         N: Deref<Target = NetGraphMsgHandler<A, L>>,
119         A: Deref,
120         L: Deref,
121 > EventHandler for DecoratingEventHandler<E, N, A, L>
122 where A::Target: chain::Access, L::Target: Logger {
123         fn handle_event(&self, event: &Event) {
124                 if let Some(event_handler) = &self.net_graph_msg_handler {
125                         event_handler.handle_event(event);
126                 }
127                 self.event_handler.handle_event(event);
128         }
129 }
130
131 impl BackgroundProcessor {
132         /// Start a background thread that takes care of responsibilities enumerated in the [top-level
133         /// documentation].
134         ///
135         /// The thread runs indefinitely unless the object is dropped, [`stop`] is called, or
136         /// `persist_manager` returns an error. In case of an error, the error is retrieved by calling
137         /// either [`join`] or [`stop`].
138         ///
139         /// # Data Persistence
140         ///
141         /// `persist_manager` is responsible for writing out the [`ChannelManager`] to disk, and/or
142         /// uploading to one or more backup services. See [`ChannelManager::write`] for writing out a
143         /// [`ChannelManager`]. See [`FilesystemPersister::persist_manager`] for Rust-Lightning's
144         /// provided implementation.
145         ///
146         /// Typically, users should either implement [`ChannelManagerPersister`] to never return an
147         /// error or call [`join`] and handle any error that may arise. For the latter case,
148         /// `BackgroundProcessor` must be restarted by calling `start` again after handling the error.
149         ///
150         /// # Event Handling
151         ///
152         /// `event_handler` is responsible for handling events that users should be notified of (e.g.,
153         /// payment failed). [`BackgroundProcessor`] may decorate the given [`EventHandler`] with common
154         /// functionality implemented by other handlers.
155         /// * [`NetGraphMsgHandler`] if given will update the [`NetworkGraph`] based on payment failures.
156         ///
157         /// [top-level documentation]: Self
158         /// [`join`]: Self::join
159         /// [`stop`]: Self::stop
160         /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
161         /// [`ChannelManager::write`]: lightning::ln::channelmanager::ChannelManager#impl-Writeable
162         /// [`FilesystemPersister::persist_manager`]: lightning_persister::FilesystemPersister::persist_manager
163         /// [`NetworkGraph`]: lightning::routing::network_graph::NetworkGraph
164         pub fn start<
165                 Signer: 'static + Sign,
166                 CA: 'static + Deref + Send + Sync,
167                 CF: 'static + Deref + Send + Sync,
168                 CW: 'static + Deref + Send + Sync,
169                 T: 'static + Deref + Send + Sync,
170                 K: 'static + Deref + Send + Sync,
171                 F: 'static + Deref + Send + Sync,
172                 L: 'static + Deref + Send + Sync,
173                 P: 'static + Deref + Send + Sync,
174                 Descriptor: 'static + SocketDescriptor + Send + Sync,
175                 CMH: 'static + Deref + Send + Sync,
176                 RMH: 'static + Deref + Send + Sync,
177                 EH: 'static + EventHandler + Send,
178                 CMP: 'static + Send + ChannelManagerPersister<Signer, CW, T, K, F, L>,
179                 M: 'static + Deref<Target = ChainMonitor<Signer, CF, T, F, L, P>> + Send + Sync,
180                 CM: 'static + Deref<Target = ChannelManager<Signer, CW, T, K, F, L>> + Send + Sync,
181                 NG: 'static + Deref<Target = NetGraphMsgHandler<CA, L>> + Send + Sync,
182                 UMH: 'static + Deref + Send + Sync,
183                 PM: 'static + Deref<Target = PeerManager<Descriptor, CMH, RMH, L, UMH>> + Send + Sync,
184         >(
185                 persister: CMP, event_handler: EH, chain_monitor: M, channel_manager: CM,
186                 net_graph_msg_handler: Option<NG>, peer_manager: PM, logger: L
187         ) -> Self
188         where
189                 CA::Target: 'static + chain::Access,
190                 CF::Target: 'static + chain::Filter,
191                 CW::Target: 'static + chain::Watch<Signer>,
192                 T::Target: 'static + BroadcasterInterface,
193                 K::Target: 'static + KeysInterface<Signer = Signer>,
194                 F::Target: 'static + FeeEstimator,
195                 L::Target: 'static + Logger,
196                 P::Target: 'static + Persist<Signer>,
197                 CMH::Target: 'static + ChannelMessageHandler,
198                 RMH::Target: 'static + RoutingMessageHandler,
199                 UMH::Target: 'static + CustomMessageHandler,
200         {
201                 let stop_thread = Arc::new(AtomicBool::new(false));
202                 let stop_thread_clone = stop_thread.clone();
203                 let handle = thread::spawn(move || -> Result<(), std::io::Error> {
204                         let event_handler = DecoratingEventHandler { event_handler, net_graph_msg_handler };
205
206                         log_trace!(logger, "Calling ChannelManager's timer_tick_occurred on startup");
207                         channel_manager.timer_tick_occurred();
208
209                         let mut last_freshness_call = Instant::now();
210                         let mut last_ping_call = Instant::now();
211                         loop {
212                                 peer_manager.process_events();
213                                 channel_manager.process_pending_events(&event_handler);
214                                 chain_monitor.process_pending_events(&event_handler);
215                                 let updates_available =
216                                         channel_manager.await_persistable_update_timeout(Duration::from_millis(100));
217                                 if updates_available {
218                                         persister.persist_manager(&*channel_manager)?;
219                                 }
220                                 // Exit the loop if the background processor was requested to stop.
221                                 if stop_thread.load(Ordering::Acquire) == true {
222                                         log_trace!(logger, "Terminating background processor.");
223                                         return Ok(());
224                                 }
225                                 if last_freshness_call.elapsed().as_secs() > FRESHNESS_TIMER {
226                                         log_trace!(logger, "Calling ChannelManager's timer_tick_occurred");
227                                         channel_manager.timer_tick_occurred();
228                                         last_freshness_call = Instant::now();
229                                 }
230                                 if last_ping_call.elapsed().as_secs() > PING_TIMER * 2 {
231                                         // On various platforms, we may be starved of CPU cycles for several reasons.
232                                         // E.g. on iOS, if we've been in the background, we will be entirely paused.
233                                         // Similarly, if we're on a desktop platform and the device has been asleep, we
234                                         // may not get any cycles.
235                                         // In any case, if we've been entirely paused for more than double our ping
236                                         // timer, we should have disconnected all sockets by now (and they're probably
237                                         // dead anyway), so disconnect them by calling `timer_tick_occurred()` twice.
238                                         log_trace!(logger, "Awoke after more than double our ping timer, disconnecting peers.");
239                                         peer_manager.timer_tick_occurred();
240                                         peer_manager.timer_tick_occurred();
241                                         last_ping_call = Instant::now();
242                                 } else if last_ping_call.elapsed().as_secs() > PING_TIMER {
243                                         log_trace!(logger, "Calling PeerManager's timer_tick_occurred");
244                                         peer_manager.timer_tick_occurred();
245                                         last_ping_call = Instant::now();
246                                 }
247                         }
248                 });
249                 Self { stop_thread: stop_thread_clone, thread_handle: Some(handle) }
250         }
251
252         /// Join `BackgroundProcessor`'s thread, returning any error that occurred while persisting
253         /// [`ChannelManager`].
254         ///
255         /// # Panics
256         ///
257         /// This function panics if the background thread has panicked such as while persisting or
258         /// handling events.
259         ///
260         /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
261         pub fn join(mut self) -> Result<(), std::io::Error> {
262                 assert!(self.thread_handle.is_some());
263                 self.join_thread()
264         }
265
266         /// Stop `BackgroundProcessor`'s thread, returning any error that occurred while persisting
267         /// [`ChannelManager`].
268         ///
269         /// # Panics
270         ///
271         /// This function panics if the background thread has panicked such as while persisting or
272         /// handling events.
273         ///
274         /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
275         pub fn stop(mut self) -> Result<(), std::io::Error> {
276                 assert!(self.thread_handle.is_some());
277                 self.stop_and_join_thread()
278         }
279
280         fn stop_and_join_thread(&mut self) -> Result<(), std::io::Error> {
281                 self.stop_thread.store(true, Ordering::Release);
282                 self.join_thread()
283         }
284
285         fn join_thread(&mut self) -> Result<(), std::io::Error> {
286                 match self.thread_handle.take() {
287                         Some(handle) => handle.join().unwrap(),
288                         None => Ok(()),
289                 }
290         }
291 }
292
293 impl Drop for BackgroundProcessor {
294         fn drop(&mut self) {
295                 self.stop_and_join_thread().unwrap();
296         }
297 }
298
299 #[cfg(test)]
300 mod tests {
301         use bitcoin::blockdata::block::BlockHeader;
302         use bitcoin::blockdata::constants::genesis_block;
303         use bitcoin::blockdata::transaction::{Transaction, TxOut};
304         use bitcoin::network::constants::Network;
305         use lightning::chain::{BestBlock, Confirm, chainmonitor};
306         use lightning::chain::channelmonitor::ANTI_REORG_DELAY;
307         use lightning::chain::keysinterface::{InMemorySigner, KeysInterface, KeysManager};
308         use lightning::chain::transaction::OutPoint;
309         use lightning::get_event_msg;
310         use lightning::ln::channelmanager::{BREAKDOWN_TIMEOUT, ChainParameters, ChannelManager, SimpleArcChannelManager};
311         use lightning::ln::features::InitFeatures;
312         use lightning::ln::msgs::{ChannelMessageHandler, Init};
313         use lightning::ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler};
314         use lightning::routing::scorer::Scorer;
315         use lightning::routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
316         use lightning::util::config::UserConfig;
317         use lightning::util::events::{Event, MessageSendEventsProvider, MessageSendEvent};
318         use lightning::util::ser::Writeable;
319         use lightning::util::test_utils;
320         use lightning_invoice::payment::{InvoicePayer, RetryAttempts};
321         use lightning_invoice::utils::DefaultRouter;
322         use lightning_persister::FilesystemPersister;
323         use std::fs;
324         use std::path::PathBuf;
325         use std::sync::{Arc, Mutex};
326         use std::time::Duration;
327         use super::{BackgroundProcessor, FRESHNESS_TIMER};
328
329         const EVENT_DEADLINE: u64 = 5 * FRESHNESS_TIMER;
330
331         #[derive(Clone, Eq, Hash, PartialEq)]
332         struct TestDescriptor{}
333         impl SocketDescriptor for TestDescriptor {
334                 fn send_data(&mut self, _data: &[u8], _resume_read: bool) -> usize {
335                         0
336                 }
337
338                 fn disconnect_socket(&mut self) {}
339         }
340
341         type ChainMonitor = chainmonitor::ChainMonitor<InMemorySigner, Arc<test_utils::TestChainSource>, Arc<test_utils::TestBroadcaster>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>, Arc<FilesystemPersister>>;
342
343         struct Node {
344                 node: Arc<SimpleArcChannelManager<ChainMonitor, test_utils::TestBroadcaster, test_utils::TestFeeEstimator, test_utils::TestLogger>>,
345                 net_graph_msg_handler: Option<Arc<NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>>>,
346                 peer_manager: Arc<PeerManager<TestDescriptor, Arc<test_utils::TestChannelMessageHandler>, Arc<test_utils::TestRoutingMessageHandler>, Arc<test_utils::TestLogger>, IgnoringMessageHandler>>,
347                 chain_monitor: Arc<ChainMonitor>,
348                 persister: Arc<FilesystemPersister>,
349                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
350                 logger: Arc<test_utils::TestLogger>,
351                 best_block: BestBlock,
352         }
353
354         impl Drop for Node {
355                 fn drop(&mut self) {
356                         let data_dir = self.persister.get_data_dir();
357                         match fs::remove_dir_all(data_dir.clone()) {
358                                 Err(e) => println!("Failed to remove test persister directory {}: {}", data_dir, e),
359                                 _ => {}
360                         }
361                 }
362         }
363
364         fn get_full_filepath(filepath: String, filename: String) -> String {
365                 let mut path = PathBuf::from(filepath);
366                 path.push(filename);
367                 path.to_str().unwrap().to_string()
368         }
369
370         fn create_nodes(num_nodes: usize, persist_dir: String) -> Vec<Node> {
371                 let mut nodes = Vec::new();
372                 for i in 0..num_nodes {
373                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))});
374                         let fee_estimator = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) });
375                         let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
376                         let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
377                         let persister = Arc::new(FilesystemPersister::new(format!("{}_persister_{}", persist_dir, i)));
378                         let seed = [i as u8; 32];
379                         let network = Network::Testnet;
380                         let genesis_block = genesis_block(network);
381                         let now = Duration::from_secs(genesis_block.header.time as u64);
382                         let keys_manager = Arc::new(KeysManager::new(&seed, now.as_secs(), now.subsec_nanos()));
383                         let chain_monitor = Arc::new(chainmonitor::ChainMonitor::new(Some(chain_source.clone()), tx_broadcaster.clone(), logger.clone(), fee_estimator.clone(), persister.clone()));
384                         let best_block = BestBlock::from_genesis(network);
385                         let params = ChainParameters { network, best_block };
386                         let manager = Arc::new(ChannelManager::new(fee_estimator.clone(), chain_monitor.clone(), tx_broadcaster.clone(), logger.clone(), keys_manager.clone(), UserConfig::default(), params));
387                         let network_graph = NetworkGraph::new(genesis_block.header.block_hash());
388                         let net_graph_msg_handler = Some(Arc::new(NetGraphMsgHandler::new(network_graph, Some(chain_source.clone()), logger.clone())));
389                         let msg_handler = MessageHandler { chan_handler: Arc::new(test_utils::TestChannelMessageHandler::new()), route_handler: Arc::new(test_utils::TestRoutingMessageHandler::new() )};
390                         let peer_manager = Arc::new(PeerManager::new(msg_handler, keys_manager.get_node_secret(), &seed, logger.clone(), IgnoringMessageHandler{}));
391                         let node = Node { node: manager, net_graph_msg_handler, peer_manager, chain_monitor, persister, tx_broadcaster, logger, best_block };
392                         nodes.push(node);
393                 }
394
395                 for i in 0..num_nodes {
396                         for j in (i+1)..num_nodes {
397                                 nodes[i].node.peer_connected(&nodes[j].node.get_our_node_id(), &Init { features: InitFeatures::known() });
398                                 nodes[j].node.peer_connected(&nodes[i].node.get_our_node_id(), &Init { features: InitFeatures::known() });
399                         }
400                 }
401
402                 nodes
403         }
404
405         macro_rules! open_channel {
406                 ($node_a: expr, $node_b: expr, $channel_value: expr) => {{
407                         begin_open_channel!($node_a, $node_b, $channel_value);
408                         let events = $node_a.node.get_and_clear_pending_events();
409                         assert_eq!(events.len(), 1);
410                         let (temporary_channel_id, tx) = handle_funding_generation_ready!(&events[0], $channel_value);
411                         end_open_channel!($node_a, $node_b, temporary_channel_id, tx);
412                         tx
413                 }}
414         }
415
416         macro_rules! begin_open_channel {
417                 ($node_a: expr, $node_b: expr, $channel_value: expr) => {{
418                         $node_a.node.create_channel($node_b.node.get_our_node_id(), $channel_value, 100, 42, None).unwrap();
419                         $node_b.node.handle_open_channel(&$node_a.node.get_our_node_id(), InitFeatures::known(), &get_event_msg!($node_a, MessageSendEvent::SendOpenChannel, $node_b.node.get_our_node_id()));
420                         $node_a.node.handle_accept_channel(&$node_b.node.get_our_node_id(), InitFeatures::known(), &get_event_msg!($node_b, MessageSendEvent::SendAcceptChannel, $node_a.node.get_our_node_id()));
421                 }}
422         }
423
424         macro_rules! handle_funding_generation_ready {
425                 ($event: expr, $channel_value: expr) => {{
426                         match $event {
427                                 &Event::FundingGenerationReady { temporary_channel_id, channel_value_satoshis, ref output_script, user_channel_id } => {
428                                         assert_eq!(channel_value_satoshis, $channel_value);
429                                         assert_eq!(user_channel_id, 42);
430
431                                         let tx = Transaction { version: 1 as i32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
432                                                 value: channel_value_satoshis, script_pubkey: output_script.clone(),
433                                         }]};
434                                         (temporary_channel_id, tx)
435                                 },
436                                 _ => panic!("Unexpected event"),
437                         }
438                 }}
439         }
440
441         macro_rules! end_open_channel {
442                 ($node_a: expr, $node_b: expr, $temporary_channel_id: expr, $tx: expr) => {{
443                         $node_a.node.funding_transaction_generated(&$temporary_channel_id, $tx.clone()).unwrap();
444                         $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()));
445                         $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()));
446                 }}
447         }
448
449         fn confirm_transaction_depth(node: &mut Node, tx: &Transaction, depth: u32) {
450                 for i in 1..=depth {
451                         let prev_blockhash = node.best_block.block_hash();
452                         let height = node.best_block.height() + 1;
453                         let header = BlockHeader { version: 0x20000000, prev_blockhash, merkle_root: Default::default(), time: height, bits: 42, nonce: 42 };
454                         let txdata = vec![(0, tx)];
455                         node.best_block = BestBlock::new(header.block_hash(), height);
456                         match i {
457                                 1 => {
458                                         node.node.transactions_confirmed(&header, &txdata, height);
459                                         node.chain_monitor.transactions_confirmed(&header, &txdata, height);
460                                 },
461                                 x if x == depth => {
462                                         node.node.best_block_updated(&header, height);
463                                         node.chain_monitor.best_block_updated(&header, height);
464                                 },
465                                 _ => {},
466                         }
467                 }
468         }
469         fn confirm_transaction(node: &mut Node, tx: &Transaction) {
470                 confirm_transaction_depth(node, tx, ANTI_REORG_DELAY);
471         }
472
473         #[test]
474         fn test_background_processor() {
475                 // Test that when a new channel is created, the ChannelManager needs to be re-persisted with
476                 // updates. Also test that when new updates are available, the manager signals that it needs
477                 // re-persistence and is successfully re-persisted.
478                 let nodes = create_nodes(2, "test_background_processor".to_string());
479
480                 // Go through the channel creation process so that each node has something to persist. Since
481                 // open_channel consumes events, it must complete before starting BackgroundProcessor to
482                 // avoid a race with processing events.
483                 let tx = open_channel!(nodes[0], nodes[1], 100000);
484
485                 // Initiate the background processors to watch each node.
486                 let data_dir = nodes[0].persister.get_data_dir();
487                 let persister = move |node: &ChannelManager<InMemorySigner, Arc<ChainMonitor>, Arc<test_utils::TestBroadcaster>, Arc<KeysManager>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>>| FilesystemPersister::persist_manager(data_dir.clone(), node);
488                 let event_handler = |_: &_| {};
489                 let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].net_graph_msg_handler.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone());
490
491                 macro_rules! check_persisted_data {
492                         ($node: expr, $filepath: expr, $expected_bytes: expr) => {
493                                 match $node.write(&mut $expected_bytes) {
494                                         Ok(()) => {
495                                                 loop {
496                                                         match std::fs::read($filepath) {
497                                                                 Ok(bytes) => {
498                                                                         if bytes == $expected_bytes {
499                                                                                 break
500                                                                         } else {
501                                                                                 continue
502                                                                         }
503                                                                 },
504                                                                 Err(_) => continue
505                                                         }
506                                                 }
507                                         },
508                                         Err(e) => panic!("Unexpected error: {}", e)
509                                 }
510                         }
511                 }
512
513                 // Check that the initial channel manager data is persisted as expected.
514                 let filepath = get_full_filepath("test_background_processor_persister_0".to_string(), "manager".to_string());
515                 let mut expected_bytes = Vec::new();
516                 check_persisted_data!(nodes[0].node, filepath.clone(), expected_bytes);
517                 loop {
518                         if !nodes[0].node.get_persistence_condvar_value() { break }
519                 }
520
521                 // Force-close the channel.
522                 nodes[0].node.force_close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
523
524                 // Check that the force-close updates are persisted.
525                 let mut expected_bytes = Vec::new();
526                 check_persisted_data!(nodes[0].node, filepath.clone(), expected_bytes);
527                 loop {
528                         if !nodes[0].node.get_persistence_condvar_value() { break }
529                 }
530
531                 assert!(bg_processor.stop().is_ok());
532         }
533
534         #[test]
535         fn test_timer_tick_called() {
536                 // Test that ChannelManager's and PeerManager's `timer_tick_occurred` is called every
537                 // `FRESHNESS_TIMER`.
538                 let nodes = create_nodes(1, "test_timer_tick_called".to_string());
539                 let data_dir = nodes[0].persister.get_data_dir();
540                 let persister = move |node: &ChannelManager<InMemorySigner, Arc<ChainMonitor>, Arc<test_utils::TestBroadcaster>, Arc<KeysManager>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>>| FilesystemPersister::persist_manager(data_dir.clone(), node);
541                 let event_handler = |_: &_| {};
542                 let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].net_graph_msg_handler.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone());
543                 loop {
544                         let log_entries = nodes[0].logger.lines.lock().unwrap();
545                         let desired_log = "Calling ChannelManager's timer_tick_occurred".to_string();
546                         let second_desired_log = "Calling PeerManager's timer_tick_occurred".to_string();
547                         if log_entries.get(&("lightning_background_processor".to_string(), desired_log)).is_some() &&
548                                         log_entries.get(&("lightning_background_processor".to_string(), second_desired_log)).is_some() {
549                                 break
550                         }
551                 }
552
553                 assert!(bg_processor.stop().is_ok());
554         }
555
556         #[test]
557         fn test_persist_error() {
558                 // Test that if we encounter an error during manager persistence, the thread panics.
559                 let nodes = create_nodes(2, "test_persist_error".to_string());
560                 open_channel!(nodes[0], nodes[1], 100000);
561
562                 let persister = |_: &_| Err(std::io::Error::new(std::io::ErrorKind::Other, "test"));
563                 let event_handler = |_: &_| {};
564                 let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].net_graph_msg_handler.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone());
565                 match bg_processor.join() {
566                         Ok(_) => panic!("Expected error persisting manager"),
567                         Err(e) => {
568                                 assert_eq!(e.kind(), std::io::ErrorKind::Other);
569                                 assert_eq!(e.get_ref().unwrap().to_string(), "test");
570                         },
571                 }
572         }
573
574         #[test]
575         fn test_background_event_handling() {
576                 let mut nodes = create_nodes(2, "test_background_event_handling".to_string());
577                 let channel_value = 100000;
578                 let data_dir = nodes[0].persister.get_data_dir();
579                 let persister = move |node: &_| FilesystemPersister::persist_manager(data_dir.clone(), node);
580
581                 // Set up a background event handler for FundingGenerationReady events.
582                 let (sender, receiver) = std::sync::mpsc::sync_channel(1);
583                 let event_handler = move |event: &Event| {
584                         sender.send(handle_funding_generation_ready!(event, channel_value)).unwrap();
585                 };
586                 let bg_processor = BackgroundProcessor::start(persister.clone(), event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].net_graph_msg_handler.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone());
587
588                 // Open a channel and check that the FundingGenerationReady event was handled.
589                 begin_open_channel!(nodes[0], nodes[1], channel_value);
590                 let (temporary_channel_id, funding_tx) = receiver
591                         .recv_timeout(Duration::from_secs(EVENT_DEADLINE))
592                         .expect("FundingGenerationReady not handled within deadline");
593                 end_open_channel!(nodes[0], nodes[1], temporary_channel_id, funding_tx);
594
595                 // Confirm the funding transaction.
596                 confirm_transaction(&mut nodes[0], &funding_tx);
597                 let as_funding = get_event_msg!(nodes[0], MessageSendEvent::SendFundingLocked, nodes[1].node.get_our_node_id());
598                 confirm_transaction(&mut nodes[1], &funding_tx);
599                 let bs_funding = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id());
600                 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &bs_funding);
601                 let _as_channel_update = get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
602                 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding);
603                 let _bs_channel_update = get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
604
605                 assert!(bg_processor.stop().is_ok());
606
607                 // Set up a background event handler for SpendableOutputs events.
608                 let (sender, receiver) = std::sync::mpsc::sync_channel(1);
609                 let event_handler = move |event: &Event| sender.send(event.clone()).unwrap();
610                 let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].net_graph_msg_handler.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone());
611
612                 // Force close the channel and check that the SpendableOutputs event was handled.
613                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
614                 let commitment_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().pop().unwrap();
615                 confirm_transaction_depth(&mut nodes[0], &commitment_tx, BREAKDOWN_TIMEOUT as u32);
616                 let event = receiver
617                         .recv_timeout(Duration::from_secs(EVENT_DEADLINE))
618                         .expect("SpendableOutputs not handled within deadline");
619                 match event {
620                         Event::SpendableOutputs { .. } => {},
621                         Event::ChannelClosed { .. } => {},
622                         _ => panic!("Unexpected event: {:?}", event),
623                 }
624
625                 assert!(bg_processor.stop().is_ok());
626         }
627
628         #[test]
629         fn test_invoice_payer() {
630                 let nodes = create_nodes(2, "test_invoice_payer".to_string());
631
632                 // Initiate the background processors to watch each node.
633                 let data_dir = nodes[0].persister.get_data_dir();
634                 let persister = move |node: &ChannelManager<InMemorySigner, Arc<ChainMonitor>, Arc<test_utils::TestBroadcaster>, Arc<KeysManager>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>>| FilesystemPersister::persist_manager(data_dir.clone(), node);
635                 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
636                 let router = DefaultRouter::new(network_graph, Arc::clone(&nodes[0].logger));
637                 let scorer = Arc::new(Mutex::new(Scorer::default()));
638                 let invoice_payer = Arc::new(InvoicePayer::new(Arc::clone(&nodes[0].node), router, scorer, Arc::clone(&nodes[0].logger), |_: &_| {}, RetryAttempts(2)));
639                 let event_handler = Arc::clone(&invoice_payer);
640                 let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].net_graph_msg_handler.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone());
641                 assert!(bg_processor.stop().is_ok());
642         }
643 }