Update `ChannelUpdate::timestamp` when channels are dis-/en-abled
[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 ///
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<G, A, L>>,
107         G: Deref<Target = NetworkGraph>,
108         A: Deref,
109         L: Deref,
110 >
111 where A::Target: chain::Access, L::Target: Logger {
112         event_handler: E,
113         net_graph_msg_handler: Option<N>,
114 }
115
116 impl<
117         E: EventHandler,
118         N: Deref<Target = NetGraphMsgHandler<G, A, L>>,
119         G: Deref<Target = NetworkGraph>,
120         A: Deref,
121         L: Deref,
122 > EventHandler for DecoratingEventHandler<E, N, G, 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]: BackgroundProcessor
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                 G: 'static + Deref<Target = NetworkGraph> + Send + Sync,
174                 L: 'static + Deref + Send + Sync,
175                 P: 'static + Deref + Send + Sync,
176                 Descriptor: 'static + SocketDescriptor + Send + Sync,
177                 CMH: 'static + Deref + Send + Sync,
178                 RMH: 'static + Deref + Send + Sync,
179                 EH: 'static + EventHandler + Send,
180                 CMP: 'static + Send + ChannelManagerPersister<Signer, CW, T, K, F, L>,
181                 M: 'static + Deref<Target = ChainMonitor<Signer, CF, T, F, L, P>> + Send + Sync,
182                 CM: 'static + Deref<Target = ChannelManager<Signer, CW, T, K, F, L>> + Send + Sync,
183                 NG: 'static + Deref<Target = NetGraphMsgHandler<G, CA, L>> + Send + Sync,
184                 UMH: 'static + Deref + Send + Sync,
185                 PM: 'static + Deref<Target = PeerManager<Descriptor, CMH, RMH, L, UMH>> + Send + Sync,
186         >(
187                 persister: CMP, event_handler: EH, chain_monitor: M, channel_manager: CM,
188                 net_graph_msg_handler: Option<NG>, peer_manager: PM, logger: L
189         ) -> Self
190         where
191                 CA::Target: 'static + chain::Access,
192                 CF::Target: 'static + chain::Filter,
193                 CW::Target: 'static + chain::Watch<Signer>,
194                 T::Target: 'static + BroadcasterInterface,
195                 K::Target: 'static + KeysInterface<Signer = Signer>,
196                 F::Target: 'static + FeeEstimator,
197                 L::Target: 'static + Logger,
198                 P::Target: 'static + Persist<Signer>,
199                 CMH::Target: 'static + ChannelMessageHandler,
200                 RMH::Target: 'static + RoutingMessageHandler,
201                 UMH::Target: 'static + CustomMessageHandler,
202         {
203                 let stop_thread = Arc::new(AtomicBool::new(false));
204                 let stop_thread_clone = stop_thread.clone();
205                 let handle = thread::spawn(move || -> Result<(), std::io::Error> {
206                         let event_handler = DecoratingEventHandler { event_handler, net_graph_msg_handler };
207
208                         log_trace!(logger, "Calling ChannelManager's timer_tick_occurred on startup");
209                         channel_manager.timer_tick_occurred();
210
211                         let mut last_freshness_call = Instant::now();
212                         let mut last_ping_call = Instant::now();
213                         loop {
214                                 peer_manager.process_events();
215                                 channel_manager.process_pending_events(&event_handler);
216                                 chain_monitor.process_pending_events(&event_handler);
217                                 let updates_available =
218                                         channel_manager.await_persistable_update_timeout(Duration::from_millis(100));
219                                 if updates_available {
220                                         log_trace!(logger, "Persisting ChannelManager...");
221                                         persister.persist_manager(&*channel_manager)?;
222                                         log_trace!(logger, "Done persisting ChannelManager.");
223                                 }
224                                 // Exit the loop if the background processor was requested to stop.
225                                 if stop_thread.load(Ordering::Acquire) == true {
226                                         log_trace!(logger, "Terminating background processor.");
227                                         return Ok(());
228                                 }
229                                 if last_freshness_call.elapsed().as_secs() > FRESHNESS_TIMER {
230                                         log_trace!(logger, "Calling ChannelManager's timer_tick_occurred");
231                                         channel_manager.timer_tick_occurred();
232                                         last_freshness_call = Instant::now();
233                                 }
234                                 if last_ping_call.elapsed().as_secs() > PING_TIMER * 2 {
235                                         // On various platforms, we may be starved of CPU cycles for several reasons.
236                                         // E.g. on iOS, if we've been in the background, we will be entirely paused.
237                                         // Similarly, if we're on a desktop platform and the device has been asleep, we
238                                         // may not get any cycles.
239                                         // In any case, if we've been entirely paused for more than double our ping
240                                         // timer, we should have disconnected all sockets by now (and they're probably
241                                         // dead anyway), so disconnect them by calling `timer_tick_occurred()` twice.
242                                         log_trace!(logger, "Awoke after more than double our ping timer, disconnecting peers.");
243                                         peer_manager.disconnect_all_peers();
244                                         last_ping_call = Instant::now();
245                                 } else if last_ping_call.elapsed().as_secs() > PING_TIMER {
246                                         log_trace!(logger, "Calling PeerManager's timer_tick_occurred");
247                                         peer_manager.timer_tick_occurred();
248                                         last_ping_call = Instant::now();
249                                 }
250                         }
251                 });
252                 Self { stop_thread: stop_thread_clone, thread_handle: Some(handle) }
253         }
254
255         /// Join `BackgroundProcessor`'s thread, returning any error that occurred while persisting
256         /// [`ChannelManager`].
257         ///
258         /// # Panics
259         ///
260         /// This function panics if the background thread has panicked such as while persisting or
261         /// handling events.
262         ///
263         /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
264         pub fn join(mut self) -> Result<(), std::io::Error> {
265                 assert!(self.thread_handle.is_some());
266                 self.join_thread()
267         }
268
269         /// Stop `BackgroundProcessor`'s thread, returning any error that occurred while persisting
270         /// [`ChannelManager`].
271         ///
272         /// # Panics
273         ///
274         /// This function panics if the background thread has panicked such as while persisting or
275         /// handling events.
276         ///
277         /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
278         pub fn stop(mut self) -> Result<(), std::io::Error> {
279                 assert!(self.thread_handle.is_some());
280                 self.stop_and_join_thread()
281         }
282
283         fn stop_and_join_thread(&mut self) -> Result<(), std::io::Error> {
284                 self.stop_thread.store(true, Ordering::Release);
285                 self.join_thread()
286         }
287
288         fn join_thread(&mut self) -> Result<(), std::io::Error> {
289                 match self.thread_handle.take() {
290                         Some(handle) => handle.join().unwrap(),
291                         None => Ok(()),
292                 }
293         }
294 }
295
296 impl Drop for BackgroundProcessor {
297         fn drop(&mut self) {
298                 self.stop_and_join_thread().unwrap();
299         }
300 }
301
302 #[cfg(test)]
303 mod tests {
304         use bitcoin::blockdata::block::BlockHeader;
305         use bitcoin::blockdata::constants::genesis_block;
306         use bitcoin::blockdata::transaction::{Transaction, TxOut};
307         use bitcoin::network::constants::Network;
308         use lightning::chain::{BestBlock, Confirm, chainmonitor};
309         use lightning::chain::channelmonitor::ANTI_REORG_DELAY;
310         use lightning::chain::keysinterface::{InMemorySigner, KeysInterface, KeysManager};
311         use lightning::chain::transaction::OutPoint;
312         use lightning::get_event_msg;
313         use lightning::ln::channelmanager::{BREAKDOWN_TIMEOUT, ChainParameters, ChannelManager, SimpleArcChannelManager};
314         use lightning::ln::features::InitFeatures;
315         use lightning::ln::msgs::{ChannelMessageHandler, Init};
316         use lightning::ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler};
317         use lightning::routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
318         use lightning::util::config::UserConfig;
319         use lightning::util::events::{Event, MessageSendEventsProvider, MessageSendEvent};
320         use lightning::util::ser::Writeable;
321         use lightning::util::test_utils;
322         use lightning_invoice::payment::{InvoicePayer, RetryAttempts};
323         use lightning_invoice::utils::DefaultRouter;
324         use lightning_persister::FilesystemPersister;
325         use std::fs;
326         use std::path::PathBuf;
327         use std::sync::{Arc, Mutex};
328         use std::time::Duration;
329         use super::{BackgroundProcessor, FRESHNESS_TIMER};
330
331         const EVENT_DEADLINE: u64 = 5 * FRESHNESS_TIMER;
332
333         #[derive(Clone, Eq, Hash, PartialEq)]
334         struct TestDescriptor{}
335         impl SocketDescriptor for TestDescriptor {
336                 fn send_data(&mut self, _data: &[u8], _resume_read: bool) -> usize {
337                         0
338                 }
339
340                 fn disconnect_socket(&mut self) {}
341         }
342
343         type ChainMonitor = chainmonitor::ChainMonitor<InMemorySigner, Arc<test_utils::TestChainSource>, Arc<test_utils::TestBroadcaster>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>, Arc<FilesystemPersister>>;
344
345         struct Node {
346                 node: Arc<SimpleArcChannelManager<ChainMonitor, test_utils::TestBroadcaster, test_utils::TestFeeEstimator, test_utils::TestLogger>>,
347                 net_graph_msg_handler: Option<Arc<NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>>>,
348                 peer_manager: Arc<PeerManager<TestDescriptor, Arc<test_utils::TestChannelMessageHandler>, Arc<test_utils::TestRoutingMessageHandler>, Arc<test_utils::TestLogger>, IgnoringMessageHandler>>,
349                 chain_monitor: Arc<ChainMonitor>,
350                 persister: Arc<FilesystemPersister>,
351                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
352                 network_graph: Arc<NetworkGraph>,
353                 logger: Arc<test_utils::TestLogger>,
354                 best_block: BestBlock,
355         }
356
357         impl Drop for Node {
358                 fn drop(&mut self) {
359                         let data_dir = self.persister.get_data_dir();
360                         match fs::remove_dir_all(data_dir.clone()) {
361                                 Err(e) => println!("Failed to remove test persister directory {}: {}", data_dir, e),
362                                 _ => {}
363                         }
364                 }
365         }
366
367         fn get_full_filepath(filepath: String, filename: String) -> String {
368                 let mut path = PathBuf::from(filepath);
369                 path.push(filename);
370                 path.to_str().unwrap().to_string()
371         }
372
373         fn create_nodes(num_nodes: usize, persist_dir: String) -> Vec<Node> {
374                 let mut nodes = Vec::new();
375                 for i in 0..num_nodes {
376                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))});
377                         let fee_estimator = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) });
378                         let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
379                         let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
380                         let persister = Arc::new(FilesystemPersister::new(format!("{}_persister_{}", persist_dir, i)));
381                         let seed = [i as u8; 32];
382                         let network = Network::Testnet;
383                         let genesis_block = genesis_block(network);
384                         let now = Duration::from_secs(genesis_block.header.time as u64);
385                         let keys_manager = Arc::new(KeysManager::new(&seed, now.as_secs(), now.subsec_nanos()));
386                         let chain_monitor = Arc::new(chainmonitor::ChainMonitor::new(Some(chain_source.clone()), tx_broadcaster.clone(), logger.clone(), fee_estimator.clone(), persister.clone()));
387                         let best_block = BestBlock::from_genesis(network);
388                         let params = ChainParameters { network, best_block };
389                         let manager = Arc::new(ChannelManager::new(fee_estimator.clone(), chain_monitor.clone(), tx_broadcaster.clone(), logger.clone(), keys_manager.clone(), UserConfig::default(), params));
390                         let network_graph = Arc::new(NetworkGraph::new(genesis_block.header.block_hash()));
391                         let net_graph_msg_handler = Some(Arc::new(NetGraphMsgHandler::new(network_graph.clone(), Some(chain_source.clone()), logger.clone())));
392                         let msg_handler = MessageHandler { chan_handler: Arc::new(test_utils::TestChannelMessageHandler::new()), route_handler: Arc::new(test_utils::TestRoutingMessageHandler::new() )};
393                         let peer_manager = Arc::new(PeerManager::new(msg_handler, keys_manager.get_node_secret(), &seed, logger.clone(), IgnoringMessageHandler{}));
394                         let node = Node { node: manager, net_graph_msg_handler, peer_manager, chain_monitor, persister, tx_broadcaster, network_graph, logger, best_block };
395                         nodes.push(node);
396                 }
397
398                 for i in 0..num_nodes {
399                         for j in (i+1)..num_nodes {
400                                 nodes[i].node.peer_connected(&nodes[j].node.get_our_node_id(), &Init { features: InitFeatures::known() });
401                                 nodes[j].node.peer_connected(&nodes[i].node.get_our_node_id(), &Init { features: InitFeatures::known() });
402                         }
403                 }
404
405                 nodes
406         }
407
408         macro_rules! open_channel {
409                 ($node_a: expr, $node_b: expr, $channel_value: expr) => {{
410                         begin_open_channel!($node_a, $node_b, $channel_value);
411                         let events = $node_a.node.get_and_clear_pending_events();
412                         assert_eq!(events.len(), 1);
413                         let (temporary_channel_id, tx) = handle_funding_generation_ready!(&events[0], $channel_value);
414                         end_open_channel!($node_a, $node_b, temporary_channel_id, tx);
415                         tx
416                 }}
417         }
418
419         macro_rules! begin_open_channel {
420                 ($node_a: expr, $node_b: expr, $channel_value: expr) => {{
421                         $node_a.node.create_channel($node_b.node.get_our_node_id(), $channel_value, 100, 42, None).unwrap();
422                         $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()));
423                         $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()));
424                 }}
425         }
426
427         macro_rules! handle_funding_generation_ready {
428                 ($event: expr, $channel_value: expr) => {{
429                         match $event {
430                                 &Event::FundingGenerationReady { temporary_channel_id, channel_value_satoshis, ref output_script, user_channel_id } => {
431                                         assert_eq!(channel_value_satoshis, $channel_value);
432                                         assert_eq!(user_channel_id, 42);
433
434                                         let tx = Transaction { version: 1 as i32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
435                                                 value: channel_value_satoshis, script_pubkey: output_script.clone(),
436                                         }]};
437                                         (temporary_channel_id, tx)
438                                 },
439                                 _ => panic!("Unexpected event"),
440                         }
441                 }}
442         }
443
444         macro_rules! end_open_channel {
445                 ($node_a: expr, $node_b: expr, $temporary_channel_id: expr, $tx: expr) => {{
446                         $node_a.node.funding_transaction_generated(&$temporary_channel_id, $tx.clone()).unwrap();
447                         $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()));
448                         $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()));
449                 }}
450         }
451
452         fn confirm_transaction_depth(node: &mut Node, tx: &Transaction, depth: u32) {
453                 for i in 1..=depth {
454                         let prev_blockhash = node.best_block.block_hash();
455                         let height = node.best_block.height() + 1;
456                         let header = BlockHeader { version: 0x20000000, prev_blockhash, merkle_root: Default::default(), time: height, bits: 42, nonce: 42 };
457                         let txdata = vec![(0, tx)];
458                         node.best_block = BestBlock::new(header.block_hash(), height);
459                         match i {
460                                 1 => {
461                                         node.node.transactions_confirmed(&header, &txdata, height);
462                                         node.chain_monitor.transactions_confirmed(&header, &txdata, height);
463                                 },
464                                 x if x == depth => {
465                                         node.node.best_block_updated(&header, height);
466                                         node.chain_monitor.best_block_updated(&header, height);
467                                 },
468                                 _ => {},
469                         }
470                 }
471         }
472         fn confirm_transaction(node: &mut Node, tx: &Transaction) {
473                 confirm_transaction_depth(node, tx, ANTI_REORG_DELAY);
474         }
475
476         #[test]
477         fn test_background_processor() {
478                 // Test that when a new channel is created, the ChannelManager needs to be re-persisted with
479                 // updates. Also test that when new updates are available, the manager signals that it needs
480                 // re-persistence and is successfully re-persisted.
481                 let nodes = create_nodes(2, "test_background_processor".to_string());
482
483                 // Go through the channel creation process so that each node has something to persist. Since
484                 // open_channel consumes events, it must complete before starting BackgroundProcessor to
485                 // avoid a race with processing events.
486                 let tx = open_channel!(nodes[0], nodes[1], 100000);
487
488                 // Initiate the background processors to watch each node.
489                 let data_dir = nodes[0].persister.get_data_dir();
490                 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);
491                 let event_handler = |_: &_| {};
492                 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());
493
494                 macro_rules! check_persisted_data {
495                         ($node: expr, $filepath: expr, $expected_bytes: expr) => {
496                                 loop {
497                                         $expected_bytes.clear();
498                                         match $node.write(&mut $expected_bytes) {
499                                                 Ok(()) => {
500                                                         match std::fs::read($filepath) {
501                                                                 Ok(bytes) => {
502                                                                         if bytes == $expected_bytes {
503                                                                                 break
504                                                                         } else {
505                                                                                 continue
506                                                                         }
507                                                                 },
508                                                                 Err(_) => continue
509                                                         }
510                                                 },
511                                                 Err(e) => panic!("Unexpected error: {}", e)
512                                         }
513                                 }
514                         }
515                 }
516
517                 // Check that the initial channel manager data is persisted as expected.
518                 let filepath = get_full_filepath("test_background_processor_persister_0".to_string(), "manager".to_string());
519                 let mut expected_bytes = Vec::new();
520                 check_persisted_data!(nodes[0].node, filepath.clone(), expected_bytes);
521                 loop {
522                         if !nodes[0].node.get_persistence_condvar_value() { break }
523                 }
524
525                 // Force-close the channel.
526                 nodes[0].node.force_close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
527
528                 // Check that the force-close updates are persisted.
529                 let mut expected_bytes = Vec::new();
530                 check_persisted_data!(nodes[0].node, filepath.clone(), expected_bytes);
531                 loop {
532                         if !nodes[0].node.get_persistence_condvar_value() { break }
533                 }
534
535                 assert!(bg_processor.stop().is_ok());
536         }
537
538         #[test]
539         fn test_timer_tick_called() {
540                 // Test that ChannelManager's and PeerManager's `timer_tick_occurred` is called every
541                 // `FRESHNESS_TIMER`.
542                 let nodes = create_nodes(1, "test_timer_tick_called".to_string());
543                 let data_dir = nodes[0].persister.get_data_dir();
544                 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);
545                 let event_handler = |_: &_| {};
546                 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());
547                 loop {
548                         let log_entries = nodes[0].logger.lines.lock().unwrap();
549                         let desired_log = "Calling ChannelManager's timer_tick_occurred".to_string();
550                         let second_desired_log = "Calling PeerManager's timer_tick_occurred".to_string();
551                         if log_entries.get(&("lightning_background_processor".to_string(), desired_log)).is_some() &&
552                                         log_entries.get(&("lightning_background_processor".to_string(), second_desired_log)).is_some() {
553                                 break
554                         }
555                 }
556
557                 assert!(bg_processor.stop().is_ok());
558         }
559
560         #[test]
561         fn test_persist_error() {
562                 // Test that if we encounter an error during manager persistence, the thread panics.
563                 let nodes = create_nodes(2, "test_persist_error".to_string());
564                 open_channel!(nodes[0], nodes[1], 100000);
565
566                 let persister = |_: &_| Err(std::io::Error::new(std::io::ErrorKind::Other, "test"));
567                 let event_handler = |_: &_| {};
568                 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());
569                 match bg_processor.join() {
570                         Ok(_) => panic!("Expected error persisting manager"),
571                         Err(e) => {
572                                 assert_eq!(e.kind(), std::io::ErrorKind::Other);
573                                 assert_eq!(e.get_ref().unwrap().to_string(), "test");
574                         },
575                 }
576         }
577
578         #[test]
579         fn test_background_event_handling() {
580                 let mut nodes = create_nodes(2, "test_background_event_handling".to_string());
581                 let channel_value = 100000;
582                 let data_dir = nodes[0].persister.get_data_dir();
583                 let persister = move |node: &_| FilesystemPersister::persist_manager(data_dir.clone(), node);
584
585                 // Set up a background event handler for FundingGenerationReady events.
586                 let (sender, receiver) = std::sync::mpsc::sync_channel(1);
587                 let event_handler = move |event: &Event| {
588                         sender.send(handle_funding_generation_ready!(event, channel_value)).unwrap();
589                 };
590                 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());
591
592                 // Open a channel and check that the FundingGenerationReady event was handled.
593                 begin_open_channel!(nodes[0], nodes[1], channel_value);
594                 let (temporary_channel_id, funding_tx) = receiver
595                         .recv_timeout(Duration::from_secs(EVENT_DEADLINE))
596                         .expect("FundingGenerationReady not handled within deadline");
597                 end_open_channel!(nodes[0], nodes[1], temporary_channel_id, funding_tx);
598
599                 // Confirm the funding transaction.
600                 confirm_transaction(&mut nodes[0], &funding_tx);
601                 let as_funding = get_event_msg!(nodes[0], MessageSendEvent::SendFundingLocked, nodes[1].node.get_our_node_id());
602                 confirm_transaction(&mut nodes[1], &funding_tx);
603                 let bs_funding = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id());
604                 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &bs_funding);
605                 let _as_channel_update = get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
606                 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding);
607                 let _bs_channel_update = get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
608
609                 assert!(bg_processor.stop().is_ok());
610
611                 // Set up a background event handler for SpendableOutputs events.
612                 let (sender, receiver) = std::sync::mpsc::sync_channel(1);
613                 let event_handler = move |event: &Event| sender.send(event.clone()).unwrap();
614                 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());
615
616                 // Force close the channel and check that the SpendableOutputs event was handled.
617                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
618                 let commitment_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().pop().unwrap();
619                 confirm_transaction_depth(&mut nodes[0], &commitment_tx, BREAKDOWN_TIMEOUT as u32);
620                 let event = receiver
621                         .recv_timeout(Duration::from_secs(EVENT_DEADLINE))
622                         .expect("SpendableOutputs not handled within deadline");
623                 match event {
624                         Event::SpendableOutputs { .. } => {},
625                         Event::ChannelClosed { .. } => {},
626                         _ => panic!("Unexpected event: {:?}", event),
627                 }
628
629                 assert!(bg_processor.stop().is_ok());
630         }
631
632         #[test]
633         fn test_invoice_payer() {
634                 let nodes = create_nodes(2, "test_invoice_payer".to_string());
635
636                 // Initiate the background processors to watch each node.
637                 let data_dir = nodes[0].persister.get_data_dir();
638                 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);
639                 let router = DefaultRouter::new(Arc::clone(&nodes[0].network_graph), Arc::clone(&nodes[0].logger));
640                 let scorer = Arc::new(Mutex::new(test_utils::TestScorer::default()));
641                 let invoice_payer = Arc::new(InvoicePayer::new(Arc::clone(&nodes[0].node), router, scorer, Arc::clone(&nodes[0].logger), |_: &_| {}, RetryAttempts(2)));
642                 let event_handler = Arc::clone(&invoice_payer);
643                 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());
644                 assert!(bg_processor.stop().is_ok());
645         }
646 }