Skip to content

Commit d10cabf

Browse files
Add BackgroundProcessor for ChannelManager persistence and other
Other includes calling timer_chan_freshness_every_minute() and in the future, possibly persisting channel graph data. This struct is suitable for things that need to happen periodically and can happen in the background.
1 parent 6a6898e commit d10cabf

File tree

2 files changed

+220
-0
lines changed

2 files changed

+220
-0
lines changed
Lines changed: 219 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,219 @@
1+
use lightning::chain;
2+
use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
3+
use lightning::chain::keysinterface::{ChannelKeys, KeysInterface};
4+
use lightning::ln::channelmanager;
5+
use lightning::ln::channelmanager::ChannelManager;
6+
use lightning::util::logger::Logger;
7+
use lightning::util::ser::Writeable;
8+
use std::sync::Arc;
9+
use std::sync::mpsc::{self, Sender, TryRecvError};
10+
use std::thread;
11+
use std::time::{Duration, SystemTime};
12+
13+
/// BackgroundProcesser runs a background thread that monitors whether the ChannelManager it's given on
14+
/// start has new updates to persist. If it does, then it writes said ChannelManager to disk/backups.
15+
pub struct BackgroundProcessor {
16+
#[cfg(test)]
17+
pub thread_terminator: Sender<()>,
18+
#[cfg(not(test))]
19+
/// Used to send a message to the thread in BackgroundProcessor::start() to exit the thread.
20+
thread_terminator: Sender<()>,
21+
}
22+
23+
impl BackgroundProcessor {
24+
/// Start the background thread that checks whether new updates are available for the ChannelManager,
25+
/// and writes it to disk if so.
26+
/// We also call ChannelManager::timer_chan_freshness_every_min(), since we're already eating the
27+
/// cost of running a thread, we may as well pack as many operations into it as make sense.
28+
// Mark as must_use because otherwise the result is dropped immediately, resulting in the thread
29+
// being terminated.
30+
#[must_use]
31+
pub fn start<ChanSigner: 'static + ChannelKeys + Writeable, M: 'static + chain::Watch<Keys=ChanSigner>, T: 'static + BroadcasterInterface, K: 'static + KeysInterface<ChanKeySigner=ChanSigner>, F: 'static + FeeEstimator, L: 'static + Logger>(persister: Arc<dyn channelmanager::Persist<ChanSigner, M, T, K, F, L>>, manager: Arc<ChannelManager<ChanSigner, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>>) -> Self {
32+
let (sender, receiver) = mpsc::channel();
33+
// See ChannelMananger::persistence_lock for more documentation on the persistence process.
34+
thread::spawn(move || {
35+
let mut current_time = SystemTime::now();
36+
loop {
37+
let updates_available = manager.block_until_needs_persist(Some(Duration::from_millis(1000)));
38+
if updates_available {
39+
if let Err(e) = persister.persist_manager(manager.clone()) {
40+
println!("Errored persisting manager: {}", e);
41+
};
42+
}
43+
// If we receive a message from the thread_terminator, we should exit now.
44+
match receiver.try_recv() {
45+
Ok(_) | Err(TryRecvError::Disconnected) => {
46+
println!("Terminating.");
47+
break;
48+
}
49+
Err(TryRecvError::Empty) => {}
50+
}
51+
match current_time.elapsed() {
52+
Ok(elapsed) => {
53+
if elapsed.as_secs() > 60 {
54+
manager.timer_chan_freshness_every_min();
55+
current_time = SystemTime::now();
56+
}
57+
},
58+
Err(e) => println!("Errored retrieving elapsed time: {}", e),
59+
}
60+
}
61+
});
62+
Self {
63+
thread_terminator: sender,
64+
}
65+
}
66+
67+
pub fn stop(&self) {
68+
let _ = self.thread_terminator.send(());
69+
}
70+
}
71+
72+
#[cfg(test)]
73+
mod tests {
74+
use bitcoin::blockdata::constants::genesis_block;
75+
use bitcoin::blockdata::transaction::{Transaction, TxOut};
76+
use bitcoin::network::constants::Network;
77+
use crate::FilesystemPersister;
78+
use crate::utils;
79+
use lightning::chain::chainmonitor;
80+
use lightning::chain::keysinterface::{InMemoryChannelKeys, KeysManager};
81+
use lightning::chain::transaction::OutPoint;
82+
use lightning::get_event_msg;
83+
use lightning::ln::channelmanager::{ChannelManager, SimpleArcChannelManager};
84+
use lightning::ln::features::{InitFeatures};
85+
use lightning::ln::msgs::ChannelMessageHandler;
86+
use lightning::util::config::UserConfig;
87+
use lightning::util::events::{Event, EventsProvider, MessageSendEventsProvider, MessageSendEvent};
88+
use lightning::util::ser::{Writeable};
89+
use lightning::util::test_utils;
90+
use std::fs;
91+
use std::mem;
92+
use std::sync::{Arc, Mutex};
93+
use std::time::Duration;
94+
use super::BackgroundProcessor;
95+
96+
type ChainMonitor = chainmonitor::ChainMonitor<InMemoryChannelKeys, Arc<test_utils::TestChainSource>, Arc<test_utils::TestBroadcaster>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>, Arc<FilesystemPersister>>;
97+
98+
struct Node {
99+
node: SimpleArcChannelManager<ChainMonitor, test_utils::TestBroadcaster, test_utils::TestFeeEstimator, test_utils::TestLogger>,
100+
persister: Arc<FilesystemPersister>
101+
}
102+
103+
fn create_nodes(num_nodes: usize) -> Vec<Node> {
104+
let mut nodes = Vec::new();
105+
for i in 0..num_nodes {
106+
let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
107+
let fee_estimator = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
108+
let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
109+
let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
110+
let persister = Arc::new(FilesystemPersister::new(format!("persister_{}", i)));
111+
let seed = [i as u8; 32];
112+
let network = Network::Testnet;
113+
let now = Duration::from_secs(genesis_block(network).header.time as u64);
114+
let keys_manager = Arc::new(KeysManager::new(&seed, network, now.as_secs(), now.subsec_nanos()));
115+
let chain_monitor = Arc::new(chainmonitor::ChainMonitor::new(Some(chain_source.clone()), tx_broadcaster.clone(), logger.clone(), fee_estimator.clone(), persister.clone()));
116+
let manager = Arc::new(ChannelManager::new(Network::Testnet, fee_estimator.clone(), chain_monitor.clone(), tx_broadcaster, logger.clone(), keys_manager.clone(), UserConfig::default(), i));
117+
let node = Node { node: manager, persister };
118+
nodes.push(node);
119+
}
120+
nodes
121+
}
122+
123+
#[test]
124+
fn test_background_processor() {
125+
let nodes = create_nodes(2);
126+
127+
// Initiate the background processors to watch each node.
128+
let _processor_0 = BackgroundProcessor::start(nodes[0].persister.clone(), nodes[0].node.clone());
129+
let _processor_1 = BackgroundProcessor::start(nodes[1].persister.clone(), nodes[1].node.clone());
130+
131+
// Go through the channel creation process until each node should have something persisted.
132+
let channel_value = 100000;
133+
nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value, 100, 42, None).unwrap();
134+
nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
135+
nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
136+
let events = nodes[0].node.get_and_clear_pending_events();
137+
assert_eq!(events.len(), 1);
138+
let (temporary_channel_id, tx, funding_output) = match events[0] {
139+
Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
140+
assert_eq!(*channel_value_satoshis, channel_value);
141+
assert_eq!(user_channel_id, 42);
142+
143+
let tx = Transaction { version: 1 as i32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
144+
value: *channel_value_satoshis, script_pubkey: output_script.clone(),
145+
}]};
146+
let funding_outpoint = OutPoint { txid: tx.txid(), index: 0 };
147+
(*temporary_channel_id, tx, funding_outpoint)
148+
},
149+
_ => panic!("Unexpected event"),
150+
};
151+
152+
nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
153+
nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id()));
154+
nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id()));
155+
156+
macro_rules! check_persisted_data {
157+
($node: expr, $filepath: expr) => {
158+
let bytes = loop {
159+
match std::fs::read($filepath) {
160+
Ok(bytes) => break bytes,
161+
Err(_) => continue
162+
}
163+
};
164+
let mut expected_bytes = Vec::new();
165+
assert!($node.write(&mut expected_bytes).is_ok());
166+
assert_eq!(bytes, expected_bytes);
167+
// Check that the ChannelManager reset the persistence lock's bool to
168+
// false after signalling for updates.
169+
let mutcond = Arc::clone(&$node.persistence_lock);
170+
let &(ref mtx, ref cvar) = &*mutcond;
171+
let mut guard = mtx.lock().unwrap();
172+
assert_eq!(*guard, false);
173+
mem::drop(guard);
174+
}
175+
}
176+
177+
// Check that the initial channel manager data is persisted as expected.
178+
let filepath_0 = utils::get_full_filepath("persister_0".to_string(), "manager".to_string());
179+
let filepath_1 = utils::get_full_filepath("persister_1".to_string(), "manager".to_string());
180+
check_persisted_data!(nodes[0].node, filepath_0.clone());
181+
check_persisted_data!(nodes[1].node, filepath_1.clone());
182+
183+
// Save the current bytes then trigger another update.
184+
let current_bytes = std::fs::read(filepath_0.clone()).unwrap();
185+
186+
// Force-close the channel.
187+
nodes[0].node.force_close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id());
188+
189+
// Loop until what's written on disk changes.
190+
loop {
191+
match std::fs::read(filepath_0.clone()) {
192+
Ok(bytes) => {
193+
if bytes == current_bytes { continue } else { break }
194+
},
195+
Err(_) => continue
196+
}
197+
};
198+
// Make sure the update was persisted properly.
199+
check_persisted_data!(nodes[0].node, filepath_0.clone());
200+
// TODO(val): `Drop` is never called on the FilesystemPersisters (causing their directories to linger). why?
201+
let _ = fs::remove_dir_all("persister_0");
202+
let _ = fs::remove_dir_all("persister_1");
203+
}
204+
205+
#[test]
206+
fn test_stop_bg_thread() {
207+
let nodes = create_nodes(1);
208+
let bg_processor = BackgroundProcessor::start(nodes[0].persister.clone(), nodes[0].node.clone());
209+
210+
// Stop the background processor and check that it terminated.
211+
bg_processor.stop();
212+
loop {
213+
match bg_processor.thread_terminator.send(()) {
214+
Err(_) => break, // A send operation can only fail if the receiving end is disconnected.
215+
Ok(()) => continue
216+
}
217+
}
218+
}
219+
}

lightning-persister/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
pub mod background_processor;
12
pub(crate) mod utils;
23

34
extern crate lightning;

0 commit comments

Comments
 (0)