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