1 #[macro_use] extern crate lightning;
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;
10 use std::sync::atomic::{AtomicBool, Ordering};
12 use std::thread::JoinHandle;
13 use std::time::{Duration, Instant};
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
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>>,
36 const CHAN_FRESHNESS_TIMER: u64 = 60;
38 const CHAN_FRESHNESS_TIMER: u64 = 1;
40 impl BackgroundProcessor {
41 /// Start a background thread that takes care of responsibilities enumerated in the top-level
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`
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.
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,
63 PM: 'static + Send + Fn(&ChannelManager<ChanSigner, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>) -> Result<(), std::io::Error>,
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();
70 let updates_available = manager.wait_timeout(Duration::from_millis(100));
71 if updates_available {
72 persist_manager(&*manager)?;
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.");
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();
87 stop_thread: stop_thread_clone,
88 thread_handle: handle,
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()
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;
120 use std::path::PathBuf;
121 use std::sync::{Arc, Mutex};
122 use std::time::Duration;
123 use super::BackgroundProcessor;
125 type ChainMonitor = chainmonitor::ChainMonitor<InMemoryChannelKeys, Arc<test_utils::TestChainSource>, Arc<test_utils::TestBroadcaster>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>, Arc<FilesystemPersister>>;
128 node: SimpleArcChannelManager<ChainMonitor, test_utils::TestBroadcaster, test_utils::TestFeeEstimator, test_utils::TestLogger>,
129 persister: Arc<FilesystemPersister>,
130 logger: Arc<test_utils::TestLogger>,
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),
143 fn get_full_filepath(filepath: String, filename: String) -> String {
144 let mut path = PathBuf::from(filepath);
146 path.to_str().unwrap().to_string()
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, network, 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 };
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);
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(),
184 let funding_outpoint = OutPoint { txid: tx.txid(), index: 0 };
185 (*temporary_channel_id, tx, funding_outpoint)
187 _ => panic!("Unexpected event"),
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()));
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());
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>>| {
207 println!("VMW: callback being invoked");
208 FilesystemPersister::persist_manager(data_dir.clone(), node)
210 let bg_processor = BackgroundProcessor::start(callback, nodes[0].node.clone(), nodes[0].logger.clone());
212 // Go through the channel creation process until each node should have something persisted.
213 let tx = open_channel!(nodes[0], nodes[1], 100000);
215 let mut num_calls = 0;
216 macro_rules! check_persisted_data {
217 ($node: expr, $filepath: expr, $expected_bytes: expr) => {
218 match $node.write(&mut $expected_bytes) {
221 match std::fs::read($filepath) {
224 println!("VMW: bytes of node: {}, bytes on disk: {}", $expected_bytes.len(), bytes.len());
227 if bytes == $expected_bytes {
230 // println!("VMW: continuing 1");
235 println!("VMW: continuing 2");
241 Err(e) => panic!("Unexpected error: {}", e)
246 // Check that the initial channel manager data is persisted as expected.
247 let filepath = get_full_filepath("test_background_processor_persister_0".to_string(), "manager".to_string());
248 let mut expected_bytes = Vec::new();
249 println!("VMW: about to check for persisted 1...");
250 check_persisted_data!(nodes[0].node, filepath.clone(), expected_bytes);
252 println!("VMW: checking condvar 1");
253 if !nodes[0].node.get_persistence_condvar_value() { break }
256 // Force-close the channel.
257 nodes[0].node.force_close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
259 // Check that the force-close updates are persisted.
260 let mut expected_bytes = Vec::new();
261 println!("VMW: about to check for persisted 2...");
262 check_persisted_data!(nodes[0].node, filepath.clone(), expected_bytes);
264 println!("VMW: checking condvar 2");
265 if !nodes[0].node.get_persistence_condvar_value() { break }
268 assert!(bg_processor.stop().is_ok());
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<InMemoryChannelKeys, 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());
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(&("background_processor".to_string(), desired_log)).is_some() {
287 assert!(bg_processor.stop().is_ok());
291 fn test_persist_error() {
292 // Test that if we encounter an error during manager persistence, the thread panics.
293 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>
294 where ChanSigner: 'static + ChannelKeys + Writeable,
295 M: 'static + chain::Watch<Keys=ChanSigner>,
296 T: 'static + BroadcasterInterface,
297 K: 'static + KeysInterface<ChanKeySigner=ChanSigner>,
298 F: 'static + FeeEstimator,
301 Err(std::io::Error::new(std::io::ErrorKind::Other, "test"))
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);
308 let _ = bg_processor.thread_handle.join().unwrap().expect_err("Errored persisting manager: test");