Skip to content

Commit 006777a

Browse files
committed
Generate ClaimEvent for HolderFundingOutput inputs from anchor channels
1 parent af0bdec commit 006777a

File tree

3 files changed

+136
-26
lines changed

3 files changed

+136
-26
lines changed

lightning/src/chain/onchaintx.rs

Lines changed: 89 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,12 @@ use bitcoin::secp256k1;
2323

2424
use ln::msgs::DecodeError;
2525
use ln::PaymentPreimage;
26+
use ln::chan_utils;
2627
use ln::chan_utils::{ChannelTransactionParameters, HolderCommitmentTransaction};
27-
use chain::chaininterface::{FeeEstimator, BroadcasterInterface, LowerBoundedFeeEstimator};
28+
use chain::chaininterface::{ConfirmationTarget, FeeEstimator, BroadcasterInterface, LowerBoundedFeeEstimator};
2829
use chain::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER};
2930
use chain::keysinterface::{Sign, KeysInterface};
30-
use chain::package::PackageTemplate;
31+
use chain::package::{PackageSolvingData, PackageTemplate};
3132
use util::logger::Logger;
3233
use util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, VecWriter};
3334
use util::byte_utils;
@@ -162,8 +163,17 @@ impl Writeable for Option<Vec<Option<(usize, Signature)>>> {
162163
}
163164
}
164165

166+
pub(crate) enum ClaimEvent {
167+
BumpCommitment {
168+
package_target_feerate_sat_per_1000_weight: u32,
169+
commitment_tx: Transaction,
170+
anchor_output_idx: u32,
171+
},
172+
}
173+
165174
pub(crate) enum OnchainClaim {
166175
Tx(Transaction),
176+
Event(ClaimEvent),
167177
}
168178

169179
/// OnchainTxHandler receives claiming requests, aggregates them if it's sound, broadcast and
@@ -196,6 +206,7 @@ pub struct OnchainTxHandler<ChannelSigner: Sign> {
196206
pub(crate) pending_claim_requests: HashMap<Txid, PackageTemplate>,
197207
#[cfg(not(test))]
198208
pending_claim_requests: HashMap<Txid, PackageTemplate>,
209+
pending_claim_events: HashMap<Txid, ClaimEvent>,
199210

200211
// Used to link outpoints claimed in a connected block to a pending claim request.
201212
// Key is outpoint than monitor parsing has detected we have keys/scripts to claim
@@ -345,6 +356,7 @@ impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
345356
locktimed_packages,
346357
pending_claim_requests,
347358
onchain_events_awaiting_threshold_conf,
359+
pending_claim_events: HashMap::new(),
348360
secp_ctx,
349361
})
350362
}
@@ -364,6 +376,7 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
364376
claimable_outpoints: HashMap::new(),
365377
locktimed_packages: BTreeMap::new(),
366378
onchain_events_awaiting_threshold_conf: Vec::new(),
379+
pending_claim_events: HashMap::new(),
367380

368381
secp_ctx,
369382
}
@@ -377,10 +390,14 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
377390
self.holder_commitment.to_broadcaster_value_sat()
378391
}
379392

