X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Fchain%2Fchannelmonitor.rs;h=b89c58646fbfd960ccf98a5736fc4d300b26db8f;hb=ab0739e3ea5df4552cb77d051b7625349e222229;hp=a0f5eb71d7b3fdf69ef076183fdb1ccc76ff0fc4;hpb=a8038a8234b70bc261f633a9e2b40adebebcd8d4;p=rust-lightning diff --git a/lightning/src/chain/channelmonitor.rs b/lightning/src/chain/channelmonitor.rs index a0f5eb71..b89c5864 100644 --- a/lightning/src/chain/channelmonitor.rs +++ b/lightning/src/chain/channelmonitor.rs @@ -37,9 +37,9 @@ use ln::{PaymentHash, PaymentPreimage}; use ln::msgs::DecodeError; use ln::chan_utils; use ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLCType, ChannelTransactionParameters, HolderCommitmentTransaction}; -use ln::channelmanager::{BestBlock, HTLCSource}; +use ln::channelmanager::HTLCSource; use chain; -use chain::WatchedOutput; +use chain::{BestBlock, WatchedOutput}; use chain::chaininterface::{BroadcasterInterface, FeeEstimator}; use chain::transaction::{OutPoint, TransactionData}; use chain::keysinterface::{SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, Sign, KeysInterface}; @@ -52,11 +52,10 @@ use util::byte_utils; use util::events::Event; use prelude::*; -use std::collections::{HashMap, HashSet}; use core::{cmp, mem}; -use std::io::Error; +use io::{self, Error}; use core::ops::Deref; -use std::sync::Mutex; +use sync::Mutex; /// An update generated by the underlying Channel itself which contains some new information the /// ChannelMonitor should be made aware of. @@ -89,33 +88,35 @@ pub struct ChannelMonitorUpdate { pub const CLOSED_CHANNEL_UPDATE_ID: u64 = core::u64::MAX; impl Writeable for ChannelMonitorUpdate { - fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> { + fn write(&self, w: &mut W) -> Result<(), io::Error> { write_ver_prefix!(w, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION); self.update_id.write(w)?; (self.updates.len() as u64).write(w)?; for update_step in self.updates.iter() { update_step.write(w)?; } - write_tlv_fields!(w, {}, {}); + write_tlv_fields!(w, {}); Ok(()) } } impl Readable for ChannelMonitorUpdate { - fn read(r: &mut R) -> Result { + fn read(r: &mut R) -> Result { let _ver = read_ver_prefix!(r, SERIALIZATION_VERSION); let update_id: u64 = Readable::read(r)?; let len: u64 = Readable::read(r)?; let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::core::mem::size_of::())); for _ in 0..len { - updates.push(Readable::read(r)?); + if let Some(upd) = MaybeReadable::read(r)? { + updates.push(upd); + } } - read_tlv_fields!(r, {}, {}); + read_tlv_fields!(r, {}); Ok(Self { update_id, updates }) } } /// An error enum representing a failure to persist a channel monitor update. -#[derive(Clone, Debug)] +#[derive(Clone, Copy, Debug, PartialEq)] pub enum ChannelMonitorUpdateErr { /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of /// our state failed, but is expected to succeed at some point in the future). @@ -189,8 +190,8 @@ pub enum MonitorEvent { /// A monitor event containing an HTLCUpdate. HTLCEvent(HTLCUpdate), - /// A monitor event that the Channel's commitment transaction was broadcasted. - CommitmentTxBroadcasted(OutPoint), + /// A monitor event that the Channel's commitment transaction was confirmed. + CommitmentTxConfirmed(OutPoint), } /// Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on @@ -200,14 +201,15 @@ pub enum MonitorEvent { pub struct HTLCUpdate { pub(crate) payment_hash: PaymentHash, pub(crate) payment_preimage: Option, - pub(crate) source: HTLCSource + pub(crate) source: HTLCSource, + pub(crate) onchain_value_satoshis: Option, } impl_writeable_tlv_based!(HTLCUpdate, { - (0, payment_hash), - (2, source), -}, { - (4, payment_preimage) -}, {}); + (0, payment_hash, required), + (1, onchain_value_satoshis, option), + (2, source, required), + (4, payment_preimage, option), +}); /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction, /// instead claiming it in its own individual transaction. @@ -230,8 +232,13 @@ pub(crate) const CLTV_CLAIM_BUFFER: u32 = 18; /// with at worst this delay, so we are not only using this value as a mercy for them but also /// us as a safeguard to delay with enough time. pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3; -/// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding inbound -/// HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us losing money. +/// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding +/// inbound HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us +/// losing money. +/// +/// Note that this is a library-wide security assumption. If a reorg deeper than this number of +/// blocks occurs, counterparties may be able to steal funds or claims made by and balances exposed +/// by a [`ChannelMonitor`] may be incorrect. // We also use this delay to be sure we can remove our in-flight claim txn from bump candidates buffer. // It may cause spurious generation of bumped claim txn but that's alright given the outpoint is already // solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not @@ -270,79 +277,70 @@ struct HolderSignedTx { b_htlc_key: PublicKey, delayed_payment_key: PublicKey, per_commitment_point: PublicKey, - feerate_per_kw: u32, htlc_outputs: Vec<(HTLCOutputInCommitment, Option, Option)>, + to_self_value_sat: u64, + feerate_per_kw: u32, } impl_writeable_tlv_based!(HolderSignedTx, { - (0, txid), - (2, revocation_key), - (4, a_htlc_key), - (6, b_htlc_key), - (8, delayed_payment_key), - (10, per_commitment_point), - (12, feerate_per_kw), -}, {}, { - (14, htlc_outputs) + (0, txid, required), + // Note that this is filled in with data from OnchainTxHandler if it's missing. + // For HolderSignedTx objects serialized with 0.0.100+, this should be filled in. + (1, to_self_value_sat, (default_value, u64::max_value())), + (2, revocation_key, required), + (4, a_htlc_key, required), + (6, b_htlc_key, required), + (8, delayed_payment_key, required), + (10, per_commitment_point, required), + (12, feerate_per_kw, required), + (14, htlc_outputs, vec_type) }); -/// We use this to track counterparty commitment transactions and htlcs outputs and -/// use it to generate any justice or 2nd-stage preimage/timeout transactions. +/// We use this to track static counterparty commitment transaction data and to generate any +/// justice or 2nd-stage preimage/timeout transactions. #[derive(PartialEq)] -struct CounterpartyCommitmentTransaction { +struct CounterpartyCommitmentParameters { counterparty_delayed_payment_base_key: PublicKey, counterparty_htlc_base_key: PublicKey, on_counterparty_tx_csv: u16, - per_htlc: HashMap> } -impl Writeable for CounterpartyCommitmentTransaction { - fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> { - w.write_all(&byte_utils::be64_to_array(self.per_htlc.len() as u64))?; - for (ref txid, ref htlcs) in self.per_htlc.iter() { - w.write_all(&txid[..])?; - w.write_all(&byte_utils::be64_to_array(htlcs.len() as u64))?; - for &ref htlc in htlcs.iter() { - htlc.write(w)?; - } - } +impl Writeable for CounterpartyCommitmentParameters { + fn write(&self, w: &mut W) -> Result<(), io::Error> { + w.write_all(&byte_utils::be64_to_array(0))?; write_tlv_fields!(w, { - (0, self.counterparty_delayed_payment_base_key), - (2, self.counterparty_htlc_base_key), - (4, self.on_counterparty_tx_csv), - }, {}); + (0, self.counterparty_delayed_payment_base_key, required), + (2, self.counterparty_htlc_base_key, required), + (4, self.on_counterparty_tx_csv, required), + }); Ok(()) } } -impl Readable for CounterpartyCommitmentTransaction { - fn read(r: &mut R) -> Result { +impl Readable for CounterpartyCommitmentParameters { + fn read(r: &mut R) -> Result { let counterparty_commitment_transaction = { + // Versions prior to 0.0.100 had some per-HTLC state stored here, which is no longer + // used. Read it for compatibility. let per_htlc_len: u64 = Readable::read(r)?; - let mut per_htlc = HashMap::with_capacity(cmp::min(per_htlc_len as usize, MAX_ALLOC_SIZE / 64)); for _ in 0..per_htlc_len { - let txid: Txid = Readable::read(r)?; + let _txid: Txid = Readable::read(r)?; let htlcs_count: u64 = Readable::read(r)?; - let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32)); for _ in 0..htlcs_count { - let htlc = Readable::read(r)?; - htlcs.push(htlc); - } - if let Some(_) = per_htlc.insert(txid, htlcs) { - return Err(DecodeError::InvalidValue); + let _htlc: HTLCOutputInCommitment = Readable::read(r)?; } } + let mut counterparty_delayed_payment_base_key = OptionDeserWrapper(None); let mut counterparty_htlc_base_key = OptionDeserWrapper(None); let mut on_counterparty_tx_csv: u16 = 0; read_tlv_fields!(r, { - (0, counterparty_delayed_payment_base_key), - (2, counterparty_htlc_base_key), - (4, on_counterparty_tx_csv), - }, {}); - CounterpartyCommitmentTransaction { + (0, counterparty_delayed_payment_base_key, required), + (2, counterparty_htlc_base_key, required), + (4, on_counterparty_tx_csv, required), + }); + CounterpartyCommitmentParameters { counterparty_delayed_payment_base_key: counterparty_delayed_payment_base_key.0.unwrap(), counterparty_htlc_base_key: counterparty_htlc_base_key.0.unwrap(), on_counterparty_tx_csv, - per_htlc, } }; Ok(counterparty_commitment_transaction) @@ -363,18 +361,27 @@ struct OnchainEventEntry { impl OnchainEventEntry { fn confirmation_threshold(&self) -> u32 { let mut conf_threshold = self.height + ANTI_REORG_DELAY - 1; - if let OnchainEvent::MaturingOutput { - descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor) - } = self.event { - // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means - // it's broadcastable when we see the previous block. - conf_threshold = cmp::max(conf_threshold, self.height + descriptor.to_self_delay as u32 - 1); + match self.event { + OnchainEvent::MaturingOutput { + descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor) + } => { + // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means + // it's broadcastable when we see the previous block. + conf_threshold = cmp::max(conf_threshold, self.height + descriptor.to_self_delay as u32 - 1); + }, + OnchainEvent::FundingSpendConfirmation { on_local_output_csv: Some(csv), .. } | + OnchainEvent::HTLCSpendConfirmation { on_to_local_output_csv: Some(csv), .. } => { + // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means + // it's broadcastable when we see the previous block. + conf_threshold = cmp::max(conf_threshold, self.height + csv as u32 - 1); + }, + _ => {}, } conf_threshold } - fn has_reached_confirmation_threshold(&self, height: u32) -> bool { - height >= self.confirmation_threshold() + fn has_reached_confirmation_threshold(&self, best_block: &BestBlock) -> bool { + best_block.height() >= self.confirmation_threshold() } } @@ -382,33 +389,98 @@ impl OnchainEventEntry { /// once they mature to enough confirmations (ANTI_REORG_DELAY) #[derive(PartialEq)] enum OnchainEvent { - /// HTLC output getting solved by a timeout, at maturation we pass upstream payment source information to solve - /// inbound HTLC in backward channel. Note, in case of preimage, we pass info to upstream without delay as we can - /// only win from it, so it's never an OnchainEvent + /// An outbound HTLC failing after a transaction is confirmed. Used + /// * when an outbound HTLC output is spent by us after the HTLC timed out + /// * an outbound HTLC which was not present in the commitment transaction which appeared + /// on-chain (either because it was not fully committed to or it was dust). + /// Note that this is *not* used for preimage claims, as those are passed upstream immediately, + /// appearing only as an `HTLCSpendConfirmation`, below. HTLCUpdate { source: HTLCSource, payment_hash: PaymentHash, + onchain_value_satoshis: Option, + /// None in the second case, above, ie when there is no relevant output in the commitment + /// transaction which appeared on chain. + input_idx: Option, }, MaturingOutput { descriptor: SpendableOutputDescriptor, }, + /// A spend of the funding output, either a commitment transaction or a cooperative closing + /// transaction. + FundingSpendConfirmation { + /// The CSV delay for the output of the funding spend transaction (implying it is a local + /// commitment transaction, and this is the delay on the to_self output). + on_local_output_csv: Option, + }, + /// A spend of a commitment transaction HTLC output, set in the cases where *no* `HTLCUpdate` + /// is constructed. This is used when + /// * an outbound HTLC is claimed by our counterparty with a preimage, causing us to + /// immediately claim the HTLC on the inbound edge and track the resolution here, + /// * an inbound HTLC is claimed by our counterparty (with a timeout), + /// * an inbound HTLC is claimed by us (with a preimage). + /// * a revoked-state HTLC transaction was broadcasted, which was claimed by the revocation + /// signature. + HTLCSpendConfirmation { + input_idx: u32, + /// If the claim was made by either party with a preimage, this is filled in + preimage: Option, + /// If the claim was made by us on an inbound HTLC against a local commitment transaction, + /// we set this to the output CSV value which we will have to wait until to spend the + /// output (and generate a SpendableOutput event). + on_to_local_output_csv: Option, + }, } -impl_writeable_tlv_based!(OnchainEventEntry, { - (0, txid), - (2, height), - (4, event), -}, {}, {}); +impl Writeable for OnchainEventEntry { + fn write(&self, writer: &mut W) -> Result<(), io::Error> { + write_tlv_fields!(writer, { + (0, self.txid, required), + (2, self.height, required), + (4, self.event, required), + }); + Ok(()) + } +} + +impl MaybeReadable for OnchainEventEntry { + fn read(reader: &mut R) -> Result, DecodeError> { + let mut txid = Default::default(); + let mut height = 0; + let mut event = None; + read_tlv_fields!(reader, { + (0, txid, required), + (2, height, required), + (4, event, ignorable), + }); + if let Some(ev) = event { + Ok(Some(Self { txid, height, event: ev })) + } else { + Ok(None) + } + } +} -impl_writeable_tlv_based_enum!(OnchainEvent, +impl_writeable_tlv_based_enum_upgradable!(OnchainEvent, (0, HTLCUpdate) => { - (0, source), - (2, payment_hash), - }, {}, {}, + (0, source, required), + (1, onchain_value_satoshis, option), + (2, payment_hash, required), + (3, input_idx, option), + }, (1, MaturingOutput) => { - (0, descriptor), - }, {}, {}, -;); + (0, descriptor, required), + }, + (3, FundingSpendConfirmation) => { + (0, on_local_output_csv, option), + }, + (5, HTLCSpendConfirmation) => { + (0, input_idx, required), + (2, preimage, option), + (4, on_to_local_output_csv, option), + }, + +); #[cfg_attr(any(test, feature = "fuzztarget", feature = "_test_utils"), derive(PartialEq))] #[derive(Clone)] @@ -437,32 +509,102 @@ pub(crate) enum ChannelMonitorUpdateStep { /// think we've fallen behind! should_broadcast: bool, }, + ShutdownScript { + scriptpubkey: Script, + }, } -impl_writeable_tlv_based_enum!(ChannelMonitorUpdateStep, +impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep, (0, LatestHolderCommitmentTXInfo) => { - (0, commitment_tx), - }, {}, { - (2, htlc_outputs), + (0, commitment_tx, required), + (2, htlc_outputs, vec_type), }, (1, LatestCounterpartyCommitmentTXInfo) => { - (0, commitment_txid), - (2, commitment_number), - (4, their_revocation_point), - }, {}, { - (6, htlc_outputs), + (0, commitment_txid, required), + (2, commitment_number, required), + (4, their_revocation_point, required), + (6, htlc_outputs, vec_type), }, (2, PaymentPreimage) => { - (0, payment_preimage), - }, {}, {}, + (0, payment_preimage, required), + }, (3, CommitmentSecret) => { - (0, idx), - (2, secret), - }, {}, {}, + (0, idx, required), + (2, secret, required), + }, (4, ChannelForceClosed) => { - (0, should_broadcast), - }, {}, {}, -;); + (0, should_broadcast, required), + }, + (5, ShutdownScript) => { + (0, scriptpubkey, required), + }, +); + +/// Details about the balance(s) available for spending once the channel appears on chain. +/// +/// See [`ChannelMonitor::get_claimable_balances`] for more details on when these will or will not +/// be provided. +#[derive(Clone, Debug, PartialEq, Eq)] +#[cfg_attr(test, derive(PartialOrd, Ord))] +pub enum Balance { + /// The channel is not yet closed (or the commitment or closing transaction has not yet + /// appeared in a block). The given balance is claimable (less on-chain fees) if the channel is + /// force-closed now. + ClaimableOnChannelClose { + /// The amount available to claim, in satoshis, excluding the on-chain fees which will be + /// required to do so. + claimable_amount_satoshis: u64, + }, + /// The channel has been closed, and the given balance is ours but awaiting confirmations until + /// we consider it spendable. + ClaimableAwaitingConfirmations { + /// The amount available to claim, in satoshis, possibly excluding the on-chain fees which + /// were spent in broadcasting the transaction. + claimable_amount_satoshis: u64, + /// The height at which an [`Event::SpendableOutputs`] event will be generated for this + /// amount. + confirmation_height: u32, + }, + /// The channel has been closed, and the given balance should be ours but awaiting spending + /// transaction confirmation. If the spending transaction does not confirm in time, it is + /// possible our counterparty can take the funds by broadcasting an HTLC timeout on-chain. + /// + /// Once the spending transaction confirms, before it has reached enough confirmations to be + /// considered safe from chain reorganizations, the balance will instead be provided via + /// [`Balance::ClaimableAwaitingConfirmations`]. + ContentiousClaimable { + /// The amount available to claim, in satoshis, excluding the on-chain fees which will be + /// required to do so. + claimable_amount_satoshis: u64, + /// The height at which the counterparty may be able to claim the balance if we have not + /// done so. + timeout_height: u32, + }, + /// HTLCs which we sent to our counterparty which are claimable after a timeout (less on-chain + /// fees) if the counterparty does not know the preimage for the HTLCs. These are somewhat + /// likely to be claimed by our counterparty before we do. + MaybeClaimableHTLCAwaitingTimeout { + /// The amount available to claim, in satoshis, excluding the on-chain fees which will be + /// required to do so. + claimable_amount_satoshis: u64, + /// The height at which we will be able to claim the balance if our counterparty has not + /// done so. + claimable_height: u32, + }, +} + +/// An HTLC which has been irrevocably resolved on-chain, and has reached ANTI_REORG_DELAY. +#[derive(PartialEq)] +struct IrrevocablyResolvedHTLC { + input_idx: u32, + /// Only set if the HTLC claim was ours using a payment preimage + payment_preimage: Option, +} + +impl_writeable_tlv_based!(IrrevocablyResolvedHTLC, { + (0, input_idx, required), + (2, payment_preimage, option), +}); /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates /// on-chain transactions to ensure no loss of funds occurs. @@ -494,7 +636,7 @@ pub(crate) struct ChannelMonitorImpl { destination_script: Script, broadcasted_holder_revokable_script: Option<(Script, PublicKey, PublicKey)>, counterparty_payment_script: Script, - shutdown_script: Script, + shutdown_script: Option