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