|
| 1 | +//! Logic for persisting data from ChannelMonitors on-disk. Per-platform data |
| 2 | +//! persisters are separated into the lightning-persist-data crate. These |
| 3 | +//! objects mainly interface with the ChainMonitor when a channel monitor is |
| 4 | +//! added or updated, and when they are all synced on startup. |
| 5 | +use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr}; |
| 6 | +use chain::keysinterface::ChannelKeys; |
| 7 | +use chain::transaction::OutPoint; |
| 8 | +use util::ser::{Writeable, Readable}; |
| 9 | + |
| 10 | +use bitcoin::hash_types::{BlockHash, Txid}; |
| 11 | +use bitcoin::hashes::hex::{ToHex, FromHex}; |
| 12 | +use std::fs; |
| 13 | +use std::io::{Error, ErrorKind, Cursor}; |
| 14 | +use std::collections::HashMap; |
| 15 | +use std::marker::PhantomData; |
| 16 | + |
| 17 | +/// ChannelDataPersister is responsible for persisting channel data: this could |
| 18 | +/// mean writing once to disk, and/or uploading to several backup services. |
| 19 | +/// |
| 20 | +/// Note that for every new monitor, you **must** persist the new ChannelMonitor |
| 21 | +/// to disk/backups. And, on every update, you **must** persist either the |
| 22 | +/// ChannelMonitorUpdate or the updated monitor itself. Otherwise, there is risk |
| 23 | +/// of situations such as revoking a transaction, then crashing before this |
| 24 | +/// revocation can be persisted, then unintentionally broadcasting a revoked |
| 25 | +/// transaction and losing money. This is a risk because previous channel states |
| 26 | +/// are toxic, so it's important that whatever channel state is persisted is |
| 27 | +/// kept up-to-date. |
| 28 | +/// |
| 29 | +/// Upon calls to update_channel_data, implementers of this trait should either |
| 30 | +/// persist the ChannelMonitorUpdate or the ChannelMonitor. If an implementer |
| 31 | +/// chooses to persist the updates only, they need to make sure that all the |
| 32 | +/// updates are applied to the ChannelMonitors *before* the set of channel |
| 33 | +/// monitors is given to the ChainMonitor at startup time (e.g., all monitors |
| 34 | +/// returned by `load_channel_data` must be up-to-date). If full ChannelMonitors |
| 35 | +/// are persisted, then there is no need to persist individual updates. |
| 36 | +/// |
| 37 | +/// Note that there could be a performance tradeoff between persisting complete |
| 38 | +/// channel monitors on every update vs. persisting only updates and applying |
| 39 | +/// them in batches. |
| 40 | +/// |
| 41 | +/// Given multiple backups, situations may arise where one or more backup sources |
| 42 | +/// have fallen behind or disagree on the current state. Because these backup |
| 43 | +/// sources don't have any transaction signing/broadcasting duties and are only |
| 44 | +/// supposed to be persisting bytes of data, backup sources may be considered |
| 45 | +/// "in consensus" if a majority of them agree on the current state and are on |
| 46 | +/// the highest known commitment number. See individual methods for more info. |
| 47 | +pub trait ChannelDataPersister: Send + Sync { |
| 48 | + /// The concrete type which signs for transactions and provides access to our channel public |
| 49 | + /// keys. |
| 50 | + type Keys: ChannelKeys; |
| 51 | + |
| 52 | + /// Persist a new channel's data. The majority of backups should agree on a |
| 53 | + /// channel's state and be on the latest [`update_id`]. The data |
| 54 | + /// can be stored with any file name/path, but the identifier provided is the |
| 55 | + /// channel's outpoint. |
| 56 | + /// |
| 57 | + /// See [`ChannelMonitor::write_for_disk`] for writing out a ChannelMonitor. |
| 58 | + /// |
| 59 | + /// [`update_id`]: struct.ChannelMonitorUpdate.html#structfield.update_id |
| 60 | + /// [`ChannelMonitor::write_for_disk`]: ../../chain/channelmonitor/struct.ChannelMonitor.html#method.write_for_disk |
| 61 | + fn persist_channel_data(&self, id: OutPoint, data: &ChannelMonitor<Self::Keys>) -> Result<(), ChannelMonitorUpdateErr>; |
| 62 | + |
| 63 | + /// Update one channel's data. The provided ChannelMonitor has already |
| 64 | + /// applied the given update. |
| 65 | + /// |
| 66 | + /// Note that on every update, you **must** persist either the |
| 67 | + /// ChannelMonitorUpdate or the updated monitor itself to disk/backups. |
| 68 | + /// Otherwise, there is risk of situations such as revoking a transaction, |
| 69 | + /// then crashing before this revocation can be persisted, then |
| 70 | + /// unintentionally broadcasting a revoked transaction and losing money. This |
| 71 | + /// is a risk because previous channel states are toxic, so it's important |
| 72 | + /// that whatever channel state is persisted is kept up-to-date. |
| 73 | + /// |
| 74 | + /// If an implementer chooses to persist the updates only, they need to make |
| 75 | + /// sure that all the updates are applied to the ChannelMonitors *before* the |
| 76 | + /// set of channel monitors is given to the ChainMonitor at startup time |
| 77 | + /// (e.g., all monitors returned by [`load_channel_data`] must be up-to-date). |
| 78 | + /// If full ChannelMonitors are persisted, then there is no need to persist |
| 79 | + /// individual updates. |
| 80 | + /// |
| 81 | + /// In the case where one or more backups fail, it's likely safe to only |
| 82 | + /// require that the majority of backups succeed and agree on the latest |
| 83 | + /// [`update_id`] to succeed this method. |
| 84 | + /// |
| 85 | + /// See [`ChannelMonitor::write_for_disk`] for writing out a ChannelMonitor |
| 86 | + /// and [`ChannelMonitorUpdate::write`] for writing out an update. |
| 87 | + /// |
| 88 | + /// [`load_channel_data`]: trait.ChannelDataPersister.html#tymethod.load_channel_data |
| 89 | + /// [`update_id`]: struct.ChannelMonitorUpdate.html#structfield.update_id |
| 90 | + /// [`ChannelMonitor::write_for_disk`]: struct.ChannelMonitor.html#method.write_for_disk |
| 91 | + /// [`ChannelMonitorUpdate::write`]: struct.ChannelMonitorUpdate.html#method.write |
| 92 | + fn update_channel_data(&self, id: OutPoint, update: &ChannelMonitorUpdate, data: &ChannelMonitor<Self::Keys>) -> Result<(), ChannelMonitorUpdateErr>; |
| 93 | + |
| 94 | + /// Load the data for all channels. Generally only called on startup. You must |
| 95 | + /// ensure that the ChannelMonitors returned are on the latest [`update_id`], |
| 96 | + /// with all of the updates given in [`update_channel_data`] applied. Otherwise, |
| 97 | + /// there is a risk of broadcasting a revoked transaction and losing money. |
| 98 | + /// |
| 99 | + /// See [`ChannelMonitor::read`] for deserializing a ChannelMonitor. |
| 100 | + /// |
| 101 | + /// [`update_id`]: struct.ChannelMonitorUpdate.html#structfield.update_id |
| 102 | + /// [`update_channel_data`]: trait.ChannelDataPersister.html#tymethod.update_channel_data |
| 103 | + /// [`ChannelMonitor::read`]: trait.Readable.html |
| 104 | + fn load_channel_data(&self) -> Result<HashMap<OutPoint, ChannelMonitor<Self::Keys>>, ChannelMonitorUpdateErr>; |
| 105 | +} |
| 106 | + |
| 107 | +/// LinuxPersister can persist channel data on disk on Linux machines, where |
| 108 | +/// each channel's data is stored in a file named after its funding outpoint. |
| 109 | +pub struct LinuxPersister<ChanSigner: ChannelKeys + Readable + Writeable> { |
| 110 | + path_to_channel_data: String, |
| 111 | + phantom: PhantomData<ChanSigner>, // TODO: is there a way around this? |
| 112 | +} |
| 113 | + |
| 114 | +impl<ChanSigner: ChannelKeys + Readable + Writeable> LinuxPersister<ChanSigner> { |
| 115 | + /// Initialize a new LinuxPersister and set the path to the individual channels' |
| 116 | + /// files. |
| 117 | + pub fn new(path_to_channel_data: String) -> Self { |
| 118 | + return Self { |
| 119 | + path_to_channel_data, |
| 120 | + phantom: PhantomData, |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + fn get_full_filepath(&self, funding_txo: OutPoint) -> String { |
| 125 | + format!("{}/{}_{}", self.path_to_channel_data, funding_txo.txid.to_hex(), funding_txo.index) |
| 126 | + } |
| 127 | + |
| 128 | + fn write_channel_data(&self, funding_txo: OutPoint, monitor: &ChannelMonitor<ChanSigner>) -> std::io::Result<()> { |
| 129 | + // Do a crazy dance with lots of fsync()s to be overly cautious here... |
| 130 | + // We never want to end up in a state where we've lost the old data, or end up using the |
| 131 | + // old data on power loss after we've returned |
| 132 | + // Note that this actually *isn't* enough (at least on Linux)! We need to fsync an fd with |
| 133 | + // the containing dir, but Rust doesn't let us do that directly, sadly. TODO: Fix this with |
| 134 | + // the libc crate! |
| 135 | + let filename = self.get_full_filepath(funding_txo); |
| 136 | + let tmp_filename = filename.clone() + ".tmp"; |
| 137 | + |
| 138 | + { |
| 139 | + let mut f = fs::File::create(&tmp_filename)?; |
| 140 | + monitor.write_for_disk(&mut f)?; |
| 141 | + f.sync_all()?; |
| 142 | + } |
| 143 | + // We don't need to create a backup if didn't already have the file, but in any other case |
| 144 | + // try to create the backup and expect failure on fs::copy() if eg there's a perms issue. |
| 145 | + let need_bk = match fs::metadata(&filename) { |
| 146 | + Ok(data) => { |
| 147 | + if !data.is_file() { return Err(Error::new(ErrorKind::InvalidInput, "Filename given was not a file")); } |
| 148 | + true |
| 149 | + }, |
| 150 | + Err(e) => match e.kind() { |
| 151 | + std::io::ErrorKind::NotFound => false, |
| 152 | + _ => true, |
| 153 | + } |
| 154 | + }; |
| 155 | + let bk_filename = filename.clone() + ".bk"; |
| 156 | + if need_bk { |
| 157 | + fs::copy(&filename, &bk_filename)?; |
| 158 | + { |
| 159 | + let f = fs::File::open(&bk_filename)?; |
| 160 | + f.sync_all()?; |
| 161 | + } |
| 162 | + } |
| 163 | + fs::rename(&tmp_filename, &filename)?; |
| 164 | + { |
| 165 | + let f = fs::File::open(&filename)?; |
| 166 | + f.sync_all()?; |
| 167 | + } |
| 168 | + if need_bk { |
| 169 | + fs::remove_file(&bk_filename)?; |
| 170 | + } |
| 171 | + Ok(()) |
| 172 | + } |
| 173 | +} |
| 174 | + |
| 175 | +impl<ChanSigner: ChannelKeys + Readable + Writeable + Send + Sync> ChannelDataPersister for LinuxPersister<ChanSigner> { |
| 176 | + type Keys = ChanSigner; |
| 177 | + |
| 178 | + fn persist_channel_data(&self, funding_txo: OutPoint, monitor: &ChannelMonitor<Self::Keys>) -> Result<(), ChannelMonitorUpdateErr> { |
| 179 | + match self.write_channel_data(funding_txo, monitor) { |
| 180 | + Ok(_) => Ok(()), |
| 181 | + Err(_) => Err(ChannelMonitorUpdateErr::TemporaryFailure) |
| 182 | + } |
| 183 | + } |
| 184 | + |
| 185 | + fn update_channel_data(&self, funding_txo: OutPoint, _update: &ChannelMonitorUpdate, monitor: &ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr> { |
| 186 | + match self.write_channel_data(funding_txo, monitor) { |
| 187 | + Ok(_) => Ok(()), |
| 188 | + Err(_) => Err(ChannelMonitorUpdateErr::TemporaryFailure) |
| 189 | + } |
| 190 | + } |
| 191 | + |
| 192 | + fn load_channel_data(&self) -> Result<HashMap<OutPoint, ChannelMonitor<ChanSigner>>, ChannelMonitorUpdateErr> { |
| 193 | + if let Err(_) = fs::create_dir_all(&self.path_to_channel_data) { |
| 194 | + return Err(ChannelMonitorUpdateErr::TemporaryFailure); |
| 195 | + } |
| 196 | + let mut res = HashMap::new(); |
| 197 | + for file_option in fs::read_dir(&self.path_to_channel_data).unwrap() { |
| 198 | + let mut loaded = false; |
| 199 | + let file = file_option.unwrap(); |
| 200 | + if let Some(filename) = file.file_name().to_str() { |
| 201 | + if filename.is_ascii() && filename.len() > 65 { |
| 202 | + if let Ok(txid) = Txid::from_hex(filename.split_at(64).0) { |
| 203 | + if let Ok(index) = filename.split_at(65).1.split('.').next().unwrap().parse() { |
| 204 | + if let Ok(contents) = fs::read(&file.path()) { |
| 205 | + if let Ok((_, loaded_monitor)) = <(BlockHash, ChannelMonitor<ChanSigner>)>::read(&mut Cursor::new(&contents)) { |
| 206 | + res.insert(OutPoint { txid, index }, loaded_monitor); |
| 207 | + loaded = true; |
| 208 | + } |
| 209 | + } |
| 210 | + } |
| 211 | + } |
| 212 | + } |
| 213 | + } |
| 214 | + if !loaded { |
| 215 | + // TODO(val): this should prob error not just print something |
| 216 | + println!("WARNING: Failed to read one of the channel monitor storage files! Check perms!"); |
| 217 | + } |
| 218 | + } |
| 219 | + Ok(res) |
| 220 | + } |
| 221 | +} |
0 commit comments