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