0151b1e464ea6af8559e147ef19084331485f8f9
[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;
10 use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
11 use lightning::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr};
12 use lightning::chain::channelmonitor;
13 use lightning::chain::keysinterface::{Sign, KeysInterface};
14 use lightning::chain::transaction::OutPoint;
15 use lightning::ln::channelmanager::ChannelManager;
16 use lightning::util::logger::Logger;
17 use lightning::util::ser::Writeable;
18 use std::fs;
19 use std::io::Error;
20 use std::path::PathBuf;
21 use std::sync::Arc;
22
23 #[cfg(test)]
24 use {
25         lightning::util::ser::ReadableArgs,
26         bitcoin::{BlockHash, Txid},
27         bitcoin::hashes::hex::FromHex,
28         std::collections::HashMap,
29         std::io::Cursor
30 };
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, T, K, F, L> DiskWriteable for ChannelManager<Signer, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>
55 where M: chain::Watch<Signer>,
56       T: BroadcasterInterface,
57       K: KeysInterface<Signer=Signer>,
58       F: FeeEstimator,
59       L: 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         pub fn get_data_dir(&self) -> String {
76                 self.path_to_channel_data.clone()
77         }
78
79         pub(crate) fn path_to_monitor_data(&self) -> PathBuf {
80                 let mut path = PathBuf::from(self.path_to_channel_data.clone());
81                 path.push("monitors");
82                 path
83         }
84
85         /// Writes the provided `ChannelManager` to the path provided at `FilesystemPersister`
86         /// initialization, within a file called "manager".
87         pub fn persist_manager<Signer, M, T, K, F, L>(
88                 data_dir: String,
89                 manager: &ChannelManager<Signer, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>
90         ) -> Result<(), std::io::Error>
91         where Signer: Sign,
92               M: chain::Watch<Signer>,
93               T: BroadcasterInterface,
94               K: KeysInterface<Signer=Signer>,
95               F: FeeEstimator,
96               L: Logger
97         {
98                 let path = PathBuf::from(data_dir);
99                 util::write_to_file(path, "manager".to_string(), manager)
100         }
101
102         #[cfg(test)]
103         fn load_channel_data<Keys: KeysInterface>(&self, keys: &Keys) ->
104                 Result<HashMap<OutPoint, ChannelMonitor<Keys::Signer>>, ChannelMonitorUpdateErr> {
105                         if let Err(_) = fs::create_dir_all(self.path_to_monitor_data()) {
106                                 return Err(ChannelMonitorUpdateErr::PermanentFailure);
107                         }
108                         let mut res = HashMap::new();
109                         for file_option in fs::read_dir(self.path_to_monitor_data()).unwrap() {
110                                 let file = file_option.unwrap();
111                                 let owned_file_name = file.file_name();
112                                 let filename = owned_file_name.to_str();
113                                 if !filename.is_some() || !filename.unwrap().is_ascii() || filename.unwrap().len() < 65 {
114                                         return Err(ChannelMonitorUpdateErr::PermanentFailure);
115                                 }
116
117                                 let txid = Txid::from_hex(filename.unwrap().split_at(64).0);
118                                 if txid.is_err() { return Err(ChannelMonitorUpdateErr::PermanentFailure); }
119
120                                 let index = filename.unwrap().split_at(65).1.split('.').next().unwrap().parse();
121                                 if index.is_err() { return Err(ChannelMonitorUpdateErr::PermanentFailure); }
122
123                                 let contents = fs::read(&file.path());
124                                 if contents.is_err() { return Err(ChannelMonitorUpdateErr::PermanentFailure); }
125
126                                 if let Ok((_, loaded_monitor)) =
127                                         <(Option<BlockHash>, ChannelMonitor<Keys::Signer>)>::read(&mut Cursor::new(&contents.unwrap()), keys) {
128                                                 res.insert(OutPoint { txid: txid.unwrap(), index: index.unwrap() }, loaded_monitor);
129                                         } else {
130                                                 return Err(ChannelMonitorUpdateErr::PermanentFailure);
131                                         }
132                         }
133                         Ok(res)
134                 }
135 }
136
137 impl<ChannelSigner: Sign + Send + Sync> channelmonitor::Persist<ChannelSigner> for FilesystemPersister {
138         fn persist_new_channel(&self, funding_txo: OutPoint, monitor: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr> {
139                 let filename = format!("{}_{}", funding_txo.txid.to_hex(), funding_txo.index);
140                 util::write_to_file(self.path_to_monitor_data(), filename, monitor)
141                   .map_err(|_| ChannelMonitorUpdateErr::PermanentFailure)
142         }
143
144         fn update_persisted_channel(&self, funding_txo: OutPoint, _update: &ChannelMonitorUpdate, monitor: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr> {
145                 let filename = format!("{}_{}", funding_txo.txid.to_hex(), funding_txo.index);
146                 util::write_to_file(self.path_to_monitor_data(), filename, monitor)
147                   .map_err(|_| ChannelMonitorUpdateErr::PermanentFailure)
148         }
149 }
150
151 #[cfg(test)]
152 mod tests {
153         extern crate lightning;
154         extern crate bitcoin;
155         use crate::FilesystemPersister;
156         use bitcoin::blockdata::block::{Block, BlockHeader};
157         use bitcoin::hashes::hex::FromHex;
158         use bitcoin::Txid;
159         use lightning::chain::channelmonitor::{Persist, ChannelMonitorUpdateErr};
160         use lightning::chain::transaction::OutPoint;
161         use lightning::{check_closed_broadcast, check_added_monitors};
162         use lightning::ln::features::InitFeatures;
163         use lightning::ln::functional_test_utils::*;
164         use lightning::ln::msgs::ErrorAction;
165         use lightning::util::events::{MessageSendEventsProvider, MessageSendEvent};
166         use lightning::util::test_utils;
167         use std::fs;
168         #[cfg(target_os = "windows")]
169         use {
170                 lightning::get_event_msg,
171                 lightning::ln::msgs::ChannelMessageHandler,
172         };
173
174         impl Drop for FilesystemPersister {
175                 fn drop(&mut self) {
176                         // We test for invalid directory names, so it's OK if directory removal
177                         // fails.
178                         match fs::remove_dir_all(&self.path_to_channel_data) {
179                                 Err(e) => println!("Failed to remove test persister directory: {}", e),
180                                 _ => {}
181                         }
182                 }
183         }
184
185         // Integration-test the FilesystemPersister. Test relaying a few payments
186         // and check that the persisted data is updated the appropriate number of
187         // times.
188         #[test]
189         fn test_filesystem_persister() {
190                 // Create the nodes, giving them FilesystemPersisters for data persisters.
191                 let persister_0 = FilesystemPersister::new("test_filesystem_persister_0".to_string());
192                 let persister_1 = FilesystemPersister::new("test_filesystem_persister_1".to_string());
193                 let chanmon_cfgs = create_chanmon_cfgs(2);
194                 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
195                 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);
196                 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);
197                 node_cfgs[0].chain_monitor = chain_mon_0;
198                 node_cfgs[1].chain_monitor = chain_mon_1;
199                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
200                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
201
202                 // Check that the persisted channel data is empty before any channels are
203                 // open.
204                 let mut persisted_chan_data_0 = persister_0.load_channel_data(nodes[0].keys_manager).unwrap();
205                 assert_eq!(persisted_chan_data_0.keys().len(), 0);
206                 let mut persisted_chan_data_1 = persister_1.load_channel_data(nodes[1].keys_manager).unwrap();
207                 assert_eq!(persisted_chan_data_1.keys().len(), 0);
208
209                 // Helper to make sure the channel is on the expected update ID.
210                 macro_rules! check_persisted_data {
211                         ($expected_update_id: expr) => {
212                                 persisted_chan_data_0 = persister_0.load_channel_data(nodes[0].keys_manager).unwrap();
213                                 assert_eq!(persisted_chan_data_0.keys().len(), 1);
214                                 for mon in persisted_chan_data_0.values() {
215                                         assert_eq!(mon.get_latest_update_id(), $expected_update_id);
216                                 }
217                                 persisted_chan_data_1 = persister_1.load_channel_data(nodes[1].keys_manager).unwrap();
218                                 assert_eq!(persisted_chan_data_1.keys().len(), 1);
219                                 for mon in persisted_chan_data_1.values() {
220                                         assert_eq!(mon.get_latest_update_id(), $expected_update_id);
221                                 }
222                         }
223                 }
224
225                 // Create some initial channel and check that a channel was persisted.
226                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
227                 check_persisted_data!(0);
228
229                 // Send a few payments and make sure the monitors are updated to the latest.
230                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
231                 check_persisted_data!(5);
232                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 4000000, 4_000_000);
233                 check_persisted_data!(10);
234
235                 // Force close because cooperative close doesn't result in any persisted
236                 // updates.
237                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
238                 check_closed_broadcast!(nodes[0], false);
239                 check_added_monitors!(nodes[0], 1);
240
241                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
242                 assert_eq!(node_txn.len(), 1);
243
244                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
245                 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[0].clone()]}, 1);
246                 check_closed_broadcast!(nodes[1], false);
247                 check_added_monitors!(nodes[1], 1);
248
249                 // Make sure everything is persisted as expected after close.
250                 check_persisted_data!(11);
251         }
252
253         // Test that if the persister's path to channel data is read-only, writing a
254         // monitor to it results in the persister returning a PermanentFailure.
255         // Windows ignores the read-only flag for folders, so this test is Unix-only.
256         #[cfg(not(target_os = "windows"))]
257         #[test]
258         fn test_readonly_dir_perm_failure() {
259                 let persister = FilesystemPersister::new("test_readonly_dir_perm_failure".to_string());
260                 fs::create_dir_all(&persister.path_to_channel_data).unwrap();
261
262                 // Set up a dummy channel and force close. This will produce a monitor
263                 // that we can then use to test persistence.
264                 let chanmon_cfgs = create_chanmon_cfgs(2);
265                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
266                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
267                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
268                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
269                 nodes[1].node.force_close_channel(&chan.2).unwrap();
270                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
271
272                 // Set the persister's directory to read-only, which should result in
273                 // returning a permanent failure when we then attempt to persist a
274                 // channel update.
275                 let path = &persister.path_to_channel_data;
276                 let mut perms = fs::metadata(path).unwrap().permissions();
277                 perms.set_readonly(true);
278                 fs::set_permissions(path, perms).unwrap();
279
280                 let test_txo = OutPoint {
281                         txid: Txid::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(),
282                         index: 0
283                 };
284                 match persister.persist_new_channel(test_txo, &added_monitors[0].1) {
285                         Err(ChannelMonitorUpdateErr::PermanentFailure) => {},
286                         _ => panic!("unexpected result from persisting new channel")
287                 }
288
289                 nodes[1].node.get_and_clear_pending_msg_events();
290                 added_monitors.clear();
291         }
292
293         // Test that if a persister's directory name is invalid, monitor persistence
294         // will fail.
295         #[cfg(target_os = "windows")]
296         #[test]
297         fn test_fail_on_open() {
298                 // Set up a dummy channel and force close. This will produce a monitor
299                 // that we can then use to test persistence.
300                 let chanmon_cfgs = create_chanmon_cfgs(2);
301                 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
302                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
303                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
304                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
305                 nodes[1].node.force_close_channel(&chan.2).unwrap();
306                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
307
308                 // Create the persister with an invalid directory name and test that the
309                 // channel fails to open because the directories fail to be created. There
310                 // don't seem to be invalid filename characters on Unix that Rust doesn't
311                 // handle, hence why the test is Windows-only.
312                 let persister = FilesystemPersister::new(":<>/".to_string());
313
314                 let test_txo = OutPoint {
315                         txid: Txid::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(),
316                         index: 0
317                 };
318                 match persister.persist_new_channel(test_txo, &added_monitors[0].1) {
319                         Err(ChannelMonitorUpdateErr::PermanentFailure) => {},
320                         _ => panic!("unexpected result from persisting new channel")
321                 }
322
323                 nodes[1].node.get_and_clear_pending_msg_events();
324                 added_monitors.clear();
325         }
326 }