Add a `payment_metadata` field to `RecipientOnionFields`
[rust-lightning] / lightning / src / chain / onchaintx.rs
index 18679f0aacd5cd34fead7952fc91be997ad4e57b..f690d3664273b94e8ee9fe8d6d4c9f16d44ece0e 100644 (file)
 //! OnchainTxHandler objects are fully-part of ChannelMonitor and encapsulates all
 //! building, tracking, bumping and notifications functions.
 
+#[cfg(anchors)]
+use bitcoin::PackedLockTime;
 use bitcoin::blockdata::transaction::Transaction;
 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
 use bitcoin::blockdata::script::Script;
 
-use bitcoin::hash_types::Txid;
+use bitcoin::hash_types::{Txid, BlockHash};
 
 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature};
 use bitcoin::secp256k1;
 
+use crate::chain::keysinterface::{ChannelSigner, EntropySource, SignerProvider};
 use crate::ln::msgs::DecodeError;
 use crate::ln::PaymentPreimage;
 #[cfg(anchors)]
-use crate::ln::chan_utils;
+use crate::ln::chan_utils::{self, HTLCOutputInCommitment};
 use crate::ln::chan_utils::{ChannelTransactionParameters, HolderCommitmentTransaction};
 #[cfg(anchors)]
 use crate::chain::chaininterface::ConfirmationTarget;
 use crate::chain::chaininterface::{FeeEstimator, BroadcasterInterface, LowerBoundedFeeEstimator};
 use crate::chain::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER};
-use crate::chain::keysinterface::{Sign, KeysInterface};
+use crate::chain::keysinterface::WriteableEcdsaChannelSigner;
 #[cfg(anchors)]
 use crate::chain::package::PackageSolvingData;
 use crate::chain::package::PackageTemplate;
 use crate::util::logger::Logger;
-use crate::util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, VecWriter};
-use crate::util::byte_utils;
+use crate::util::ser::{Readable, ReadableArgs, MaybeReadable, UpgradableRequired, Writer, Writeable, VecWriter};
 
 use crate::io;
 use crate::prelude::*;
@@ -58,6 +60,7 @@ const MAX_ALLOC_SIZE: usize = 64*1024;
 struct OnchainEventEntry {
        txid: Txid,
        height: u32,
+       block_hash: Option<BlockHash>, // Added as optional, will be filled in for any entry generated on 0.0.113 or after
        event: OnchainEvent,
 }
 
@@ -71,18 +74,23 @@ impl OnchainEventEntry {
        }
 }
 
-/// 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)
+/// Events for claims the [`OnchainTxHandler`] has generated. Once the events are considered safe
+/// from a chain reorg, the [`OnchainTxHandler`] will act accordingly.
 #[derive(PartialEq, Eq)]
 enum OnchainEvent {
-       /// Outpoint under claim process by our own tx, once this one get enough confirmations, we remove it from
-       /// bump-txn candidate buffer.
+       /// A pending request has been claimed by a transaction spending the exact same set of outpoints
+       /// as the request. This claim can either be ours or from the counterparty. Once the claiming
+       /// transaction has met [`ANTI_REORG_DELAY`] confirmations, we consider it final and remove the
+       /// pending request.
        Claim {
-               claim_request: Txid,
+               package_id: PackageID,
        },
-       /// Claim tx aggregate multiple claimable outpoints. One of the outpoint may be claimed by a counterparty party tx.
-       /// In this case, we need to drop the outpoint and regenerate a new claim tx. By safety, we keep tracking
-       /// the outpoint to be sure to resurect it back to the claim tx if reorgs happen.
+       /// The counterparty has claimed an outpoint from one of our pending requests through a
+       /// different transaction than ours. If our transaction was attempting to claim multiple
+       /// outputs, we need to drop the outpoint claimed by the counterparty and regenerate a new claim
+       /// transaction for ourselves. We keep tracking, separately, the outpoint claimed by the
+       /// counterparty up to [`ANTI_REORG_DELAY`] confirmations to ensure we attempt to re-claim it
+       /// if the counterparty's claim is reorged from the chain.
        ContentiousOutpoint {
                package: PackageTemplate,
        }
@@ -92,6 +100,7 @@ impl Writeable for OnchainEventEntry {
        fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
                write_tlv_fields!(writer, {
                        (0, self.txid, required),
+                       (1, self.block_hash, option),
                        (2, self.height, required),
                        (4, self.event, required),
                });
@@ -103,23 +112,21 @@ impl MaybeReadable for OnchainEventEntry {
        fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
                let mut txid = Txid::all_zeros();
                let mut height = 0;
-               let mut event = None;
+               let mut block_hash = None;
+               let mut event = UpgradableRequired(None);
                read_tlv_fields!(reader, {
                        (0, txid, required),
+                       (1, block_hash, option),
                        (2, height, required),
-                       (4, event, ignorable),
+                       (4, event, upgradable_required),
                });
-               if let Some(ev) = event {
-                       Ok(Some(Self { txid, height, event: ev }))
-               } else {
-                       Ok(None)
-               }
+               Ok(Some(Self { txid, height, block_hash, event: _init_tlv_based_struct_field!(event, upgradable_required) }))
        }
 }
 
 impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
        (0, Claim) => {
-               (0, claim_request, required),
+               (0, package_id, required),
        },
        (1, ContentiousOutpoint) => {
                (0, package, required),
@@ -170,6 +177,16 @@ impl Writeable for Option<Vec<Option<(usize, Signature)>>> {
        }
 }
 
+#[cfg(anchors)]
+/// The claim commonly referred to as the pre-signed second-stage HTLC transaction.
+pub(crate) struct ExternalHTLCClaim {
+       pub(crate) commitment_txid: Txid,
+       pub(crate) per_commitment_number: u64,
+       pub(crate) htlc: HTLCOutputInCommitment,
+       pub(crate) preimage: Option<PaymentPreimage>,
+       pub(crate) counterparty_sig: Signature,
+}
+
 // Represents the different types of claims for which events are yielded externally to satisfy said
 // claims.
 #[cfg(anchors)]
@@ -181,6 +198,13 @@ pub(crate) enum ClaimEvent {
                commitment_tx: Transaction,
                anchor_output_idx: u32,
        },
+       /// Event yielded to signal that the commitment transaction has confirmed and its HTLCs must be
+       /// resolved by broadcasting a transaction with sufficient fee to claim them.
+       BumpHTLC {
+               target_feerate_sat_per_1000_weight: u32,
+               htlcs: Vec<ExternalHTLCClaim>,
+               tx_lock_time: PackedLockTime,
+       },
 }
 
 /// Represents the different ways an output can be claimed (i.e., spent to an address under our
