]> git.bitcoin.ninja Git - rust-lightning/blob - lightning-persister/src/lib.rs
Remove unnecessary todo
[rust-lightning] / lightning-persister / src / lib.rs
1 extern crate lightning;
2 extern crate bitcoin;
3 extern crate libc;
4
5 use bitcoin::hashes::hex::ToHex;
6 use lightning::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr};
7 use lightning::chain::channelmonitor;
8 use lightning::chain::keysinterface::ChannelKeys;
9 use lightning::chain::transaction::OutPoint;
10 use lightning::util::ser::{Writeable, Readable};
11 use std::fs;
12 use std::io::Error;
13 use std::path::{Path, PathBuf};
14
15 #[cfg(test)]
16 use {
17         bitcoin::{BlockHash, Txid},
18         bitcoin::hashes::hex::FromHex,
19         std::collections::HashMap,
20         std::io::Cursor
21 };
22
23 #[cfg(not(target_os = "windows"))]
24 use std::os::unix::io::AsRawFd;
25
26 /// FilesystemPersister persists channel data on disk, where each channel's
27 /// data is stored in a file named after its funding outpoint.
28 ///
29 /// Warning: this module does the best it can with calls to persist data, but it
30 /// can only guarantee that the data is passed to the drive. It is up to the
31 /// drive manufacturers to do the actual persistence properly, which they often
32 /// don't (especially on consumer-grade hardware). Therefore, it is up to the
33 /// user to validate their entire storage stack, to ensure the writes are
34 /// persistent.
35 /// Corollary: especially when dealing with larger amounts of money, it is best
36 /// practice to have multiple channel data backups and not rely only on one
37 /// FilesystemPersister.
38 pub struct FilesystemPersister {
39         path_to_channel_data: String,
40 }
41
42 trait DiskWriteable {
43         fn write(&self, writer: &mut fs::File) -> Result<(), Error>;
44 }
45
46 impl<ChanSigner: ChannelKeys + Writeable> DiskWriteable for ChannelMonitor<ChanSigner> {
47         fn write(&self, writer: &mut fs::File) -> Result<(), Error> {
48                 self.serialize_for_disk(writer)
49         }
50 }
51
52 impl FilesystemPersister {
53         /// Initialize a new FilesystemPersister and set the path to the individual channels'
54         /// files.
55         pub fn new(path_to_channel_data: String) -> Self {
56                 return Self {
57                         path_to_channel_data,
58                 }
59         }
60
61         fn get_full_filepath(&self, funding_txo: OutPoint) -> String {
62                 let mut path = PathBuf::from(&self.path_to_channel_data);
63                 path.push(format!("{}_{}", funding_txo.txid.to_hex(), funding_txo.index));
64                 path.to_str().unwrap().to_string()
65         }
66
67         // Utility to write a file to disk.
68         fn write_channel_data(&self, funding_txo: OutPoint, monitor: &dyn DiskWriteable) -> std::io::Result<()> {
69                 fs::create_dir_all(&self.path_to_channel_data)?;
70                 // Do a crazy dance with lots of fsync()s to be overly cautious here...
71                 // We never want to end up in a state where we've lost the old data, or end up using the
72                 // old data on power loss after we've returned.
73                 // The way to atomically write a file on Unix platforms is:
74                 // open(tmpname), write(tmpfile), fsync(tmpfile), close(tmpfile), rename(), fsync(dir)
75                 let filename = self.get_full_filepath(funding_txo);
76                 let tmp_filename = format!("{}.tmp", filename.clone());
77
78                 {
79                         // Note that going by rust-lang/rust@d602a6b, on MacOS it is only safe to use
80                         // rust stdlib 1.36 or higher.
81                         let mut f = fs::File::create(&tmp_filename)?;
82                         monitor.write(&mut f)?;
83                         f.sync_all()?;
84                 }
85                 fs::rename(&tmp_filename, &filename)?;
86                 // Fsync the parent directory on Unix.
87                 #[cfg(not(target_os = "windows"))]
88                 {
89                         let path = Path::new(&filename).parent().unwrap();
90                         let dir_file = fs::OpenOptions::new().read(true).open(path)?;
91                         unsafe { libc::fsync(dir_file.as_raw_fd()); }
92                 }
93                 Ok(())
94         }
95
96         #[cfg(test)]
97         fn load_channel_data<ChanSigner: ChannelKeys + Readable + Writeable>(&self) ->
98                 Result<HashMap<OutPoint, ChannelMonitor<ChanSigner>>, ChannelMonitorUpdateErr> {
99                 if let Err(_) = fs::create_dir_all(&self.path_to_channel_data) {
100                         return Err(ChannelMonitorUpdateErr::PermanentFailure);
101                 }
102                 let mut res = HashMap::new();
103                 for file_option in fs::read_dir(&self.path_to_channel_data).unwrap() {
104                         let file = file_option.unwrap();
105                         let owned_file_name = file.file_name();
106                         let filename = owned_file_name.to_str();
107                         if !filename.is_some() || !filename.unwrap().is_ascii() || filename.unwrap().len() < 65 {
108                                 return Err(ChannelMonitorUpdateErr::PermanentFailure);
109                         }
110
111                         let txid = Txid::from_hex(filename.unwrap().split_at(64).0);
112                         if txid.is_err() { return Err(ChannelMonitorUpdateErr::PermanentFailure); }
113
114                         let index = filename.unwrap().split_at(65).1.split('.').next().unwrap().parse();
115                         if index.is_err() { return Err(ChannelMonitorUpdateErr::PermanentFailure); }
116
117                         let contents = fs::read(&file.path());
118                         if contents.is_err() { return Err(ChannelMonitorUpdateErr::PermanentFailure); }
119
120                         if let Ok((_, loaded_monitor)) =
121                                 <(BlockHash, ChannelMonitor<ChanSigner>)>::read(&mut Cursor::new(&contents.unwrap())) {
122                                 res.insert(OutPoint { txid: txid.unwrap(), index: index.unwrap() }, loaded_monitor);
123                         } else {
124                                 return Err(ChannelMonitorUpdateErr::PermanentFailure);
125                         }
126                 }
127                 Ok(res)
128         }
129 }
130
131 impl<ChanSigner: ChannelKeys + Readable + Writeable + Send + Sync> channelmonitor::Persist<ChanSigner> for FilesystemPersister {
132         fn persist_new_channel(&self, funding_txo: OutPoint, monitor: &ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr> {
133                 self.write_channel_data(funding_txo, monitor)
134                   .map_err(|_| ChannelMonitorUpdateErr::PermanentFailure)
135         }
136
137         fn update_persisted_channel(&self, funding_txo: OutPoint, _update: &ChannelMonitorUpdate, monitor: &ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr> {
138                 self.write_channel_data(funding_txo, monitor)
139                   .map_err(|_| ChannelMonitorUpdateErr::PermanentFailure)
140         }
141 }
142
143 #[cfg(test)]
144 impl Drop for FilesystemPersister {
145         fn drop(&mut self) {
146                 // We test for invalid directory names, so it's OK if directory removal
147                 // fails.
148                 match fs::remove_dir_all(&self.path_to_channel_data) {
149                         Err(e) => println!("Failed to remove test persister directory: {}", e),
150                         _ => {}
151                 }
152         }
153 }
154
155 #[cfg(test)]
156 mod tests {
157         extern crate lightning;
158         extern crate bitcoin;
159         use crate::FilesystemPersister;
160         use bitcoin::blockdata::block::{Block, BlockHeader};
161         use bitcoin::hashes::hex::FromHex;
162         use bitcoin::Txid;
163         use DiskWriteable;
164         use Error;
165         use lightning::chain::channelmonitor::{Persist, ChannelMonitorUpdateErr};
166         use lightning::chain::transaction::OutPoint;
167         use lightning::{check_closed_broadcast, check_added_monitors};
168         use lightning::ln::features::InitFeatures;
169         use lightning::ln::functional_test_utils::*;
170         use lightning::ln::msgs::ErrorAction;
171         use lightning::util::enforcing_trait_impls::EnforcingChannelKeys;
172         use lightning::util::events::{MessageSendEventsProvider, MessageSendEvent};
173         use lightning::util::ser::Writer;
174         use lightning::util::test_utils;
175         use std::fs;
176         use std::io;
177         #[cfg(target_os = "windows")]
178         use {
179                 lightning::get_event_msg,
180                 lightning::ln::msgs::ChannelMessageHandler,
181         };
182
183         struct TestWriteable{}
184         impl DiskWriteable for TestWriteable {
185                 fn write(&self, writer: &mut fs::File) -> Result<(), Error> {
186                         writer.write_all(&[42; 1])
187                 }
188         }
189
190         // Integration-test the FilesystemPersister. Test relaying a few payments
191         // and check that the persisted data is updated the appropriate number of
192         // times.
193         #[test]
194         fn test_filesystem_persister() {
195                 // Create the nodes, giving them FilesystemPersisters for data persisters.
196                 let persister_0 = FilesystemPersister::new("test_filesystem_persister_0".to_string());
197                 let persister_1 = FilesystemPersister::new("test_filesystem_persister_1".to_string());
198                 let chanmon_cfgs = create_chanmon_cfgs(2);
199                 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
200                 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);
201                 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);
202                 node_cfgs[0].chain_monitor = chain_mon_0;
203                 node_cfgs[1].chain_monitor = chain_mon_1;
204                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
205                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
206
207                 // Check that the persisted channel data is empty before any channels are
208                 // open.
209                 let mut persisted_chan_data_0 = persister_0.load_channel_data::<EnforcingChannelKeys>().unwrap();
210                 assert_eq!(persisted_chan_data_0.keys().len(), 0);
211                 let mut persisted_chan_data_1 = persister_1.load_channel_data::<EnforcingChannelKeys>().unwrap();
212                 assert_eq!(persisted_chan_data_1.keys().len(), 0);
213
214                 // Helper to make sure the channel is on the expected update ID.
215                 macro_rules! check_persisted_data {
216                         ($expected_update_id: expr) => {
217                                 persisted_chan_data_0 = persister_0.load_channel_data::<EnforcingChannelKeys>().unwrap();
218                                 assert_eq!(persisted_chan_data_0.keys().len(), 1);
219                                 for mon in persisted_chan_data_0.values() {
220                                         assert_eq!(mon.get_latest_update_id(), $expected_update_id);
221                                 }
222                                 persisted_chan_data_1 = persister_1.load_channel_data::<EnforcingChannelKeys>().unwrap();
223                                 assert_eq!(persisted_chan_data_1.keys().len(), 1);
224                                 for mon in persisted_chan_data_1.values() {
225                                         assert_eq!(mon.get_latest_update_id(), $expected_update_id);
226                                 }
227                         }
228                 }
229
230                 // Create some initial channel and check that a channel was persisted.
231                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
232                 check_persisted_data!(0);
233
234                 // Send a few payments and make sure the monitors are updated to the latest.
235                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
236                 check_persisted_data!(5);
237                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 4000000, 4_000_000);
238                 check_persisted_data!(10);
239
240                 // Force close because cooperative close doesn't result in any persisted
241                 // updates.
242                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
243                 check_closed_broadcast!(nodes[0], false);
244                 check_added_monitors!(nodes[0], 1);
245
246                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
247                 assert_eq!(node_txn.len(), 1);
248
249                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
250                 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[0].clone()]}, 1);
251                 check_closed_broadcast!(nodes[1], false);
252                 check_added_monitors!(nodes[1], 1);
253
254                 // Make sure everything is persisted as expected after close.
255                 check_persisted_data!(11);
256         }
257
258         // Test that if the persister's path to channel data is read-only, writing
259         // data to it fails. Windows ignores the read-only flag for folders, so this
260         // test is Unix-only.
261         #[cfg(not(target_os = "windows"))]
262         #[test]
263         fn test_readonly_dir() {
264                 let persister = FilesystemPersister::new("test_readonly_dir_persister".to_string());
265                 let test_writeable = TestWriteable{};
266                 let test_txo = OutPoint {
267                         txid: Txid::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(),
268                         index: 0
269                 };
270                 // Create the persister's directory and set it to read-only.
271                 let path = &persister.path_to_channel_data;
272                 fs::create_dir_all(path).unwrap();
273                 let mut perms = fs::metadata(path).unwrap().permissions();
274                 perms.set_readonly(true);
275                 fs::set_permissions(path, perms).unwrap();
276                 match persister.write_channel_data(test_txo, &test_writeable) {
277                         Err(e) => assert_eq!(e.kind(), io::ErrorKind::PermissionDenied),
278                         _ => panic!("Unexpected error message")
279                 }
280         }
281
282         // Test failure to rename in the process of atomically creating a channel
283         // monitor's file. We induce this failure by making the `tmp` file a
284         // directory.
285         // Explanation: given "from" = the file being renamed, "to" = the
286         // renamee that already exists: Windows should fail because it'll fail
287         // whenever "to" is a directory, and Unix should fail because if "from" is a
288         // file, then "to" is also required to be a file.
289         #[test]
290         fn test_rename_failure() {
291                 let persister = FilesystemPersister::new("test_rename_failure".to_string());
292                 let test_writeable = TestWriteable{};
293                 let txid_hex = "8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be";
294                 let outp_idx = 0;
295                 let test_txo = OutPoint {
296                         txid: Txid::from_hex(txid_hex).unwrap(),
297                         index: outp_idx,
298                 };
299                 // Create the channel data file and make it a directory.
300                 let path = &persister.path_to_channel_data;
301                 fs::create_dir_all(format!("{}/{}_{}", path, txid_hex, outp_idx)).unwrap();
302                 match persister.write_channel_data(test_txo, &test_writeable) {
303                         Err(e) => {
304                                 #[cfg(not(target_os = "windows"))]
305                                 assert_eq!(e.kind(), io::ErrorKind::Other);
306                                 #[cfg(target_os = "windows")]
307                                 assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
308                         }
309                         _ => panic!("Unexpected error message")
310                 }
311         }
312
313         // Test failure to create the temporary file in the persistence process.
314         // We induce this failure by having the temp file already exist and be a
315         // directory.
316         #[test]
317         fn test_tmp_file_creation_failure() {
318                 let persister = FilesystemPersister::new("test_tmp_file_creation_failure".to_string());
319                 let test_writeable = TestWriteable{};
320                 let txid_hex = "8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be";
321                 let outp_idx = 0;
322                 let test_txo = OutPoint {
323                         txid: Txid::from_hex(txid_hex).unwrap(),
324                         index: outp_idx,
325                 };
326                 // Create the tmp file and make it a directory.
327                 let path = &persister.path_to_channel_data;
328                 fs::create_dir_all(format!("{}/{}_{}.tmp", path, txid_hex, outp_idx)).unwrap();
329                 match persister.write_channel_data(test_txo, &test_writeable) {
330                         Err(e) => {
331                                 #[cfg(not(target_os = "windows"))]
332                                 assert_eq!(e.kind(), io::ErrorKind::Other);
333                                 #[cfg(target_os = "windows")]
334                                 assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
335                         }
336                         _ => panic!("Unexpected error message")
337                 }
338         }
339
340         // Test that if the persister's path to channel data is read-only, writing a
341         // monitor to it results in the persister returning a PermanentFailure.
342         // Windows ignores the read-only flag for folders, so this test is Unix-only.
343         #[cfg(not(target_os = "windows"))]
344         #[test]
345         fn test_readonly_dir_perm_failure() {
346                 let persister = FilesystemPersister::new("test_readonly_dir_perm_failure".to_string());
347                 fs::create_dir_all(&persister.path_to_channel_data).unwrap();
348
349                 // Set up a dummy channel and force close. This will produce a monitor
350                 // that we can then use to test persistence.
351                 let chanmon_cfgs = create_chanmon_cfgs(2);
352                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
353                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
354                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
355                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
356                 nodes[1].node.force_close_channel(&chan.2);
357                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
358
359                 // Set the persister's directory to read-only, which should result in
360                 // returning a permanent failure when we then attempt to persist a
361                 // channel update.
362                 let path = &persister.path_to_channel_data;
363                 let mut perms = fs::metadata(path).unwrap().permissions();
364                 perms.set_readonly(true);
365                 fs::set_permissions(path, perms).unwrap();
366
367                 let test_txo = OutPoint {
368                         txid: Txid::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(),
369                         index: 0
370                 };
371                 match persister.persist_new_channel(test_txo, &added_monitors[0].1) {
372                         Err(ChannelMonitorUpdateErr::PermanentFailure) => {},
373                         _ => panic!("unexpected result from persisting new channel")
374                 }
375
376                 nodes[1].node.get_and_clear_pending_msg_events();
377                 added_monitors.clear();
378         }
379
380         // Test that if a persister's directory name is invalid, monitor persistence
381         // will fail.
382         #[cfg(target_os = "windows")]
383         #[test]
384         fn test_fail_on_open() {
385                 // Set up a dummy channel and force close. This will produce a monitor
386                 // that we can then use to test persistence.
387                 let chanmon_cfgs = create_chanmon_cfgs(2);
388                 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
389                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
390                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
391                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
392                 nodes[1].node.force_close_channel(&chan.2);
393                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
394
395                 // Create the persister with an invalid directory name and test that the
396                 // channel fails to open because the directories fail to be created. There
397                 // don't seem to be invalid filename characters on Unix that Rust doesn't
398                 // handle, hence why the test is Windows-only.
399                 let persister = FilesystemPersister::new(":<>/".to_string());
400
401                 let test_txo = OutPoint {
402                         txid: Txid::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(),
403                         index: 0
404                 };
405                 match persister.persist_new_channel(test_txo, &added_monitors[0].1) {
406                         Err(ChannelMonitorUpdateErr::PermanentFailure) => {},
407                         _ => panic!("unexpected result from persisting new channel")
408                 }
409
410                 nodes[1].node.get_and_clear_pending_msg_events();
411                 added_monitors.clear();
412         }
413 }