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