@@ -194,9 +218,12 @@ pub(crate) enum OnchainClaim {
        Event(ClaimEvent),
 }
 
+/// An internal identifier to track pending package claims within the `OnchainTxHandler`.
+type PackageID = [u8; 32];
+
 /// OnchainTxHandler receives claiming requests, aggregates them if it's sound, broadcast and
 /// do RBF bumping if possible.
-pub struct OnchainTxHandler<ChannelSigner: Sign> {
+pub struct OnchainTxHandler<ChannelSigner: WriteableEcdsaChannelSigner> {
        destination_script: Script,
        holder_commitment: HolderCommitmentTransaction,
        // holder_htlc_sigs and prev_holder_htlc_sigs are in the order as they appear in the commitment
@@ -221,22 +248,33 @@ pub struct OnchainTxHandler<ChannelSigner: Sign> {
        // us and is immutable until all outpoint of the claimable set are post-anti-reorg-delay solved.
        // Entry is cache of elements need to generate a bumped claiming transaction (see ClaimTxBumpMaterial)
        #[cfg(test)] // Used in functional_test to verify sanitization
-       pub(crate) pending_claim_requests: HashMap<Txid, PackageTemplate>,
+       pub(crate) pending_claim_requests: HashMap<PackageID, PackageTemplate>,
        #[cfg(not(test))]
-       pending_claim_requests: HashMap<Txid, PackageTemplate>,
+       pending_claim_requests: HashMap<PackageID, PackageTemplate>,
+
+       // Used to track external events that need to be forwarded to the `ChainMonitor`. This `Vec`
+       // essentially acts as an insertion-ordered `HashMap` – there should only ever be one occurrence
+       // of a `PackageID`, which tracks its latest `ClaimEvent`, i.e., if a pending claim exists, and
+       // a new block has been connected, resulting in a new claim, the previous will be replaced with
+       // the new.
+       //
+       // These external events may be generated in the following cases:
+       //      - A channel has been force closed by broadcasting the holder's latest commitment transaction
+       //      - A block being connected/disconnected
+       //      - Learning the preimage for an HTLC we can claim onchain
        #[cfg(anchors)]
-       pending_claim_events: HashMap<Txid, ClaimEvent>,
-
-       // Used to link outpoints claimed in a connected block to a pending claim request.
-       // Key is outpoint than monitor parsing has detected we have keys/scripts to claim
-       // Value is (pending claim request identifier, confirmation_block), identifier
-       // is txid of the initial claiming transaction and is immutable until outpoint is
-       // post-anti-reorg-delay solved, confirmaiton_block is used to erase entry if
-       // block with output gets disconnected.
+       pending_claim_events: Vec<(PackageID, ClaimEvent)>,
+
+       // Used to link outpoints claimed in a connected block to a pending claim request. The keys
+       // represent the outpoints that our `ChannelMonitor` has detected we have keys/scripts to
+       // claim. The values track the pending claim request identifier and the initial confirmation
+       // block height, and are immutable until the outpoint has enough confirmations to meet our
+       // [`ANTI_REORG_DELAY`]. The initial confirmation block height is used to remove the entry if
+       // the block gets disconnected.
        #[cfg(test)] // Used in functional_test to verify sanitization
-       pub claimable_outpoints: HashMap<BitcoinOutPoint, (Txid, u32)>,
+       pub claimable_outpoints: HashMap<BitcoinOutPoint, (PackageID, u32)>,
        #[cfg(not(test))]
-       claimable_outpoints: HashMap<BitcoinOutPoint, (Txid, u32)>,
+       claimable_outpoints: HashMap<BitcoinOutPoint, (PackageID, u32)>,
 
        locktimed_packages: BTreeMap<u32, Vec<PackageTemplate>>,
 
@@ -245,10 +283,26 @@ pub struct OnchainTxHandler<ChannelSigner: Sign> {
        pub(super) secp_ctx: Secp256k1<secp256k1::All>,
 }
 
+impl<ChannelSigner: WriteableEcdsaChannelSigner> PartialEq for OnchainTxHandler<ChannelSigner> {
+       fn eq(&self, other: &Self) -> bool {
+               // `signer`, `secp_ctx`, and `pending_claim_events` are excluded on purpose.
+               self.destination_script == other.destination_script &&
+                       self.holder_commitment == other.holder_commitment &&
+                       self.holder_htlc_sigs == other.holder_htlc_sigs &&
+                       self.prev_holder_commitment == other.prev_holder_commitment &&
+                       self.prev_holder_htlc_sigs == other.prev_holder_htlc_sigs &&
+                       self.channel_transaction_parameters == other.channel_transaction_parameters &&
+                       self.pending_claim_requests == other.pending_claim_requests &&
+                       self.claimable_outpoints == other.claimable_outpoints &&
+                       self.locktimed_packages == other.locktimed_packages &&
+                       self.onchain_events_awaiting_threshold_conf == other.onchain_events_awaiting_threshold_conf
+       }
+}
+
 const SERIALIZATION_VERSION: u8 = 1;
 const MIN_SERIALIZATION_VERSION: u8 = 1;
 
-impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
+impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner> {
        pub(crate) fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
                write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
 
@@ -267,29 +321,29 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                (key_data.0.len() as u32).write(writer)?;
                writer.write_all(&key_data.0[..])?;
 
-               writer.write_all(&byte_utils::be64_to_array(self.pending_claim_requests.len() as u64))?;
+               writer.write_all(&(self.pending_claim_requests.len() as u64).to_be_bytes())?;
                for (ref ancestor_claim_txid, request) in self.pending_claim_requests.iter() {
                        ancestor_claim_txid.write(writer)?;
                        request.write(writer)?;
                }
 
-               writer.write_all(&byte_utils::be64_to_array(self.claimable_outpoints.len() as u64))?;
+               writer.write_all(&(self.claimable_outpoints.len() as u64).to_be_bytes())?;
                for (ref outp, ref claim_and_height) in self.claimable_outpoints.iter() {
                        outp.write(writer)?;
                        claim_and_height.0.write(writer)?;
                        claim_and_height.1.write(writer)?;
                }
 
-               writer.write_all(&byte_utils::be64_to_array(self.locktimed_packages.len() as u64))?;
+               writer.write_all(&(self.locktimed_packages.len() as u64).to_be_bytes())?;
                for (ref locktime, ref packages) in self.locktimed_packages.iter() {
                        locktime.write(writer)?;
-                       writer.write_all(&byte_utils::be64_to_array(packages.len() as u64))?;
+                       writer.write_all(&(packages.len() as u64).to_be_bytes())?;
                        for ref package in packages.iter() {
                                package.write(writer)?;
                        }
                }
 
-               writer.write_all(&byte_utils::be64_to_array(self.onchain_events_awaiting_threshold_conf.len() as u64))?;
+               writer.write_all(&(self.onchain_events_awaiting_threshold_conf.len() as u64).to_be_bytes())?;
                for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
                        entry.write(writer)?;
                }
@@ -299,8 +353,13 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
        }
 }
 
-impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
-       fn read<R: io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
+impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP, u64, [u8; 32])> for OnchainTxHandler<SP::Signer> {
+       fn read<R: io::Read>(reader: &mut R, args: (&'a ES, &'b SP, u64, [u8; 32])) -> Result<Self, DecodeError> {
+               let entropy_source = args.0;
+               let signer_provider = args.1;
+               let channel_value_satoshis = args.2;
+               let channel_keys_id = args.3;
+
                let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
 
                let destination_script = Readable::read(reader)?;
@@ -312,16 +371,21 @@ impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
 
                let channel_parameters = Readable::read(reader)?;
 
+               // Read the serialized signer bytes, but don't deserialize them, as we'll obtain our signer
+               // by re-deriving the private key material.
                let keys_len: u32 = Readable::read(reader)?;
-               let mut keys_data = Vec::with_capacity(cmp::min(keys_len as usize, MAX_ALLOC_SIZE));
-               while keys_data.len() != keys_len as usize {
+               let mut bytes_read = 0;
+               while bytes_read != keys_len as usize {
                        // Read 1KB at a time to avoid accidentally allocating 4GB on corrupted channel keys
                        let mut data = [0; 1024];
-                       let read_slice = &mut data[0..cmp::min(1024, keys_len as usize - keys_data.len())];
+                       let bytes_to_read = cmp::min(1024, keys_len as usize - bytes_read);
+                       let read_slice = &mut data[0..bytes_to_read];
                        reader.read_exact(read_slice)?;
-                       keys_data.extend_from_slice(read_slice);
+                       bytes_read += bytes_to_read;
                }
-               let signer = keys_manager.read_chan_signer(&keys_data)?;
+
+               let mut signer = signer_provider.derive_channel_signer(channel_value_satoshis, channel_keys_id);
+               signer.provide_channel_parameters(&channel_parameters);
 
                let pending_claim_requests_len: u64 = Readable::read(reader)?;
                let mut pending_claim_requests = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
@@ -361,7 +425,7 @@ impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
                read_tlv_fields!(reader, {});
 
                let mut secp_ctx = Secp256k1::new();
-               secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
+               secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
 
                Ok(OnchainTxHandler {
                        destination_script,
@@ -376,13 +440,13 @@ impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
                        pending_claim_requests,
                        onchain_events_awaiting_threshold_conf,
                        #[cfg(anchors)]
-                       pending_claim_events: HashMap::new(),
+                       pending_claim_events: Vec::new(),
                        secp_ctx,
                })
        }
 }
 
-impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
+impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner> {
        pub(crate) fn new(destination_script: Script, signer: ChannelSigner, channel_parameters: ChannelTransactionParameters, holder_commitment: HolderCommitmentTransaction, secp_ctx: Secp256k1<secp256k1::All>) -> Self {
                OnchainTxHandler {
                        destination_script,
@@ -397,8 +461,7 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                        locktimed_packages: BTreeMap::new(),
                        onchain_events_awaiting_threshold_conf: Vec::new(),
                        #[cfg(anchors)]
-                       pending_claim_events: HashMap::new(),
-
+                       pending_claim_events: Vec::new(),
                        secp_ctx,
                }
        }
@@ -413,9 +476,9 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
 
        #[cfg(anchors)]
        pub(crate) fn get_and_clear_pending_claim_events(&mut self) -> Vec<ClaimEvent> {
-               let mut ret = HashMap::new();
-               swap(&mut ret, &mut self.pending_claim_events);
-               ret.into_iter().map(|(_, event)| event).collect::<Vec<_>>()
+               let mut events = Vec::new();
+               swap(&mut events, &mut self.pending_claim_events);
+               events.into_iter().map(|(_, event)| event).collect()
        }
 
        /// Lightning security model (i.e being able to redeem/timeout HTLC or penalize counterparty
@@ -430,21 +493,81 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                where F::Target: FeeEstimator,
                                        L::Target: Logger,
        {
-               if cached_request.outpoints().len() == 0 { return None } // But don't prune pending claiming request yet, we may have to resurrect HTLCs
+               let request_outpoints = cached_request.outpoints();
+               if request_outpoints.is_empty() {
+                       // Don't prune pending claiming request yet, we may have to resurrect HTLCs. Untractable
+                       // packages cannot be aggregated and will never be split, so we cannot end up with an
+                       // empty claim.
+                       debug_assert!(cached_request.is_malleable());
+                       return None;
+               }
+               // If we've seen transaction inclusion in the chain for all outpoints in our request, we
+               // don't need to continue generating more claims. We'll keep tracking the request to fully
+               // remove it once it reaches the confirmation threshold, or to generate a new claim if the
+               // transaction is reorged out.
+               let mut all_inputs_have_confirmed_spend = true;
+               for outpoint in request_outpoints.iter() {
+                       if let Some((request_package_id, _)) = self.claimable_outpoints.get(*outpoint) {
+                               // We check for outpoint spends within claims individually rather than as a set
+                               // since requests can have outpoints split off.
+                               if !self.onchain_events_awaiting_threshold_conf.iter()
+                                       .any(|event_entry| if let OnchainEvent::Claim { package_id } = event_entry.event {
+                                               *request_package_id == package_id
+                                       } else {
+                                               // The onchain event is not a claim, keep seeking until we find one.
+                                               false
+                                       })
+                               {
+                                       // Either we had no `OnchainEvent::Claim`, or we did but none matched the
+                                       // outpoint's registered spend.
+                                       all_inputs_have_confirmed_spend = false;
+                               }
+                       } else {
+                               // The request's outpoint spend does not exist yet.
+                               all_inputs_have_confirmed_spend = false;
+                       }
+               }
+               if all_inputs_have_confirmed_spend {
+                       return None;
+               }
 
                // Compute new height timer to decide when we need to regenerate a new bumped version of the claim tx (if we
                // didn't receive confirmation of it before, or not enough reorg-safe depth on top of it).
                let new_timer = Some(cached_request.get_height_timer(cur_height));
                if cached_request.is_malleable() {
+                       #[cfg(anchors)]
+                       { // Attributes are not allowed on if expressions on our current MSRV of 1.41.
+                               if cached_request.requires_external_funding() {
+                                       let target_feerate_sat_per_1000_weight = cached_request
+                                               .compute_package_feerate(fee_estimator, ConfirmationTarget::HighPriority);
+                                       if let Some(htlcs) = cached_request.construct_malleable_package_with_external_funding(self) {
+                                               return Some((
+                                                       new_timer,
+                                                       target_feerate_sat_per_1000_weight as u64,
+                                                       OnchainClaim::Event(ClaimEvent::BumpHTLC {
+                                                               target_feerate_sat_per_1000_weight,
+                                                               htlcs,
+                                                               tx_lock_time: PackedLockTime(cached_request.package_locktime(cur_height)),
+                                                       }),
+                                               ));
+                                       } else {
+                                               return None;
+                                       }
+                               }
+                       }
+
                        let predicted_weight = cached_request.package_weight(&self.destination_script);
-                       if let Some((output_value, new_feerate)) =
-                                       cached_request.compute_package_output(predicted_weight, self.destination_script.dust_value().to_sat(), fee_estimator, logger) {
+                       if let Some((output_value, new_feerate)) = cached_request.compute_package_output(
+                               predicted_weight, self.destination_script.dust_value().to_sat(), fee_estimator, logger,
+                       ) {
                                assert!(new_feerate != 0);
 
-                               let transaction = cached_request.finalize_malleable_package(self, output_value, self.destination_script.clone(), logger).unwrap();
+                               let transaction = cached_request.finalize_malleable_package(
+                                       cur_height, self, output_value, self.destination_script.clone(), logger
+                               ).unwrap();
                                log_trace!(logger, "...with timer {} and feerate {}", new_timer.unwrap(), new_feerate);
                                assert!(predicted_weight >= transaction.weight());
-                               return Some((new_timer, new_feerate, OnchainClaim::Tx(transaction)))
+                               return Some((new_timer, new_feerate, OnchainClaim::Tx(transaction)));
                        }
                } else {
                        // Untractable packages cannot have their fees bumped through Replace-By-Fee. Some
@@ -500,24 +623,29 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                                        debug_assert!(false, "Only HolderFundingOutput inputs should be untractable and require external funding");
                                        None
                                },
-                       });
+                       })
                }
                None
        }
 
        /// Upon channelmonitor.block_connected(..) or upon provision of a preimage on the forward link
        /// for this channel, provide new relevant on-chain transactions and/or new claim requests.
