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