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