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