380-
/// 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
381-
/// (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.
382-
/// Panics if there are signing errors, because signing operations in reaction to on-chain events
383-
/// are not expected to fail, and if they do, we may lose funds.
393+
/// Lightning security model (i.e being able to redeem/timeout HTLC or penalize counterparty
394+
/// onchain) lays on the assumption of claim transactions getting confirmed before timelock
395+
/// expiration (CSV or CLTV following cases). In case of high-fee spikes, claim tx may get stuck
396+
/// in the mempool, so you need to bump its feerate quickly using Replace-By-Fee or
397+
/// Child-Pay-For-Parent.
398+
///
399+
/// Panics if there are signing errors, because signing operations in reaction to on-chain
400+
/// events are not expected to fail, and if they do, we may lose funds.
384401
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)>
385402
where F::Target: FeeEstimator,
386403
L::Target: Logger,
@@ -402,12 +419,51 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
402419
return Some((new_timer, new_feerate, OnchainClaim::Tx(transaction)))
403420
}
404421
} else {
405-
// Note: Currently, amounts of holder outputs spending witnesses aren't used
406-
// as we can't malleate spending package to increase their feerate. This
407-
// should change with the remaining anchor output patchset.
408-
if let Some(transaction) = cached_request.finalize_untractable_package(self, logger) {
409-
return Some((None, 0, OnchainClaim::Tx(transaction)));
422+
// Untractable packages cannot have their fees bumped through Replace-By-Fee. Some
423+
// packages may support fee bumping through Child-Pays-For-Parent, indicated by those
424+
// which require external funding.
425+
let inputs = cached_request.inputs();
426+
debug_assert_eq!(inputs.len(), 1);
427+
let tx = match cached_request.finalize_untractable_package(self, logger) {
428+
Some(tx) => tx,
429+
None => return None,
430+
};
431+
if !cached_request.requires_external_funding() {
432+
return Some((None, 0, OnchainClaim::Tx(tx)));
410433
}
434+
return inputs.iter().find_map(|input| match input {
435+
// Commitment inputs with anchors support are the only untractable inputs supported
436+
// thus far that require external funding.
437+
PackageSolvingData::HolderFundingOutput(..) => {
438+
// We'll locate an anchor output we can spend within the commitment transaction.
439+
let funding_pubkey = &self.channel_transaction_parameters.holder_pubkeys.funding_pubkey;
440+
match chan_utils::get_anchor_output(&tx, funding_pubkey) {
441+
// An anchor output was found, so we should yield a funding event externally.
442+
Some((idx, _)) => {
443+
let package_target_feerate_sat_per_1000_weight = cached_request
444+
.compute_package_feerate(fee_estimator, ConfirmationTarget::HighPriority);
445+
Some((
446+
new_timer,
447+
package_target_feerate_sat_per_1000_weight as u64,
448+
OnchainClaim::Event(ClaimEvent::BumpCommitment {
449+
package_target_feerate_sat_per_1000_weight,
450+
commitment_tx: tx.clone(),
451+
anchor_output_idx: idx,
452+
}),
453+
))
454+
},
455+
// An anchor output was not found. There's nothing we can do other than
456+
// attempt to broadcast the transaction with its current fee rate and hope
457+
// it confirms. This is essentially the same behavior as a commitment
458+
// transaction without anchor outputs.
459+
None => Some((None, 0, OnchainClaim::Tx(tx.clone()))),
460+
}
461+
},
462+
_ => {
463+
debug_assert!(false, "Only HolderFundingOutput inputs should be untractable and require external funding");
464+
None
465+
},
466+
});
411467
}
412468
None
413469
}
@@ -481,18 +537,25 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
481537
if let Some((new_timer, new_feerate, claim)) = self.generate_claim(cur_height, &req, &*fee_estimator, &*logger) {
482538
req.set_timer(new_timer);
483539
req.set_feerate(new_feerate);
484-
match claim {
540+
let txid = match claim {
485541
OnchainClaim::Tx(tx) => {
486-
let txid = tx.txid();
487-
for k in req.outpoints() {
488-
log_info!(logger, "Registering claiming request for {}:{}", k.txid, k.vout);
489-
self.claimable_outpoints.insert(k.clone(), (txid, conf_height));
490-
}
491-
self.pending_claim_requests.insert(txid, req);
492542
log_info!(logger, "Broadcasting onchain {}", log_tx!(tx));
493543
broadcaster.broadcast_transaction(&tx);
544+
tx.txid()
545+
},
546+
OnchainClaim::Event(claim_event) => {
547+
let txid = match claim_event {
548+
ClaimEvent::BumpCommitment { ref commitment_tx, .. } => commitment_tx.txid(),
549+
};
550+
self.pending_claim_events.insert(txid, claim_event);
551+
txid
494552
},
553+
};
554+
for k in req.outpoints() {
555+
log_info!(logger, "Registering claiming request for {}:{}", k.txid, k.vout);
556+
self.claimable_outpoints.insert(k.clone(), (txid, conf_height));
495557
}
558+
self.pending_claim_requests.insert(txid, req);
496559
}
497560
}
498561

