Merge pull request #1843 from TheBlueMatt/2022-11-fix-bp-exit-docs
[rust-lightning] / lightning / src / chain / onchaintx.rs
index 30493eb56c696ed2f055d477db033a4cecfe8500..2ce2ed41ba1fcf0e00325aec5005e8757d10c76b 100644 (file)
@@ -16,27 +16,37 @@ 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, Signature};
+use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature};
 use bitcoin::secp256k1;
 
-use ln::msgs::DecodeError;
-use ln::PaymentPreimage;
-use ln::chan_utils::{ChannelTransactionParameters, HolderCommitmentTransaction};
-use chain::chaininterface::{FeeEstimator, BroadcasterInterface};
-use chain::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER};
-use chain::keysinterface::{Sign, KeysInterface};
-use chain::package::PackageTemplate;
-use util::logger::Logger;
-use util::ser::{Readable, ReadableArgs, Writer, Writeable, VecWriter};
-use util::byte_utils;
-
-use prelude::*;
+use crate::ln::msgs::DecodeError;
+use crate::ln::PaymentPreimage;
+#[cfg(anchors)]
+use crate::ln::chan_utils;
+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};
+#[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::io;
+use crate::prelude::*;
 use alloc::collections::BTreeMap;
 use core::cmp;
 use core::ops::Deref;
 use core::mem::replace;
+#[cfg(anchors)]
+use core::mem::swap;
+use bitcoin::hashes::Hash;
 
 const MAX_ALLOC_SIZE: usize = 64*1024;
 
@@ -44,10 +54,11 @@ const MAX_ALLOC_SIZE: usize = 64*1024;
 /// transaction causing it.
 ///
 /// Used to determine when the on-chain event can be considered safe from a chain reorganization.
-#[derive(PartialEq)]
+#[derive(PartialEq, Eq)]
 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,
 }
 
@@ -63,7 +74,7 @@ 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)
-#[derive(PartialEq)]
+#[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.
@@ -78,23 +89,49 @@ enum OnchainEvent {
        }
 }
 
-impl_writeable_tlv_based!(OnchainEventEntry, {
-       (0, txid),
-       (2, height),
-       (4, event),
-}, {}, {});
+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),
+               });
+               Ok(())
+       }
+}
+
+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 block_hash = None;
+               let mut event = None;
+               read_tlv_fields!(reader, {
+                       (0, txid, required),
+                       (1, block_hash, option),
+                       (2, height, required),
+                       (4, event, ignorable),
+               });
+               if let Some(ev) = event {
+                       Ok(Some(Self { txid, height, block_hash, event: ev }))
+               } else {
+                       Ok(None)
+               }
+       }
+}
 
