Enforce no missing docs in all crates (+ add docs that were missing)
[rust-lightning] / background-processor / src / lib.rs
1 //! Utilities that take care of tasks that (1) need to happen periodically to keep Rust-Lightning
2 //! running properly, and (2) either can or should be run in the background. See docs for
3 //! [`BackgroundProcessor`] for more details on the nitty-gritty.
4
5 #![deny(broken_intra_doc_links)]
6 #![deny(missing_docs)]
7 #![deny(unsafe_code)]
8
9 #[macro_use] extern crate lightning;
10
11 use lightning::chain;
12 use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
13 use lightning::chain::keysinterface::{Sign, KeysInterface};
14 use lightning::ln::channelmanager::ChannelManager;
15 use lightning::util::logger::Logger;
16 use std::sync::Arc;
17 use std::sync::atomic::{AtomicBool, Ordering};
18 use std::thread;
19 use std::thread::JoinHandle;
20 use std::time::{Duration, Instant};
21
22 /// BackgroundProcessor takes care of tasks that (1) need to happen periodically to keep
23 /// Rust-Lightning running properly, and (2) either can or should be run in the background. Its
24 /// responsibilities are:
25 /// * Monitoring whether the ChannelManager needs to be re-persisted to disk, and if so,
26 ///   writing it to disk/backups by invoking the callback given to it at startup.
27 ///   ChannelManager persistence should be done in the background.
28 /// * Calling `ChannelManager::timer_chan_freshness_every_min()` every minute (can be done in the
29 ///   background).
30 ///
31 /// Note that if ChannelManager persistence fails and the persisted manager becomes out-of-date,
32 /// then there is a risk of channels force-closing on startup when the manager realizes it's
33 /// outdated. However, as long as `ChannelMonitor` backups are sound, no funds besides those used
34 /// for unilateral chain closure fees are at risk.
35 pub struct BackgroundProcessor {
36         stop_thread: Arc<AtomicBool>,
37         /// May be used to retrieve and handle the error if `BackgroundProcessor`'s thread
38         /// exits due to an error while persisting.
39         pub thread_handle: JoinHandle<Result<(), std::io::Error>>,
40 }
41
42 #[cfg(not(test))]
43 const CHAN_FRESHNESS_TIMER: u64 = 60;
44 #[cfg(test)]
45 const CHAN_FRESHNESS_TIMER: u64 = 1;
46
47 impl BackgroundProcessor {
48         /// Start a background thread that takes care of responsibilities enumerated in the top-level
49         /// documentation.
50         ///
51         /// If `persist_manager` returns an error, then this thread will return said error (and `start()`
52         /// will need to be called again to restart the `BackgroundProcessor`). Users should wait on
53         /// [`thread_handle`]'s `join()` method to be able to tell if and when an error is returned, or
54         /// implement `persist_manager` such that an error is never returned to the `BackgroundProcessor`
55         ///
56         /// `persist_manager` is responsible for writing out the `ChannelManager` to disk, and/or uploading
57         /// to one or more backup services. See [`ChannelManager::write`] for writing out a `ChannelManager`.
58         /// See [`FilesystemPersister::persist_manager`] for Rust-Lightning's provided implementation.
59         ///
60         /// [`thread_handle`]: struct.BackgroundProcessor.html#structfield.thread_handle
61         /// [`ChannelManager::write`]: ../lightning/ln/channelmanager/struct.ChannelManager.html#method.write
62         /// [`FilesystemPersister::persist_manager`]: ../lightning_persister/struct.FilesystemPersister.html#impl
63         pub fn start<PM, Signer, M, T, K, F, L>(persist_manager: PM, manager: Arc<ChannelManager<Signer, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>>, logger: Arc<L>) -> Self
64         where Signer: 'static + Sign,
65               M: 'static + chain::Watch<Signer>,
66               T: 'static + BroadcasterInterface,
67               K: 'static + KeysInterface<Signer=Signer>,
68               F: 'static + FeeEstimator,
69               L: 'static + Logger,
70               PM: 'static + Send + Fn(&ChannelManager<Signer, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>) -> Result<(), std::io::Error>,
71         {
72                 let stop_thread = Arc::new(AtomicBool::new(false));
73                 let stop_thread_clone = stop_thread.clone();
74                 let handle = thread::spawn(move || -> Result<(), std::io::Error> {
75                         let mut current_time = Instant::now();
76                         loop {
77                                 let updates_available = manager.await_persistable_update_timeout(Duration::from_millis(100));
78                                 if updates_available {
79                                         persist_manager(&*manager)?;
80                                 }
81                                 // Exit the loop if the background processor was requested to stop.
82                                 if stop_thread.load(Ordering::Acquire) == true {
83                                         log_trace!(logger, "Terminating background processor.");
84                                         return Ok(())
85                                 }
86                                 if current_time.elapsed().as_secs() > CHAN_FRESHNESS_TIMER {
87                                         log_trace!(logger, "Calling manager's timer_chan_freshness_every_min");
88                                         manager.timer_chan_freshness_every_min();
89                                         current_time = Instant::now();
90                                 }
91                         }
92                 });
93                 Self {
94                         stop_thread: stop_thread_clone,
95                         thread_handle: handle,
96                 }
97         }
98
99         /// Stop `BackgroundProcessor`'s thread.
100         pub fn stop(self) -> Result<(), std::io::Error> {
101                 self.stop_thread.store(true, Ordering::Release);
102                 self.thread_handle.join().unwrap()
103         }
104 }
105
106 #[cfg(test)]
107 mod tests {
108         use bitcoin::blockdata::constants::genesis_block;
109         use bitcoin::blockdata::transaction::{Transaction, TxOut};
110         use bitcoin::network::constants::Network;
111         use lightning::chain;
112         use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
113         use lightning::chain::chainmonitor;
114         use lightning::chain::keysinterface::{Sign, InMemorySigner, KeysInterface, KeysManager};
115         use lightning::chain::transaction::OutPoint;
116         use lightning::get_event_msg;
117         use lightning::ln::channelmanager::{ChainParameters, ChannelManager, SimpleArcChannelManager};
118         use lightning::ln::features::InitFeatures;
119         use lightning::ln::msgs::ChannelMessageHandler;
120         use lightning::util::config::UserConfig;
121         use lightning::util::events::{Event, EventsProvider, MessageSendEventsProvider, MessageSendEvent};
122         use lightning::util::logger::Logger;
123         use lightning::util::ser::Writeable;
124         use lightning::util::test_utils;
125         use lightning_persister::FilesystemPersister;
126         use std::fs;
127         use std::path::PathBuf;
128         use std::sync::{Arc, Mutex};
129         use std::time::Duration;
130         use super::BackgroundProcessor;
131
132         type ChainMonitor = chainmonitor::ChainMonitor<InMemorySigner, Arc<test_utils::TestChainSource>, Arc<test_utils::TestBroadcaster>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>, Arc<FilesystemPersister>>;
133
134         struct Node {
135                 node: Arc<SimpleArcChannelManager<ChainMonitor, test_utils::TestBroadcaster, test_utils::TestFeeEstimator, test_utils::TestLogger>>,
136                 persister: Arc<FilesystemPersister>,
137                 logger: Arc<test_utils::TestLogger>,
138         }
139
140         impl Drop for Node {
141                 fn drop(&mut self) {
142                         let data_dir = self.persister.get_data_dir();
143                         match fs::remove_dir_all(data_dir.clone()) {
144                                 Err(e) => println!("Failed to remove test persister directory {}: {}", data_dir, e),
145                                 _ => {}
146                         }
147                 }
148         }
149
150         fn get_full_filepath(filepath: String, filename: String) -> String {
151                 let mut path = PathBuf::from(filepath);
152                 path.push(filename);
153                 path.to_str().unwrap().to_string()
154         }
155
156         fn create_nodes(num_nodes: usize, persist_dir: String) -> Vec<Node> {
157                 let mut nodes = Vec::new();
158                 for i in 0..num_nodes {
159                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
160                         let fee_estimator = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
161                         let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
162                         let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
163                         let persister = Arc::new(FilesystemPersister::new(format!("{}_persister_{}", persist_dir, i)));
164                         let seed = [i as u8; 32];
165                         let network = Network::Testnet;
166                         let genesis_block = genesis_block(network);
167                         let now = Duration::from_secs(genesis_block.header.time as u64);
168                         let keys_manager = Arc::new(KeysManager::new(&seed, now.as_secs(), now.subsec_nanos()));
169                         let chain_monitor = Arc::new(chainmonitor::ChainMonitor::new(Some(chain_source.clone()), tx_broadcaster.clone(), logger.clone(), fee_estimator.clone(), persister.clone()));
170                         let params = ChainParameters {
171                                 network,
172                                 latest_hash: genesis_block.block_hash(),
173                                 latest_height: 0,
174                         };
175                         let manager = Arc::new(ChannelManager::new(fee_estimator.clone(), chain_monitor.clone(), tx_broadcaster, logger.clone(), keys_manager.clone(), UserConfig::default(), params));
176                         let node = Node { node: manager, persister, logger };
177                         nodes.push(node);
178                 }
179                 nodes
180         }
181
182         macro_rules! open_channel {
183                 ($node_a: expr, $node_b: expr, $channel_value: expr) => {{
184                         $node_a.node.create_channel($node_b.node.get_our_node_id(), $channel_value, 100, 42, None).unwrap();
185                         $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()));
186                         $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()));
187                         let events = $node_a.node.get_and_clear_pending_events();
188                         assert_eq!(events.len(), 1);
189                         let (temporary_channel_id, tx, funding_output) = match events[0] {
190                                 Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
191                                         assert_eq!(*channel_value_satoshis, $channel_value);
192                                         assert_eq!(user_channel_id, 42);
193
194                                         let tx = Transaction { version: 1 as i32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
195                                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
196                                         }]};
197                                         let funding_outpoint = OutPoint { txid: tx.txid(), index: 0 };
198                                         (*temporary_channel_id, tx, funding_outpoint)
199                                 },
200                                 _ => panic!("Unexpected event"),
201                         };
202
203                         $node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
204                         $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()));
205                         $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()));
206                         tx
207                 }}
208         }
209
210         #[test]
211         fn test_background_processor() {
212                 // Test that when a new channel is created, the ChannelManager needs to be re-persisted with
213                 // updates. Also test that when new updates are available, the manager signals that it needs
214                 // re-persistence and is successfully re-persisted.
215                 let nodes = create_nodes(2, "test_background_processor".to_string());
216
217                 // Initiate the background processors to watch each node.
218                 let data_dir = nodes[0].persister.get_data_dir();
219                 let callback = 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);
220                 let bg_processor = BackgroundProcessor::start(callback, nodes[0].node.clone(), nodes[0].logger.clone());
221
222                 // Go through the channel creation process until each node should have something persisted.
223                 let tx = open_channel!(nodes[0], nodes[1], 100000);
224
225                 macro_rules! check_persisted_data {
226                         ($node: expr, $filepath: expr, $expected_bytes: expr) => {
227                                 match $node.write(&mut $expected_bytes) {
228                                         Ok(()) => {
229                                                 loop {
230                                                         match std::fs::read($filepath) {
231                                                                 Ok(bytes) => {
232                                                                         if bytes == $expected_bytes {
233                                                                                 break
234                                                                         } else {
235                                                                                 continue
236                                                                         }
237                                                                 },
238                                                                 Err(_) => continue
239                                                         }
240                                                 }
241                                         },
242                                         Err(e) => panic!("Unexpected error: {}", e)
243                                 }
244                         }
245                 }
246
247                 // Check that the initial channel manager data is persisted as expected.
248                 let filepath = get_full_filepath("test_background_processor_persister_0".to_string(), "manager".to_string());
249                 let mut expected_bytes = Vec::new();
250                 check_persisted_data!(nodes[0].node, filepath.clone(), expected_bytes);
251                 loop {
252                         if !nodes[0].node.get_persistence_condvar_value() { break }
253                 }
254
255                 // Force-close the channel.
256                 nodes[0].node.force_close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
257
258                 // Check that the force-close updates are persisted.
259                 let mut expected_bytes = Vec::new();
260                 check_persisted_data!(nodes[0].node, filepath.clone(), expected_bytes);
261                 loop {
262                         if !nodes[0].node.get_persistence_condvar_value() { break }
263                 }
264
265                 assert!(bg_processor.stop().is_ok());
266         }
267
268         #[test]
269         fn test_chan_freshness_called() {
270                 // Test that ChannelManager's `timer_chan_freshness_every_min` is called every
271                 // `CHAN_FRESHNESS_TIMER`.
272                 let nodes = create_nodes(1, "test_chan_freshness_called".to_string());
273                 let data_dir = nodes[0].persister.get_data_dir();
274                 let callback = 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);
275                 let bg_processor = BackgroundProcessor::start(callback, nodes[0].node.clone(), nodes[0].logger.clone());
276                 loop {
277                         let log_entries = nodes[0].logger.lines.lock().unwrap();
278                         let desired_log = "Calling manager's timer_chan_freshness_every_min".to_string();
279                         if log_entries.get(&("lightning_background_processor".to_string(), desired_log)).is_some() {
280                                 break
281                         }
282                 }
283
284                 assert!(bg_processor.stop().is_ok());
285         }
286
287         #[test]
288         fn test_persist_error() {
289                 // Test that if we encounter an error during manager persistence, the thread panics.
290                 fn persist_manager<Signer, M, T, K, F, L>(_data: &ChannelManager<Signer, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>) -> Result<(), std::io::Error>
291                 where Signer: 'static + Sign,
292                       M: 'static + chain::Watch<Signer>,
293                       T: 'static + BroadcasterInterface,
294                       K: 'static + KeysInterface<Signer=Signer>,
295                       F: 'static + FeeEstimator,
296                       L: 'static + Logger,
297                 {
298                         Err(std::io::Error::new(std::io::ErrorKind::Other, "test"))
299                 }
300
301                 let nodes = create_nodes(2, "test_persist_error".to_string());
302                 let bg_processor = BackgroundProcessor::start(persist_manager, nodes[0].node.clone(), nodes[0].logger.clone());
303                 open_channel!(nodes[0], nodes[1], 100000);
304
305                 let _ = bg_processor.thread_handle.join().unwrap().expect_err("Errored persisting manager: test");
306         }
307 }