X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Fchain%2Fchannelmonitor.rs;h=66d083377b0e6c23b5f863adb1c2f2aa0b7f98a4;hb=2c0fcf21f227ad1a01e4a884dda72b9537c16fae;hp=b2fd968b102295761a2cf14d579964d74755cd6d;hpb=2cae6f0ccb0e6b9e3d1c94359a906ddb4421be10;p=rust-lightning diff --git a/lightning/src/chain/channelmonitor.rs b/lightning/src/chain/channelmonitor.rs index b2fd968b..66d08337 100644 --- a/lightning/src/chain/channelmonitor.rs +++ b/lightning/src/chain/channelmonitor.rs @@ -20,45 +20,44 @@ //! security-domain-separated system design, you should consider having multiple paths for //! ChannelMonitors to get out of the HSM and onto monitoring devices. -use bitcoin::blockdata::block::BlockHeader; +use bitcoin::blockdata::block::Header; use bitcoin::blockdata::transaction::{OutPoint as BitcoinOutPoint, TxOut, Transaction}; -use bitcoin::blockdata::script::{Script, Builder}; -use bitcoin::blockdata::opcodes; +use bitcoin::blockdata::script::{Script, ScriptBuf}; use bitcoin::hashes::Hash; use bitcoin::hashes::sha256::Hash as Sha256; -use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash}; +use bitcoin::hash_types::{Txid, BlockHash}; use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature}; use bitcoin::secp256k1::{SecretKey, PublicKey}; use bitcoin::secp256k1; +use bitcoin::sighash::EcdsaSighashType; -use crate::ln::{PaymentHash, PaymentPreimage}; +use crate::ln::channel::INITIAL_COMMITMENT_NUMBER; +use crate::ln::{PaymentHash, PaymentPreimage, ChannelId}; use crate::ln::msgs::DecodeError; -use crate::ln::chan_utils; -use crate::ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLCClaim, ChannelTransactionParameters, HolderCommitmentTransaction}; +use crate::ln::channel_keys::{DelayedPaymentKey, DelayedPaymentBasepoint, HtlcBasepoint, HtlcKey, RevocationKey, RevocationBasepoint}; +use crate::ln::chan_utils::{self,CommitmentTransaction, CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLCClaim, ChannelTransactionParameters, HolderCommitmentTransaction, TxCreationKeys}; use crate::ln::channelmanager::{HTLCSource, SentHTLCId}; use crate::chain; use crate::chain::{BestBlock, WatchedOutput}; use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator, LowerBoundedFeeEstimator}; use crate::chain::transaction::{OutPoint, TransactionData}; -use crate::chain::keysinterface::{SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, WriteableEcdsaChannelSigner, SignerProvider, EntropySource}; -#[cfg(anchors)] -use crate::chain::onchaintx::ClaimEvent; -use crate::chain::onchaintx::OnchainTxHandler; +use crate::sign::{ChannelDerivationParameters, HTLCDescriptor, SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, ecdsa::WriteableEcdsaChannelSigner, SignerProvider, EntropySource}; +use crate::chain::onchaintx::{ClaimEvent, FeerateStrategy, OnchainTxHandler}; use crate::chain::package::{CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderFundingOutput, HolderHTLCOutput, PackageSolvingData, PackageTemplate, RevokedOutput, RevokedHTLCOutput}; use crate::chain::Filter; -use crate::util::logger::Logger; +use crate::util::logger::{Logger, Record}; use crate::util::ser::{Readable, ReadableArgs, RequiredWrapper, MaybeReadable, UpgradableRequired, Writer, Writeable, U48}; use crate::util::byte_utils; -use crate::events::Event; -#[cfg(anchors)] -use crate::events::bump_transaction::{AnchorDescriptor, HTLCDescriptor, BumpTransactionEvent}; +use crate::events::{ClosureReason, Event, EventHandler}; +use crate::events::bump_transaction::{AnchorDescriptor, BumpTransactionEvent}; +#[allow(unused_imports)] use crate::prelude::*; + use core::{cmp, mem}; use crate::io::{self, Error}; -use core::convert::TryInto; use core::ops::Deref; use crate::sync::{Mutex, LockTestExt}; @@ -69,10 +68,19 @@ use crate::sync::{Mutex, LockTestExt}; /// much smaller than a full [`ChannelMonitor`]. However, for large single commitment transaction /// updates (e.g. ones during which there are hundreds of HTLCs pending on the commitment /// transaction), a single update may reach upwards of 1 MiB in serialized size. -#[derive(Clone, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] #[must_use] pub struct ChannelMonitorUpdate { pub(crate) updates: Vec, + /// Historically, [`ChannelMonitor`]s didn't know their counterparty node id. However, + /// `ChannelManager` really wants to know it so that it can easily look up the corresponding + /// channel. For now, this results in a temporary map in `ChannelManager` to look up channels + /// by only the funding outpoint. + /// + /// To eventually remove that, we repeat the counterparty node id here so that we can upgrade + /// `ChannelMonitor`s to become aware of the counterparty node id if they were generated prior + /// to when it was stored directly in them. + pub(crate) counterparty_node_id: Option, /// The sequence number of this update. Updates *must* be replayed in-order according to this /// sequence number (and updates may panic if they are not). The update_id values are strictly /// increasing and increase by one for each new update, with two exceptions specified below. @@ -89,6 +97,11 @@ pub struct ChannelMonitorUpdate { /// /// [`ChannelMonitorUpdateStatus::InProgress`]: super::ChannelMonitorUpdateStatus::InProgress pub update_id: u64, + /// The channel ID associated with these updates. + /// + /// Will be `None` for `ChannelMonitorUpdate`s constructed on LDK versions prior to 0.0.121 and + /// always `Some` otherwise. + pub channel_id: Option, } /// The update ID used for a [`ChannelMonitorUpdate`] that is either: @@ -109,7 +122,10 @@ impl Writeable for ChannelMonitorUpdate { for update_step in self.updates.iter() { update_step.write(w)?; } - write_tlv_fields!(w, {}); + write_tlv_fields!(w, { + (1, self.counterparty_node_id, option), + (3, self.channel_id, option), + }); Ok(()) } } @@ -124,8 +140,13 @@ impl Readable for ChannelMonitorUpdate { updates.push(upd); } } - read_tlv_fields!(r, {}); - Ok(Self { update_id, updates }) + let mut counterparty_node_id = None; + let mut channel_id = None; + read_tlv_fields!(r, { + (1, counterparty_node_id, option), + (3, channel_id, option), + }); + Ok(Self { update_id, counterparty_node_id, updates, channel_id }) } } @@ -135,8 +156,20 @@ pub enum MonitorEvent { /// A monitor event containing an HTLCUpdate. HTLCEvent(HTLCUpdate), - /// A monitor event that the Channel's commitment transaction was confirmed. - CommitmentTxConfirmed(OutPoint), + /// Indicates we broadcasted the channel's latest commitment transaction and thus closed the + /// channel. Holds information about the channel and why it was closed. + HolderForceClosedWithInfo { + /// The reason the channel was closed. + reason: ClosureReason, + /// The funding outpoint of the channel. + outpoint: OutPoint, + /// The channel ID of the channel. + channel_id: ChannelId, + }, + + /// Indicates we broadcasted the channel's latest commitment transaction and thus closed the + /// channel. + HolderForceClosed(OutPoint), /// Indicates a [`ChannelMonitor`] update has completed. See /// [`ChannelMonitorUpdateStatus::InProgress`] for more information on how this is used. @@ -145,6 +178,8 @@ pub enum MonitorEvent { Completed { /// The funding outpoint of the [`ChannelMonitor`] that was updated funding_txo: OutPoint, + /// The channel ID of the channel associated with the [`ChannelMonitor`] + channel_id: ChannelId, /// The Update ID from [`ChannelMonitorUpdate::update_id`] which was applied or /// [`ChannelMonitor::get_latest_update_id`]. /// @@ -152,24 +187,24 @@ pub enum MonitorEvent { /// same [`ChannelMonitor`] have been applied and persisted. monitor_update_id: u64, }, - - /// Indicates a [`ChannelMonitor`] update has failed. See - /// [`ChannelMonitorUpdateStatus::PermanentFailure`] for more information on how this is used. - /// - /// [`ChannelMonitorUpdateStatus::PermanentFailure`]: super::ChannelMonitorUpdateStatus::PermanentFailure - UpdateFailed(OutPoint), } impl_writeable_tlv_based_enum_upgradable!(MonitorEvent, - // Note that Completed and UpdateFailed are currently never serialized to disk as they are - // generated only in ChainMonitor + // Note that Completed is currently never serialized to disk as it is generated only in + // ChainMonitor. (0, Completed) => { (0, funding_txo, required), (2, monitor_update_id, required), + (4, channel_id, required), + }, + (5, HolderForceClosedWithInfo) => { + (0, reason, upgradable_required), + (2, outpoint, required), + (4, channel_id, required), }, ; (2, HTLCEvent), - (4, CommitmentTxConfirmed), - (6, UpdateFailed), + (4, HolderForceClosed), + // 6 was `UpdateFailed` until LDK 0.0.117 ); /// Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on @@ -245,10 +280,10 @@ pub(crate) const HTLC_FAIL_BACK_BUFFER: u32 = CLTV_CLAIM_BUFFER + LATENCY_GRACE_ struct HolderSignedTx { /// txid of the transaction in tx, just used to make comparison faster txid: Txid, - revocation_key: PublicKey, - a_htlc_key: PublicKey, - b_htlc_key: PublicKey, - delayed_payment_key: PublicKey, + revocation_key: RevocationKey, + a_htlc_key: HtlcKey, + b_htlc_key: HtlcKey, + delayed_payment_key: DelayedPaymentKey, per_commitment_point: PublicKey, htlc_outputs: Vec<(HTLCOutputInCommitment, Option, Option)>, to_self_value_sat: u64, @@ -265,10 +300,9 @@ impl_writeable_tlv_based!(HolderSignedTx, { (8, delayed_payment_key, required), (10, per_commitment_point, required), (12, feerate_per_kw, required), - (14, htlc_outputs, vec_type) + (14, htlc_outputs, required_vec) }); -#[cfg(anchors)] impl HolderSignedTx { fn non_dust_htlcs(&self) -> Vec { self.htlc_outputs.iter().filter_map(|(htlc, _, _)| { @@ -284,10 +318,10 @@ impl HolderSignedTx { /// We use this to track static counterparty commitment transaction data and to generate any /// justice or 2nd-stage preimage/timeout transactions. -#[derive(PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] struct CounterpartyCommitmentParameters { - counterparty_delayed_payment_base_key: PublicKey, - counterparty_htlc_base_key: PublicKey, + counterparty_delayed_payment_base_key: DelayedPaymentBasepoint, + counterparty_htlc_base_key: HtlcBasepoint, on_counterparty_tx_csv: u16, } @@ -338,7 +372,7 @@ impl Readable for CounterpartyCommitmentParameters { /// observed, as well as the transaction causing it. /// /// Used to determine when the on-chain event can be considered safe from a chain reorganization. -#[derive(PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] struct OnchainEventEntry { txid: Txid, height: u32, @@ -370,7 +404,7 @@ impl OnchainEventEntry { } fn has_reached_confirmation_threshold(&self, best_block: &BestBlock) -> bool { - best_block.height() >= self.confirmation_threshold() + best_block.height >= self.confirmation_threshold() } } @@ -381,7 +415,7 @@ type CommitmentTxCounterpartyOutputInfo = Option<(u32, u64)>; /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it /// once they mature to enough confirmations (ANTI_REORG_DELAY) -#[derive(PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] enum 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 @@ -490,7 +524,7 @@ impl_writeable_tlv_based_enum_upgradable!(OnchainEvent, ); -#[derive(Clone, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum ChannelMonitorUpdateStep { LatestHolderCommitmentTXInfo { commitment_tx: HolderCommitmentTransaction, @@ -506,6 +540,9 @@ pub(crate) enum ChannelMonitorUpdateStep { htlc_outputs: Vec<(HTLCOutputInCommitment, Option>)>, commitment_number: u64, their_per_commitment_point: PublicKey, + feerate_per_kw: Option, + to_broadcaster_value_sat: Option, + to_countersignatory_value_sat: Option, }, PaymentPreimage { payment_preimage: PaymentPreimage, @@ -522,7 +559,7 @@ pub(crate) enum ChannelMonitorUpdateStep { should_broadcast: bool, }, ShutdownScript { - scriptpubkey: Script, + scriptpubkey: ScriptBuf, }, } @@ -542,15 +579,18 @@ impl ChannelMonitorUpdateStep { impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep, (0, LatestHolderCommitmentTXInfo) => { (0, commitment_tx, required), - (1, claimed_htlcs, vec_type), - (2, htlc_outputs, vec_type), + (1, claimed_htlcs, optional_vec), + (2, htlc_outputs, required_vec), (4, nondust_htlc_sources, optional_vec), }, (1, LatestCounterpartyCommitmentTXInfo) => { (0, commitment_txid, required), + (1, feerate_per_kw, option), (2, commitment_number, required), + (3, to_broadcaster_value_sat, option), (4, their_per_commitment_point, required), - (6, htlc_outputs, vec_type), + (5, to_countersignatory_value_sat, option), + (6, htlc_outputs, required_vec), }, (2, PaymentPreimage) => { (0, payment_preimage, required), @@ -580,14 +620,14 @@ pub enum Balance { ClaimableOnChannelClose { /// The amount available to claim, in satoshis, excluding the on-chain fees which will be /// required to do so. - claimable_amount_satoshis: u64, + 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, + amount_satoshis: u64, /// The height at which an [`Event::SpendableOutputs`] event will be generated for this /// amount. confirmation_height: u32, @@ -602,7 +642,7 @@ pub enum Balance { ContentiousClaimable { /// The amount available to claim, in satoshis, excluding the on-chain fees which will be /// required to do so. - claimable_amount_satoshis: u64, + 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, @@ -617,7 +657,7 @@ pub enum Balance { MaybeTimeoutClaimableHTLC { /// The amount potentially available to claim, in satoshis, excluding the on-chain fees /// which will be required to do so. - claimable_amount_satoshis: u64, + 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, @@ -630,7 +670,7 @@ pub enum Balance { MaybePreimageClaimableHTLC { /// The amount potentially available to claim, in satoshis, excluding the on-chain fees /// which will be required to do so. - claimable_amount_satoshis: u64, + amount_satoshis: u64, /// The height at which our counterparty will be able to claim the balance if we have not /// yet received the preimage and claimed it ourselves. expiry_height: u32, @@ -647,12 +687,33 @@ pub enum Balance { /// /// Note that for outputs from HTLC balances this may be excluding some on-chain fees that /// were already spent. - claimable_amount_satoshis: u64, + amount_satoshis: u64, }, } +impl Balance { + /// The amount claimable, in satoshis. This excludes balances that we are unsure if we are able + /// to claim, this is because we are waiting for a preimage or for a timeout to expire. For more + /// information on these balances see [`Balance::MaybeTimeoutClaimableHTLC`] and + /// [`Balance::MaybePreimageClaimableHTLC`]. + /// + /// On-chain fees required to claim the balance are not included in this amount. + pub fn claimable_amount_satoshis(&self) -> u64 { + match self { + Balance::ClaimableOnChannelClose { amount_satoshis, .. }| + Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. }| + Balance::ContentiousClaimable { amount_satoshis, .. }| + Balance::CounterpartyRevokedOutputClaimable { amount_satoshis, .. } + => *amount_satoshis, + Balance::MaybeTimeoutClaimableHTLC { .. }| + Balance::MaybePreimageClaimableHTLC { .. } + => 0, + } + } +} + /// An HTLC which has been irrevocably resolved on-chain, and has reached ANTI_REORG_DELAY. -#[derive(PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] struct IrrevocablyResolvedHTLC { commitment_tx_output_idx: Option, /// The txid of the transaction which resolved the HTLC, this may be a commitment (if the HTLC @@ -708,11 +769,6 @@ impl Readable for IrrevocablyResolvedHTLC { /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date /// information and are actively monitoring the chain. /// -/// Pending Events or updated HTLCs which have not yet been read out by -/// get_and_clear_pending_monitor_events or get_and_clear_pending_events are serialized to disk and -/// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events -/// gotten are fully handled before re-serializing the new state. -/// /// Note that the deserializer is only implemented for (BlockHash, ChannelMonitor), which /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along /// the "reorg path" (ie disconnecting blocks until you find a common ancestor from both the @@ -722,27 +778,35 @@ pub struct ChannelMonitor { #[cfg(test)] pub(crate) inner: Mutex>, #[cfg(not(test))] - inner: Mutex>, + pub(super) inner: Mutex>, } -#[derive(PartialEq)] +impl Clone for ChannelMonitor where Signer: Clone { + fn clone(&self) -> Self { + let inner = self.inner.lock().unwrap().clone(); + ChannelMonitor::from_impl(inner) + } +} + +#[derive(Clone, PartialEq)] pub(crate) struct ChannelMonitorImpl { latest_update_id: u64, commitment_transaction_number_obscure_factor: u64, - destination_script: Script, - broadcasted_holder_revokable_script: Option<(Script, PublicKey, PublicKey)>, - counterparty_payment_script: Script, - shutdown_script: Option