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