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