Skip to content

Commit 20fd381

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 45ea2ea commit 20fd381

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