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.
5 #![deny(broken_intra_doc_links)]
9 #[macro_use] extern crate lightning;
12 use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
13 use lightning::chain::chainmonitor::ChainMonitor;
14 use lightning::chain::channelmonitor;
15 use lightning::chain::keysinterface::{Sign, KeysInterface};
16 use lightning::ln::channelmanager::ChannelManager;
17 use lightning::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler};
18 use lightning::ln::peer_handler::{PeerManager, SocketDescriptor};
19 use lightning::ln::peer_handler::CustomMessageHandler;
20 use lightning::util::events::{EventHandler, EventsProvider};
21 use lightning::util::logger::Logger;
23 use std::sync::atomic::{AtomicBool, Ordering};
25 use std::thread::JoinHandle;
26 use std::time::{Duration, Instant};
29 /// `BackgroundProcessor` takes care of tasks that (1) need to happen periodically to keep
30 /// Rust-Lightning running properly, and (2) either can or should be run in the background. Its
31 /// responsibilities are:
32 /// * Processing [`Event`]s with a user-provided [`EventHandler`].
33 /// * Monitoring whether the [`ChannelManager`] needs to be re-persisted to disk, and if so,
34 /// writing it to disk/backups by invoking the callback given to it at startup.
35 /// [`ChannelManager`] persistence should be done in the background.
36 /// * Calling [`ChannelManager::timer_tick_occurred`] and [`PeerManager::timer_tick_occurred`]
37 /// at the appropriate intervals.
39 /// It will also call [`PeerManager::process_events`] periodically though this shouldn't be relied
40 /// upon as doing so may result in high latency.
44 /// If [`ChannelManager`] persistence fails and the persisted manager becomes out-of-date, then
45 /// there is a risk of channels force-closing on startup when the manager realizes it's outdated.
46 /// However, as long as [`ChannelMonitor`] backups are sound, no funds besides those used for
47 /// unilateral chain closure fees are at risk.
49 /// [`ChannelMonitor`]: lightning::chain::channelmonitor::ChannelMonitor
50 /// [`Event`]: lightning::util::events::Event
51 #[must_use = "BackgroundProcessor will immediately stop on drop. It should be stored until shutdown."]
52 pub struct BackgroundProcessor {
53 stop_thread: Arc<AtomicBool>,
54 thread_handle: Option<JoinHandle<Result<(), std::io::Error>>>,
58 const FRESHNESS_TIMER: u64 = 60;
60 const FRESHNESS_TIMER: u64 = 1;
62 #[cfg(not(debug_assertions))]
63 const PING_TIMER: u64 = 5;
64 /// Signature operations take a lot longer without compiler optimisations.
65 /// Increasing the ping timer allows for this but slower devices will be disconnected if the
66 /// timeout is reached.
67 #[cfg(debug_assertions)]
68 const PING_TIMER: u64 = 30;
70 /// Trait which handles persisting a [`ChannelManager`] to disk.
72 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
73 pub trait ChannelManagerPersister<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
75 M::Target: 'static + chain::Watch<Signer>,
76 T::Target: 'static + BroadcasterInterface,
77 K::Target: 'static + KeysInterface<Signer = Signer>,
78 F::Target: 'static + FeeEstimator,
79 L::Target: 'static + Logger,
81 /// Persist the given [`ChannelManager`] to disk, returning an error if persistence failed
82 /// (which will cause the [`BackgroundProcessor`] which called this method to exit.
84 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
85 fn persist_manager(&self, channel_manager: &ChannelManager<Signer, M, T, K, F, L>) -> Result<(), std::io::Error>;
88 impl<Fun, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
89 ChannelManagerPersister<Signer, M, T, K, F, L> for Fun where
90 M::Target: 'static + chain::Watch<Signer>,
91 T::Target: 'static + BroadcasterInterface,
92 K::Target: 'static + KeysInterface<Signer = Signer>,
93 F::Target: 'static + FeeEstimator,
94 L::Target: 'static + Logger,
95 Fun: Fn(&ChannelManager<Signer, M, T, K, F, L>) -> Result<(), std::io::Error>,
97 fn persist_manager(&self, channel_manager: &ChannelManager<Signer, M, T, K, F, L>) -> Result<(), std::io::Error> {
102 impl BackgroundProcessor {
103 /// Start a background thread that takes care of responsibilities enumerated in the [top-level
106 /// The thread runs indefinitely unless the object is dropped, [`stop`] is called, or
107 /// `persist_manager` returns an error. In case of an error, the error is retrieved by calling
108 /// either [`join`] or [`stop`].
110 /// # Data Persistence
112 /// `persist_manager` is responsible for writing out the [`ChannelManager`] to disk, and/or
113 /// uploading to one or more backup services. See [`ChannelManager::write`] for writing out a
114 /// [`ChannelManager`]. See [`FilesystemPersister::persist_manager`] for Rust-Lightning's
115 /// provided implementation.
117 /// Typically, users should either implement [`ChannelManagerPersister`] to never return an
118 /// error or call [`join`] and handle any error that may arise. For the latter case,
119 /// `BackgroundProcessor` must be restarted by calling `start` again after handling the error.
123 /// `event_handler` is responsible for handling events that users should be notified of (e.g.,
124 /// payment failed). A user's [`EventHandler`] may be decorated with other handlers to implement
125 /// common functionality. See individual [`Event`]s for further details.
127 /// [top-level documentation]: Self
128 /// [`join`]: Self::join
129 /// [`stop`]: Self::stop
130 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
131 /// [`ChannelManager::write`]: lightning::ln::channelmanager::ChannelManager#impl-Writeable
132 /// [`FilesystemPersister::persist_manager`]: lightning_persister::FilesystemPersister::persist_manager
133 /// [`Event`]: lightning::util::events::Event
135 Signer: 'static + Sign,
136 CF: 'static + Deref + Send + Sync,
137 CW: 'static + Deref + Send + Sync,
138 T: 'static + Deref + Send + Sync,
139 K: 'static + Deref + Send + Sync,
140 F: 'static + Deref + Send + Sync,
141 L: 'static + Deref + Send + Sync,
142 P: 'static + Deref + Send + Sync,
143 Descriptor: 'static + SocketDescriptor + Send + Sync,
144 CMH: 'static + Deref + Send + Sync,
145 RMH: 'static + Deref + Send + Sync,
146 EH: 'static + EventHandler + Send + Sync,
147 CMP: 'static + Send + ChannelManagerPersister<Signer, CW, T, K, F, L>,
148 M: 'static + Deref<Target = ChainMonitor<Signer, CF, T, F, L, P>> + Send + Sync,
149 CM: 'static + Deref<Target = ChannelManager<Signer, CW, T, K, F, L>> + Send + Sync,
150 UMH: 'static + Deref + Send + Sync,
151 PM: 'static + Deref<Target = PeerManager<Descriptor, CMH, RMH, L, UMH>> + Send + Sync,
153 (persister: CMP, event_handler: EH, chain_monitor: M, channel_manager: CM, peer_manager: PM, logger: L) -> Self
155 CF::Target: 'static + chain::Filter,
156 CW::Target: 'static + chain::Watch<Signer>,
157 T::Target: 'static + BroadcasterInterface,
158 K::Target: 'static + KeysInterface<Signer = Signer>,
159 F::Target: 'static + FeeEstimator,
160 L::Target: 'static + Logger,
161 P::Target: 'static + channelmonitor::Persist<Signer>,
162 CMH::Target: 'static + ChannelMessageHandler,
163 RMH::Target: 'static + RoutingMessageHandler,
164 UMH::Target: 'static + CustomMessageHandler,
166 let stop_thread = Arc::new(AtomicBool::new(false));
167 let stop_thread_clone = stop_thread.clone();
168 let handle = thread::spawn(move || -> Result<(), std::io::Error> {
169 log_trace!(logger, "Calling ChannelManager's timer_tick_occurred on startup");
170 channel_manager.timer_tick_occurred();
172 let mut last_freshness_call = Instant::now();
173 let mut last_ping_call = Instant::now();
175 peer_manager.process_events();
176 channel_manager.process_pending_events(&event_handler);
177 chain_monitor.process_pending_events(&event_handler);
178 let updates_available =
179 channel_manager.await_persistable_update_timeout(Duration::from_millis(100));
180 if updates_available {
181 persister.persist_manager(&*channel_manager)?;
183 // Exit the loop if the background processor was requested to stop.
184 if stop_thread.load(Ordering::Acquire) == true {
185 log_trace!(logger, "Terminating background processor.");
188 if last_freshness_call.elapsed().as_secs() > FRESHNESS_TIMER {
189 log_trace!(logger, "Calling ChannelManager's timer_tick_occurred");
190 channel_manager.timer_tick_occurred();
191 last_freshness_call = Instant::now();
193 if last_ping_call.elapsed().as_secs() > PING_TIMER * 2 {
194 // On various platforms, we may be starved of CPU cycles for several reasons.
195 // E.g. on iOS, if we've been in the background, we will be entirely paused.
196 // Similarly, if we're on a desktop platform and the device has been asleep, we
197 // may not get any cycles.
198 // In any case, if we've been entirely paused for more than double our ping
199 // timer, we should have disconnected all sockets by now (and they're probably
200 // dead anyway), so disconnect them by calling `timer_tick_occurred()` twice.
201 log_trace!(logger, "Awoke after more than double our ping timer, disconnecting peers.");
202 peer_manager.timer_tick_occurred();
203 peer_manager.timer_tick_occurred();
204 last_ping_call = Instant::now();
205 } else if last_ping_call.elapsed().as_secs() > PING_TIMER {
206 log_trace!(logger, "Calling PeerManager's timer_tick_occurred");
207 peer_manager.timer_tick_occurred();
208 last_ping_call = Instant::now();
212 Self { stop_thread: stop_thread_clone, thread_handle: Some(handle) }
215 /// Join `BackgroundProcessor`'s thread, returning any error that occurred while persisting
216 /// [`ChannelManager`].
220 /// This function panics if the background thread has panicked such as while persisting or
223 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
224 pub fn join(mut self) -> Result<(), std::io::Error> {
225 assert!(self.thread_handle.is_some());
229 /// Stop `BackgroundProcessor`'s thread, returning any error that occurred while persisting
230 /// [`ChannelManager`].
234 /// This function panics if the background thread has panicked such as while persisting or
237 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
238 pub fn stop(mut self) -> Result<(), std::io::Error> {
239 assert!(self.thread_handle.is_some());
240 self.stop_and_join_thread()
243 fn stop_and_join_thread(&mut self) -> Result<(), std::io::Error> {
244 self.stop_thread.store(true, Ordering::Release);
248 fn join_thread(&mut self) -> Result<(), std::io::Error> {
249 match self.thread_handle.take() {
250 Some(handle) => handle.join().unwrap(),
256 impl Drop for BackgroundProcessor {
258 self.stop_and_join_thread().unwrap();
264 use bitcoin::blockdata::block::BlockHeader;
265 use bitcoin::blockdata::constants::genesis_block;
266 use bitcoin::blockdata::transaction::{Transaction, TxOut};
267 use bitcoin::network::constants::Network;
268 use lightning::chain::{BestBlock, Confirm, chainmonitor};
269 use lightning::chain::channelmonitor::ANTI_REORG_DELAY;
270 use lightning::chain::keysinterface::{InMemorySigner, KeysInterface, KeysManager};
271 use lightning::chain::transaction::OutPoint;
272 use lightning::get_event_msg;
273 use lightning::ln::channelmanager::{BREAKDOWN_TIMEOUT, ChainParameters, ChannelManager, SimpleArcChannelManager};
274 use lightning::ln::features::InitFeatures;
275 use lightning::ln::msgs::{ChannelMessageHandler, Init};
276 use lightning::ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler};
277 use lightning::util::config::UserConfig;
278 use lightning::util::events::{Event, MessageSendEventsProvider, MessageSendEvent};
279 use lightning::util::ser::Writeable;
280 use lightning::util::test_utils;
281 use lightning_persister::FilesystemPersister;
283 use std::path::PathBuf;
284 use std::sync::{Arc, Mutex};
285 use std::time::Duration;
286 use super::{BackgroundProcessor, FRESHNESS_TIMER};
288 const EVENT_DEADLINE: u64 = 5 * FRESHNESS_TIMER;
290 #[derive(Clone, Eq, Hash, PartialEq)]
291 struct TestDescriptor{}
292 impl SocketDescriptor for TestDescriptor {
293 fn send_data(&mut self, _data: &[u8], _resume_read: bool) -> usize {
297 fn disconnect_socket(&mut self) {}
300 type ChainMonitor = chainmonitor::ChainMonitor<InMemorySigner, Arc<test_utils::TestChainSource>, Arc<test_utils::TestBroadcaster>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>, Arc<FilesystemPersister>>;
303 node: Arc<SimpleArcChannelManager<ChainMonitor, test_utils::TestBroadcaster, test_utils::TestFeeEstimator, test_utils::TestLogger>>,
304 peer_manager: Arc<PeerManager<TestDescriptor, Arc<test_utils::TestChannelMessageHandler>, Arc<test_utils::TestRoutingMessageHandler>, Arc<test_utils::TestLogger>, IgnoringMessageHandler>>,
305 chain_monitor: Arc<ChainMonitor>,
306 persister: Arc<FilesystemPersister>,
307 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
308 logger: Arc<test_utils::TestLogger>,
309 best_block: BestBlock,
314 let data_dir = self.persister.get_data_dir();
315 match fs::remove_dir_all(data_dir.clone()) {
316 Err(e) => println!("Failed to remove test persister directory {}: {}", data_dir, e),
322 fn get_full_filepath(filepath: String, filename: String) -> String {
323 let mut path = PathBuf::from(filepath);
325 path.to_str().unwrap().to_string()
328 fn create_nodes(num_nodes: usize, persist_dir: String) -> Vec<Node> {
329 let mut nodes = Vec::new();
330 for i in 0..num_nodes {
331 let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))});
332 let fee_estimator = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) });
333 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
334 let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
335 let persister = Arc::new(FilesystemPersister::new(format!("{}_persister_{}", persist_dir, i)));
336 let seed = [i as u8; 32];
337 let network = Network::Testnet;
338 let now = Duration::from_secs(genesis_block(network).header.time as u64);
339 let keys_manager = Arc::new(KeysManager::new(&seed, now.as_secs(), now.subsec_nanos()));
340 let chain_monitor = Arc::new(chainmonitor::ChainMonitor::new(Some(chain_source.clone()), tx_broadcaster.clone(), logger.clone(), fee_estimator.clone(), persister.clone()));
341 let best_block = BestBlock::from_genesis(network);
342 let params = ChainParameters { network, best_block };
343 let manager = Arc::new(ChannelManager::new(fee_estimator.clone(), chain_monitor.clone(), tx_broadcaster.clone(), logger.clone(), keys_manager.clone(), UserConfig::default(), params));
344 let msg_handler = MessageHandler { chan_handler: Arc::new(test_utils::TestChannelMessageHandler::new()), route_handler: Arc::new(test_utils::TestRoutingMessageHandler::new() )};
345 let peer_manager = Arc::new(PeerManager::new(msg_handler, keys_manager.get_node_secret(), &seed, logger.clone(), IgnoringMessageHandler{}));
346 let node = Node { node: manager, peer_manager, chain_monitor, persister, tx_broadcaster, logger, best_block };
350 for i in 0..num_nodes {
351 for j in (i+1)..num_nodes {
352 nodes[i].node.peer_connected(&nodes[j].node.get_our_node_id(), &Init { features: InitFeatures::known() });
353 nodes[j].node.peer_connected(&nodes[i].node.get_our_node_id(), &Init { features: InitFeatures::known() });
360 macro_rules! open_channel {
361 ($node_a: expr, $node_b: expr, $channel_value: expr) => {{
362 begin_open_channel!($node_a, $node_b, $channel_value);
363 let events = $node_a.node.get_and_clear_pending_events();
364 assert_eq!(events.len(), 1);
365 let (temporary_channel_id, tx) = handle_funding_generation_ready!(&events[0], $channel_value);
366 end_open_channel!($node_a, $node_b, temporary_channel_id, tx);
371 macro_rules! begin_open_channel {
372 ($node_a: expr, $node_b: expr, $channel_value: expr) => {{
373 $node_a.node.create_channel($node_b.node.get_our_node_id(), $channel_value, 100, 42, None).unwrap();
374 $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()));
375 $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()));
379 macro_rules! handle_funding_generation_ready {
380 ($event: expr, $channel_value: expr) => {{
382 &Event::FundingGenerationReady { temporary_channel_id, channel_value_satoshis, ref output_script, user_channel_id } => {
383 assert_eq!(channel_value_satoshis, $channel_value);
384 assert_eq!(user_channel_id, 42);
386 let tx = Transaction { version: 1 as i32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
387 value: channel_value_satoshis, script_pubkey: output_script.clone(),
389 (temporary_channel_id, tx)
391 _ => panic!("Unexpected event"),
396 macro_rules! end_open_channel {
397 ($node_a: expr, $node_b: expr, $temporary_channel_id: expr, $tx: expr) => {{
398 $node_a.node.funding_transaction_generated(&$temporary_channel_id, $tx.clone()).unwrap();
399 $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()));
400 $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()));
404 fn confirm_transaction_depth(node: &mut Node, tx: &Transaction, depth: u32) {
406 let prev_blockhash = node.best_block.block_hash();
407 let height = node.best_block.height() + 1;
408 let header = BlockHeader { version: 0x20000000, prev_blockhash, merkle_root: Default::default(), time: height, bits: 42, nonce: 42 };
409 let txdata = vec![(0, tx)];
410 node.best_block = BestBlock::new(header.block_hash(), height);
413 node.node.transactions_confirmed(&header, &txdata, height);
414 node.chain_monitor.transactions_confirmed(&header, &txdata, height);
417 node.node.best_block_updated(&header, height);
418 node.chain_monitor.best_block_updated(&header, height);
424 fn confirm_transaction(node: &mut Node, tx: &Transaction) {
425 confirm_transaction_depth(node, tx, ANTI_REORG_DELAY);
429 fn test_background_processor() {
430 // Test that when a new channel is created, the ChannelManager needs to be re-persisted with
431 // updates. Also test that when new updates are available, the manager signals that it needs
432 // re-persistence and is successfully re-persisted.
433 let nodes = create_nodes(2, "test_background_processor".to_string());
435 // Go through the channel creation process so that each node has something to persist. Since
436 // open_channel consumes events, it must complete before starting BackgroundProcessor to
437 // avoid a race with processing events.
438 let tx = open_channel!(nodes[0], nodes[1], 100000);
440 // Initiate the background processors to watch each node.
441 let data_dir = nodes[0].persister.get_data_dir();
442 let persister = 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);
443 let event_handler = |_: &_| {};
444 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());
446 macro_rules! check_persisted_data {
447 ($node: expr, $filepath: expr, $expected_bytes: expr) => {
448 match $node.write(&mut $expected_bytes) {
451 match std::fs::read($filepath) {
453 if bytes == $expected_bytes {
463 Err(e) => panic!("Unexpected error: {}", e)
468 // Check that the initial channel manager data is persisted as expected.
469 let filepath = get_full_filepath("test_background_processor_persister_0".to_string(), "manager".to_string());
470 let mut expected_bytes = Vec::new();
471 check_persisted_data!(nodes[0].node, filepath.clone(), expected_bytes);
473 if !nodes[0].node.get_persistence_condvar_value() { break }
476 // Force-close the channel.
477 nodes[0].node.force_close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
479 // Check that the force-close updates are persisted.
480 let mut expected_bytes = Vec::new();
481 check_persisted_data!(nodes[0].node, filepath.clone(), expected_bytes);
483 if !nodes[0].node.get_persistence_condvar_value() { break }
486 assert!(bg_processor.stop().is_ok());
490 fn test_timer_tick_called() {
491 // Test that ChannelManager's and PeerManager's `timer_tick_occurred` is called every
492 // `FRESHNESS_TIMER`.
493 let nodes = create_nodes(1, "test_timer_tick_called".to_string());
494 let data_dir = nodes[0].persister.get_data_dir();
495 let persister = 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);
496 let event_handler = |_: &_| {};
497 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());
499 let log_entries = nodes[0].logger.lines.lock().unwrap();
500 let desired_log = "Calling ChannelManager's timer_tick_occurred".to_string();
501 let second_desired_log = "Calling PeerManager's timer_tick_occurred".to_string();
502 if log_entries.get(&("lightning_background_processor".to_string(), desired_log)).is_some() &&
503 log_entries.get(&("lightning_background_processor".to_string(), second_desired_log)).is_some() {
508 assert!(bg_processor.stop().is_ok());
512 fn test_persist_error() {
513 // Test that if we encounter an error during manager persistence, the thread panics.
514 let nodes = create_nodes(2, "test_persist_error".to_string());
515 open_channel!(nodes[0], nodes[1], 100000);
517 let persister = |_: &_| Err(std::io::Error::new(std::io::ErrorKind::Other, "test"));
518 let event_handler = |_: &_| {};
519 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());
520 match bg_processor.join() {
521 Ok(_) => panic!("Expected error persisting manager"),
523 assert_eq!(e.kind(), std::io::ErrorKind::Other);
524 assert_eq!(e.get_ref().unwrap().to_string(), "test");
530 fn test_background_event_handling() {
531 let mut nodes = create_nodes(2, "test_background_event_handling".to_string());
532 let channel_value = 100000;
533 let data_dir = nodes[0].persister.get_data_dir();
534 let persister = move |node: &_| FilesystemPersister::persist_manager(data_dir.clone(), node);
536 // Set up a background event handler for FundingGenerationReady events.
537 let (sender, receiver) = std::sync::mpsc::sync_channel(1);
538 let event_handler = move |event: &Event| {
539 sender.send(handle_funding_generation_ready!(event, channel_value)).unwrap();
541 let bg_processor = BackgroundProcessor::start(persister.clone(), event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone());
543 // Open a channel and check that the FundingGenerationReady event was handled.
544 begin_open_channel!(nodes[0], nodes[1], channel_value);
545 let (temporary_channel_id, funding_tx) = receiver
546 .recv_timeout(Duration::from_secs(EVENT_DEADLINE))
547 .expect("FundingGenerationReady not handled within deadline");
548 end_open_channel!(nodes[0], nodes[1], temporary_channel_id, funding_tx);
550 // Confirm the funding transaction.
551 confirm_transaction(&mut nodes[0], &funding_tx);
552 let as_funding = get_event_msg!(nodes[0], MessageSendEvent::SendFundingLocked, nodes[1].node.get_our_node_id());
553 confirm_transaction(&mut nodes[1], &funding_tx);
554 let bs_funding = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id());
555 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &bs_funding);
556 let _as_channel_update = get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
557 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding);
558 let _bs_channel_update = get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
560 assert!(bg_processor.stop().is_ok());
562 // Set up a background event handler for SpendableOutputs events.
563 let (sender, receiver) = std::sync::mpsc::sync_channel(1);
564 let event_handler = move |event: &Event| sender.send(event.clone()).unwrap();
565 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());
567 // Force close the channel and check that the SpendableOutputs event was handled.
568 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
569 let commitment_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().pop().unwrap();
570 confirm_transaction_depth(&mut nodes[0], &commitment_tx, BREAKDOWN_TIMEOUT as u32);
572 .recv_timeout(Duration::from_secs(EVENT_DEADLINE))
573 .expect("SpendableOutputs not handled within deadline");
575 Event::SpendableOutputs { .. } => {},
576 _ => panic!("Unexpected event: {:?}", event),
579 assert!(bg_processor.stop().is_ok());