X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Fln%2Fchannelmonitor.rs;h=c8fe6f1e306fd0840226580510ef469377ba319d;hb=07db23d102738d1e84e3d2cb36101cef92e1761d;hp=514a95d27db9339edc8b78989a0477695ae102ab;hpb=3cba654e327c1fe7336d2515c7b07fb023fc52be;p=rust-lightning diff --git a/lightning/src/ln/channelmonitor.rs b/lightning/src/ln/channelmonitor.rs index 514a95d2..c8fe6f1e 100644 --- a/lightning/src/ln/channelmonitor.rs +++ b/lightning/src/ln/channelmonitor.rs @@ -19,14 +19,13 @@ use bitcoin::blockdata::opcodes; use bitcoin::consensus::encode; use bitcoin::util::hash::BitcoinHash; -use bitcoin_hashes::Hash; -use bitcoin_hashes::sha256::Hash as Sha256; -use bitcoin_hashes::hash160::Hash as Hash160; -use bitcoin_hashes::sha256d::Hash as Sha256dHash; +use bitcoin::hashes::Hash; +use bitcoin::hashes::sha256::Hash as Sha256; +use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash}; -use secp256k1::{Secp256k1,Signature}; -use secp256k1::key::{SecretKey,PublicKey}; -use secp256k1; +use bitcoin::secp256k1::{Secp256k1,Signature}; +use bitcoin::secp256k1::key::{SecretKey,PublicKey}; +use bitcoin::secp256k1; use ln::msgs::DecodeError; use ln::chan_utils; @@ -124,9 +123,11 @@ pub enum ChannelMonitorUpdateErr { TemporaryFailure, /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a /// different watchtower and cannot update with all watchtowers that were previously informed - /// of this channel). This will force-close the channel in question. + /// of this channel). This will force-close the channel in question (which will generate one + /// final ChannelMonitorUpdate which must be delivered to at least one ChannelMonitor copy). /// - /// Should also be used to indicate a failure to update the local copy of the channel monitor. + /// Should also be used to indicate a failure to update the local persisted copy of the channel + /// monitor. PermanentFailure, } @@ -153,6 +154,13 @@ impl_writeable!(HTLCUpdate, 0, { payment_hash, payment_preimage, source }); /// events to it, while also taking any add/update_monitor events and passing them to some remote /// server(s). /// +/// In general, you must always have at least one local copy in memory, which must never fail to +/// update (as it is responsible for broadcasting the latest state in case the channel is closed), +/// and then persist it to various on-disk locations. If, for some reason, the in-memory copy fails +/// to update (eg out-of-memory or some other condition), you must immediately shut down without +/// taking any further action such as writing the current state to disk. This should likely be +/// accomplished via panic!() or abort(). +/// /// Note that any updates to a channel's monitor *must* be applied to each instance of the /// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If /// an update occurs and a remote watchtower is left with old state, it may broadcast transactions @@ -281,23 +289,9 @@ impl return Err(MonitorUpdateError("Channel monitor for given key is already present")), hash_map::Entry::Vacant(e) => e, }; - match monitor.key_storage { - Storage::Local { ref funding_info, .. } => { - match funding_info { - &None => { - return Err(MonitorUpdateError("Try to update a useless monitor without funding_txo !")); - }, - &Some((ref outpoint, ref script)) => { - log_trace!(self, "Got new Channel Monitor for channel {}", log_bytes!(outpoint.to_channel_id()[..])); - self.chain_monitor.install_watch_tx(&outpoint.txid, script); - self.chain_monitor.install_watch_outpoint((outpoint.txid, outpoint.index as u32), script); - }, - } - }, - Storage::Watchtower { .. } => { - self.chain_monitor.watch_all_txn(); - } - } + log_trace!(self, "Got new Channel Monitor for channel {}", log_bytes!(monitor.funding_info.0.to_channel_id()[..])); + self.chain_monitor.install_watch_tx(&monitor.funding_info.0.txid, &monitor.funding_info.1); + self.chain_monitor.install_watch_outpoint((monitor.funding_info.0.txid, monitor.funding_info.0.index as u32), &monitor.funding_info.1); for (txid, outputs) in monitor.get_outputs_to_watch().iter() { for (idx, script) in outputs.iter().enumerate() { self.chain_monitor.install_watch_outpoint((*txid, idx as u32), script); @@ -312,8 +306,8 @@ impl { - log_trace!(self, "Updating Channel Monitor for channel {}", log_funding_info!(orig_monitor.key_storage)); - orig_monitor.update_monitor(update) + log_trace!(self, "Updating Channel Monitor for channel {}", log_funding_info!(orig_monitor)); + orig_monitor.update_monitor(update, &self.broadcaster) }, None => Err(MonitorUpdateError("No such monitor registered")) } @@ -388,54 +382,33 @@ pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3; /// solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not /// keeping bumping another claim tx to solve the outpoint. pub(crate) const ANTI_REORG_DELAY: u32 = 6; - -enum Storage { - Local { - keys: ChanSigner, - funding_key: SecretKey, - revocation_base_key: SecretKey, - htlc_base_key: SecretKey, - delayed_payment_base_key: SecretKey, - payment_base_key: SecretKey, - shutdown_pubkey: PublicKey, - funding_info: Option<(OutPoint, Script)>, - current_remote_commitment_txid: Option, - prev_remote_commitment_txid: Option, - }, - Watchtower { - revocation_base_key: PublicKey, - htlc_base_key: PublicKey, - } -} - -#[cfg(any(test, feature = "fuzztarget"))] -impl PartialEq for Storage { - fn eq(&self, other: &Self) -> bool { - match *self { - Storage::Local { ref keys, .. } => { - let k = keys; - match *other { - Storage::Local { ref keys, .. } => keys.pubkeys() == k.pubkeys(), - Storage::Watchtower { .. } => false, - } - }, - Storage::Watchtower {ref revocation_base_key, ref htlc_base_key} => { - let (rbk, hbk) = (revocation_base_key, htlc_base_key); - match *other { - Storage::Local { .. } => false, - Storage::Watchtower {ref revocation_base_key, ref htlc_base_key} => - revocation_base_key == rbk && htlc_base_key == hbk, - } - }, - } - } -} +/// Number of blocks before confirmation at which we fail back an un-relayed HTLC or at which we +/// refuse to accept a new HTLC. +/// +/// This is used for a few separate purposes: +/// 1) if we've received an MPP HTLC to us and it expires within this many blocks and we are +/// waiting on additional parts (or waiting on the preimage for any HTLC from the user), we will +/// fail this HTLC, +/// 2) if we receive an HTLC within this many blocks of its expiry (plus one to avoid a race +/// condition with the above), we will fail this HTLC without telling the user we received it, +/// 3) if we are waiting on a connection or a channel state update to send an HTLC to a peer, and +/// that HTLC expires within this many blocks, we will simply fail the HTLC instead. +/// +/// (1) is all about protecting us - we need enough time to update the channel state before we hit +/// CLTV_CLAIM_BUFFER, at which point we'd go on chain to claim the HTLC with the preimage. +/// +/// (2) is the same, but with an additional buffer to avoid accepting an HTLC which is immediately +/// in a race condition between the user connecting a block (which would fail it) and the user +/// providing us the preimage (which would claim it). +/// +/// (3) is about our counterparty - we don't want to relay an HTLC to a counterparty when they may +/// end up force-closing the channel on us to claim it. +pub(crate) const HTLC_FAIL_BACK_BUFFER: u32 = CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS; #[derive(Clone, PartialEq)] struct LocalSignedTx { /// txid of the transaction in tx, just used to make comparison faster - txid: Sha256dHash, - tx: LocalCommitmentTransaction, + txid: Txid, revocation_key: PublicKey, a_htlc_key: PublicKey, b_htlc_key: PublicKey, @@ -465,10 +438,11 @@ pub(crate) enum InputMaterial { locktime: u32, }, LocalHTLC { - witness_script: Script, - sigs: (Signature, Signature), preimage: Option, amount: u64, + }, + Funding { + funding_redeemscript: Script, } } @@ -491,13 +465,14 @@ impl Writeable for InputMaterial { writer.write_all(&byte_utils::be64_to_array(*amount))?; writer.write_all(&byte_utils::be32_to_array(*locktime))?; }, - &InputMaterial::LocalHTLC { ref witness_script, ref sigs, ref preimage, ref amount } => { + &InputMaterial::LocalHTLC { ref preimage, ref amount } => { writer.write_all(&[2; 1])?; - witness_script.write(writer)?; - sigs.0.write(writer)?; - sigs.1.write(writer)?; preimage.write(writer)?; writer.write_all(&byte_utils::be64_to_array(*amount))?; + }, + &InputMaterial::Funding { ref funding_redeemscript } => { + writer.write_all(&[3; 1])?; + funding_redeemscript.write(writer)?; } } Ok(()) @@ -536,16 +511,16 @@ impl Readable for InputMaterial { } }, 2 => { - let witness_script = Readable::read(reader)?; - let their_sig = Readable::read(reader)?; - let our_sig = Readable::read(reader)?; let preimage = Readable::read(reader)?; let amount = Readable::read(reader)?; InputMaterial::LocalHTLC { - witness_script, - sigs: (their_sig, our_sig), preimage, - amount + amount, + } + }, + 3 => { + InputMaterial::Funding { + funding_redeemscript: Readable::read(reader)?, } } _ => return Err(DecodeError::InvalidValue), @@ -586,6 +561,9 @@ enum OnchainEvent { HTLCUpdate { htlc_update: (HTLCSource, PaymentHash), }, + MaturingOutput { + descriptor: SpendableOutputDescriptor, + }, } const SERIALIZATION_VERSION: u8 = 1; @@ -595,12 +573,7 @@ const MIN_SERIALIZATION_VERSION: u8 = 1; #[derive(Clone)] pub(super) enum ChannelMonitorUpdateStep { LatestLocalCommitmentTXInfo { - // TODO: We really need to not be generating a fully-signed transaction in Channel and - // passing it here, we need to hold off so that the ChanSigner can enforce a - // only-sign-local-state-for-broadcast once invariant: commitment_tx: LocalCommitmentTransaction, - local_keys: chan_utils::TxCreationKeys, - feerate_per_kw: u64, htlc_outputs: Vec<(HTLCOutputInCommitment, Option, Option)>, }, LatestRemoteCommitmentTXInfo { @@ -616,21 +589,21 @@ pub(super) enum ChannelMonitorUpdateStep { idx: u64, secret: [u8; 32], }, - /// Indicates our channel is likely a stale version, we're closing, but this update should - /// allow us to spend what is ours if our counterparty broadcasts their latest state. - RescueRemoteCommitmentTXInfo { - their_current_per_commitment_point: PublicKey, + /// Used to indicate that the no future updates will occur, and likely that the latest local + /// commitment transaction(s) should be broadcast, as the channel has been force-closed. + ChannelForceClosed { + /// If set to false, we shouldn't broadcast the latest local commitment transaction as we + /// think we've fallen behind! + should_broadcast: bool, }, } impl Writeable for ChannelMonitorUpdateStep { fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> { match self { - &ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { ref commitment_tx, ref local_keys, ref feerate_per_kw, ref htlc_outputs } => { + &ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { ref commitment_tx, ref htlc_outputs } => { 0u8.write(w)?; commitment_tx.write(w)?; - local_keys.write(w)?; - feerate_per_kw.write(w)?; (htlc_outputs.len() as u64).write(w)?; for &(ref output, ref signature, ref source) in htlc_outputs.iter() { output.write(w)?; @@ -658,9 +631,9 @@ impl Writeable for ChannelMonitorUpdateStep { idx.write(w)?; secret.write(w)?; }, - &ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo { ref their_current_per_commitment_point } => { + &ChannelMonitorUpdateStep::ChannelForceClosed { ref should_broadcast } => { 4u8.write(w)?; - their_current_per_commitment_point.write(w)?; + should_broadcast.write(w)?; }, } Ok(()) @@ -672,8 +645,6 @@ impl Readable for ChannelMonitorUpdateStep { 0u8 => { Ok(ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { commitment_tx: Readable::read(r)?, - local_keys: Readable::read(r)?, - feerate_per_kw: Readable::read(r)?, htlc_outputs: { let len: u64 = Readable::read(r)?; let mut res = Vec::new(); @@ -711,8 +682,8 @@ impl Readable for ChannelMonitorUpdateStep { }) }, 4u8 => { - Ok(ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo { - their_current_per_commitment_point: Readable::read(r)?, + Ok(ChannelMonitorUpdateStep::ChannelForceClosed { + should_broadcast: Readable::read(r)? }) }, _ => Err(DecodeError::InvalidValue), @@ -734,25 +705,34 @@ pub struct ChannelMonitor { latest_update_id: u64, commitment_transaction_number_obscure_factor: u64, - key_storage: Storage, - their_htlc_base_key: Option, - their_delayed_payment_base_key: Option, - funding_redeemscript: Option