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