X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Fchain%2Fchannelmonitor.rs;h=af0f56d882ad591531163df08f9aa05516af92a3;hb=2c0fcf21f227ad1a01e4a884dda72b9537c16fae;hp=a74c18e725d2bc0a5ec58614bf3cdcf622bed2b0;hpb=0607ed766a5593d93977126e00f43f8113722ced;p=rust-lightning diff --git a/lightning/src/chain/channelmonitor.rs b/lightning/src/chain/channelmonitor.rs index a74c18e7..66d08337 100644 --- a/lightning/src/chain/channelmonitor.rs +++ b/lightning/src/chain/channelmonitor.rs @@ -20,42 +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::sign::{SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, WriteableEcdsaChannelSigner, SignerProvider, EntropySource}; -use crate::chain::onchaintx::{ClaimEvent, 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, EventHandler}; -use crate::events::bump_transaction::{ChannelDerivationParameters, 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}; @@ -66,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. @@ -86,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: @@ -106,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(()) } } @@ -121,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 }) } } @@ -132,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. @@ -142,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`]. /// @@ -149,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 @@ -242,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, @@ -282,8 +320,8 @@ impl HolderSignedTx { /// justice or 2nd-stage preimage/timeout transactions. #[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, } @@ -366,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() } } @@ -486,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, @@ -502,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, @@ -518,7 +559,7 @@ pub(crate) enum ChannelMonitorUpdateStep { should_broadcast: bool, }, ShutdownScript { - scriptpubkey: Script, + scriptpubkey: ScriptBuf, }, } @@ -544,8 +585,11 @@ impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep, }, (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), + (5, to_countersignatory_value_sat, option), (6, htlc_outputs, required_vec), }, (2, PaymentPreimage) => { @@ -749,19 +793,20 @@ 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