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