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