@@ -584,6 +647,7 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
584647
for outpoint in request.outpoints() {
585648
log_debug!(logger, "Removing claim tracking for {} due to maturation of claim tx {}.", outpoint, claim_request);
586649
self.claimable_outpoints.remove(&outpoint);
650+
self.pending_claim_events.remove(&claim_request);
587651
}
588652
}
589653
},
@@ -616,6 +680,9 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
616680
log_info!(logger, "Broadcasting RBF-bumped onchain {}", log_tx!(bump_tx));
617681
broadcaster.broadcast_transaction(&bump_tx);
618682
},
683+
OnchainClaim::Event(claim_event) => {
684+
self.pending_claim_events.insert(*first_claim_txid, claim_event);
685+
},
619686
}
620687
if let Some(request) = self.pending_claim_requests.get_mut(first_claim_txid) {
621688
request.set_timer(new_timer);
@@ -678,7 +745,7 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
678745
self.onchain_events_awaiting_threshold_conf.push(entry);
679746
}
680747
}
681-
for (_, request) in bump_candidates.iter_mut() {
748+
for (first_claim_txid_height, request) in bump_candidates.iter_mut() {
682749
if let Some((new_timer, new_feerate, bump_claim)) = self.generate_claim(height, &request, fee_estimator, &&*logger) {
683750
request.set_timer(new_timer);
684751
request.set_feerate(new_feerate);
@@ -687,6 +754,9 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
687754
log_info!(logger, "Broadcasting onchain {}", log_tx!(bump_tx));
688755
broadcaster.broadcast_transaction(&bump_tx);
689756
},
757+
OnchainClaim::Event(claim_event) => {
758+
self.pending_claim_events.insert(first_claim_txid_height.0, claim_event);
759+
},
690760
}
691761
}
692762
}

