03e42e43e42c2b425f2ba0d830c542952883e286
[rust-lightning] / lightning-persister / src / lib.rs
1 //! Utilities that handle persisting Rust-Lightning data to disk via standard filesystem APIs.
2
3 // Prefix these with `rustdoc::` when we update our MSRV to be >= 1.52 to remove warnings.
4 #![deny(broken_intra_doc_links)]
5 #![deny(private_intra_doc_links)]
6
7 #![deny(missing_docs)]
8
9 #![cfg_attr(docsrs, feature(doc_auto_cfg))]
10
11 #![cfg_attr(all(test, feature = "_bench_unstable"), feature(test))]
12 #[cfg(all(test, feature = "_bench_unstable"))] extern crate test;
13
14 mod util;
15
16 extern crate lightning;
17 extern crate bitcoin;
18 extern crate libc;
19
20 use bitcoin::hash_types::{BlockHash, Txid};
21 use bitcoin::hashes::hex::FromHex;
22 use lightning::chain::channelmonitor::ChannelMonitor;
23 use lightning::chain::keysinterface::{Sign, KeysInterface};
24 use lightning::util::ser::{ReadableArgs, Writeable};
25 use lightning::util::persist::KVStorePersister;
26 use std::fs;
27 use std::io::Cursor;
28 use std::ops::Deref;
29 use std::path::{Path, PathBuf};
30
31 /// FilesystemPersister persists channel data on disk, where each channel's
32 /// data is stored in a file named after its funding outpoint.
33 ///
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
39 /// persistent.
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,
45 }
46
47 impl FilesystemPersister {
48         /// Initialize a new FilesystemPersister and set the path to the individual channels'
49         /// files.
50         pub fn new(path_to_channel_data: String) -> Self {
51                 return Self {
52                         path_to_channel_data,
53                 }
54         }
55
56         /// Get the directory which was provided when this persister was initialized.
57         pub fn get_data_dir(&self) -> String {
58                 self.path_to_channel_data.clone()
59         }
60
61         /// Read `ChannelMonitor`s from disk.
62         pub fn read_channelmonitors<Signer: Sign, K: Deref> (
63                 &self, keys_manager: K
64         ) -> Result<Vec<(BlockHash, ChannelMonitor<Signer>)>, std::io::Error>
65                 where K::Target: KeysInterface<Signer=Signer> + Sized,
66         {
67                 let mut path = PathBuf::from(&self.path_to_channel_data);
68                 path.push("monitors");
69                 if !Path::new(&path).exists() {
70                         return Ok(Vec::new());
71                 }
72                 let mut res = Vec::new();
73                 for file_option in fs::read_dir(path).unwrap() {
74                         let file = file_option.unwrap();
75                         let owned_file_name = file.file_name();
76                         let filename = owned_file_name.to_str();
77                         if !filename.is_some() || !filename.unwrap().is_ascii() || filename.unwrap().len() < 65 {
78                                 return Err(std::io::Error::new(
79                                         std::io::ErrorKind::InvalidData,
80                                         "Invalid ChannelMonitor file name",
81                                 ));
82                         }
83                         if filename.unwrap().ends_with(".tmp") {
84                                 // If we were in the middle of committing an new update and crashed, it should be
85                                 // safe to ignore the update - we should never have returned to the caller and
86                                 // irrevocably committed to the new state in any way.
87                                 continue;
88                         }
89
90                         let txid = Txid::from_hex(filename.unwrap().split_at(64).0);
91                         if txid.is_err() {
92                                 return Err(std::io::Error::new(
93                                         std::io::ErrorKind::InvalidData,
94                                         "Invalid tx ID in filename",
95                                 ));
96                         }
97
98                         let index = filename.unwrap().split_at(65).1.parse();
99                         if index.is_err() {
100                                 return Err(std::io::Error::new(
101                                         std::io::ErrorKind::InvalidData,
102                                         "Invalid tx index in filename",
103                                 ));
104                         }
105
106                         let contents = fs::read(&file.path())?;
107                         let mut buffer = Cursor::new(&contents);
108                         match <(BlockHash, ChannelMonitor<Signer>)>::read(&mut buffer, &*keys_manager) {
109                                 Ok((blockhash, channel_monitor)) => {
110                                         if channel_monitor.get_funding_txo().0.txid != txid.unwrap() || channel_monitor.get_funding_txo().0.index != index.unwrap() {
111                                                 return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "ChannelMonitor was stored in the wrong file"));
112                                         }
113                                         res.push((blockhash, channel_monitor));
114                                 }
115                                 Err(e) => return Err(std::io::Error::new(
116                                         std::io::ErrorKind::InvalidData,
117                                         format!("Failed to deserialize ChannelMonitor: {}", e),
118                                 ))
119                         }
120                 }
121                 Ok(res)
122         }
123 }
124
125 impl KVStorePersister for FilesystemPersister {
126         fn persist<W: Writeable>(&self, key: &str, object: &W) -> std::io::Result<()> {
127                 let mut dest_file = PathBuf::from(self.path_to_channel_data.clone());
128                 dest_file.push(key);
129                 util::write_to_file(dest_file, object)
130         }
131 }
132
133 #[cfg(test)]
134 mod tests {
135         extern crate lightning;
136         extern crate bitcoin;
137         use crate::FilesystemPersister;
138         use bitcoin::blockdata::block::{Block, BlockHeader};
139         use bitcoin::hashes::hex::FromHex;
140         use bitcoin::{Txid, TxMerkleNode};
141         use lightning::chain::ChannelMonitorUpdateErr;
142         use lightning::chain::chainmonitor::Persist;
143         use lightning::chain::transaction::OutPoint;
144         use lightning::{check_closed_broadcast, check_closed_event, check_added_monitors};
145         use lightning::ln::channelmanager;
146         use lightning::ln::functional_test_utils::*;
147         use lightning::util::events::{ClosureReason, MessageSendEventsProvider};
148         use lightning::util::test_utils;
149         use std::fs;
150         use bitcoin::hashes::Hash;
151         #[cfg(target_os = "windows")]
152         use {
153                 lightning::get_event_msg,
154                 lightning::ln::msgs::ChannelMessageHandler,
155         };
156
157         impl Drop for FilesystemPersister {
158                 fn drop(&mut self) {
159                         // We test for invalid directory names, so it's OK if directory removal
160                         // fails.
161                         match fs::remove_dir_all(&self.path_to_channel_data) {
162                                 Err(e) => println!("Failed to remove test persister directory: {}", e),
163                                 _ => {}
164                         }
165                 }
166         }
167
168         // Integration-test the FilesystemPersister. Test relaying a few payments
169         // and check that the persisted data is updated the appropriate number of
170         // times.
171         #[test]
172         fn test_filesystem_persister() {
173                 // Create the nodes, giving them FilesystemPersisters for data persisters.
174                 let persister_0 = FilesystemPersister::new("test_filesystem_persister_0".to_string());
175                 let persister_1 = FilesystemPersister::new("test_filesystem_persister_1".to_string());
176                 let chanmon_cfgs = create_chanmon_cfgs(2);
177                 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
178                 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);
179                 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);
180                 node_cfgs[0].chain_monitor = chain_mon_0;
181                 node_cfgs[1].chain_monitor = chain_mon_1;
182                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
183                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
184
185                 // Check that the persisted channel data is empty before any channels are
186                 // open.
187                 let mut persisted_chan_data_0 = persister_0.read_channelmonitors(nodes[0].keys_manager).unwrap();
188                 assert_eq!(persisted_chan_data_0.len(), 0);
189                 let mut persisted_chan_data_1 = persister_1.read_channelmonitors(nodes[1].keys_manager).unwrap();
190                 assert_eq!(persisted_chan_data_1.len(), 0);
191
192                 // Helper to make sure the channel is on the expected update ID.
193                 macro_rules! check_persisted_data {
194                         ($expected_update_id: expr) => {
195                                 persisted_chan_data_0 = persister_0.read_channelmonitors(nodes[0].keys_manager).unwrap();
196                                 assert_eq!(persisted_chan_data_0.len(), 1);
197                                 for (_, mon) in persisted_chan_data_0.iter() {
198                                         assert_eq!(mon.get_latest_update_id(), $expected_update_id);
199                                 }
200                                 persisted_chan_data_1 = persister_1.read_channelmonitors(nodes[1].keys_manager).unwrap();
201                                 assert_eq!(persisted_chan_data_1.len(), 1);
202                                 for (_, mon) in persisted_chan_data_1.iter() {
203                                         assert_eq!(mon.get_latest_update_id(), $expected_update_id);
204                                 }
205                         }
206                 }
207
208                 // Create some initial channel and check that a channel was persisted.
209                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
210                 check_persisted_data!(0);
211
212                 // Send a few payments and make sure the monitors are updated to the latest.
213                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
214                 check_persisted_data!(5);
215                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 4000000);
216                 check_persisted_data!(10);
217
218                 // Force close because cooperative close doesn't result in any persisted
219                 // updates.
220                 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
221                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
222                 check_closed_broadcast!(nodes[0], true);
223                 check_added_monitors!(nodes[0], 1);
224
225                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
226                 assert_eq!(node_txn.len(), 1);
227
228                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
229                 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[0].clone()]});
230                 check_closed_broadcast!(nodes[1], true);
231                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
232                 check_added_monitors!(nodes[1], 1);
233
234                 // Make sure everything is persisted as expected after close.
235                 check_persisted_data!(11);
236         }
237
238         // Test that if the persister's path to channel data is read-only, writing a
239         // monitor to it results in the persister returning a PermanentFailure.
240         // Windows ignores the read-only flag for folders, so this test is Unix-only.
241         #[cfg(not(target_os = "windows"))]
242         #[test]
243         fn test_readonly_dir_perm_failure() {
244                 let persister = FilesystemPersister::new("test_readonly_dir_perm_failure".to_string());
245                 fs::create_dir_all(&persister.path_to_channel_data).unwrap();
246
247                 // Set up a dummy channel and force close. This will produce a monitor
248                 // that we can then use to test persistence.
249                 let chanmon_cfgs = create_chanmon_cfgs(2);
250                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
251                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
252                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
253                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
254                 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
255                 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
256                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
257                 let update_map = nodes[1].chain_monitor.latest_monitor_update_id.lock().unwrap();
258                 let update_id = update_map.get(&added_monitors[0].0.to_channel_id()).unwrap();
259
260                 // Set the persister's directory to read-only, which should result in
261                 // returning a permanent failure when we then attempt to persist a
262                 // channel update.
263                 let path = &persister.path_to_channel_data;
264                 let mut perms = fs::metadata(path).unwrap().permissions();
265                 perms.set_readonly(true);
266                 fs::set_permissions(path, perms).unwrap();
267
268                 let test_txo = OutPoint {
269                         txid: Txid::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(),
270                         index: 0
271                 };
272                 match persister.persist_new_channel(test_txo, &added_monitors[0].1, update_id.2) {
273                         Err(ChannelMonitorUpdateErr::PermanentFailure) => {},
274                         _ => panic!("unexpected result from persisting new channel")
275                 }
276
277                 nodes[1].node.get_and_clear_pending_msg_events();
278                 added_monitors.clear();
279         }
280
281         // Test that if a persister's directory name is invalid, monitor persistence
282         // will fail.
283         #[cfg(target_os = "windows")]
284         #[test]
285         fn test_fail_on_open() {
286                 // Set up a dummy channel and force close. This will produce a monitor
287                 // that we can then use to test persistence.
288                 let chanmon_cfgs = create_chanmon_cfgs(2);
289                 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
290                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
291                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
292                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
293                 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
294                 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
295                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
296                 let update_map = nodes[1].chain_monitor.latest_monitor_update_id.lock().unwrap();
297                 let update_id = update_map.get(&added_monitors[0].0.to_channel_id()).unwrap();
298
299                 // Create the persister with an invalid directory name and test that the
300                 // channel fails to open because the directories fail to be created. There
301                 // don't seem to be invalid filename characters on Unix that Rust doesn't
302                 // handle, hence why the test is Windows-only.
303                 let persister = FilesystemPersister::new(":<>/".to_string());
304
305                 let test_txo = OutPoint {
306                         txid: Txid::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(),
307                         index: 0
308                 };
309                 match persister.persist_new_channel(test_txo, &added_monitors[0].1, update_id.2) {
310                         Err(ChannelMonitorUpdateErr::PermanentFailure) => {},
311                         _ => panic!("unexpected result from persisting new channel")
312                 }
313
314                 nodes[1].node.get_and_clear_pending_msg_events();
315                 added_monitors.clear();
316         }
317 }
318
319 #[cfg(all(test, feature = "_bench_unstable"))]
320 pub mod bench {
321         use test::Bencher;
322
323         #[bench]
324         fn bench_sends(bench: &mut Bencher) {
325                 let persister_a = super::FilesystemPersister::new("bench_filesystem_persister_a".to_string());
326                 let persister_b = super::FilesystemPersister::new("bench_filesystem_persister_b".to_string());
327                 lightning::ln::channelmanager::bench::bench_two_sends(bench, persister_a, persister_b);
328         }
329 }