-impl_writeable_tlv_based_enum!(OnchainEvent,
+impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
        (0, Claim) => {
-               (0, claim_request),
-       }, {}, {},
+               (0, claim_request, required),
+       },
        (1, ContentiousOutpoint) => {
-               (0, package),
-       }, {}, {},
-;);
+               (0, package, required),
+       },
+);
 
 impl Readable for Option<Vec<Option<(usize, Signature)>>> {
-       fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
+       fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
                match Readable::read(reader)? {
                        0u8 => Ok(None),
                        1u8 => {
@@ -115,7 +152,7 @@ impl Readable for Option<Vec<Option<(usize, Signature)>>> {
 }
 
 impl Writeable for Option<Vec<Option<(usize, Signature)>>> {
-       fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
+       fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
                match self {
                        &Some(ref vec) => {
                                1u8.write(writer)?;
@@ -137,6 +174,29 @@ impl Writeable for Option<Vec<Option<(usize, Signature)>>> {
        }
 }
 
+// Represents the different types of claims for which events are yielded externally to satisfy said
+// claims.
+#[cfg(anchors)]
+pub(crate) enum ClaimEvent {
+       /// Event yielded to signal that the commitment transaction fee must be bumped to claim any
+       /// encumbered funds and proceed to HTLC resolution, if any HTLCs exist.
+       BumpCommitment {
+               package_target_feerate_sat_per_1000_weight: u32,
+               commitment_tx: Transaction,
+               anchor_output_idx: u32,
+       },
+}
+
+/// Represents the different ways an output can be claimed (i.e., spent to an address under our
+/// control) onchain.
+pub(crate) enum OnchainClaim {
+       /// A finalized transaction pending confirmation spending the output to claim.
+       Tx(Transaction),
+       #[cfg(anchors)]
+       /// An event yielded externally to signal additional inputs must be added to a transaction
+       /// pending confirmation spending the output to claim.
+       Event(ClaimEvent),
+}
 
 /// OnchainTxHandler receives claiming requests, aggregates them if it's sound, broadcast and
 /// do RBF bumping if possible.
@@ -168,6 +228,8 @@ pub struct OnchainTxHandler<ChannelSigner: Sign> {
        pub(crate) pending_claim_requests: HashMap<Txid, PackageTemplate>,
        #[cfg(not(test))]
        pending_claim_requests: HashMap<Txid, PackageTemplate>,
+       #[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
@@ -191,7 +253,7 @@ const SERIALIZATION_VERSION: u8 = 1;
 const MIN_SERIALIZATION_VERSION: u8 = 1;
 
 impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
-       pub(crate) fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
+       pub(crate) fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
                write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
 
                self.destination_script.write(writer)?;
@@ -236,13 +298,13 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                        entry.write(writer)?;
                }
 
-               write_tlv_fields!(writer, {}, {});
+               write_tlv_fields!(writer, {});
                Ok(())
        }
 }
 
 impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
-       fn read<R: ::std::io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
+       fn read<R: io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
                let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
 
                let destination_script = Readable::read(reader)?;
@@ -285,7 +347,7 @@ impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
                for _ in 0..locktimed_packages_len {
                        let locktime = Readable::read(reader)?;
                        let packages_len: u64 = Readable::read(reader)?;
-                       let mut packages = Vec::with_capacity(cmp::min(packages_len as usize, MAX_ALLOC_SIZE / std::mem::size_of::<PackageTemplate>()));
+                       let mut packages = Vec::with_capacity(cmp::min(packages_len as usize, MAX_ALLOC_SIZE / core::mem::size_of::<PackageTemplate>()));
                        for _ in 0..packages_len {
                                packages.push(Readable::read(reader)?);
                        }
@@ -295,10 +357,12 @@ impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
                let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
                let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
                for _ in 0..waiting_threshold_conf_len {
-                       onchain_events_awaiting_threshold_conf.push(Readable::read(reader)?);
+                       if let Some(val) = MaybeReadable::read(reader)? {
+                               onchain_events_awaiting_threshold_conf.push(val);
+                       }
                }
 
-               read_tlv_fields!(reader, {}, {});
+               read_tlv_fields!(reader, {});
 
                let mut secp_ctx = Secp256k1::new();
                secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
@@ -315,6 +379,8 @@ impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
                        locktimed_packages,
                        pending_claim_requests,
                        onchain_events_awaiting_threshold_conf,
+                       #[cfg(anchors)]
+                       pending_claim_events: HashMap::new(),
                        secp_ctx,
                })
        }
@@ -334,55 +400,169 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                        claimable_outpoints: HashMap::new(),
                        locktimed_packages: BTreeMap::new(),
                        onchain_events_awaiting_threshold_conf: Vec::new(),
+                       #[cfg(anchors)]
+                       pending_claim_events: HashMap::new(),
 
                        secp_ctx,
                }
        }
 