lightning/src/chain/package.rs

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ use util::ser::{Readable, Writer, Writeable};
3434
use io;
3535
use prelude::*;
3636
use core::cmp;
37+
use core::convert::TryInto;
3738
use core::mem;
3839
use core::ops::Deref;
3940
use bitcoin::{PackedLockTime, Sequence, Witness};
@@ -548,6 +549,9 @@ impl PackageTemplate {
548549
pub(crate) fn outpoints(&self) -> Vec<&BitcoinOutPoint> {
549550
self.inputs.iter().map(|(o, _)| o).collect()
550551
}
552+
pub(crate) fn inputs(&self) -> Vec<&PackageSolvingData> {
553+
self.inputs.iter().map(|(_, i)| i).collect()
554+
}
551555
pub(crate) fn split_package(&mut self, split_outp: &BitcoinOutPoint) -> Option<PackageTemplate> {
552556
match self.malleability {
553557
PackageMalleability::Malleable => {
@@ -611,7 +615,7 @@ impl PackageTemplate {
611615
}
612616
/// Gets the amount of all outptus being spent by this package, only valid for malleable
613617
/// packages.
614-
fn package_amount(&self) -> u64 {
618+
pub(crate) fn package_amount(&self) -> u64 {
615619
let mut amounts = 0;
616620
for (_, outp) in self.inputs.iter() {
617621
amounts += outp.amount();
@@ -713,14 +717,42 @@ impl PackageTemplate {
713717
}
714718
None
715719
}
720+
721+
/// Computes a feerate based on the given confirmation target. If a previous feerate was used,
722+
/// and the new feerate is below it, we'll use a 25% increase of the previous feerate instead of
723+
/// the new one.
724+
pub(crate) fn compute_package_feerate<F: Deref>(
725+
&self, fee_estimator: &LowerBoundedFeeEstimator<F>, conf_target: ConfirmationTarget,
726+
) -> u32 where F::Target: FeeEstimator {
727+
let feerate_estimate = fee_estimator.bounded_sat_per_1000_weight(conf_target);
728+
if self.feerate_previous != 0 {
729+
// If old feerate inferior to actual one given back by Fee Estimator, use it to compute new fee...
730+
if feerate_estimate as u64 > self.feerate_previous {
731+
feerate_estimate
732+
} else {
733+
// ...else just increase the previous feerate by 25% (because that's a nice number)
734+
(self.feerate_previous + (self.feerate_previous / 4)).try_into().unwrap()
735+
}
736+
} else {
737+
feerate_estimate
738+
}
739+
}
740+
741+
pub(crate) fn requires_external_funding(&self) -> bool {
742+
self.inputs.iter().find(|input| match input.1 {
743+
PackageSolvingData::HolderFundingOutput(ref outp) => outp.opt_anchors(),
744+
_ => false,
745+
}).is_some()
746+
}
747+
716748
pub (crate) fn build_package(txid: Txid, vout: u32, input_solving_data: PackageSolvingData, soonest_conf_deadline: u32, aggregable: bool, height_original: u32) -> Self {
717749
let malleability = match input_solving_data {
718-
PackageSolvingData::RevokedOutput(..) => { PackageMalleability::Malleable },
719-
PackageSolvingData::RevokedHTLCOutput(..) => { PackageMalleability::Malleable },
720-
PackageSolvingData::CounterpartyOfferedHTLCOutput(..) => { PackageMalleability::Malleable },
721-
PackageSolvingData::CounterpartyReceivedHTLCOutput(..) => { PackageMalleability::Malleable },
722-
PackageSolvingData::HolderHTLCOutput(..) => { PackageMalleability::Untractable },
723-
PackageSolvingData::HolderFundingOutput(..) => { PackageMalleability::Untractable },
750+
PackageSolvingData::RevokedOutput(..) => PackageMalleability::Malleable,
751+
PackageSolvingData::RevokedHTLCOutput(..) => PackageMalleability::Malleable,
752+
PackageSolvingData::CounterpartyOfferedHTLCOutput(..) => PackageMalleability::Malleable,
753+
PackageSolvingData::CounterpartyReceivedHTLCOutput(..) => PackageMalleability::Malleable,
754+
PackageSolvingData::HolderHTLCOutput(..) => PackageMalleability::Untractable,
755+
PackageSolvingData::HolderFundingOutput(..) => PackageMalleability::Untractable,
724756
};
725757
let mut inputs = Vec::with_capacity(1);
726758
inputs.push((BitcoinOutPoint { txid, vout }, input_solving_data));

lightning/src/ln/chan_utils.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -726,6 +726,14 @@ pub fn get_anchor_redeemscript(funding_pubkey: &PublicKey) -> Script {
726726
.into_script()
727727
}
728728

729+
/// Locates the output with an anchor script paying to `funding_pubkey` within `commitment_tx`.
730+
pub(crate) fn get_anchor_output<'a>(commitment_tx: &'a Transaction, funding_pubkey: &PublicKey) -> Option<(u32, &'a TxOut)> {
731+
let anchor_script = chan_utils::get_anchor_redeemscript(funding_pubkey).to_v0_p2wsh();
732+
commitment_tx.output.iter().enumerate()
733+
.find(|(_, txout)| txout.script_pubkey == anchor_script)
734+
.map(|(idx, txout)| (idx as u32, txout))
735+
}
736+
729737
/// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
730738
/// The fields are organized by holder/counterparty.
731739
///

0 commit comments

Comments
 (0)