Drop separate `Locked` type on `LockableScore`
[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(ldk_bench)] extern crate criterion;
12
13 mod util;
14
15 extern crate lightning;
16 extern crate bitcoin;
17 extern crate libc;
18
19 use bitcoin::hash_types::{BlockHash, Txid};
20 use bitcoin::hashes::hex::FromHex;
21 use lightning::chain::channelmonitor::ChannelMonitor;
22 use lightning::sign::{EntropySource, SignerProvider, WriteableEcdsaChannelSigner};
23 use lightning::util::ser::{ReadableArgs, Writeable};
24 use lightning::util::persist::KVStorePersister;
25 use std::fs;
26 use std::io::Cursor;
27 use std::ops::Deref;
28 use std::path::{Path, PathBuf};
29
30 /// FilesystemPersister persists channel data on disk, where each channel's
31 /// data is stored in a file named after its funding outpoint.
32 ///
33 /// Warning: this module does the best it can with calls to persist data, but it
34 /// can only guarantee that the data is passed to the drive. It is up to the
35 /// drive manufacturers to do the actual persistence properly, which they often
36 /// don't (especially on consumer-grade hardware). Therefore, it is up to the
37 /// user to validate their entire storage stack, to ensure the writes are
38 /// persistent.
39 /// Corollary: especially when dealing with larger amounts of money, it is best
40 /// practice to have multiple channel data backups and not rely only on one
41 /// FilesystemPersister.
42 pub struct FilesystemPersister {
43         path_to_channel_data: String,
44 }
45
46 impl FilesystemPersister {
47         /// Initialize a new FilesystemPersister and set the path to the individual channels'
48         /// files.
49         pub fn new(path_to_channel_data: String) -> Self {
50                 Self {
51                         path_to_channel_data,
52                 }
53         }
54
55         /// Get the directory which was provided when this persister was initialized.
56         pub fn get_data_dir(&self) -> String {
57                 self.path_to_channel_data.clone()
58         }
59
60         /// Read `ChannelMonitor`s from disk.
61         pub fn read_channelmonitors<ES: Deref, WES: WriteableEcdsaChannelSigner, SP: SignerProvider<Signer = WES> + Sized, SPD: Deref<Target=SP>> (
62                 &self, entropy_source: ES, signer_provider: SPD
63         ) -> Result<Vec<(BlockHash, ChannelMonitor<WES>)>, std::io::Error>
64                 where
65                         ES::Target: EntropySource + 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)? {
74                         let file = file_option.unwrap();
75                         let owned_file_name = file.file_name();
76                         let filename = owned_file_name.to_str()
77                                 .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidData,
78                                         "File name is not a valid utf8 string"))?;
79                         if !filename.is_ascii() || filename.len() < 65 {
80                                 return Err(std::io::Error::new(
81                                         std::io::ErrorKind::InvalidData,
82                                         "Invalid ChannelMonitor file name",
83                                 ));
84                         }
85                         if filename.ends_with(".tmp") {
86                                 // If we were in the middle of committing an new update and crashed, it should be
87                                 // safe to ignore the update - we should never have returned to the caller and
88                                 // irrevocably committed to the new state in any way.
89                                 continue;
90                         }
91
92                         let txid: Txid = Txid::from_hex(filename.split_at(64).0)
93                                 .map_err(|_| std::io::Error::new(
94                                         std::io::ErrorKind::InvalidData,
95                                         "Invalid tx ID in filename",
96                                 ))?;
97
98                         let index: u16 = filename.split_at(65).1.parse()
99                                 .map_err(|_| std::io::Error::new(
100                                         std::io::ErrorKind::InvalidData,
101                                         "Invalid tx index in filename",
102                                 ))?;
103
104                         let contents = fs::read(&file.path())?;
105                         let mut buffer = Cursor::new(&contents);
106                         match <(BlockHash, ChannelMonitor<WES>)>::read(&mut buffer, (&*entropy_source, &*signer_provider)) {
107                                 Ok((blockhash, channel_monitor)) => {
108                                         if channel_monitor.get_funding_txo().0.txid != txid || channel_monitor.get_funding_txo().0.index != index {
109                                                 return Err(std::io::Error::new(std::io::ErrorKind::InvalidData,
110                                                                                "ChannelMonitor was stored in the wrong file"));
111                                         }
112                                         res.push((blockhash, channel_monitor));
113                                 }
114                                 Err(e) => return Err(std::io::Error::new(
115                                         std::io::ErrorKind::InvalidData,
116                                         format!("Failed to deserialize ChannelMonitor: {}", e),
117                                 ))
118                         }
119                 }
120                 Ok(res)
121         }
122 }
123
124 impl KVStorePersister for FilesystemPersister {
125         fn persist<W: Writeable>(&self, key: &str, object: &W) -> std::io::Result<()> {
126                 let mut dest_file = PathBuf::from(self.path_to_channel_data.clone());
127                 dest_file.push(key);
128                 util::write_to_file(dest_file, object)
129         }
130 }
131
132 #[cfg(test)]
133 mod tests {
134         extern crate lightning;
135         extern crate bitcoin;
136         use crate::FilesystemPersister;
137         use bitcoin::hashes::hex::FromHex;
138         use bitcoin::Txid;
139         use lightning::chain::ChannelMonitorUpdateStatus;
140         use lightning::chain::chainmonitor::Persist;
141         use lightning::chain::channelmonitor::CLOSED_CHANNEL_UPDATE_ID;
142         use lightning::chain::transaction::OutPoint;
143         use lightning::{check_closed_broadcast, check_closed_event, check_added_monitors};
144         use lightning::events::{ClosureReason, MessageSendEventsProvider};
145         use lightning::ln::functional_test_utils::*;
146         use lightning::util::test_utils;
147         use std::fs;
148         #[cfg(target_os = "windows")]
149         use {
150                 lightning::get_event_msg,
151                 lightning::ln::msgs::ChannelMessageHandler,
152         };
153
154         impl Drop for FilesystemPersister {
155                 fn drop(&mut self) {
156                         // We test for invalid directory names, so it's OK if directory removal
157                         // fails.
158                         match fs::remove_dir_all(&self.path_to_channel_data) {
159                                 Err(e) => println!("Failed to remove test persister directory: {}", e),
160                                 _ => {}
161                         }
162                 }
163         }
164
165         #[test]
166         fn test_if_monitors_is_not_dir() {
167                 let persister = FilesystemPersister::new("test_monitors_is_not_dir".to_string());
168
169                 fs::create_dir_all(&persister.path_to_channel_data).unwrap();
170                 let mut path = std::path::PathBuf::from(&persister.path_to_channel_data);
171                 path.push("monitors");
172                 fs::File::create(path).unwrap();
173
174                 let chanmon_cfgs = create_chanmon_cfgs(1);
175                 let mut node_cfgs = create_node_cfgs(1, &chanmon_cfgs);
176                 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, node_cfgs[0].keys_manager);
177                 node_cfgs[0].chain_monitor = chain_mon_0;
178                 let node_chanmgrs = create_node_chanmgrs(1, &node_cfgs, &[None]);
179                 let nodes = create_network(1, &node_cfgs, &node_chanmgrs);
180
181                 // Check that read_channelmonitors() returns error if monitors/ is not a
182                 // directory.
183                 assert!(persister.read_channelmonitors(nodes[0].keys_manager, nodes[0].keys_manager).is_err());
184         }
185
186         // Integration-test the FilesystemPersister. Test relaying a few payments
187         // and check that the persisted data is updated the appropriate number of
188         // times.
189         #[test]
190         fn test_filesystem_persister() {
191                 // Create the nodes, giving them FilesystemPersisters for data persisters.
192                 let persister_0 = FilesystemPersister::new("test_filesystem_persister_0".to_string());
193                 let persister_1 = FilesystemPersister::new("test_filesystem_persister_1".to_string());
194                 let chanmon_cfgs = create_chanmon_cfgs(2);
195                 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
196                 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);
197                 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);
198                 node_cfgs[0].chain_monitor = chain_mon_0;
199                 node_cfgs[1].chain_monitor = chain_mon_1;
200                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
201                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
202
203                 // Check that the persisted channel data is empty before any channels are
204                 // open.
205                 let mut persisted_chan_data_0 = persister_0.read_channelmonitors(nodes[0].keys_manager, nodes[0].keys_manager).unwrap();
206                 assert_eq!(persisted_chan_data_0.len(), 0);
207                 let mut persisted_chan_data_1 = persister_1.read_channelmonitors(nodes[1].keys_manager, nodes[1].keys_manager).unwrap();
208                 assert_eq!(persisted_chan_data_1.len(), 0);
209
210                 // Helper to make sure the channel is on the expected update ID.
211                 macro_rules! check_persisted_data {
212                         ($expected_update_id: expr) => {
213                                 persisted_chan_data_0 = persister_0.read_channelmonitors(nodes[0].keys_manager, nodes[0].keys_manager).unwrap();
214                                 assert_eq!(persisted_chan_data_0.len(), 1);
215                                 for (_, mon) in persisted_chan_data_0.iter() {
216                                         assert_eq!(mon.get_latest_update_id(), $expected_update_id);
217                                 }
218                                 persisted_chan_data_1 = persister_1.read_channelmonitors(nodes[1].keys_manager, nodes[1].keys_manager).unwrap();
219                                 assert_eq!(persisted_chan_data_1.len(), 1);
220                                 for (_, mon) in persisted_chan_data_1.iter() {
221                                         assert_eq!(mon.get_latest_update_id(), $expected_update_id);
222                                 }
223                         }
224                 }
225
226                 // Create some initial channel and check that a channel was persisted.
227                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1);
228                 check_persisted_data!(0);
229
230                 // Send a few payments and make sure the monitors are updated to the latest.
231                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
232                 check_persisted_data!(5);
233                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 4000000);
234                 check_persisted_data!(10);
235
236                 // Force close because cooperative close doesn't result in any persisted
237                 // updates.
238                 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
239                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
240                 check_closed_broadcast!(nodes[0], true);
241                 check_added_monitors!(nodes[0], 1);
242
243                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
244                 assert_eq!(node_txn.len(), 1);
245
246                 connect_block(&nodes[1], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[0].clone()]));
247                 check_closed_broadcast!(nodes[1], true);
248                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
249                 check_added_monitors!(nodes[1], 1);
250
251                 // Make sure everything is persisted as expected after close.
252                 check_persisted_data!(CLOSED_CHANNEL_UPDATE_ID);
253         }
254
255         // Test that if the persister's path to channel data is read-only, writing a
256         // monitor to it results in the persister returning a PermanentFailure.
257         // Windows ignores the read-only flag for folders, so this test is Unix-only.
258         #[cfg(not(target_os = "windows"))]
259         #[test]
260         fn test_readonly_dir_perm_failure() {
261                 let persister = FilesystemPersister::new("test_readonly_dir_perm_failure".to_string());
262                 fs::create_dir_all(&persister.path_to_channel_data).unwrap();
263
264                 // Set up a dummy channel and force close. This will produce a monitor
265                 // that we can then use to test persistence.
266                 let chanmon_cfgs = create_chanmon_cfgs(2);
267                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
268                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
269                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
270                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
271                 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
272                 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
273                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
274                 let update_map = nodes[1].chain_monitor.latest_monitor_update_id.lock().unwrap();
275                 let update_id = update_map.get(&added_monitors[0].0.to_channel_id()).unwrap();
276
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
279                 // channel update.
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();
284
285                 let test_txo = OutPoint {
286                         txid: Txid::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(),
287                         index: 0
288                 };
289                 match persister.persist_new_channel(test_txo, &added_monitors[0].1, update_id.2) {
290                         ChannelMonitorUpdateStatus::PermanentFailure => {},
291                         _ => panic!("unexpected result from persisting new channel")
292                 }
293
294                 nodes[1].node.get_and_clear_pending_msg_events();
295                 added_monitors.clear();
296         }
297
298         // Test that if a persister's directory name is invalid, monitor persistence
299         // will fail.
300         #[cfg(target_os = "windows")]
301         #[test]
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);
310                 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
311                 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
312                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
313                 let update_map = nodes[1].chain_monitor.latest_monitor_update_id.lock().unwrap();
314                 let update_id = update_map.get(&added_monitors[0].0.to_channel_id()).unwrap();
315
316                 // Create the persister with an invalid directory name and test that the
317                 // channel fails to open because the directories fail to be created. There
318                 // don't seem to be invalid filename characters on Unix that Rust doesn't
319                 // handle, hence why the test is Windows-only.
320                 let persister = FilesystemPersister::new(":<>/".to_string());
321
322                 let test_txo = OutPoint {
323                         txid: Txid::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(),
324                         index: 0
325                 };
326                 match persister.persist_new_channel(test_txo, &added_monitors[0].1, update_id.2) {
327                         ChannelMonitorUpdateStatus::PermanentFailure => {},
328                         _ => panic!("unexpected result from persisting new channel")
329                 }
330
331                 nodes[1].node.get_and_clear_pending_msg_events();
332                 added_monitors.clear();
333         }
334 }
335
336 #[cfg(ldk_bench)]
337 /// Benches
338 pub mod bench {
339         use criterion::Criterion;
340
341         /// Bench!
342         pub fn bench_sends(bench: &mut Criterion) {
343                 let persister_a = super::FilesystemPersister::new("bench_filesystem_persister_a".to_string());
344                 let persister_b = super::FilesystemPersister::new("bench_filesystem_persister_b".to_string());
345                 lightning::ln::channelmanager::bench::bench_two_sends(
346                         bench, "bench_filesystem_persisted_sends", persister_a, persister_b);
347         }
348 }