Pipe filesystem writes in `lightning-persister` through `BufWriter`
[rust-lightning] / lightning-persister / src / lib.rs
1 //! Utilities that handle persisting Rust-Lightning data to disk via standard filesystem APIs.
2
3 #![deny(broken_intra_doc_links)]
4 #![deny(missing_docs)]
5
6 #![cfg_attr(docsrs, feature(doc_auto_cfg))]
7
8 #![cfg_attr(all(test, feature = "_bench_unstable"), feature(test))]
9 #[cfg(all(test, feature = "_bench_unstable"))] extern crate test;
10
11 mod util;
12
13 extern crate lightning;
14 extern crate bitcoin;
15 extern crate libc;
16
17 use bitcoin::hash_types::{BlockHash, Txid};
18 use bitcoin::hashes::hex::{FromHex, ToHex};
19 use lightning::routing::network_graph::NetworkGraph;
20 use crate::util::DiskWriteable;
21 use lightning::chain;
22 use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
23 use lightning::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate};
24 use lightning::chain::chainmonitor;
25 use lightning::chain::keysinterface::{Sign, KeysInterface};
26 use lightning::chain::transaction::OutPoint;
27 use lightning::ln::channelmanager::ChannelManager;
28 use lightning::util::logger::Logger;
29 use lightning::util::ser::{ReadableArgs, Writeable};
30 use std::fs;
31 use std::io::{Cursor, Error, Write};
32 use std::ops::Deref;
33 use std::path::{Path, PathBuf};
34
35 /// FilesystemPersister persists channel data on disk, where each channel's
36 /// data is stored in a file named after its funding outpoint.
37 ///
38 /// Warning: this module does the best it can with calls to persist data, but it
39 /// can only guarantee that the data is passed to the drive. It is up to the
40 /// drive manufacturers to do the actual persistence properly, which they often
41 /// don't (especially on consumer-grade hardware). Therefore, it is up to the
42 /// user to validate their entire storage stack, to ensure the writes are
43 /// persistent.
44 /// Corollary: especially when dealing with larger amounts of money, it is best
45 /// practice to have multiple channel data backups and not rely only on one
46 /// FilesystemPersister.
47 pub struct FilesystemPersister {
48         path_to_channel_data: String,
49 }
50
51 impl<Signer: Sign> DiskWriteable for ChannelMonitor<Signer> {
52         fn write_to_file<W: Write>(&self, writer: &mut W) -> Result<(), Error> {
53                 self.write(writer)
54         }
55 }
56
57 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> DiskWriteable for ChannelManager<Signer, M, T, K, F, L>
58 where
59         M::Target: chain::Watch<Signer>,
60         T::Target: BroadcasterInterface,
61         K::Target: KeysInterface<Signer=Signer>,
62         F::Target: FeeEstimator,
63         L::Target: Logger,
64 {
65         fn write_to_file<W: Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
66                 self.write(writer)
67         }
68 }
69
70 impl DiskWriteable for NetworkGraph {
71         fn write_to_file<W: Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
72                 self.write(writer)
73         }
74 }
75
76 impl FilesystemPersister {
77         /// Initialize a new FilesystemPersister and set the path to the individual channels'
78         /// files.
79         pub fn new(path_to_channel_data: String) -> Self {
80                 return Self {
81                         path_to_channel_data,
82                 }
83         }
84
85         /// Get the directory which was provided when this persister was initialized.
86         pub fn get_data_dir(&self) -> String {
87                 self.path_to_channel_data.clone()
88         }
89
90         pub(crate) fn path_to_monitor_data(&self) -> PathBuf {
91                 let mut path = PathBuf::from(self.path_to_channel_data.clone());
92                 path.push("monitors");
93                 path
94         }
95
96         /// Writes the provided `ChannelManager` to the path provided at `FilesystemPersister`
97         /// initialization, within a file called "manager".
98         pub fn persist_manager<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
99                 data_dir: String,
100                 manager: &ChannelManager<Signer, M, T, K, F, L>
101         ) -> Result<(), std::io::Error>
102         where
103                 M::Target: chain::Watch<Signer>,
104                 T::Target: BroadcasterInterface,
105                 K::Target: KeysInterface<Signer=Signer>,
106                 F::Target: FeeEstimator,
107                 L::Target: Logger,
108         {
109                 let path = PathBuf::from(data_dir);
110                 util::write_to_file(path, "manager".to_string(), manager)
111         }
112
113         /// Write the provided `NetworkGraph` to the path provided at `FilesystemPersister`
114         /// initialization, within a file called "network_graph"
115         pub fn persist_network_graph(data_dir: String, network_graph: &NetworkGraph) -> Result<(), std::io::Error> {
116                 let path = PathBuf::from(data_dir);
117                 util::write_to_file(path, "network_graph".to_string(), network_graph)
118         }
119
120         /// Read `ChannelMonitor`s from disk.
121         pub fn read_channelmonitors<Signer: Sign, K: Deref> (
122                 &self, keys_manager: K
123         ) -> Result<Vec<(BlockHash, ChannelMonitor<Signer>)>, std::io::Error>
124                 where K::Target: KeysInterface<Signer=Signer> + Sized,
125         {
126                 let path = self.path_to_monitor_data();
127                 if !Path::new(&path).exists() {
128                         return Ok(Vec::new());
129                 }
130                 let mut res = Vec::new();
131                 for file_option in fs::read_dir(path).unwrap() {
132                         let file = file_option.unwrap();
133                         let owned_file_name = file.file_name();
134                         let filename = owned_file_name.to_str();
135                         if !filename.is_some() || !filename.unwrap().is_ascii() || filename.unwrap().len() < 65 {
136                                 return Err(std::io::Error::new(
137                                         std::io::ErrorKind::InvalidData,
138                                         "Invalid ChannelMonitor file name",
139                                 ));
140                         }
141                         if filename.unwrap().ends_with(".tmp") {
142                                 // If we were in the middle of committing an new update and crashed, it should be
143                                 // safe to ignore the update - we should never have returned to the caller and
144                                 // irrevocably committed to the new state in any way.
145                                 continue;
146                         }
147
148                         let txid = Txid::from_hex(filename.unwrap().split_at(64).0);
149                         if txid.is_err() {
150                                 return Err(std::io::Error::new(
151                                         std::io::ErrorKind::InvalidData,
152                                         "Invalid tx ID in filename",
153                                 ));
154                         }
155
156                         let index = filename.unwrap().split_at(65).1.parse();
157                         if index.is_err() {
158                                 return Err(std::io::Error::new(
159                                         std::io::ErrorKind::InvalidData,
160                                         "Invalid tx index in filename",
161                                 ));
162                         }
163
164                         let contents = fs::read(&file.path())?;
165                         let mut buffer = Cursor::new(&contents);
166                         match <(BlockHash, ChannelMonitor<Signer>)>::read(&mut buffer, &*keys_manager) {
167                                 Ok((blockhash, channel_monitor)) => {
168                                         if channel_monitor.get_funding_txo().0.txid != txid.unwrap() || channel_monitor.get_funding_txo().0.index != index.unwrap() {
169                                                 return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "ChannelMonitor was stored in the wrong file"));
170                                         }
171                                         res.push((blockhash, channel_monitor));
172                                 }
173                                 Err(e) => return Err(std::io::Error::new(
174                                         std::io::ErrorKind::InvalidData,
175                                         format!("Failed to deserialize ChannelMonitor: {}", e),
176                                 ))
177                         }
178                 }
179                 Ok(res)
180         }
181 }
182
183 impl<ChannelSigner: Sign> chainmonitor::Persist<ChannelSigner> for FilesystemPersister {
184         // TODO: We really need a way for the persister to inform the user that its time to crash/shut
185         // down once these start returning failure.
186         // A PermanentFailure implies we need to shut down since we're force-closing channels without
187         // even broadcasting!
188
189         fn persist_new_channel(&self, funding_txo: OutPoint, monitor: &ChannelMonitor<ChannelSigner>, _update_id: chainmonitor::MonitorUpdateId) -> Result<(), chain::ChannelMonitorUpdateErr> {
190                 let filename = format!("{}_{}", funding_txo.txid.to_hex(), funding_txo.index);
191                 util::write_to_file(self.path_to_monitor_data(), filename, monitor)
192                         .map_err(|_| chain::ChannelMonitorUpdateErr::PermanentFailure)
193         }
194
195         fn update_persisted_channel(&self, funding_txo: OutPoint, _update: &Option<ChannelMonitorUpdate>, monitor: &ChannelMonitor<ChannelSigner>, _update_id: chainmonitor::MonitorUpdateId) -> Result<(), chain::ChannelMonitorUpdateErr> {
196                 let filename = format!("{}_{}", funding_txo.txid.to_hex(), funding_txo.index);
197                 util::write_to_file(self.path_to_monitor_data(), filename, monitor)
198                         .map_err(|_| chain::ChannelMonitorUpdateErr::PermanentFailure)
199         }
200 }
201
202 #[cfg(test)]
203 mod tests {
204         extern crate lightning;
205         extern crate bitcoin;
206         use crate::FilesystemPersister;
207         use bitcoin::blockdata::block::{Block, BlockHeader};
208         use bitcoin::hashes::hex::FromHex;
209         use bitcoin::Txid;
210         use lightning::chain::ChannelMonitorUpdateErr;
211         use lightning::chain::chainmonitor::Persist;
212         use lightning::chain::transaction::OutPoint;
213         use lightning::{check_closed_broadcast, check_closed_event, check_added_monitors};
214         use lightning::ln::features::InitFeatures;
215         use lightning::ln::functional_test_utils::*;
216         use lightning::util::events::{ClosureReason, MessageSendEventsProvider};
217         use lightning::util::test_utils;
218         use std::fs;
219         #[cfg(target_os = "windows")]
220         use {
221                 lightning::get_event_msg,
222                 lightning::ln::msgs::ChannelMessageHandler,
223         };
224
225         impl Drop for FilesystemPersister {
226                 fn drop(&mut self) {
227                         // We test for invalid directory names, so it's OK if directory removal
228                         // fails.
229                         match fs::remove_dir_all(&self.path_to_channel_data) {
230                                 Err(e) => println!("Failed to remove test persister directory: {}", e),
231                                 _ => {}
232                         }
233                 }
234         }
235
236         // Integration-test the FilesystemPersister. Test relaying a few payments
237         // and check that the persisted data is updated the appropriate number of
238         // times.
239         #[test]
240         fn test_filesystem_persister() {
241                 // Create the nodes, giving them FilesystemPersisters for data persisters.
242                 let persister_0 = FilesystemPersister::new("test_filesystem_persister_0".to_string());
243                 let persister_1 = FilesystemPersister::new("test_filesystem_persister_1".to_string());
244                 let chanmon_cfgs = create_chanmon_cfgs(2);
245                 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
246                 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);
247                 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);
248                 node_cfgs[0].chain_monitor = chain_mon_0;
249                 node_cfgs[1].chain_monitor = chain_mon_1;
250                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
251                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
252
253                 // Check that the persisted channel data is empty before any channels are
254                 // open.
255                 let mut persisted_chan_data_0 = persister_0.read_channelmonitors(nodes[0].keys_manager).unwrap();
256                 assert_eq!(persisted_chan_data_0.len(), 0);
257                 let mut persisted_chan_data_1 = persister_1.read_channelmonitors(nodes[1].keys_manager).unwrap();
258                 assert_eq!(persisted_chan_data_1.len(), 0);
259
260                 // Helper to make sure the channel is on the expected update ID.
261                 macro_rules! check_persisted_data {
262                         ($expected_update_id: expr) => {
263                                 persisted_chan_data_0 = persister_0.read_channelmonitors(nodes[0].keys_manager).unwrap();
264                                 assert_eq!(persisted_chan_data_0.len(), 1);
265                                 for (_, mon) in persisted_chan_data_0.iter() {
266                                         assert_eq!(mon.get_latest_update_id(), $expected_update_id);
267                                 }
268                                 persisted_chan_data_1 = persister_1.read_channelmonitors(nodes[1].keys_manager).unwrap();
269                                 assert_eq!(persisted_chan_data_1.len(), 1);
270                                 for (_, mon) in persisted_chan_data_1.iter() {
271                                         assert_eq!(mon.get_latest_update_id(), $expected_update_id);
272                                 }
273                         }
274                 }
275
276                 // Create some initial channel and check that a channel was persisted.
277                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
278                 check_persisted_data!(0);
279
280                 // Send a few payments and make sure the monitors are updated to the latest.
281                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
282                 check_persisted_data!(5);
283                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 4000000);
284                 check_persisted_data!(10);
285
286                 // Force close because cooperative close doesn't result in any persisted
287                 // updates.
288                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
289                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
290                 check_closed_broadcast!(nodes[0], true);
291                 check_added_monitors!(nodes[0], 1);
292
293                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
294                 assert_eq!(node_txn.len(), 1);
295
296                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
297                 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[0].clone()]});
298                 check_closed_broadcast!(nodes[1], true);
299                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
300                 check_added_monitors!(nodes[1], 1);
301
302                 // Make sure everything is persisted as expected after close.
303                 check_persisted_data!(11);
304         }
305
306         // Test that if the persister's path to channel data is read-only, writing a
307         // monitor to it results in the persister returning a PermanentFailure.
308         // Windows ignores the read-only flag for folders, so this test is Unix-only.
309         #[cfg(not(target_os = "windows"))]
310         #[test]
311         fn test_readonly_dir_perm_failure() {
312                 let persister = FilesystemPersister::new("test_readonly_dir_perm_failure".to_string());
313                 fs::create_dir_all(&persister.path_to_channel_data).unwrap();
314
315                 // Set up a dummy channel and force close. This will produce a monitor
316                 // that we can then use to test persistence.
317                 let chanmon_cfgs = create_chanmon_cfgs(2);
318                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
319                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
320                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
321                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
322                 nodes[1].node.force_close_channel(&chan.2).unwrap();
323                 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
324                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
325                 let update_map = nodes[1].chain_monitor.latest_monitor_update_id.lock().unwrap();
326                 let update_id = update_map.get(&added_monitors[0].0.to_channel_id()).unwrap();
327
328                 // Set the persister's directory to read-only, which should result in
329                 // returning a permanent failure when we then attempt to persist a
330                 // channel update.
331                 let path = &persister.path_to_channel_data;
332                 let mut perms = fs::metadata(path).unwrap().permissions();
333                 perms.set_readonly(true);
334                 fs::set_permissions(path, perms).unwrap();
335
336                 let test_txo = OutPoint {
337                         txid: Txid::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(),
338                         index: 0
339                 };
340                 match persister.persist_new_channel(test_txo, &added_monitors[0].1, update_id.2) {
341                         Err(ChannelMonitorUpdateErr::PermanentFailure) => {},
342                         _ => panic!("unexpected result from persisting new channel")
343                 }
344
345                 nodes[1].node.get_and_clear_pending_msg_events();
346                 added_monitors.clear();
347         }
348
349         // Test that if a persister's directory name is invalid, monitor persistence
350         // will fail.
351         #[cfg(target_os = "windows")]
352         #[test]
353         fn test_fail_on_open() {
354                 // Set up a dummy channel and force close. This will produce a monitor
355                 // that we can then use to test persistence.
356                 let chanmon_cfgs = create_chanmon_cfgs(2);
357                 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
358                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
359                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
360                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
361                 nodes[1].node.force_close_channel(&chan.2).unwrap();
362                 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
363                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
364                 let update_map = nodes[1].chain_monitor.latest_monitor_update_id.lock().unwrap();
365                 let update_id = update_map.get(&added_monitors[0].0.to_channel_id()).unwrap();
366
367                 // Create the persister with an invalid directory name and test that the
368                 // channel fails to open because the directories fail to be created. There
369                 // don't seem to be invalid filename characters on Unix that Rust doesn't
370                 // handle, hence why the test is Windows-only.
371                 let persister = FilesystemPersister::new(":<>/".to_string());
372
373                 let test_txo = OutPoint {
374                         txid: Txid::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(),
375                         index: 0
376                 };
377                 match persister.persist_new_channel(test_txo, &added_monitors[0].1, update_id.2) {
378                         Err(ChannelMonitorUpdateErr::PermanentFailure) => {},
379                         _ => panic!("unexpected result from persisting new channel")
380                 }
381
382                 nodes[1].node.get_and_clear_pending_msg_events();
383                 added_monitors.clear();
384         }
385 }
386
387 #[cfg(all(test, feature = "_bench_unstable"))]
388 pub mod bench {
389         use test::Bencher;
390
391         #[bench]
392         fn bench_sends(bench: &mut Bencher) {
393                 let persister_a = super::FilesystemPersister::new("bench_filesystem_persister_a".to_string());
394                 let persister_b = super::FilesystemPersister::new("bench_filesystem_persister_b".to_string());
395                 lightning::ln::channelmanager::bench::bench_two_sends(bench, persister_a, persister_b);
396         }
397 }