-       /// Lightning security model (i.e being able to redeem/timeout HTLC or penalize coutnerparty onchain) lays on the assumption of claim transactions getting confirmed before timelock expiration
-       /// (CSV or CLTV following cases). In case of high-fee spikes, claim tx may stuck in the mempool, so you need to bump its feerate quickly using Replace-By-Fee or Child-Pay-For-Parent.
-       /// Panics if there are signing errors, because signing operations in reaction to on-chain events
-       /// are not expected to fail, and if they do, we may lose funds.
-       fn generate_claim_tx<F: Deref, L: Deref>(&mut self, height: u32, cached_request: &PackageTemplate, fee_estimator: &F, logger: &L) -> Option<(Option<u32>, u64, Transaction)>
+       pub(crate) fn get_prev_holder_commitment_to_self_value(&self) -> Option<u64> {
+               self.prev_holder_commitment.as_ref().map(|commitment| commitment.to_broadcaster_value_sat())
+       }
+
+       pub(crate) fn get_cur_holder_commitment_to_self_value(&self) -> u64 {
+               self.holder_commitment.to_broadcaster_value_sat()
+       }
+
+       #[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<_>>()
+       }
+
+       /// Lightning security model (i.e being able to redeem/timeout HTLC or penalize counterparty
+       /// onchain) lays on the assumption of claim transactions getting confirmed before timelock
+       /// expiration (CSV or CLTV following cases). In case of high-fee spikes, claim tx may get stuck
+       /// in the mempool, so you need to bump its feerate quickly using Replace-By-Fee or
+       /// Child-Pay-For-Parent.
+       ///
+       /// Panics if there are signing errors, because signing operations in reaction to on-chain
+       /// events are not expected to fail, and if they do, we may lose funds.
+       fn generate_claim<F: Deref, L: Deref>(&mut self, cur_height: u32, cached_request: &PackageTemplate, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L) -> Option<(Option<u32>, u64, OnchainClaim)>
                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 {
+                       if let Some(first_claim_txid_height) = 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 { claim_request } = event_entry.event {
+                                               first_claim_txid_height.0 == claim_request
+                                       } 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(height));
+               let new_timer = Some(cached_request.get_height_timer(cur_height));
                if cached_request.is_malleable() {
                        let predicted_weight = cached_request.package_weight(&self.destination_script);
-                       if let Some((output_value, new_feerate)) = cached_request.compute_package_output(predicted_weight, 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_package(self, output_value, self.destination_script.clone(), logger).unwrap();
+                               let transaction = cached_request.finalize_malleable_package(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.get_weight());
-                               return Some((new_timer, new_feerate, transaction))
+                               assert!(predicted_weight >= transaction.weight());
+                               return Some((new_timer, new_feerate, OnchainClaim::Tx(transaction)))
                        }
                } else {
-                       // Note: Currently, amounts of holder outputs spending witnesses aren't used
-                       // as we can't malleate spending package to increase their feerate. This
-                       // should change with the remaining anchor output patchset.
-                       if let Some(transaction) = cached_request.finalize_package(self, 0, self.destination_script.clone(), logger) {
-                               return Some((None, 0, transaction));
+                       // Untractable packages cannot have their fees bumped through Replace-By-Fee. Some
+                       // packages may support fee bumping through Child-Pays-For-Parent, indicated by those
+                       // which require external funding.
+                       #[cfg(not(anchors))]
+                       let inputs = cached_request.inputs();
+                       #[cfg(anchors)]
+                       let mut inputs = cached_request.inputs();
+                       debug_assert_eq!(inputs.len(), 1);
+                       let tx = match cached_request.finalize_untractable_package(self, logger) {
+                               Some(tx) => tx,
+                               None => return None,
+                       };
+                       if !cached_request.requires_external_funding() {
+                               return Some((None, 0, OnchainClaim::Tx(tx)));
                        }
+                       #[cfg(anchors)]
+                       return inputs.find_map(|input| match input {
+                               // Commitment inputs with anchors support are the only untractable inputs supported
+                               // thus far that require external funding.
+                               PackageSolvingData::HolderFundingOutput(..) => {
+                                       debug_assert_eq!(tx.txid(), self.holder_commitment.trust().txid(),
+                                               "Holder commitment transaction mismatch");
+                                       // We'll locate an anchor output we can spend within the commitment transaction.
+                                       let funding_pubkey = &self.channel_transaction_parameters.holder_pubkeys.funding_pubkey;
+                                       match chan_utils::get_anchor_output(&tx, funding_pubkey) {
+                                               // An anchor output was found, so we should yield a funding event externally.
+                                               Some((idx, _)) => {
+                                                       // TODO: Use a lower confirmation target when both our and the
+                                                       // counterparty's latest commitment don't have any HTLCs present.
+                                                       let conf_target = ConfirmationTarget::HighPriority;
+                                                       let package_target_feerate_sat_per_1000_weight = cached_request
+                                                               .compute_package_feerate(fee_estimator, conf_target);
+                                                       Some((
+                                                               new_timer,
+                                                               package_target_feerate_sat_per_1000_weight as u64,
+                                                               OnchainClaim::Event(ClaimEvent::BumpCommitment {
+                                                                       package_target_feerate_sat_per_1000_weight,
+                                                                       commitment_tx: tx.clone(),
+                                                                       anchor_output_idx: idx,
+                                                               }),
+                                                       ))
+                                               },
+                                               // An anchor output was not found. There's nothing we can do other than
+                                               // attempt to broadcast the transaction with its current fee rate and hope
+                                               // it confirms. This is essentially the same behavior as a commitment
+                                               // transaction without anchor outputs.
+                                               None => Some((None, 0, OnchainClaim::Tx(tx.clone()))),
+                                       }
+                               },
+                               _ => {
+                                       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.
-       pub(crate) fn update_claims_view<B: Deref, F: Deref, L: Deref>(&mut self, txn_matched: &[&Transaction], requests: Vec<PackageTemplate>, height: u32, broadcaster: &B, fee_estimator: &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_trace!(logger, "Updating claims view at height {} with {} matched transactions and {} claim requests", height, txn_matched.len(), 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;
 
@@ -391,27 +571,27 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                for req in requests {
                        // Don't claim a outpoint twice that would be bad for privacy and may uselessly lock a CPFP input for a while
                        if let Some(_) = self.claimable_outpoints.get(req.outpoints()[0]) {
-                               log_trace!(logger, "Ignoring second claim for outpoint {}:{}, already registered its claiming request", req.outpoints()[0].txid, req.outpoints()[0].vout);
+                               log_info!(logger, "Ignoring second claim for outpoint {}:{}, already registered its claiming request", req.outpoints()[0].txid, req.outpoints()[0].vout);
                        } else {
                                let timelocked_equivalent_package = self.locktimed_packages.iter().map(|v| v.1.iter()).flatten()
                                        .find(|locked_package| locked_package.outpoints() == req.outpoints());
                                if let Some(package) = timelocked_equivalent_package {
-                                       log_trace!(logger, "Ignoring second claim for outpoint {}:{}, we already have one which we're waiting on a timelock at {} for.",
+                                       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());
                                        continue;
                                }
 
-                               if req.package_timelock() > height + 1 {
-                                       log_debug!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", req.package_timelock(), height);
+                               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);
                                        for outpoint in req.outpoints() {
-                                               log_debug!(logger, "  Outpoint {}", outpoint);
+                                               log_info!(logger, "  Outpoint {}", outpoint);
                                        }
                                        self.locktimed_packages.entry(req.package_timelock()).or_insert(Vec::new()).push(req);
                                        continue;
                                }
 
-                               log_trace!(logger, "Test if outpoint can be aggregated with expiration {} against {}", req.timelock(), height + CLTV_SHARED_CLAIM_BUFFER);
-                               if req.timelock() <= height + CLTV_SHARED_CLAIM_BUFFER || !req.aggregable() {
+                               log_trace!(logger, "Test if outpoint can be aggregated with expiration {} against {}", req.timelock(), cur_height + CLTV_SHARED_CLAIM_BUFFER);
+                               if req.timelock() <= cur_height + CLTV_SHARED_CLAIM_BUFFER || !req.aggregable() {
                                        // Don't aggregate if outpoint package timelock is soon or marked as non-aggregable
                                        preprocessed_requests.push(req);
                                } else if aggregated_request.is_none() {
@@ -425,8 +605,8 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                        preprocessed_requests.push(req);
                }
 
-               // Claim everything up to and including height + 1
-               let remaining_locked_packages = self.locktimed_packages.split_off(&(height + 2));
+               // Claim everything up to and including cur_height + 1
+               let remaining_locked_packages = self.locktimed_packages.split_off(&(cur_height + 2));
                for (pop_height, mut entry) in self.locktimed_packages.iter_mut() {
                        log_trace!(logger, "Restoring delayed claim of package(s) at their timelock at {}.", pop_height);
                        preprocessed_requests.append(&mut entry);
@@ -436,20 +616,51 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                // Generate claim transactions and track them to bump if necessary at
                // height timer expiration (i.e in how many blocks we're going to take action).
                for mut req in preprocessed_requests {
-                       if let Some((new_timer, new_feerate, tx)) = self.generate_claim_tx(height, &req, &*fee_estimator, &*logger) {
+                       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 = tx.txid();
+                               let txid = match claim {
+                                       OnchainClaim::Tx(tx) => {
+                                               log_info!(logger, "Broadcasting onchain {}", log_tx!(tx));
+                                               broadcaster.broadcast_transaction(&tx);
+                                               tx.txid()
+                                       },
+                                       #[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(),
+                                               };
+                                               self.pending_claim_events.insert(txid, claim_event);
+                                               txid
+                                       },
+                               };
                                for k in req.outpoints() {
-                                       log_trace!(logger, "Registering claiming request for {}:{}", k.txid, k.vout);
-                                       self.claimable_outpoints.insert(k.clone(), (txid, height));
+                                       log_info!(logger, "Registering claiming request for {}:{}", k.txid, k.vout);
+                                       self.claimable_outpoints.insert(k.clone(), (txid, conf_height));
                                }
                                self.pending_claim_requests.insert(txid, req);
-                               log_trace!(logger, "Broadcasting onchain {}", log_tx!(tx));
-                               broadcaster.broadcast_transaction(&tx);
                        }
                }
+       }
 
+       /// 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
@@ -476,7 +687,8 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                                                        () => {
                                                                let entry = OnchainEventEntry {
                                                                        txid: tx.txid(),
-                                                                       height,
+                                                                       height: conf_height,
+                                                                       block_hash: Some(conf_hash),
                                                                        event: OnchainEvent::Claim { claim_request: first_claim_txid_height.0.clone() }
                                                                };
                                                                if !self.onchain_events_awaiting_threshold_conf.contains(&entry) {
@@ -516,7 +728,8 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                        for package in claimed_outputs_material.drain(..) {
                                let entry = OnchainEventEntry {
                                        txid: tx.txid(),
-                                       height,
+                                       height: conf_height,
+                                       block_hash: Some(conf_hash),
                                        event: OnchainEvent::ContentiousOutpoint { package },
                                };
                                if !self.onchain_events_awaiting_threshold_conf.contains(&entry) {
@@ -529,18 +742,23 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                let onchain_events_awaiting_threshold_conf =
                        self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
                for entry in onchain_events_awaiting_threshold_conf {
-                       if entry.has_reached_confirmation_threshold(height) {
+                       if entry.has_reached_confirmation_threshold(cur_height) {
                                match entry.event {
                                        OnchainEvent::Claim { claim_request } => {
                                                // 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) {
                                                        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);
                                                        }
                                                }
                                        },
                                        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]);
                                        }
                                }
@@ -552,7 +770,7 @@ 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() {
                        if let Some(h) = request.timer() {
-                               if height >= h {
+                               if cur_height >= h {
                                        bump_candidates.insert(*first_claim_txid, (*request).clone());
                                }
                        }
@@ -561,9 +779,18 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                // Build, bump and rebroadcast tx accordingly
                log_trace!(logger, "Bumping {} candidates", bump_candidates.len());
                for (first_claim_txid, request) in bump_candidates.iter() {
-                       if let Some((new_timer, new_feerate, bump_tx)) = self.generate_claim_tx(height, &request, &*fee_estimator, &*logger) {
-                               log_trace!(logger, "Broadcasting onchain {}", log_tx!(bump_tx));
-                               broadcaster.broadcast_transaction(&bump_tx);
+                       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) => {
+                                               log_info!(logger, "Broadcasting RBF-bumped onchain {}", log_tx!(bump_tx));
+                                               broadcaster.broadcast_transaction(&bump_tx);
+                                       },
+                                       #[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);
+                                       },
+                               }
                                if let Some(request) = self.pending_claim_requests.get_mut(first_claim_txid) {
                                        request.set_timer(new_timer);
                                        request.set_feerate(new_feerate);
@@ -576,7 +803,7 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                &mut self,
                txid: &Txid,
                broadcaster: B,
-               fee_estimator: F,
+               fee_estimator: &LowerBoundedFeeEstimator<F>,
                logger: L,
        ) where
                B::Target: BroadcasterInterface,
@@ -596,7 +823,7 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                }
        }
 
-       pub(crate) fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, height: u32, broadcaster: B, fee_estimator: F, logger: L)
+       pub(crate) fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, height: u32, broadcaster: B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: L)
                where B::Target: BroadcasterInterface,
                      F::Target: FeeEstimator,
                                        L::Target: Logger,
@@ -625,12 +852,21 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                                self.onchain_events_awaiting_threshold_conf.push(entry);
                        }
                }
-               for (_, request) in bump_candidates.iter_mut() {
-                       if let Some((new_timer, new_feerate, bump_tx)) = self.generate_claim_tx(height, &request, &&*fee_estimator, &&*logger) {
+               for (_first_claim_txid_height, 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);
-                               log_info!(logger, "Broadcasting onchain {}", log_tx!(bump_tx));
-                               broadcaster.broadcast_transaction(&bump_tx);
+                               match bump_claim {
+                                       OnchainClaim::Tx(bump_tx) => {
+                                               log_info!(logger, "Broadcasting onchain {}", log_tx!(bump_tx));
+                                               broadcaster.broadcast_transaction(&bump_tx);
+                                       },
+                                       #[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);
+                                       },
+                               }
                        }
                }
                for (ancestor_claim_txid, request) in bump_candidates.drain() {
@@ -649,12 +885,16 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                }
        }
 
-       pub(crate) fn get_relevant_txids(&self) -> Vec<Txid> {
-               let mut txids: Vec<Txid> = self.onchain_events_awaiting_threshold_conf
+       pub(crate) fn is_output_spend_pending(&self, outpoint: &BitcoinOutPoint) -> bool {
+               self.claimable_outpoints.get(outpoint).is_some()
+       }
+
+       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
        }
@@ -745,6 +985,10 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                htlc_tx
        }
 
+       pub(crate) fn opt_anchors(&self) -> bool {
+               self.channel_transaction_parameters.opt_anchors.is_some()
+       }
+
        #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
        pub(crate) fn unsafe_get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>) -> Option<Transaction> {
                let latest_had_sigs = self.holder_htlc_sigs.is_some();