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