X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning-background-processor%2Fsrc%2Flib.rs;h=c75c47262e51d2873a335acc37518bccd6ed2984;hb=0f1a3b16984063d9a7e745d2e4a0afb532d634d0;hp=69aa2ea0047fa3f9177876405fc2e4f7b8441173;hpb=f8450a7c2cd6d31b0691e771c1b36ea857c26c2a;p=rust-lightning diff --git a/lightning-background-processor/src/lib.rs b/lightning-background-processor/src/lib.rs index 69aa2ea0..c75c4726 100644 --- a/lightning-background-processor/src/lib.rs +++ b/lightning-background-processor/src/lib.rs @@ -41,9 +41,7 @@ use std::ops::Deref; /// for unilateral chain closure fees are at risk. pub struct BackgroundProcessor { stop_thread: Arc, - /// May be used to retrieve and handle the error if `BackgroundProcessor`'s thread - /// exits due to an error while persisting. - pub thread_handle: JoinHandle>, + thread_handle: Option>>, } #[cfg(not(test))] @@ -51,6 +49,8 @@ const FRESHNESS_TIMER: u64 = 60; #[cfg(test)] const FRESHNESS_TIMER: u64 = 1; +const PING_TIMER: u64 = 5; + /// Trait which handles persisting a [`ChannelManager`] to disk. /// /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager @@ -84,21 +84,25 @@ ChannelManagerPersister for Fun where } impl BackgroundProcessor { - /// Start a background thread that takes care of responsibilities enumerated in the top-level - /// documentation. + /// Start a background thread that takes care of responsibilities enumerated in the [top-level + /// documentation]. + /// + /// The thread runs indefinitely unless the object is dropped, [`stop`] is called, or + /// `persist_manager` returns an error. In case of an error, the error is retrieved by calling + /// either [`join`] or [`stop`]. /// - /// If `persist_manager` returns an error, then this thread will return said error (and - /// `start()` will need to be called again to restart the `BackgroundProcessor`). Users should - /// wait on [`thread_handle`]'s `join()` method to be able to tell if and when an error is - /// returned, or implement `persist_manager` such that an error is never returned to the - /// `BackgroundProcessor` + /// Typically, users should either implement [`ChannelManagerPersister`] to never return an + /// error or call [`join`] and handle any error that may arise. For the latter case, the + /// `BackgroundProcessor` must be restarted by calling `start` again after handling the error. /// /// `persist_manager` is responsible for writing out the [`ChannelManager`] to disk, and/or /// uploading to one or more backup services. See [`ChannelManager::write`] for writing out a /// [`ChannelManager`]. See [`FilesystemPersister::persist_manager`] for Rust-Lightning's /// provided implementation. /// - /// [`thread_handle`]: BackgroundProcessor::thread_handle + /// [top-level documentation]: Self + /// [`join`]: Self::join + /// [`stop`]: Self::stop /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager /// [`ChannelManager::write`]: lightning::ln::channelmanager::ChannelManager#impl-Writeable /// [`FilesystemPersister::persist_manager`]: lightning_persister::FilesystemPersister::persist_manager @@ -135,7 +139,8 @@ impl BackgroundProcessor { let stop_thread = Arc::new(AtomicBool::new(false)); let stop_thread_clone = stop_thread.clone(); let handle = thread::spawn(move || -> Result<(), std::io::Error> { - let mut current_time = Instant::now(); + let mut last_freshness_call = Instant::now(); + let mut last_ping_call = Instant::now(); loop { peer_manager.process_events(); channel_manager.process_pending_events(&event_handler); @@ -150,21 +155,77 @@ impl BackgroundProcessor { log_trace!(logger, "Terminating background processor."); return Ok(()); } - if current_time.elapsed().as_secs() > FRESHNESS_TIMER { - log_trace!(logger, "Calling ChannelManager's and PeerManager's timer_tick_occurred"); + if last_freshness_call.elapsed().as_secs() > FRESHNESS_TIMER { + log_trace!(logger, "Calling ChannelManager's timer_tick_occurred"); channel_manager.timer_tick_occurred(); + last_freshness_call = Instant::now(); + } + if last_ping_call.elapsed().as_secs() > PING_TIMER * 2 { + // On various platforms, we may be starved of CPU cycles for several reasons. + // E.g. on iOS, if we've been in the background, we will be entirely paused. + // Similarly, if we're on a desktop platform and the device has been asleep, we + // may not get any cycles. + // In any case, if we've been entirely paused for more than double our ping + // timer, we should have disconnected all sockets by now (and they're probably + // dead anyway), so disconnect them by calling `timer_tick_occurred()` twice. + log_trace!(logger, "Awoke after more than double our ping timer, disconnecting peers."); + peer_manager.timer_tick_occurred(); peer_manager.timer_tick_occurred(); - current_time = Instant::now(); + last_ping_call = Instant::now(); + } else if last_ping_call.elapsed().as_secs() > PING_TIMER { + log_trace!(logger, "Calling PeerManager's timer_tick_occurred"); + peer_manager.timer_tick_occurred(); + last_ping_call = Instant::now(); } } }); - Self { stop_thread: stop_thread_clone, thread_handle: handle } + Self { stop_thread: stop_thread_clone, thread_handle: Some(handle) } + } + + /// Join `BackgroundProcessor`'s thread, returning any error that occurred while persisting + /// [`ChannelManager`]. + /// + /// # Panics + /// + /// This function panics if the background thread has panicked such as while persisting or + /// handling events. + /// + /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager + pub fn join(mut self) -> Result<(), std::io::Error> { + assert!(self.thread_handle.is_some()); + self.join_thread() } - /// Stop `BackgroundProcessor`'s thread. - pub fn stop(self) -> Result<(), std::io::Error> { + /// Stop `BackgroundProcessor`'s thread, returning any error that occurred while persisting + /// [`ChannelManager`]. + /// + /// # Panics + /// + /// This function panics if the background thread has panicked such as while persisting or + /// handling events. + /// + /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager + pub fn stop(mut self) -> Result<(), std::io::Error> { + assert!(self.thread_handle.is_some()); + self.stop_and_join_thread() + } + + fn stop_and_join_thread(&mut self) -> Result<(), std::io::Error> { self.stop_thread.store(true, Ordering::Release); - self.thread_handle.join().unwrap() + self.join_thread() + } + + fn join_thread(&mut self) -> Result<(), std::io::Error> { + match self.thread_handle.take() { + Some(handle) => handle.join().unwrap(), + None => Ok(()), + } + } +} + +impl Drop for BackgroundProcessor { + fn drop(&mut self) { + self.stop_and_join_thread().unwrap(); } } @@ -174,13 +235,12 @@ mod tests { use bitcoin::blockdata::constants::genesis_block; use bitcoin::blockdata::transaction::{Transaction, TxOut}; use bitcoin::network::constants::Network; - use lightning::chain::Confirm; - use lightning::chain::chainmonitor; + use lightning::chain::{BestBlock, Confirm, chainmonitor}; use lightning::chain::channelmonitor::ANTI_REORG_DELAY; use lightning::chain::keysinterface::{InMemorySigner, KeysInterface, KeysManager}; use lightning::chain::transaction::OutPoint; use lightning::get_event_msg; - use lightning::ln::channelmanager::{BestBlock, ChainParameters, ChannelManager, SimpleArcChannelManager}; + use lightning::ln::channelmanager::{BREAKDOWN_TIMEOUT, ChainParameters, ChannelManager, SimpleArcChannelManager}; use lightning::ln::features::InitFeatures; use lightning::ln::msgs::ChannelMessageHandler; use lightning::ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor}; @@ -238,8 +298,8 @@ mod tests { fn create_nodes(num_nodes: usize, persist_dir: String) -> Vec { let mut nodes = Vec::new(); for i in 0..num_nodes { - let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())}); - let fee_estimator = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }); + let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))}); + let fee_estimator = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }); let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet)); let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i))); let persister = Arc::new(FilesystemPersister::new(format!("{}_persister_{}", persist_dir, i))); @@ -303,8 +363,8 @@ mod tests { }} } - fn confirm_transaction(node: &mut Node, tx: &Transaction) { - for i in 1..=ANTI_REORG_DELAY { + fn confirm_transaction_depth(node: &mut Node, tx: &Transaction, depth: u32) { + for i in 1..=depth { let prev_blockhash = node.best_block.block_hash(); let height = node.best_block.height() + 1; let header = BlockHeader { version: 0x20000000, prev_blockhash, merkle_root: Default::default(), time: height, bits: 42, nonce: 42 }; @@ -315,7 +375,7 @@ mod tests { node.node.transactions_confirmed(&header, &txdata, height); node.chain_monitor.transactions_confirmed(&header, &txdata, height); }, - ANTI_REORG_DELAY => { + x if x == depth => { node.node.best_block_updated(&header, height); node.chain_monitor.best_block_updated(&header, height); }, @@ -323,6 +383,9 @@ mod tests { } } } + fn confirm_transaction(node: &mut Node, tx: &Transaction) { + confirm_transaction_depth(node, tx, ANTI_REORG_DELAY); + } #[test] fn test_background_processor() { @@ -396,8 +459,10 @@ mod tests { let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone()); loop { let log_entries = nodes[0].logger.lines.lock().unwrap(); - let desired_log = "Calling ChannelManager's and PeerManager's timer_tick_occurred".to_string(); - if log_entries.get(&("lightning_background_processor".to_string(), desired_log)).is_some() { + let desired_log = "Calling ChannelManager's timer_tick_occurred".to_string(); + let second_desired_log = "Calling PeerManager's timer_tick_occurred".to_string(); + if log_entries.get(&("lightning_background_processor".to_string(), desired_log)).is_some() && + log_entries.get(&("lightning_background_processor".to_string(), second_desired_log)).is_some() { break } } @@ -414,7 +479,13 @@ mod tests { let persister = |_: &_| Err(std::io::Error::new(std::io::ErrorKind::Other, "test")); let event_handler = |_| {}; let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone()); - let _ = bg_processor.thread_handle.join().unwrap().expect_err("Errored persisting manager: test"); + match bg_processor.join() { + Ok(_) => panic!("Expected error persisting manager"), + Err(e) => { + assert_eq!(e.kind(), std::io::ErrorKind::Other); + assert_eq!(e.get_ref().unwrap().to_string(), "test"); + }, + } } #[test] @@ -440,9 +511,13 @@ mod tests { // Confirm the funding transaction. confirm_transaction(&mut nodes[0], &funding_tx); + let as_funding = get_event_msg!(nodes[0], MessageSendEvent::SendFundingLocked, nodes[1].node.get_our_node_id()); confirm_transaction(&mut nodes[1], &funding_tx); - nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id())); - nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendFundingLocked, nodes[1].node.get_our_node_id())); + let bs_funding = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id()); + nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &bs_funding); + let _as_channel_update = get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id()); + nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding); + let _bs_channel_update = get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id()); assert!(bg_processor.stop().is_ok()); @@ -454,7 +529,7 @@ mod tests { // Force close the channel and check that the SpendableOutputs event was handled. nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap(); let commitment_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().pop().unwrap(); - confirm_transaction(&mut nodes[0], &commitment_tx); + confirm_transaction_depth(&mut nodes[0], &commitment_tx, BREAKDOWN_TIMEOUT as u32); let event = receiver .recv_timeout(Duration::from_secs(EVENT_DEADLINE)) .expect("SpendableOutputs not handled within deadline");