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