3 extern crate lightning;
7 use bitcoin::hashes::hex::ToHex;
8 use crate::util::DiskWriteable;
10 use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
11 use lightning::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr};
12 use lightning::chain::channelmonitor;
13 use lightning::chain::keysinterface::{ChannelKeys, KeysInterface};
14 use lightning::chain::transaction::OutPoint;
15 use lightning::ln::channelmanager::ChannelManager;
16 use lightning::util::logger::Logger;
17 use lightning::util::ser::Writeable;
24 lightning::util::ser::ReadableArgs,
25 bitcoin::{BlockHash, Txid},
26 bitcoin::hashes::hex::FromHex,
27 std::collections::HashMap,
31 /// FilesystemPersister persists channel data on disk, where each channel's
32 /// data is stored in a file named after its funding outpoint.
34 /// Warning: this module does the best it can with calls to persist data, but it
35 /// can only guarantee that the data is passed to the drive. It is up to the
36 /// drive manufacturers to do the actual persistence properly, which they often
37 /// don't (especially on consumer-grade hardware). Therefore, it is up to the
38 /// user to validate their entire storage stack, to ensure the writes are
40 /// Corollary: especially when dealing with larger amounts of money, it is best
41 /// practice to have multiple channel data backups and not rely only on one
42 /// FilesystemPersister.
43 pub struct FilesystemPersister {
44 path_to_channel_data: String,
47 impl<ChanSigner: ChannelKeys> DiskWriteable for ChannelMonitor<ChanSigner> {
48 fn write_to_file(&self, writer: &mut fs::File) -> Result<(), Error> {
53 impl<ChanSigner, M, T, K, F, L> DiskWriteable for ChannelManager<ChanSigner, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>
54 where ChanSigner: ChannelKeys + Writeable,
55 M: chain::Watch<Keys=ChanSigner>,
56 T: BroadcasterInterface,
57 K: KeysInterface<ChanKeySigner=ChanSigner>,
61 fn write_to_file(&self, writer: &mut fs::File) -> Result<(), std::io::Error> {
66 impl FilesystemPersister {
67 /// Initialize a new FilesystemPersister and set the path to the individual channels'
69 pub fn new(path_to_channel_data: String) -> Self {
75 pub fn get_data_dir(&self) -> String {
76 self.path_to_channel_data.clone()
79 /// Writes the provided `ChannelManager` to the path provided at `FilesystemPersister`
80 /// initialization, within a file called "manager".
81 pub fn persist_manager<ChanSigner, M, T, K, F, L>(
83 manager: &ChannelManager<ChanSigner, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>
84 ) -> Result<(), std::io::Error>
85 where ChanSigner: ChannelKeys + Writeable,
86 M: chain::Watch<Keys=ChanSigner>,
87 T: BroadcasterInterface,
88 K: KeysInterface<ChanKeySigner=ChanSigner>,
92 let mut manager_bytes = Vec::new();
93 manager.write(&mut manager_bytes).unwrap();
94 println!("VMW manager bytes being persisted: {}", manager_bytes.len());
95 match util::write_to_file(data_dir, "manager".to_string(), manager) {
97 println!("VMW: writing manager was Ok");
101 println!("VMW: errored persisting manager: {:?}", e);
108 fn load_channel_data<Keys: KeysInterface>(&self, keys: &Keys) ->
109 Result<HashMap<OutPoint, ChannelMonitor<Keys::ChanKeySigner>>, ChannelMonitorUpdateErr> {
110 if let Err(_) = fs::create_dir_all(&self.path_to_channel_data) {
111 return Err(ChannelMonitorUpdateErr::PermanentFailure);
113 let mut res = HashMap::new();
114 for file_option in fs::read_dir(&self.path_to_channel_data).unwrap() {
115 let file = file_option.unwrap();
116 let owned_file_name = file.file_name();
117 let filename = owned_file_name.to_str();
118 if !filename.is_some() || !filename.unwrap().is_ascii() || filename.unwrap().len() < 65 {
119 return Err(ChannelMonitorUpdateErr::PermanentFailure);
122 let txid = Txid::from_hex(filename.unwrap().split_at(64).0);
123 if txid.is_err() { return Err(ChannelMonitorUpdateErr::PermanentFailure); }
125 let index = filename.unwrap().split_at(65).1.split('.').next().unwrap().parse();
126 if index.is_err() { return Err(ChannelMonitorUpdateErr::PermanentFailure); }
128 let contents = fs::read(&file.path());
129 if contents.is_err() { return Err(ChannelMonitorUpdateErr::PermanentFailure); }
131 if let Ok((_, loaded_monitor)) =
132 <(BlockHash, ChannelMonitor<Keys::ChanKeySigner>)>::read(&mut Cursor::new(&contents.unwrap()), keys) {
133 res.insert(OutPoint { txid: txid.unwrap(), index: index.unwrap() }, loaded_monitor);
135 return Err(ChannelMonitorUpdateErr::PermanentFailure);
142 impl<ChanSigner: ChannelKeys + Send + Sync> channelmonitor::Persist<ChanSigner> for FilesystemPersister {
143 fn persist_new_channel(&self, funding_txo: OutPoint, monitor: &ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr> {
144 let filename = format!("{}_{}", funding_txo.txid.to_hex(), funding_txo.index);
145 util::write_to_file(self.path_to_channel_data.clone(), filename, monitor)
146 .map_err(|_| ChannelMonitorUpdateErr::PermanentFailure)
149 fn update_persisted_channel(&self, funding_txo: OutPoint, _update: &ChannelMonitorUpdate, monitor: &ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr> {
150 let filename = format!("{}_{}", funding_txo.txid.to_hex(), funding_txo.index);
151 util::write_to_file(self.path_to_channel_data.clone(), filename, monitor)
152 .map_err(|_| ChannelMonitorUpdateErr::PermanentFailure)
158 extern crate lightning;
159 extern crate bitcoin;
160 use crate::FilesystemPersister;
161 use bitcoin::blockdata::block::{Block, BlockHeader};
162 use bitcoin::hashes::hex::FromHex;
164 use lightning::chain::channelmonitor::{Persist, ChannelMonitorUpdateErr};
165 use lightning::chain::transaction::OutPoint;
166 use lightning::{check_closed_broadcast, check_added_monitors};
167 use lightning::ln::features::InitFeatures;
168 use lightning::ln::functional_test_utils::*;
169 use lightning::ln::msgs::ErrorAction;
170 use lightning::util::events::{MessageSendEventsProvider, MessageSendEvent};
171 use lightning::util::test_utils;
173 #[cfg(target_os = "windows")]
175 lightning::get_event_msg,
176 lightning::ln::msgs::ChannelMessageHandler,
179 impl Drop for FilesystemPersister {
181 // We test for invalid directory names, so it's OK if directory removal
183 match fs::remove_dir_all(&self.path_to_channel_data) {
184 Err(e) => println!("Failed to remove test persister directory: {}", e),
190 // Integration-test the FilesystemPersister. Test relaying a few payments
191 // and check that the persisted data is updated the appropriate number of
194 fn test_filesystem_persister() {
195 // Create the nodes, giving them FilesystemPersisters for data persisters.
196 let persister_0 = FilesystemPersister::new("test_filesystem_persister_0".to_string());
197 let persister_1 = FilesystemPersister::new("test_filesystem_persister_1".to_string());
198 let chanmon_cfgs = create_chanmon_cfgs(2);
199 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
200 let chain_mon_0 = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[0].chain_source), &chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator, &persister_0, &node_cfgs[0].keys_manager);
201 let chain_mon_1 = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[1].chain_source), &chanmon_cfgs[1].tx_broadcaster, &chanmon_cfgs[1].logger, &chanmon_cfgs[1].fee_estimator, &persister_1, &node_cfgs[1].keys_manager);
202 node_cfgs[0].chain_monitor = chain_mon_0;
203 node_cfgs[1].chain_monitor = chain_mon_1;
204 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
205 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
207 // Check that the persisted channel data is empty before any channels are
209 let mut persisted_chan_data_0 = persister_0.load_channel_data(nodes[0].keys_manager).unwrap();
210 assert_eq!(persisted_chan_data_0.keys().len(), 0);
211 let mut persisted_chan_data_1 = persister_1.load_channel_data(nodes[1].keys_manager).unwrap();
212 assert_eq!(persisted_chan_data_1.keys().len(), 0);
214 // Helper to make sure the channel is on the expected update ID.
215 macro_rules! check_persisted_data {
216 ($expected_update_id: expr) => {
217 persisted_chan_data_0 = persister_0.load_channel_data(nodes[0].keys_manager).unwrap();
218 assert_eq!(persisted_chan_data_0.keys().len(), 1);
219 for mon in persisted_chan_data_0.values() {
220 assert_eq!(mon.get_latest_update_id(), $expected_update_id);
222 persisted_chan_data_1 = persister_1.load_channel_data(nodes[1].keys_manager).unwrap();
223 assert_eq!(persisted_chan_data_1.keys().len(), 1);
224 for mon in persisted_chan_data_1.values() {
225 assert_eq!(mon.get_latest_update_id(), $expected_update_id);
230 // Create some initial channel and check that a channel was persisted.
231 let _ = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
232 check_persisted_data!(0);
234 // Send a few payments and make sure the monitors are updated to the latest.
235 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
236 check_persisted_data!(5);
237 send_payment(&nodes[1], &vec!(&nodes[0])[..], 4000000, 4_000_000);
238 check_persisted_data!(10);
240 // Force close because cooperative close doesn't result in any persisted
242 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
243 check_closed_broadcast!(nodes[0], false);
244 check_added_monitors!(nodes[0], 1);
246 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
247 assert_eq!(node_txn.len(), 1);
249 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
250 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[0].clone()]}, 1);
251 check_closed_broadcast!(nodes[1], false);
252 check_added_monitors!(nodes[1], 1);
254 // Make sure everything is persisted as expected after close.
255 check_persisted_data!(11);
258 // Test that if the persister's path to channel data is read-only, writing a
259 // monitor to it results in the persister returning a PermanentFailure.
260 // Windows ignores the read-only flag for folders, so this test is Unix-only.
261 #[cfg(not(target_os = "windows"))]
263 fn test_readonly_dir_perm_failure() {
264 let persister = FilesystemPersister::new("test_readonly_dir_perm_failure".to_string());
265 fs::create_dir_all(&persister.path_to_channel_data).unwrap();
267 // Set up a dummy channel and force close. This will produce a monitor
268 // that we can then use to test persistence.
269 let chanmon_cfgs = create_chanmon_cfgs(2);
270 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
271 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
272 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
273 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
274 nodes[1].node.force_close_channel(&chan.2).unwrap();
275 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
277 // Set the persister's directory to read-only, which should result in
278 // returning a permanent failure when we then attempt to persist a
280 let path = &persister.path_to_channel_data;
281 let mut perms = fs::metadata(path).unwrap().permissions();
282 perms.set_readonly(true);
283 fs::set_permissions(path, perms).unwrap();
285 let test_txo = OutPoint {
286 txid: Txid::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(),
289 match persister.persist_new_channel(test_txo, &added_monitors[0].1) {
290 Err(ChannelMonitorUpdateErr::PermanentFailure) => {},
291 _ => panic!("unexpected result from persisting new channel")
294 nodes[1].node.get_and_clear_pending_msg_events();
295 added_monitors.clear();
298 // Test that if a persister's directory name is invalid, monitor persistence
300 #[cfg(target_os = "windows")]
302 fn test_fail_on_open() {
303 // Set up a dummy channel and force close. This will produce a monitor
304 // that we can then use to test persistence.
305 let chanmon_cfgs = create_chanmon_cfgs(2);
306 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
307 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
308 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
309 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
310 nodes[1].node.force_close_channel(&chan.2).unwrap();
311 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
313 // Create the persister with an invalid directory name and test that the
314 // channel fails to open because the directories fail to be created. There
315 // don't seem to be invalid filename characters on Unix that Rust doesn't
316 // handle, hence why the test is Windows-only.
317 let persister = FilesystemPersister::new(":<>/".to_string());
319 let test_txo = OutPoint {
320 txid: Txid::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(),
323 match persister.persist_new_channel(test_txo, &added_monitors[0].1) {
324 Err(ChannelMonitorUpdateErr::PermanentFailure) => {},
325 _ => panic!("unexpected result from persisting new channel")
328 nodes[1].node.get_and_clear_pending_msg_events();
329 added_monitors.clear();