Add `counterparty_node_id` to `FundingGenerationReady`
[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::routing::scoring::WriteableScore;
22 use lightning::util::events::{Event, EventHandler, EventsProvider};
23 use lightning::util::logger::Logger;
24 use lightning::util::persist::Persister;
25 use std::sync::Arc;
26 use std::sync::atomic::{AtomicBool, Ordering};
27 use std::thread;
28 use std::thread::JoinHandle;
29 use std::time::{Duration, Instant};
30 use std::ops::Deref;
31
32 /// `BackgroundProcessor` takes care of tasks that (1) need to happen periodically to keep
33 /// Rust-Lightning running properly, and (2) either can or should be run in the background. Its
34 /// responsibilities are:
35 /// * Processing [`Event`]s with a user-provided [`EventHandler`].
36 /// * Monitoring whether the [`ChannelManager`] needs to be re-persisted to disk, and if so,
37 ///   writing it to disk/backups by invoking the callback given to it at startup.
38 ///   [`ChannelManager`] persistence should be done in the background.
39 /// * Calling [`ChannelManager::timer_tick_occurred`] and [`PeerManager::timer_tick_occurred`]
40 ///   at the appropriate intervals.
41 /// * Calling [`NetworkGraph::remove_stale_channels`] (if a [`NetGraphMsgHandler`] is provided to
42 ///   [`BackgroundProcessor::start`]).
43 ///
44 /// It will also call [`PeerManager::process_events`] periodically though this shouldn't be relied
45 /// upon as doing so may result in high latency.
46 ///
47 /// # Note
48 ///
49 /// If [`ChannelManager`] persistence fails and the persisted manager becomes out-of-date, then
50 /// there is a risk of channels force-closing on startup when the manager realizes it's outdated.
51 /// However, as long as [`ChannelMonitor`] backups are sound, no funds besides those used for
52 /// unilateral chain closure fees are at risk.
53 ///
54 /// [`ChannelMonitor`]: lightning::chain::channelmonitor::ChannelMonitor
55 /// [`Event`]: lightning::util::events::Event
56 #[must_use = "BackgroundProcessor will immediately stop on drop. It should be stored until shutdown."]
57 pub struct BackgroundProcessor {
58         stop_thread: Arc<AtomicBool>,
59         thread_handle: Option<JoinHandle<Result<(), std::io::Error>>>,
60 }
61
62 #[cfg(not(test))]
63 const FRESHNESS_TIMER: u64 = 60;
64 #[cfg(test)]
65 const FRESHNESS_TIMER: u64 = 1;
66
67 #[cfg(all(not(test), not(debug_assertions)))]
68 const PING_TIMER: u64 = 10;
69 /// Signature operations take a lot longer without compiler optimisations.
70 /// Increasing the ping timer allows for this but slower devices will be disconnected if the
71 /// timeout is reached.
72 #[cfg(all(not(test), debug_assertions))]
73 const PING_TIMER: u64 = 30;
74 #[cfg(test)]
75 const PING_TIMER: u64 = 1;
76
77 /// Prune the network graph of stale entries hourly.
78 const NETWORK_PRUNE_TIMER: u64 = 60 * 60;
79
80 #[cfg(not(test))]
81 const FIRST_NETWORK_PRUNE_TIMER: u64 = 60;
82 #[cfg(test)]
83 const FIRST_NETWORK_PRUNE_TIMER: u64 = 1;
84
85
86 /// Decorates an [`EventHandler`] with common functionality provided by standard [`EventHandler`]s.
87 struct DecoratingEventHandler<
88         E: EventHandler,
89         N: Deref<Target = NetGraphMsgHandler<G, A, L>>,
90         G: Deref<Target = NetworkGraph>,
91         A: Deref,
92         L: Deref,
93 >
94 where A::Target: chain::Access, L::Target: Logger {
95         event_handler: E,
96         net_graph_msg_handler: Option<N>,
97 }
98
99 impl<
100         E: EventHandler,
101         N: Deref<Target = NetGraphMsgHandler<G, A, L>>,
102         G: Deref<Target = NetworkGraph>,
103         A: Deref,
104         L: Deref,
105 > EventHandler for DecoratingEventHandler<E, N, G, A, L>
106 where A::Target: chain::Access, L::Target: Logger {
107         fn handle_event(&self, event: &Event) {
108                 if let Some(event_handler) = &self.net_graph_msg_handler {
109                         event_handler.handle_event(event);
110                 }
111                 self.event_handler.handle_event(event);
112         }
113 }
114
115 impl BackgroundProcessor {
116         /// Start a background thread that takes care of responsibilities enumerated in the [top-level
117         /// documentation].
118         ///
119         /// The thread runs indefinitely unless the object is dropped, [`stop`] is called, or
120         /// [`Persister::persist_manager`] returns an error. In case of an error, the error is retrieved by calling
121         /// either [`join`] or [`stop`].
122         ///
123         /// # Data Persistence
124         ///
125         /// [`Persister::persist_manager`] is responsible for writing out the [`ChannelManager`] to disk, and/or
126         /// uploading to one or more backup services. See [`ChannelManager::write`] for writing out a
127         /// [`ChannelManager`]. See the `lightning-persister` crate for LDK's
128         /// provided implementation.
129         ///
130         /// [`Persister::persist_graph`] is responsible for writing out the [`NetworkGraph`] to disk. See
131         /// [`NetworkGraph::write`] for writing out a [`NetworkGraph`]. See the `lightning-persister` crate
132         /// for LDK's provided implementation.
133         ///
134         /// Typically, users should either implement [`Persister::persist_manager`] to never return an
135         /// error or call [`join`] and handle any error that may arise. For the latter case,
136         /// `BackgroundProcessor` must be restarted by calling `start` again after handling the error.
137         ///
138         /// # Event Handling
139         ///
140         /// `event_handler` is responsible for handling events that users should be notified of (e.g.,
141         /// payment failed). [`BackgroundProcessor`] may decorate the given [`EventHandler`] with common
142         /// functionality implemented by other handlers.
143         /// * [`NetGraphMsgHandler`] if given will update the [`NetworkGraph`] based on payment failures.
144         ///
145         /// [top-level documentation]: BackgroundProcessor
146         /// [`join`]: Self::join
147         /// [`stop`]: Self::stop
148         /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
149         /// [`ChannelManager::write`]: lightning::ln::channelmanager::ChannelManager#impl-Writeable
150         /// [`Persister::persist_manager`]: lightning::util::persist::Persister::persist_manager
151         /// [`Persister::persist_graph`]: lightning::util::persist::Persister::persist_graph
152         /// [`NetworkGraph`]: lightning::routing::network_graph::NetworkGraph
153         /// [`NetworkGraph::write`]: lightning::routing::network_graph::NetworkGraph#impl-Writeable
154         pub fn start<
155                 'a,
156                 Signer: 'static + Sign,
157                 CA: 'static + Deref + Send + Sync,
158                 CF: 'static + Deref + Send + Sync,
159                 CW: 'static + Deref + Send + Sync,
160                 T: 'static + Deref + Send + Sync,
161                 K: 'static + Deref + Send + Sync,
162                 F: 'static + Deref + Send + Sync,
163                 G: 'static + Deref<Target = NetworkGraph> + Send + Sync,
164                 L: 'static + Deref + Send + Sync,
165                 P: 'static + Deref + Send + Sync,
166                 Descriptor: 'static + SocketDescriptor + Send + Sync,
167                 CMH: 'static + Deref + Send + Sync,
168                 RMH: 'static + Deref + Send + Sync,
169                 EH: 'static + EventHandler + Send,
170                 PS: 'static + Deref + Send,
171                 M: 'static + Deref<Target = ChainMonitor<Signer, CF, T, F, L, P>> + Send + Sync,
172                 CM: 'static + Deref<Target = ChannelManager<Signer, CW, T, K, F, L>> + Send + Sync,
173                 NG: 'static + Deref<Target = NetGraphMsgHandler<G, CA, L>> + Send + Sync,
174                 UMH: 'static + Deref + Send + Sync,
175                 PM: 'static + Deref<Target = PeerManager<Descriptor, CMH, RMH, L, UMH>> + Send + Sync,
176                 S: 'static + Deref<Target = SC> + Send + Sync,
177                 SC: WriteableScore<'a>,
178         >(
179                 persister: PS, event_handler: EH, chain_monitor: M, channel_manager: CM,
180                 net_graph_msg_handler: Option<NG>, peer_manager: PM, logger: L, scorer: Option<S>
181         ) -> Self
182         where
183                 CA::Target: 'static + chain::Access,
184                 CF::Target: 'static + chain::Filter,
185                 CW::Target: 'static + chain::Watch<Signer>,
186                 T::Target: 'static + BroadcasterInterface,
187                 K::Target: 'static + KeysInterface<Signer = Signer>,
188                 F::Target: 'static + FeeEstimator,
189                 L::Target: 'static + Logger,
190                 P::Target: 'static + Persist<Signer>,
191                 CMH::Target: 'static + ChannelMessageHandler,
192                 RMH::Target: 'static + RoutingMessageHandler,
193                 UMH::Target: 'static + CustomMessageHandler,
194                 PS::Target: 'static + Persister<'a, Signer, CW, T, K, F, L, SC>,
195         {
196                 let stop_thread = Arc::new(AtomicBool::new(false));
197                 let stop_thread_clone = stop_thread.clone();
198                 let handle = thread::spawn(move || -> Result<(), std::io::Error> {
199                         let event_handler = DecoratingEventHandler { event_handler, net_graph_msg_handler: net_graph_msg_handler.as_ref().map(|t| t.deref()) };
200
201                         log_trace!(logger, "Calling ChannelManager's timer_tick_occurred on startup");
202                         channel_manager.timer_tick_occurred();
203
204                         let mut last_freshness_call = Instant::now();
205                         let mut last_ping_call = Instant::now();
206                         let mut last_prune_call = Instant::now();
207                         let mut have_pruned = false;
208
209                         loop {
210                                 channel_manager.process_pending_events(&event_handler);
211                                 chain_monitor.process_pending_events(&event_handler);
212
213                                 // Note that the PeerManager::process_events may block on ChannelManager's locks,
214                                 // hence it comes last here. When the ChannelManager finishes whatever it's doing,
215                                 // we want to ensure we get into `persist_manager` as quickly as we can, especially
216                                 // without running the normal event processing above and handing events to users.
217                                 //
218                                 // Specifically, on an *extremely* slow machine, we may see ChannelManager start
219                                 // processing a message effectively at any point during this loop. In order to
220                                 // minimize the time between such processing completing and persisting the updated
221                                 // ChannelManager, we want to minimize methods blocking on a ChannelManager
222                                 // generally, and as a fallback place such blocking only immediately before
223                                 // persistence.
224                                 peer_manager.process_events();
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                                         break;
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 { FIRST_NETWORK_PRUNE_TIMER } {
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                                                 if let Err(e) = persister.persist_graph(handler.network_graph()) {
279                                                         log_error!(logger, "Error: Failed to persist network graph, check your disk and permissions {}", e)
280                                                 }
281                                         }
282                                         if let Some(ref scorer) = scorer {
283                                                 log_trace!(logger, "Persisting scorer");
284                                                 if let Err(e) = persister.persist_scorer(&scorer) {
285                                                         log_error!(logger, "Error: Failed to persist scorer, check your disk and permissions {}", e)
286                                                 }
287                                         }
288
289                                         last_prune_call = Instant::now();
290                                         have_pruned = true;
291                                 }
292                         }
293
294                         // After we exit, ensure we persist the ChannelManager one final time - this avoids
295                         // some races where users quit while channel updates were in-flight, with
296                         // ChannelMonitor update(s) persisted without a corresponding ChannelManager update.
297                         persister.persist_manager(&*channel_manager)?;
298
299                         // Persist Scorer on exit
300                         if let Some(ref scorer) = scorer {
301                                 persister.persist_scorer(&scorer)?;
302                         }
303
304                         // Persist NetworkGraph on exit
305                         if let Some(ref handler) = net_graph_msg_handler {
306                                 persister.persist_graph(handler.network_graph())?;
307                         }
308
309                         Ok(())
310                 });
311                 Self { stop_thread: stop_thread_clone, thread_handle: Some(handle) }
312         }
313
314         /// Join `BackgroundProcessor`'s thread, returning any error that occurred while persisting
315         /// [`ChannelManager`].
316         ///
317         /// # Panics
318         ///
319         /// This function panics if the background thread has panicked such as while persisting or
320         /// handling events.
321         ///
322         /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
323         pub fn join(mut self) -> Result<(), std::io::Error> {
324                 assert!(self.thread_handle.is_some());
325                 self.join_thread()
326         }
327
328         /// Stop `BackgroundProcessor`'s thread, returning any error that occurred while persisting
329         /// [`ChannelManager`].
330         ///
331         /// # Panics
332         ///
333         /// This function panics if the background thread has panicked such as while persisting or
334         /// handling events.
335         ///
336         /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
337         pub fn stop(mut self) -> Result<(), std::io::Error> {
338                 assert!(self.thread_handle.is_some());
339                 self.stop_and_join_thread()
340         }
341
342         fn stop_and_join_thread(&mut self) -> Result<(), std::io::Error> {
343                 self.stop_thread.store(true, Ordering::Release);
344                 self.join_thread()
345         }
346
347         fn join_thread(&mut self) -> Result<(), std::io::Error> {
348                 match self.thread_handle.take() {
349                         Some(handle) => handle.join().unwrap(),
350                         None => Ok(()),
351                 }
352         }
353 }
354
355 impl Drop for BackgroundProcessor {
356         fn drop(&mut self) {
357                 self.stop_and_join_thread().unwrap();
358         }
359 }
360
361 #[cfg(test)]
362 mod tests {
363         use bitcoin::blockdata::block::BlockHeader;
364         use bitcoin::blockdata::constants::genesis_block;
365         use bitcoin::blockdata::transaction::{Transaction, TxOut};
366         use bitcoin::network::constants::Network;
367         use lightning::chain::{BestBlock, Confirm, chainmonitor};
368         use lightning::chain::channelmonitor::ANTI_REORG_DELAY;
369         use lightning::chain::keysinterface::{InMemorySigner, Recipient, KeysInterface, KeysManager};
370         use lightning::chain::transaction::OutPoint;
371         use lightning::get_event_msg;
372         use lightning::ln::channelmanager::{BREAKDOWN_TIMEOUT, ChainParameters, ChannelManager, SimpleArcChannelManager};
373         use lightning::ln::features::InitFeatures;
374         use lightning::ln::msgs::{ChannelMessageHandler, Init};
375         use lightning::ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler};
376         use lightning::routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
377         use lightning::util::config::UserConfig;
378         use lightning::util::events::{Event, MessageSendEventsProvider, MessageSendEvent};
379         use lightning::util::ser::Writeable;
380         use lightning::util::test_utils;
381         use lightning::util::persist::KVStorePersister;
382         use lightning_invoice::payment::{InvoicePayer, RetryAttempts};
383         use lightning_invoice::utils::DefaultRouter;
384         use lightning_persister::FilesystemPersister;
385         use std::fs;
386         use std::path::PathBuf;
387         use std::sync::{Arc, Mutex};
388         use std::time::Duration;
389         use lightning::routing::scoring::{FixedPenaltyScorer};
390         use super::{BackgroundProcessor, FRESHNESS_TIMER};
391
392         const EVENT_DEADLINE: u64 = 5 * FRESHNESS_TIMER;
393
394         #[derive(Clone, Eq, Hash, PartialEq)]
395         struct TestDescriptor{}
396         impl SocketDescriptor for TestDescriptor {
397                 fn send_data(&mut self, _data: &[u8], _resume_read: bool) -> usize {
398                         0
399                 }
400
401                 fn disconnect_socket(&mut self) {}
402         }
403
404         type ChainMonitor = chainmonitor::ChainMonitor<InMemorySigner, Arc<test_utils::TestChainSource>, Arc<test_utils::TestBroadcaster>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>, Arc<FilesystemPersister>>;
405
406         struct Node {
407                 node: Arc<SimpleArcChannelManager<ChainMonitor, test_utils::TestBroadcaster, test_utils::TestFeeEstimator, test_utils::TestLogger>>,
408                 net_graph_msg_handler: Option<Arc<NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>>>,
409                 peer_manager: Arc<PeerManager<TestDescriptor, Arc<test_utils::TestChannelMessageHandler>, Arc<test_utils::TestRoutingMessageHandler>, Arc<test_utils::TestLogger>, IgnoringMessageHandler>>,
410                 chain_monitor: Arc<ChainMonitor>,
411                 persister: Arc<FilesystemPersister>,
412                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
413                 network_graph: Arc<NetworkGraph>,
414                 logger: Arc<test_utils::TestLogger>,
415                 best_block: BestBlock,
416                 scorer: Arc<Mutex<FixedPenaltyScorer>>,
417         }
418
419         impl Drop for Node {
420                 fn drop(&mut self) {
421                         let data_dir = self.persister.get_data_dir();
422                         match fs::remove_dir_all(data_dir.clone()) {
423                                 Err(e) => println!("Failed to remove test persister directory {}: {}", data_dir, e),
424                                 _ => {}
425                         }
426                 }
427         }
428
429         struct Persister {
430                 graph_error: Option<(std::io::ErrorKind, &'static str)>,
431                 manager_error: Option<(std::io::ErrorKind, &'static str)>,
432                 scorer_error: Option<(std::io::ErrorKind, &'static str)>,
433                 filesystem_persister: FilesystemPersister,
434         }
435
436         impl Persister {
437                 fn new(data_dir: String) -> Self {
438                         let filesystem_persister = FilesystemPersister::new(data_dir.clone());
439                         Self { graph_error: None, manager_error: None, scorer_error: None, filesystem_persister }
440                 }
441
442                 fn with_graph_error(self, error: std::io::ErrorKind, message: &'static str) -> Self {
443                         Self { graph_error: Some((error, message)), ..self }
444                 }
445
446                 fn with_manager_error(self, error: std::io::ErrorKind, message: &'static str) -> Self {
447                         Self { manager_error: Some((error, message)), ..self }
448                 }
449
450                 fn with_scorer_error(self, error: std::io::ErrorKind, message: &'static str) -> Self {
451                         Self { scorer_error: Some((error, message)), ..self }
452                 }
453         }
454
455         impl KVStorePersister for Persister {
456                 fn persist<W: Writeable>(&self, key: &str, object: &W) -> std::io::Result<()> {
457                         if key == "manager" {
458                                 if let Some((error, message)) = self.manager_error {
459                                         return Err(std::io::Error::new(error, message))
460                                 }
461                         }
462
463                         if key == "network_graph" {
464                                 if let Some((error, message)) = self.graph_error {
465                                         return Err(std::io::Error::new(error, message))
466                                 }
467                         }
468
469                         if key == "scorer" {
470                                 if let Some((error, message)) = self.scorer_error {
471                                         return Err(std::io::Error::new(error, message))
472                                 }
473                         }
474
475                         self.filesystem_persister.persist(key, object)
476                 }
477         }
478
479         fn get_full_filepath(filepath: String, filename: String) -> String {
480                 let mut path = PathBuf::from(filepath);
481                 path.push(filename);
482                 path.to_str().unwrap().to_string()
483         }
484
485         fn create_nodes(num_nodes: usize, persist_dir: String) -> Vec<Node> {
486                 let mut nodes = Vec::new();
487                 for i in 0..num_nodes {
488                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))});
489                         let fee_estimator = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) });
490                         let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
491                         let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
492                         let persister = Arc::new(FilesystemPersister::new(format!("{}_persister_{}", persist_dir, i)));
493                         let seed = [i as u8; 32];
494                         let network = Network::Testnet;
495                         let genesis_block = genesis_block(network);
496                         let now = Duration::from_secs(genesis_block.header.time as u64);
497                         let keys_manager = Arc::new(KeysManager::new(&seed, now.as_secs(), now.subsec_nanos()));
498                         let chain_monitor = Arc::new(chainmonitor::ChainMonitor::new(Some(chain_source.clone()), tx_broadcaster.clone(), logger.clone(), fee_estimator.clone(), persister.clone()));
499                         let best_block = BestBlock::from_genesis(network);
500                         let params = ChainParameters { network, best_block };
501                         let manager = Arc::new(ChannelManager::new(fee_estimator.clone(), chain_monitor.clone(), tx_broadcaster.clone(), logger.clone(), keys_manager.clone(), UserConfig::default(), params));
502                         let network_graph = Arc::new(NetworkGraph::new(genesis_block.header.block_hash()));
503                         let net_graph_msg_handler = Some(Arc::new(NetGraphMsgHandler::new(network_graph.clone(), Some(chain_source.clone()), logger.clone())));
504                         let msg_handler = MessageHandler { chan_handler: Arc::new(test_utils::TestChannelMessageHandler::new()), route_handler: Arc::new(test_utils::TestRoutingMessageHandler::new() )};
505                         let peer_manager = Arc::new(PeerManager::new(msg_handler, keys_manager.get_node_secret(Recipient::Node).unwrap(), &seed, logger.clone(), IgnoringMessageHandler{}));
506                         let scorer = Arc::new(Mutex::new(test_utils::TestScorer::with_penalty(0)));
507                         let node = Node { node: manager, net_graph_msg_handler, peer_manager, chain_monitor, persister, tx_broadcaster, network_graph, logger, best_block, scorer };
508                         nodes.push(node);
509                 }
510
511                 for i in 0..num_nodes {
512                         for j in (i+1)..num_nodes {
513                                 nodes[i].node.peer_connected(&nodes[j].node.get_our_node_id(), &Init { features: InitFeatures::known(), remote_network_address: None });
514                                 nodes[j].node.peer_connected(&nodes[i].node.get_our_node_id(), &Init { features: InitFeatures::known(), remote_network_address: None });
515                         }
516                 }
517
518                 nodes
519         }
520
521         macro_rules! open_channel {
522                 ($node_a: expr, $node_b: expr, $channel_value: expr) => {{
523                         begin_open_channel!($node_a, $node_b, $channel_value);
524                         let events = $node_a.node.get_and_clear_pending_events();
525                         assert_eq!(events.len(), 1);
526                         let (temporary_channel_id, tx) = handle_funding_generation_ready!(&events[0], $channel_value);
527                         end_open_channel!($node_a, $node_b, temporary_channel_id, tx);
528                         tx
529                 }}
530         }
531
532         macro_rules! begin_open_channel {
533                 ($node_a: expr, $node_b: expr, $channel_value: expr) => {{
534                         $node_a.node.create_channel($node_b.node.get_our_node_id(), $channel_value, 100, 42, None).unwrap();
535                         $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()));
536                         $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()));
537                 }}
538         }
539
540         macro_rules! handle_funding_generation_ready {
541                 ($event: expr, $channel_value: expr) => {{
542                         match $event {
543                                 &Event::FundingGenerationReady { temporary_channel_id, channel_value_satoshis, ref output_script, user_channel_id, .. } => {
544                                         assert_eq!(channel_value_satoshis, $channel_value);
545                                         assert_eq!(user_channel_id, 42);
546
547                                         let tx = Transaction { version: 1 as i32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
548                                                 value: channel_value_satoshis, script_pubkey: output_script.clone(),
549                                         }]};
550                                         (temporary_channel_id, tx)
551                                 },
552                                 _ => panic!("Unexpected event"),
553                         }
554                 }}
555         }
556
557         macro_rules! end_open_channel {
558                 ($node_a: expr, $node_b: expr, $temporary_channel_id: expr, $tx: expr) => {{
559                         $node_a.node.funding_transaction_generated(&$temporary_channel_id, $tx.clone()).unwrap();
560                         $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()));
561                         $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()));
562                 }}
563         }
564
565         fn confirm_transaction_depth(node: &mut Node, tx: &Transaction, depth: u32) {
566                 for i in 1..=depth {
567                         let prev_blockhash = node.best_block.block_hash();
568                         let height = node.best_block.height() + 1;
569                         let header = BlockHeader { version: 0x20000000, prev_blockhash, merkle_root: Default::default(), time: height, bits: 42, nonce: 42 };
570                         let txdata = vec![(0, tx)];
571                         node.best_block = BestBlock::new(header.block_hash(), height);
572                         match i {
573                                 1 => {
574                                         node.node.transactions_confirmed(&header, &txdata, height);
575                                         node.chain_monitor.transactions_confirmed(&header, &txdata, height);
576                                 },
577                                 x if x == depth => {
578                                         node.node.best_block_updated(&header, height);
579                                         node.chain_monitor.best_block_updated(&header, height);
580                                 },
581                                 _ => {},
582                         }
583                 }
584         }
585         fn confirm_transaction(node: &mut Node, tx: &Transaction) {
586                 confirm_transaction_depth(node, tx, ANTI_REORG_DELAY);
587         }
588
589         #[test]
590         fn test_background_processor() {
591                 // Test that when a new channel is created, the ChannelManager needs to be re-persisted with
592                 // updates. Also test that when new updates are available, the manager signals that it needs
593                 // re-persistence and is successfully re-persisted.
594                 let nodes = create_nodes(2, "test_background_processor".to_string());
595
596                 // Go through the channel creation process so that each node has something to persist. Since
597                 // open_channel consumes events, it must complete before starting BackgroundProcessor to
598                 // avoid a race with processing events.
599                 let tx = open_channel!(nodes[0], nodes[1], 100000);
600
601                 // Initiate the background processors to watch each node.
602                 let data_dir = nodes[0].persister.get_data_dir();
603                 let persister = Arc::new(Persister::new(data_dir));
604                 let event_handler = |_: &_| {};
605                 let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].net_graph_msg_handler.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone(), Some(nodes[0].scorer.clone()));
606
607                 macro_rules! check_persisted_data {
608                         ($node: expr, $filepath: expr) => {
609                                 let mut expected_bytes = Vec::new();
610                                 loop {
611                                         expected_bytes.clear();
612                                         match $node.write(&mut expected_bytes) {
613                                                 Ok(()) => {
614                                                         match std::fs::read($filepath) {
615                                                                 Ok(bytes) => {
616                                                                         if bytes == expected_bytes {
617                                                                                 break
618                                                                         } else {
619                                                                                 continue
620                                                                         }
621                                                                 },
622                                                                 Err(_) => continue
623                                                         }
624                                                 },
625                                                 Err(e) => panic!("Unexpected error: {}", e)
626                                         }
627                                 }
628                         }
629                 }
630
631                 // Check that the initial channel manager data is persisted as expected.
632                 let filepath = get_full_filepath("test_background_processor_persister_0".to_string(), "manager".to_string());
633                 check_persisted_data!(nodes[0].node, filepath.clone());
634
635                 loop {
636                         if !nodes[0].node.get_persistence_condvar_value() { break }
637                 }
638
639                 // Force-close the channel.
640                 nodes[0].node.force_close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
641
642                 // Check that the force-close updates are persisted.
643                 check_persisted_data!(nodes[0].node, filepath.clone());
644                 loop {
645                         if !nodes[0].node.get_persistence_condvar_value() { break }
646                 }
647
648                 // Check network graph is persisted
649                 let filepath = get_full_filepath("test_background_processor_persister_0".to_string(), "network_graph".to_string());
650                 if let Some(ref handler) = nodes[0].net_graph_msg_handler {
651                         let network_graph = handler.network_graph();
652                         check_persisted_data!(network_graph, filepath.clone());
653                 }
654
655                 // Check scorer is persisted
656                 let filepath = get_full_filepath("test_background_processor_persister_0".to_string(), "scorer".to_string());
657                 check_persisted_data!(nodes[0].scorer, filepath.clone());
658
659                 assert!(bg_processor.stop().is_ok());
660         }
661
662         #[test]
663         fn test_timer_tick_called() {
664                 // Test that ChannelManager's and PeerManager's `timer_tick_occurred` is called every
665                 // `FRESHNESS_TIMER`.
666                 let nodes = create_nodes(1, "test_timer_tick_called".to_string());
667                 let data_dir = nodes[0].persister.get_data_dir();
668                 let persister = Arc::new(Persister::new(data_dir));
669                 let event_handler = |_: &_| {};
670                 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(), Some(nodes[0].scorer.clone()));
671                 loop {
672                         let log_entries = nodes[0].logger.lines.lock().unwrap();
673                         let desired_log = "Calling ChannelManager's timer_tick_occurred".to_string();
674                         let second_desired_log = "Calling PeerManager's timer_tick_occurred".to_string();
675                         if log_entries.get(&("lightning_background_processor".to_string(), desired_log)).is_some() &&
676                                         log_entries.get(&("lightning_background_processor".to_string(), second_desired_log)).is_some() {
677                                 break
678                         }
679                 }
680
681                 assert!(bg_processor.stop().is_ok());
682         }
683
684         #[test]
685         fn test_channel_manager_persist_error() {
686                 // Test that if we encounter an error during manager persistence, the thread panics.
687                 let nodes = create_nodes(2, "test_persist_error".to_string());
688                 open_channel!(nodes[0], nodes[1], 100000);
689
690                 let data_dir = nodes[0].persister.get_data_dir();
691                 let persister = Arc::new(Persister::new(data_dir).with_manager_error(std::io::ErrorKind::Other, "test"));
692                 let event_handler = |_: &_| {};
693                 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(), Some(nodes[0].scorer.clone()));
694                 match bg_processor.join() {
695                         Ok(_) => panic!("Expected error persisting manager"),
696                         Err(e) => {
697                                 assert_eq!(e.kind(), std::io::ErrorKind::Other);
698                                 assert_eq!(e.get_ref().unwrap().to_string(), "test");
699                         },
700                 }
701         }
702
703         #[test]
704         fn test_network_graph_persist_error() {
705                 // Test that if we encounter an error during network graph persistence, an error gets returned.
706                 let nodes = create_nodes(2, "test_persist_network_graph_error".to_string());
707                 let data_dir = nodes[0].persister.get_data_dir();
708                 let persister = Arc::new(Persister::new(data_dir).with_graph_error(std::io::ErrorKind::Other, "test"));
709                 let event_handler = |_: &_| {};
710                 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(), Some(nodes[0].scorer.clone()));
711
712                 match bg_processor.stop() {
713                         Ok(_) => panic!("Expected error persisting network graph"),
714                         Err(e) => {
715                                 assert_eq!(e.kind(), std::io::ErrorKind::Other);
716                                 assert_eq!(e.get_ref().unwrap().to_string(), "test");
717                         },
718                 }
719         }
720
721         #[test]
722         fn test_scorer_persist_error() {
723                 // Test that if we encounter an error during scorer persistence, an error gets returned.
724                 let nodes = create_nodes(2, "test_persist_scorer_error".to_string());
725                 let data_dir = nodes[0].persister.get_data_dir();
726                 let persister = Arc::new(Persister::new(data_dir).with_scorer_error(std::io::ErrorKind::Other, "test"));
727                 let event_handler = |_: &_| {};
728                 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(), Some(nodes[0].scorer.clone()));
729
730                 match bg_processor.stop() {
731                         Ok(_) => panic!("Expected error persisting scorer"),
732                         Err(e) => {
733                                 assert_eq!(e.kind(), std::io::ErrorKind::Other);
734                                 assert_eq!(e.get_ref().unwrap().to_string(), "test");
735                         },
736                 }
737         }
738
739         #[test]
740         fn test_background_event_handling() {
741                 let mut nodes = create_nodes(2, "test_background_event_handling".to_string());
742                 let channel_value = 100000;
743                 let data_dir = nodes[0].persister.get_data_dir();
744                 let persister = Arc::new(Persister::new(data_dir.clone()));
745
746                 // Set up a background event handler for FundingGenerationReady events.
747                 let (sender, receiver) = std::sync::mpsc::sync_channel(1);
748                 let event_handler = move |event: &Event| {
749                         sender.send(handle_funding_generation_ready!(event, channel_value)).unwrap();
750                 };
751                 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(), Some(nodes[0].scorer.clone()));
752
753                 // Open a channel and check that the FundingGenerationReady event was handled.
754                 begin_open_channel!(nodes[0], nodes[1], channel_value);
755                 let (temporary_channel_id, funding_tx) = receiver
756                         .recv_timeout(Duration::from_secs(EVENT_DEADLINE))
757                         .expect("FundingGenerationReady not handled within deadline");
758                 end_open_channel!(nodes[0], nodes[1], temporary_channel_id, funding_tx);
759
760                 // Confirm the funding transaction.
761                 confirm_transaction(&mut nodes[0], &funding_tx);
762                 let as_funding = get_event_msg!(nodes[0], MessageSendEvent::SendFundingLocked, nodes[1].node.get_our_node_id());
763                 confirm_transaction(&mut nodes[1], &funding_tx);
764                 let bs_funding = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id());
765                 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &bs_funding);
766                 let _as_channel_update = get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
767                 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding);
768                 let _bs_channel_update = get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
769
770                 assert!(bg_processor.stop().is_ok());
771
772                 // Set up a background event handler for SpendableOutputs events.
773                 let (sender, receiver) = std::sync::mpsc::sync_channel(1);
774                 let event_handler = move |event: &Event| sender.send(event.clone()).unwrap();
775                 let persister = Arc::new(Persister::new(data_dir));
776                 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(), Some(nodes[0].scorer.clone()));
777
778                 // Force close the channel and check that the SpendableOutputs event was handled.
779                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
780                 let commitment_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().pop().unwrap();
781                 confirm_transaction_depth(&mut nodes[0], &commitment_tx, BREAKDOWN_TIMEOUT as u32);
782                 let event = receiver
783                         .recv_timeout(Duration::from_secs(EVENT_DEADLINE))
784                         .expect("SpendableOutputs not handled within deadline");
785                 match event {
786                         Event::SpendableOutputs { .. } => {},
787                         Event::ChannelClosed { .. } => {},
788                         _ => panic!("Unexpected event: {:?}", event),
789                 }
790
791                 assert!(bg_processor.stop().is_ok());
792         }
793
794         #[test]
795         fn test_invoice_payer() {
796                 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
797                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
798                 let nodes = create_nodes(2, "test_invoice_payer".to_string());
799
800                 // Initiate the background processors to watch each node.
801                 let data_dir = nodes[0].persister.get_data_dir();
802                 let persister = Arc::new(Persister::new(data_dir));
803                 let router = DefaultRouter::new(Arc::clone(&nodes[0].network_graph), Arc::clone(&nodes[0].logger), random_seed_bytes);
804                 let invoice_payer = Arc::new(InvoicePayer::new(Arc::clone(&nodes[0].node), router, Arc::clone(&nodes[0].scorer), Arc::clone(&nodes[0].logger), |_: &_| {}, RetryAttempts(2)));
805                 let event_handler = Arc::clone(&invoice_payer);
806                 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(), Some(nodes[0].scorer.clone()));
807                 assert!(bg_processor.stop().is_ok());
808         }
809 }