//! 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::hashes::Hash;
-#[cfg(anchors)]
-use bitcoin::hashes::HashEngine;
-#[cfg(anchors)]
+use bitcoin::hashes::{Hash, HashEngine};
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::hash_types::{Txid, BlockHash};
use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature};
use bitcoin::secp256k1;
+use crate::chain::chaininterface::compute_feerate_sat_per_1000_weight;
use crate::sign::{ChannelSigner, EntropySource, SignerProvider};
use crate::ln::msgs::DecodeError;
use crate::ln::PaymentPreimage;
-#[cfg(anchors)]
-use crate::ln::chan_utils::{self, HTLCOutputInCommitment};
-use crate::ln::chan_utils::{ChannelTransactionParameters, HolderCommitmentTransaction};
+use crate::ln::chan_utils::{self, ChannelTransactionParameters, HTLCOutputInCommitment, HolderCommitmentTransaction};
use crate::chain::ClaimId;
-#[cfg(anchors)]
-use crate::chain::chaininterface::ConfirmationTarget;
-use crate::chain::chaininterface::{FeeEstimator, BroadcasterInterface, LowerBoundedFeeEstimator};
+use crate::chain::chaininterface::{ConfirmationTarget, FeeEstimator, BroadcasterInterface, LowerBoundedFeeEstimator};
use crate::chain::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER};
use crate::sign::WriteableEcdsaChannelSigner;
-#[cfg(anchors)]
-use crate::chain::package::PackageSolvingData;
-use crate::chain::package::PackageTemplate;
+use crate::chain::package::{PackageSolvingData, PackageTemplate};
use crate::util::logger::Logger;
use crate::util::ser::{Readable, ReadableArgs, MaybeReadable, UpgradableRequired, Writer, Writeable, VecWriter};
use core::cmp;
use core::ops::Deref;
use core::mem::replace;
-#[cfg(anchors)]
use core::mem::swap;
use crate::ln::features::ChannelTypeFeatures;
/// transaction causing it.
///
/// Used to determine when the on-chain event can be considered safe from a chain reorganization.
-#[derive(PartialEq, Eq)]
+#[derive(Clone, PartialEq, Eq)]
struct OnchainEventEntry {
txid: Txid,
height: u32,
/// 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)]
+#[derive(Clone, PartialEq, Eq)]
enum OnchainEvent {
/// 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
}
}
-#[cfg(anchors)]
/// The claim commonly referred to as the pre-signed second-stage HTLC transaction.
+#[derive(Clone, PartialEq, Eq)]
pub(crate) struct ExternalHTLCClaim {
pub(crate) commitment_txid: Txid,
pub(crate) per_commitment_number: u64,
// Represents the different types of claims for which events are yielded externally to satisfy said
// claims.
-#[cfg(anchors)]
+#[derive(Clone, PartialEq, Eq)]
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.
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.
+#[derive(Clone)]
pub struct OnchainTxHandler<ChannelSigner: WriteableEcdsaChannelSigner> {
destination_script: Script,
holder_commitment: HolderCommitmentTransaction,
// - 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: Vec<(ClaimId, ClaimEvent)>,
// Used to link outpoints claimed in a connected block to a pending claim request. The keys
locktimed_packages,
pending_claim_requests,
onchain_events_awaiting_threshold_conf,
- #[cfg(anchors)]
pending_claim_events: Vec::new(),
secp_ctx,
})
claimable_outpoints: HashMap::new(),
locktimed_packages: BTreeMap::new(),
onchain_events_awaiting_threshold_conf: Vec::new(),
- #[cfg(anchors)]
pending_claim_events: Vec::new(),
secp_ctx,
}
self.holder_commitment.to_broadcaster_value_sat()
}
- #[cfg(anchors)]
pub(crate) fn get_and_clear_pending_claim_events(&mut self) -> Vec<(ClaimId, ClaimEvent)> {
let mut events = Vec::new();
swap(&mut events, &mut self.pending_claim_events);
log_info!(logger, "{} onchain {}", log_start, log_tx!(tx));
broadcaster.broadcast_transactions(&[&tx]);
},
- #[cfg(anchors)]
OnchainClaim::Event(event) => {
let log_start = if bumped_feerate { "Yielding fee-bumped" } else { "Replaying" };
log_info!(logger, "{} onchain event to spend inputs {:?}", log_start,
// didn't receive confirmation of it before, or not enough reorg-safe depth on top of it).
let new_timer = 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, force_feerate_bump
- );
- 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;
- }
+ if cached_request.requires_external_funding() {
+ let target_feerate_sat_per_1000_weight = cached_request.compute_package_feerate(
+ fee_estimator, ConfirmationTarget::HighPriority, force_feerate_bump
+ );
+ 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;
}
}
// 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) {
if !cached_request.requires_external_funding() {
return Some((new_timer, 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(..) => {
+ PackageSolvingData::HolderFundingOutput(output) => {
debug_assert_eq!(tx.txid(), self.holder_commitment.trust().txid(),
"Holder commitment transaction mismatch");
+
+ let conf_target = ConfirmationTarget::HighPriority;
+ let package_target_feerate_sat_per_1000_weight = cached_request
+ .compute_package_feerate(fee_estimator, conf_target, force_feerate_bump);
+ if let Some(input_amount_sat) = output.funding_amount {
+ let fee_sat = input_amount_sat - tx.output.iter().map(|output| output.value).sum::<u64>();
+ let commitment_tx_feerate_sat_per_1000_weight =
+ compute_feerate_sat_per_1000_weight(fee_sat, tx.weight() as u64);
+ if commitment_tx_feerate_sat_per_1000_weight >= package_target_feerate_sat_per_1000_weight {
+ log_debug!(logger, "Pre-signed {} already has feerate {} sat/kW above required {} sat/kW",
+ log_tx!(tx), commitment_tx_feerate_sat_per_1000_weight,
+ package_target_feerate_sat_per_1000_weight);
+ return Some((new_timer, 0, OnchainClaim::Tx(tx.clone())));
+ }
+ }
+
// 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) {
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, force_feerate_bump);
Some((
new_timer,
package_target_feerate_sat_per_1000_weight as u64,
) {
req.set_timer(new_timer);
req.set_feerate(new_feerate);
+ // Once a pending claim has an id assigned, it remains fixed until the claim is
+ // satisfied, regardless of whether the claim switches between different variants of
+ // `OnchainClaim`.
let claim_id = match claim {
OnchainClaim::Tx(tx) => {
log_info!(logger, "Broadcasting onchain {}", log_tx!(tx));
broadcaster.broadcast_transactions(&[&tx]);
ClaimId(tx.txid().into_inner())
},
- #[cfg(anchors)]
OnchainClaim::Event(claim_event) => {
log_info!(logger, "Yielding onchain event to spend inputs {:?}", req.outpoints());
let claim_id = match claim_event {
// 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 == *claim_id).count();
- assert!(existing == 0 || existing == 1);
- }
- self.pending_claim_events.retain(|entry| entry.0 != *claim_id);
+ #[cfg(debug_assertions)] {
+ let existing = self.pending_claim_events.iter()
+ .filter(|entry| entry.0 == *claim_id).count();
+ assert!(existing == 0 || existing == 1);
}
+ self.pending_claim_events.retain(|entry| entry.0 != *claim_id);
}
}
break; //No need to iterate further, either tx is our or their
outpoint, log_bytes!(claim_id.0));
self.claimable_outpoints.remove(outpoint);
}
- #[cfg(anchors)] {
- #[cfg(debug_assertions)] {
- let num_existing = self.pending_claim_events.iter()
- .filter(|entry| entry.0 == claim_id).count();
- assert!(num_existing == 0 || num_existing == 1);
- }
- self.pending_claim_events.retain(|(id, _)| *id != claim_id);
+ #[cfg(debug_assertions)] {
+ let num_existing = self.pending_claim_events.iter()
+ .filter(|entry| entry.0 == claim_id).count();
+ assert!(num_existing == 0 || num_existing == 1);
}
+ self.pending_claim_events.retain(|(id, _)| *id != claim_id);
}
},
OnchainEvent::ContentiousOutpoint { package } => {
log_info!(logger, "Broadcasting RBF-bumped onchain {}", log_tx!(bump_tx));
broadcaster.broadcast_transactions(&[&bump_tx]);
},
- #[cfg(anchors)]
OnchainClaim::Event(claim_event) => {
log_info!(logger, "Yielding RBF-bumped onchain event to spend inputs {:?}", request.outpoints());
#[cfg(debug_assertions)] {
log_info!(logger, "Broadcasting onchain {}", log_tx!(bump_tx));
broadcaster.broadcast_transactions(&[&bump_tx]);
},
- #[cfg(anchors)]
OnchainClaim::Event(claim_event) => {
log_info!(logger, "Yielding onchain event after reorg to spend inputs {:?}", request.outpoints());
#[cfg(debug_assertions)] {
ret
}
+ pub(crate) fn get_unsigned_holder_commitment_tx(&self) -> &Transaction {
+ &self.holder_commitment.trust().built_transaction().transaction
+ }
+
//TODO: getting lastest holder transactions should be infallible and result in us "force-closing the channel", but we may
- // have empty holder commitment transaction if a ChannelMonitor is asked to force-close just after Channel::get_outbound_funding_created,
+ // have empty holder commitment transaction if a ChannelMonitor is asked to force-close just after OutboundV1Channel::get_funding_created,
// before providing a initial commitment transaction. For outbound channel, init ChannelMonitor at Channel::funding_signed, there is nothing
// to monitor before.
pub(crate) fn get_fully_signed_holder_tx(&mut self, funding_redeemscript: &Script) -> Transaction {
htlc_tx
}
- #[cfg(anchors)]
pub(crate) fn generate_external_htlc_claim(
&self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>
) -> Option<ExternalHTLCClaim> {