Expand persistence to all ChannelManagers, not just Arc-based ones
[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(all(test, feature = "unstable"), feature(test))]
7 #[cfg(all(test, feature = "unstable"))] extern crate test;
8
9 mod util;
10
11 extern crate lightning;
12 extern crate bitcoin;
13 extern crate libc;
14
15 use bitcoin::{BlockHash, Txid};
16 use bitcoin::hashes::hex::{FromHex, ToHex};
17 use crate::util::DiskWriteable;
18 use lightning::chain;
19 use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
20 use lightning::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr};
21 use lightning::chain::channelmonitor;
22 use lightning::chain::keysinterface::{Sign, KeysInterface};
23 use lightning::chain::transaction::OutPoint;
24 use lightning::ln::channelmanager::ChannelManager;
25 use lightning::util::logger::Logger;
26 use lightning::util::ser::{ReadableArgs, Writeable};
27 use std::collections::HashMap;
28 use std::fs;
29 use std::io::{Cursor, Error};
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<Signer: Sign> DiskWriteable for ChannelMonitor<Signer> {
50         fn write_to_file(&self, writer: &mut fs::File) -> Result<(), Error> {
51                 self.write(writer)
52         }
53 }
54
55 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> DiskWriteable for ChannelManager<Signer, M, T, K, F, L>
56 where M::Target: chain::Watch<Signer>,
57       T::Target: BroadcasterInterface,
58       K::Target: KeysInterface<Signer=Signer>,
59       F::Target: FeeEstimator,
60       L::Target: Logger
61 {
62         fn write_to_file(&self, writer: &mut fs::File) -> Result<(), std::io::Error> {
63                 self.write(writer)
64         }
65 }
66
67 impl FilesystemPersister {
68         /// Initialize a new FilesystemPersister and set the path to the individual channels'
69         /// files.
70         pub fn new(path_to_channel_data: String) -> Self {
71                 return Self {
72                         path_to_channel_data,
73                 }
74         }
75
76         /// Get the directory which was provided when this persister was initialized.
77         pub fn get_data_dir(&self) -> String {
78                 self.path_to_channel_data.clone()
79         }
80
81         pub(crate) fn path_to_monitor_data(&self) -> PathBuf {
82                 let mut path = PathBuf::from(self.path_to_channel_data.clone());
83                 path.push("monitors");
84                 path
85         }
86
87         /// Writes the provided `ChannelManager` to the path provided at `FilesystemPersister`
88         /// initialization, within a file called "manager".
89         pub fn persist_manager<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
90                 data_dir: String,
91                 manager: &ChannelManager<Signer, M, T, K, F, L>
92         ) -> Result<(), std::io::Error>
93         where M::Target: chain::Watch<Signer>,
94               T::Target: BroadcasterInterface,
95               K::Target: KeysInterface<Signer=Signer>,
96               F::Target: FeeEstimator,
97               L::Target: Logger
98         {
99                 let path = PathBuf::from(data_dir);
100                 util::write_to_file(path, "manager".to_string(), manager)
101         }
102
103         /// Read `ChannelMonitor`s from disk.
104         pub fn read_channelmonitors<Signer: Sign, K: Deref> (
105                 &self, keys_manager: K
106         ) -> Result<HashMap<OutPoint, (BlockHash, ChannelMonitor<Signer>)>, std::io::Error>
107              where K::Target: KeysInterface<Signer=Signer> + Sized
108         {
109                 let path = self.path_to_monitor_data();
110                 if !Path::new(&path).exists() {
111                         return Ok(HashMap::new());
112                 }
113                 let mut outpoint_to_channelmonitor = HashMap::new();
114                 for file_option in fs::read_dir(path).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(std::io::Error::new(
120                                         std::io::ErrorKind::InvalidData,
121                                         "Invalid ChannelMonitor file name",
122                                 ));
123                         }
124
125                         let txid = Txid::from_hex(filename.unwrap().split_at(64).0);
126                         if txid.is_err() {
127                                 return Err(std::io::Error::new(
128                                         std::io::ErrorKind::InvalidData,
129                                         "Invalid tx ID in filename",
130                                 ));
131                         }
132
133                         let index = filename.unwrap().split_at(65).1.parse();
134                         if index.is_err() {
135                                 return Err(std::io::Error::new(
136                                         std::io::ErrorKind::InvalidData,
137                                         "Invalid tx index in filename",
138                                 ));
139                         }
140
141                         let contents = fs::read(&file.path())?;
142                         let mut buffer = Cursor::new(&contents);
143                         match <(BlockHash, ChannelMonitor<Signer>)>::read(&mut buffer, &*keys_manager) {
144                                 Ok((blockhash, channel_monitor)) => {
145                                         outpoint_to_channelmonitor.insert(
146                                                 OutPoint { txid: txid.unwrap(), index: index.unwrap() },
147                                                 (blockhash, channel_monitor),
148                                         );
149                                 }
150                                 Err(e) => return Err(std::io::Error::new(
151                                         std::io::ErrorKind::InvalidData,
152                                         format!("Failed to deserialize ChannelMonitor: {}", e),
153                                 ))
154                         }
155                 }
156                 Ok(outpoint_to_channelmonitor)
157         }
158 }
159
160 impl<ChannelSigner: Sign> channelmonitor::Persist<ChannelSigner> for FilesystemPersister {
161         fn persist_new_channel(&self, funding_txo: OutPoint, monitor: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr> {
162                 let filename = format!("{}_{}", funding_txo.txid.to_hex(), funding_txo.index);
163                 util::write_to_file(self.path_to_monitor_data(), filename, monitor)
164                   .map_err(|_| ChannelMonitorUpdateErr::PermanentFailure)
165         }
166
167         fn update_persisted_channel(&self, funding_txo: OutPoint, _update: &ChannelMonitorUpdate, monitor: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr> {
168                 let filename = format!("{}_{}", funding_txo.txid.to_hex(), funding_txo.index);
169                 util::write_to_file(self.path_to_monitor_data(), filename, monitor)
170                   .map_err(|_| ChannelMonitorUpdateErr::PermanentFailure)
171         }
172 }
173
174 #[cfg(test)]
175 mod tests {
176         extern crate lightning;
177         extern crate bitcoin;
178         use crate::FilesystemPersister;
179         use bitcoin::blockdata::block::{Block, BlockHeader};
180         use bitcoin::hashes::hex::FromHex;
181         use bitcoin::Txid;
182         use lightning::chain::channelmonitor::{Persist, ChannelMonitorUpdateErr};
183         use lightning::chain::transaction::OutPoint;
184         use lightning::{check_closed_broadcast, check_added_monitors};
185         use lightning::ln::features::InitFeatures;
186         use lightning::ln::functional_test_utils::*;
187         use lightning::ln::msgs::ErrorAction;
188         use lightning::util::events::{MessageSendEventsProvider, MessageSendEvent};
189         use lightning::util::test_utils;
190         use std::fs;
191         #[cfg(target_os = "windows")]
192         use {
193                 lightning::get_event_msg,
194                 lightning::ln::msgs::ChannelMessageHandler,
195         };
196
197         impl Drop for FilesystemPersister {
198                 fn drop(&mut self) {
199                         // We test for invalid directory names, so it's OK if directory removal
200                         // fails.
201                         match fs::remove_dir_all(&self.path_to_channel_data) {
202                                 Err(e) => println!("Failed to remove test persister directory: {}", e),
203                                 _ => {}
204                         }
205                 }
206         }
207
208         // Integration-test the FilesystemPersister. Test relaying a few payments
209         // and check that the persisted data is updated the appropriate number of
210         // times.
211         #[test]
212         fn test_filesystem_persister() {
213                 // Create the nodes, giving them FilesystemPersisters for data persisters.
214                 let persister_0 = FilesystemPersister::new("test_filesystem_persister_0".to_string());
215                 let persister_1 = FilesystemPersister::new("test_filesystem_persister_1".to_string());
216                 let chanmon_cfgs = create_chanmon_cfgs(2);
217                 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
218                 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);
219                 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);
220                 node_cfgs[0].chain_monitor = chain_mon_0;
221                 node_cfgs[1].chain_monitor = chain_mon_1;
222                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
223                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
224
225                 // Check that the persisted channel data is empty before any channels are
226                 // open.
227                 let mut persisted_chan_data_0 = persister_0.read_channelmonitors(nodes[0].keys_manager).unwrap();
228                 assert_eq!(persisted_chan_data_0.keys().len(), 0);
229                 let mut persisted_chan_data_1 = persister_1.read_channelmonitors(nodes[1].keys_manager).unwrap();
230                 assert_eq!(persisted_chan_data_1.keys().len(), 0);
231
232                 // Helper to make sure the channel is on the expected update ID.
233                 macro_rules! check_persisted_data {
234                         ($expected_update_id: expr) => {
235                                 persisted_chan_data_0 = persister_0.read_channelmonitors(nodes[0].keys_manager).unwrap();
236                                 assert_eq!(persisted_chan_data_0.keys().len(), 1);
237                                 for (_, mon) in persisted_chan_data_0.values() {
238                                         assert_eq!(mon.get_latest_update_id(), $expected_update_id);
239                                 }
240                                 persisted_chan_data_1 = persister_1.read_channelmonitors(nodes[1].keys_manager).unwrap();
241                                 assert_eq!(persisted_chan_data_1.keys().len(), 1);
242                                 for (_, mon) in persisted_chan_data_1.values() {
243                                         assert_eq!(mon.get_latest_update_id(), $expected_update_id);
244                                 }
245                         }
246                 }
247
248                 // Create some initial channel and check that a channel was persisted.
249                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
250                 check_persisted_data!(0);
251
252                 // Send a few payments and make sure the monitors are updated to the latest.
253                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
254                 check_persisted_data!(5);
255                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 4000000, 4_000_000);
256                 check_persisted_data!(10);
257
258                 // Force close because cooperative close doesn't result in any persisted
259                 // updates.
260                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
261                 check_closed_broadcast!(nodes[0], true);
262                 check_added_monitors!(nodes[0], 1);
263
264                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
265                 assert_eq!(node_txn.len(), 1);
266
267                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
268                 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[0].clone()]});
269                 check_closed_broadcast!(nodes[1], true);
270                 check_added_monitors!(nodes[1], 1);
271
272                 // Make sure everything is persisted as expected after close.
273                 check_persisted_data!(11);
274         }
275
276         // Test that if the persister's path to channel data is read-only, writing a
277         // monitor to it results in the persister returning a PermanentFailure.
278         // Windows ignores the read-only flag for folders, so this test is Unix-only.
279         #[cfg(not(target_os = "windows"))]
280         #[test]
281         fn test_readonly_dir_perm_failure() {
282                 let persister = FilesystemPersister::new("test_readonly_dir_perm_failure".to_string());
283                 fs::create_dir_all(&persister.path_to_channel_data).unwrap();
284
285                 // Set up a dummy channel and force close. This will produce a monitor
286                 // that we can then use to test persistence.
287                 let chanmon_cfgs = create_chanmon_cfgs(2);
288                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
289                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
290                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
291                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
292                 nodes[1].node.force_close_channel(&chan.2).unwrap();
293                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
294
295                 // Set the persister's directory to read-only, which should result in
296                 // returning a permanent failure when we then attempt to persist a
297                 // channel update.
298                 let path = &persister.path_to_channel_data;
299                 let mut perms = fs::metadata(path).unwrap().permissions();
300                 perms.set_readonly(true);
301                 fs::set_permissions(path, perms).unwrap();
302
303                 let test_txo = OutPoint {
304                         txid: Txid::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(),
305                         index: 0
306                 };
307                 match persister.persist_new_channel(test_txo, &added_monitors[0].1) {
308                         Err(ChannelMonitorUpdateErr::PermanentFailure) => {},
309                         _ => panic!("unexpected result from persisting new channel")
310                 }
311
312                 nodes[1].node.get_and_clear_pending_msg_events();
313                 added_monitors.clear();
314         }
315
316         // Test that if a persister's directory name is invalid, monitor persistence
317         // will fail.
318         #[cfg(target_os = "windows")]
319         #[test]
320         fn test_fail_on_open() {
321                 // Set up a dummy channel and force close. This will produce a monitor
322                 // that we can then use to test persistence.
323                 let chanmon_cfgs = create_chanmon_cfgs(2);
324                 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
325                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
326                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
327                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
328                 nodes[1].node.force_close_channel(&chan.2).unwrap();
329                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
330
331                 // Create the persister with an invalid directory name and test that the
332                 // channel fails to open because the directories fail to be created. There
333                 // don't seem to be invalid filename characters on Unix that Rust doesn't
334                 // handle, hence why the test is Windows-only.
335                 let persister = FilesystemPersister::new(":<>/".to_string());
336
337                 let test_txo = OutPoint {
338                         txid: Txid::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(),
339                         index: 0
340                 };
341                 match persister.persist_new_channel(test_txo, &added_monitors[0].1) {
342                         Err(ChannelMonitorUpdateErr::PermanentFailure) => {},
343                         _ => panic!("unexpected result from persisting new channel")
344                 }
345
346                 nodes[1].node.get_and_clear_pending_msg_events();
347                 added_monitors.clear();
348         }
349 }
350
351 #[cfg(all(test, feature = "unstable"))]
352 pub mod bench {
353         use test::Bencher;
354
355         #[bench]
356         fn bench_sends(bench: &mut Bencher) {
357                 let persister_a = super::FilesystemPersister::new("bench_filesystem_persister_a".to_string());
358                 let persister_b = super::FilesystemPersister::new("bench_filesystem_persister_b".to_string());
359                 lightning::ln::channelmanager::bench::bench_two_sends(bench, persister_a, persister_b);
360         }
361 }