-       /// Formerly this was named `block_connected`, but it is now also used for claiming an HTLC output
-       /// if we receive a preimage after force-close.
-       /// `conf_height` represents the height at which the transactions in `txn_matched` were
-       /// confirmed. This does not need to equal the current blockchain tip height, which should be
-       /// provided via `cur_height`, however it must never be higher than `cur_height`.
-       pub(crate) fn update_claims_view<B: Deref, F: Deref, L: Deref>(&mut self, txn_matched: &[&Transaction], requests: Vec<PackageTemplate>, conf_height: u32, cur_height: u32, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L)
-               where B::Target: BroadcasterInterface,
-                     F::Target: FeeEstimator,
-                                       L::Target: Logger,
+       /// Together with `update_claims_view_from_matched_txn` this used to be named
+       /// `block_connected`, but it is now also used for claiming an HTLC output if we receive a
+       /// preimage after force-close.
+       ///
+       /// `conf_height` represents the height at which the request was generated. This
+       /// does not need to equal the current blockchain tip height, which should be provided via
+       /// `cur_height`, however it must never be higher than `cur_height`.
+       pub(crate) fn update_claims_view_from_requests<B: Deref, F: Deref, L: Deref>(
+               &mut self, requests: Vec<PackageTemplate>, conf_height: u32, cur_height: u32,
+               broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L
+       ) where
+               B::Target: BroadcasterInterface,
+               F::Target: FeeEstimator,
+               L::Target: Logger,
        {
-               log_debug!(logger, "Updating claims view at height {} with {} matched transactions in block {} and {} claim requests", cur_height, txn_matched.len(), conf_height, requests.len());
+               log_debug!(logger, "Updating claims view at height {} with {} claim requests", cur_height, requests.len());
                let mut preprocessed_requests = Vec::with_capacity(requests.len());
                let mut aggregated_request = None;
 
@@ -532,16 +660,17 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                                        .find(|locked_package| locked_package.outpoints() == req.outpoints());
                                if let Some(package) = timelocked_equivalent_package {
                                        log_info!(logger, "Ignoring second claim for outpoint {}:{}, we already have one which we're waiting on a timelock at {} for.",
-                                               req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_timelock());
+                                               req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_locktime(cur_height));
                                        continue;
                                }
 
