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