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