-                               if req.package_timelock() > cur_height + 1 {
-                                       log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", req.package_timelock(), cur_height);
+                               let package_locktime = req.package_locktime(cur_height);
+                               if package_locktime > cur_height + 1 {
+                                       log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", package_locktime, cur_height);
                                        for outpoint in req.outpoints() {
                                                log_info!(logger, "  Outpoint {}", outpoint);
                                        }
-                                       self.locktimed_packages.entry(req.package_timelock()).or_insert(Vec::new()).push(req);
+                                       self.locktimed_packages.entry(package_locktime).or_insert(Vec::new()).push(req);
                                        continue;
                                }
 
@@ -574,49 +703,78 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                        if let Some((new_timer, new_feerate, claim)) = self.generate_claim(cur_height, &req, &*fee_estimator, &*logger) {
                                req.set_timer(new_timer);
                                req.set_feerate(new_feerate);
-                               let txid = match claim {
+                               let package_id = match claim {
                                        OnchainClaim::Tx(tx) => {
                                                log_info!(logger, "Broadcasting onchain {}", log_tx!(tx));
                                                broadcaster.broadcast_transaction(&tx);
-                                               tx.txid()
+                                               tx.txid().into_inner()
                                        },
                                        #[cfg(anchors)]
                                        OnchainClaim::Event(claim_event) => {
                                                log_info!(logger, "Yielding onchain event to spend inputs {:?}", req.outpoints());
-                                               let txid = match claim_event {
-                                                       ClaimEvent::BumpCommitment { ref commitment_tx, .. } => commitment_tx.txid(),
+                                               let package_id = match claim_event {
+                                                       ClaimEvent::BumpCommitment { ref commitment_tx, .. } => commitment_tx.txid().into_inner(),
+                                                       ClaimEvent::BumpHTLC { ref htlcs, .. } => {
+                                                               // Use the same construction as a lightning channel id to generate
+                                                               // the package id for this request based on the first HTLC. It
+                                                               // doesn't matter what we use as long as it's unique per request.
+                                                               let mut package_id = [0; 32];
+                                                               package_id[..].copy_from_slice(&htlcs[0].commitment_txid[..]);
+                                                               let htlc_output_index = htlcs[0].htlc.transaction_output_index.unwrap();
+                                                               package_id[30] ^= ((htlc_output_index >> 8) & 0xff) as u8;
+                                                               package_id[31] ^= ((htlc_output_index >> 0) & 0xff) as u8;
+                                                               package_id
+                                                       },
                                                };
-                                               self.pending_claim_events.insert(txid, claim_event);
-                                               txid
+                                               debug_assert_eq!(self.pending_claim_events.iter().filter(|entry| entry.0 == package_id).count(), 0);
+                                               self.pending_claim_events.push((package_id, claim_event));
+                                               package_id
                                        },
                                };
                                for k in req.outpoints() {
                                        log_info!(logger, "Registering claiming request for {}:{}", k.txid, k.vout);
-                                       self.claimable_outpoints.insert(k.clone(), (txid, conf_height));
+                                       self.claimable_outpoints.insert(k.clone(), (package_id, conf_height));
                                }
-                               self.pending_claim_requests.insert(txid, req);
+                               self.pending_claim_requests.insert(package_id, req);
                        }
                }
+       }
 
+       /// Upon channelmonitor.block_connected(..) or upon provision of a preimage on the forward link
+       /// for this channel, provide new relevant on-chain transactions and/or new claim requests.
+       /// Together with `update_claims_view_from_requests` this used to be named `block_connected`,
+       /// but it is now also used for claiming an HTLC output if we receive a preimage after force-close.
+       ///
+       /// `conf_height` represents the height at which the transactions in `txn_matched` were
+       /// confirmed. This does not need to equal the current blockchain tip height, which should be
+       /// provided via `cur_height`, however it must never be higher than `cur_height`.
+       pub(crate) fn update_claims_view_from_matched_txn<B: Deref, F: Deref, L: Deref>(
+               &mut self, txn_matched: &[&Transaction], conf_height: u32, conf_hash: BlockHash,
+               cur_height: u32, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L
+       ) where
+               B::Target: BroadcasterInterface,
+               F::Target: FeeEstimator,
+               L::Target: Logger,
+       {
+               log_debug!(logger, "Updating claims view at height {} with {} matched transactions in block {}", cur_height, txn_matched.len(), conf_height);
                let mut bump_candidates = HashMap::new();
                for tx in txn_matched {
                        // Scan all input to verify is one of the outpoint spent is of interest for us
                        let mut claimed_outputs_material = Vec::new();
                        for inp in &tx.input {
-                               if let Some(first_claim_txid_height) = self.claimable_outpoints.get(&inp.previous_output) {
+                               if let Some((package_id, _)) = self.claimable_outpoints.get(&inp.previous_output) {
                                        // If outpoint has claim request pending on it...
-                                       if let Some(request) = self.pending_claim_requests.get_mut(&first_claim_txid_height.0) {
+                                       if let Some(request) = self.pending_claim_requests.get_mut(package_id) {
                                                //... we need to verify equality between transaction outpoints and claim request
                                                // outpoints to know if transaction is the original claim or a bumped one issued
                                                // by us.
-                                               let mut set_equality = true;
-                                               if request.outpoints().len() != tx.input.len() {
-                                                       set_equality = false;
-                                               } else {
-                                                       for (claim_inp, tx_inp) in request.outpoints().iter().zip(tx.input.iter()) {
-                                                               if **claim_inp != tx_inp.previous_output {
-                                                                       set_equality = false;
-                                                               }
+                                               let mut are_sets_equal = true;
+                                               let mut tx_inputs = tx.input.iter().map(|input| &input.previous_output).collect::<Vec<_>>();
+                                               tx_inputs.sort_unstable();
+                                               for request_input in request.outpoints() {
+                                                       if tx_inputs.binary_search(&request_input).is_err() {
+                                                               are_sets_equal = false;
+                                                               break;
                                                        }
                                                }
 
@@ -625,7 +783,8 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                                                                let entry = OnchainEventEntry {
                                                                        txid: tx.txid(),
                                                                        height: conf_height,
-                                                                       event: OnchainEvent::Claim { claim_request: first_claim_txid_height.0.clone() }
+                                                                       block_hash: Some(conf_hash),
+                                                                       event: OnchainEvent::Claim { package_id: *package_id }
                                                                };
                                                                if !self.onchain_events_awaiting_threshold_conf.contains(&entry) {
                                                                        self.onchain_events_awaiting_threshold_conf.push(entry);
@@ -636,7 +795,7 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                                                // If this is our transaction (or our counterparty spent all the outputs
                                                // before we could anyway with same inputs order than us), wait for
                                                // ANTI_REORG_DELAY and clean the RBF tracking map.
-                                               if set_equality {
+                                               if are_sets_equal {
                                                        clean_claim_request_after_safety_delay!();
                                                } else { // If false, generate new claim request with update outpoint set
                                                        let mut at_least_one_drop = false;
@@ -652,7 +811,21 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                                                        }
                                                        //TODO: recompute soonest_timelock to avoid wasting a bit on fees
                                                        if at_least_one_drop {
-                                                               bump_candidates.insert(first_claim_txid_height.0.clone(), request.clone());
+                                                               bump_candidates.insert(*package_id, request.clone());
+                                                               // If we have any pending claim events for the request being updated
+                                                               // that have yet to be consumed, we'll remove them since they will
+                                                               // end up producing an invalid transaction by double spending
+                                                               // input(s) that already have a confirmed spend. If such spend is
+                                                               // reorged out of the chain, then we'll attempt to re-spend the
+                                                               // inputs once we see it.
+                                                               #[cfg(anchors)] {
+                                                                       #[cfg(debug_assertions)] {
+                                                                               let existing = self.pending_claim_events.iter()
+                                                                                       .filter(|entry| entry.0 == *package_id).count();
+                                                                               assert!(existing == 0 || existing == 1);
+                                                                       }
+                                                                       self.pending_claim_events.retain(|entry| entry.0 != *package_id);
+                                                               }
                                                        }
                                                }
                                                break; //No need to iterate further, either tx is our or their
@@ -665,6 +838,7 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                                let entry = OnchainEventEntry {
                                        txid: tx.txid(),
                                        height: conf_height,
+                                       block_hash: Some(conf_hash),
                                        event: OnchainEvent::ContentiousOutpoint { package },
                                };
                                if !self.onchain_events_awaiting_threshold_conf.contains(&entry) {
@@ -679,22 +853,29 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                for entry in onchain_events_awaiting_threshold_conf {
                        if entry.has_reached_confirmation_threshold(cur_height) {
                                match entry.event {
-                                       OnchainEvent::Claim { claim_request } => {
+                                       OnchainEvent::Claim { package_id } => {
                                                // We may remove a whole set of claim outpoints here, as these one may have
                                                // been aggregated in a single tx and claimed so atomically
-                                               if let Some(request) = self.pending_claim_requests.remove(&claim_request) {
+                                               if let Some(request) = self.pending_claim_requests.remove(&package_id) {
                                                        for outpoint in request.outpoints() {
-                                                               log_debug!(logger, "Removing claim tracking for {} due to maturation of claim tx {}.", outpoint, claim_request);
-                                                               self.claimable_outpoints.remove(&outpoint);
-                                                               #[cfg(anchors)]
-                                                               self.pending_claim_events.remove(&claim_request);
+                                                               log_debug!(logger, "Removing claim tracking for {} due to maturation of claim package {}.",
+                                                                       outpoint, log_bytes!(package_id));
+                                                               self.claimable_outpoints.remove(outpoint);
+                                                       }
+                                                       #[cfg(anchors)] {
+                                                               #[cfg(debug_assertions)] {
+                                                                       let num_existing = self.pending_claim_events.iter()
+                                                                               .filter(|entry| entry.0 == package_id).count();
+                                                                       assert!(num_existing == 0 || num_existing == 1);
+                                                               }
+                                                               self.pending_claim_events.retain(|(id, _)| *id != package_id);
                                                        }
                                                }
                                        },
                                        OnchainEvent::ContentiousOutpoint { package } => {
                                                log_debug!(logger, "Removing claim tracking due to maturation of claim tx for outpoints:");
                                                log_debug!(logger, " {:?}", package.outpoints());
-                                               self.claimable_outpoints.remove(&package.outpoints()[0]);
+                                               self.claimable_outpoints.remove(package.outpoints()[0]);
                                        }
                                }
                        } else {
@@ -703,17 +884,17 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                }
 
                // Check if any pending claim request must be rescheduled
-               for (first_claim_txid, ref request) in self.pending_claim_requests.iter() {
+               for (package_id, request) in self.pending_claim_requests.iter() {
                        if let Some(h) = request.timer() {
                                if cur_height >= h {
-                                       bump_candidates.insert(*first_claim_txid, (*request).clone());
+                                       bump_candidates.insert(*package_id, request.clone());
                                }
                        }
                }
 
                // Build, bump and rebroadcast tx accordingly
                log_trace!(logger, "Bumping {} candidates", bump_candidates.len());
-               for (first_claim_txid, request) in bump_candidates.iter() {
+               for (package_id, request) in bump_candidates.iter() {
                        if let Some((new_timer, new_feerate, bump_claim)) = self.generate_claim(cur_height, &request, &*fee_estimator, &*logger) {
                                match bump_claim {
                                        OnchainClaim::Tx(bump_tx) => {
@@ -723,10 +904,16 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                                        #[cfg(anchors)]
                                        OnchainClaim::Event(claim_event) => {
                                                log_info!(logger, "Yielding RBF-bumped onchain event to spend inputs {:?}", request.outpoints());
-                                               self.pending_claim_events.insert(*first_claim_txid, claim_event);
+                                               #[cfg(debug_assertions)] {
+                                                       let num_existing = self.pending_claim_events.iter().
+                                                               filter(|entry| entry.0 == *package_id).count();
+                                                       assert!(num_existing == 0 || num_existing == 1);
+                                               }
+                                               self.pending_claim_events.retain(|event| event.0 != *package_id);
+                                               self.pending_claim_events.push((*package_id, claim_event));
                                        },
                                }
-                               if let Some(request) = self.pending_claim_requests.get_mut(first_claim_txid) {
+                               if let Some(request) = self.pending_claim_requests.get_mut(package_id) {
                                        request.set_timer(new_timer);
                                        request.set_feerate(new_feerate);
                                }
@@ -772,12 +959,12 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                                //- resurect outpoint back in its claimable set and regenerate tx
                                match entry.event {
                                        OnchainEvent::ContentiousOutpoint { package } => {
-                                               if let Some(ancestor_claimable_txid) = self.claimable_outpoints.get(&package.outpoints()[0]) {
-                                                       if let Some(request) = self.pending_claim_requests.get_mut(&ancestor_claimable_txid.0) {
+                                               if let Some(pending_claim) = self.claimable_outpoints.get(package.outpoints()[0]) {
+                                                       if let Some(request) = self.pending_claim_requests.get_mut(&pending_claim.0) {
                                                                request.merge_package(package);
                                                                // Using a HashMap guarantee us than if we have multiple outpoints getting
                                                                // resurrected only one bump claim tx is going to be broadcast
-                                                               bump_candidates.insert(ancestor_claimable_txid.clone(), request.clone());
+                                                               bump_candidates.insert(pending_claim.clone(), request.clone());
                                                        }
                                                }
                                        },
@@ -787,7 +974,7 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                                self.onchain_events_awaiting_threshold_conf.push(entry);
                        }
                }
-               for (_first_claim_txid_height, request) in bump_candidates.iter_mut() {
+               for ((_package_id, _), ref mut request) in bump_candidates.iter_mut() {
                        if let Some((new_timer, new_feerate, bump_claim)) = self.generate_claim(height, &request, fee_estimator, &&*logger) {
                                request.set_timer(new_timer);
                                request.set_feerate(new_feerate);
@@ -799,7 +986,13 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                                        #[cfg(anchors)]
                                        OnchainClaim::Event(claim_event) => {
                                                log_info!(logger, "Yielding onchain event after reorg to spend inputs {:?}", request.outpoints());
-                                               self.pending_claim_events.insert(_first_claim_txid_height.0, claim_event);
+                                               #[cfg(debug_assertions)] {
+                                                       let num_existing = self.pending_claim_events.iter()
+                                                               .filter(|entry| entry.0 == *_package_id).count();
+                                                       assert!(num_existing == 0 || num_existing == 1);
+                                               }
+                                               self.pending_claim_events.retain(|event| event.0 != *_package_id);
+                                               self.pending_claim_events.push((*_package_id, claim_event));
                                        },
                                }
                        }
@@ -824,12 +1017,12 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                self.claimable_outpoints.get(outpoint).is_some()
        }
 
-       pub(crate) fn get_relevant_txids(&self) -> Vec<Txid> {
-               let mut txids: Vec<Txid> = self.onchain_events_awaiting_threshold_conf
+       pub(crate) fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> {
+               let mut txids: Vec<(Txid, Option<BlockHash>)> = self.onchain_events_awaiting_threshold_conf
                        .iter()
-                       .map(|entry| entry.txid)
+                       .map(|entry| (entry.txid, entry.block_hash))
                        .collect();
-               txids.sort_unstable();
+               txids.sort_unstable_by_key(|(txid, _)| *txid);
                txids.dedup();
                txids
        }
@@ -920,6 +1113,37 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                htlc_tx
        }
 
+       #[cfg(anchors)]
+       pub(crate) fn generate_external_htlc_claim(
+               &self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>
+       ) -> Option<ExternalHTLCClaim> {
+               let find_htlc = |holder_commitment: &HolderCommitmentTransaction| -> Option<ExternalHTLCClaim> {
+                       let trusted_tx = holder_commitment.trust();
+                       if outp.txid != trusted_tx.txid() {
+                               return None;
+                       }
+                       trusted_tx.htlcs().iter().enumerate()
+                               .find(|(_, htlc)| if let Some(output_index) = htlc.transaction_output_index {
+                                       output_index == outp.vout
+                               } else {
+                                       false
+                               })
+                               .map(|(htlc_idx, htlc)| {
+                                       let counterparty_htlc_sig = holder_commitment.counterparty_htlc_sigs[htlc_idx];
+                                       ExternalHTLCClaim {
+                                               commitment_txid: trusted_tx.txid(),
+                                               per_commitment_number: trusted_tx.commitment_number(),
+                                               htlc: htlc.clone(),
+                                               preimage: *preimage,
+                                               counterparty_sig: counterparty_htlc_sig,
+                                       }
+                               })
+               };
+               // Check if the HTLC spends from the current holder commitment or the previous one otherwise.
+               find_htlc(&self.holder_commitment)
+                       .or_else(|| self.prev_holder_commitment.as_ref().map(|c| find_htlc(c)).flatten())
+       }
+
        pub(crate) fn opt_anchors(&self) -> bool {
                self.channel_transaction_parameters.opt_anchors.is_some()
        }