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