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