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