Skip to content

Commit 7c176ec

Browse files
author
Antoine Riard
committed
Structurify claim request handed between detection/reaction
1 parent 4faca51 commit 7c176ec

File tree

2 files changed

+55
-29
lines changed

2 files changed

+55
-29
lines changed

lightning/src/ln/channelmonitor.rs

Lines changed: 42 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -562,6 +562,28 @@ impl<R: ::std::io::Read> Readable<R> for InputMaterial {
562562
}
563563
}
564564

565+
/// ClaimRequest is a descriptor structure to communicate between detection
566+
/// and reaction module. They are generated by ChannelMonitor while parsing
567+
/// onchain txn leaked from a channel and handed over to OnchainTxHandler which
568+
/// is responsible for opportunistic aggregation, selecting and enforcing
569+
/// bumping logic, building and signing transactions.
570+
pub(crate) struct ClaimRequest {
571+
// Block height before which claiming is exclusive to one party,
572+
// after reaching it, claiming may be contentious.
573+
pub(crate) absolute_timelock: u32,
574+
// Timeout tx must have nLocktime set which means aggregating multiple
575+
// ones must take the higher nLocktime among them to satisfy all of them.
576+
// Sadly it has few pitfalls, a) it takes longuer to get fund back b) CLTV_DELTA
577+
// of a sooner-HTLC could be swallowed by the highest nLocktime of the HTLC set.
578+
// Do simplify we mark them as non-aggregable.
579+
pub(crate) aggregable: bool,
580+
// Basic bitcoin outpoint (txid, vout)
581+
pub(crate) outpoint: BitcoinOutPoint,
582+
// Following outpoint type, set of data needed to generate transaction digest
583+
// and satisfy witness program.
584+
pub(crate) witness_data: InputMaterial
585+
}
586+
565587
/// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
566588
/// once they mature to enough confirmations (ANTI_REORG_DELAY)
567589
#[derive(Clone, PartialEq)]
@@ -1411,7 +1433,7 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
14111433
/// HTLC-Success/HTLC-Timeout transactions.
14121434
/// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
14131435
/// revoked remote commitment tx
1414-
fn check_spend_remote_transaction(&mut self, tx: &Transaction, height: u32) -> (HashMap<Sha256dHash, Vec<(u32, bool, BitcoinOutPoint, InputMaterial)>>, (Sha256dHash, Vec<TxOut>), Vec<SpendableOutputDescriptor>) {
1436+
fn check_spend_remote_transaction(&mut self, tx: &Transaction, height: u32) -> (HashMap<Sha256dHash, Vec<ClaimRequest>>, (Sha256dHash, Vec<TxOut>), Vec<SpendableOutputDescriptor>) {
14151437
// Most secp and related errors trying to create keys means we have no hope of constructing
14161438
// a spend transaction...so we return no transactions to broadcast
14171439
let mut claim_requests_per_txid = HashMap::new();
@@ -1466,7 +1488,8 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
14661488
// First, process non-htlc outputs (to_local & to_remote)
14671489
for (idx, outp) in tx.output.iter().enumerate() {
14681490
if outp.script_pubkey == revokeable_p2wsh {
1469-
outpoints.push((height + self.our_to_self_delay as u32, true, BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 }, InputMaterial::Revoked { script: revokeable_redeemscript.clone(), pubkey: Some(revocation_pubkey), key: revocation_key, is_htlc: false, amount: outp.value }));
1491+
let witness_data = InputMaterial::Revoked { script: revokeable_redeemscript.clone(), pubkey: Some(revocation_pubkey), key: revocation_key, is_htlc: false, amount: outp.value };
1492+
outpoints.push(ClaimRequest { absolute_timelock: height + self.our_to_self_delay as u32, aggregable: true, outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 }, witness_data});
14701493
} else if Some(&outp.script_pubkey) == local_payment_p2wpkh.as_ref() {
14711494
spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
14721495
outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
@@ -1486,7 +1509,8 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
14861509
tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
14871510
return (claim_requests_per_txid, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
14881511
}
1489-
outpoints.push((htlc.cltv_expiry, true, BitcoinOutPoint { txid: commitment_txid, vout: transaction_output_index }, InputMaterial::Revoked { script: expected_script, pubkey: Some(revocation_pubkey), key: revocation_key, is_htlc: true, amount: tx.output[transaction_output_index as usize].value }));
1512+
let witness_data = InputMaterial::Revoked { script: expected_script, pubkey: Some(revocation_pubkey), key: revocation_key, is_htlc: true, amount: tx.output[transaction_output_index as usize].value };
1513+
outpoints.push(ClaimRequest { absolute_timelock: htlc.cltv_expiry, aggregable: true, outpoint: BitcoinOutPoint { txid: commitment_txid, vout: transaction_output_index }, witness_data });
14901514
}
14911515
}
14921516
}
@@ -1649,7 +1673,8 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
16491673
let preimage = if htlc.offered { if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
16501674
let aggregable = if !htlc.offered { false } else { true };
16511675
if preimage.is_some() || !htlc.offered {
1652-
outpoints.push((htlc.cltv_expiry, aggregable, BitcoinOutPoint { txid: commitment_txid, vout: transaction_output_index }, InputMaterial::RemoteHTLC { script: expected_script, key: htlc_privkey, preimage, amount: htlc.amount_msat / 1000, locktime: htlc.cltv_expiry }));
1676+
let witness_data = InputMaterial::RemoteHTLC { script: expected_script, key: htlc_privkey, preimage, amount: htlc.amount_msat / 1000, locktime: htlc.cltv_expiry };
1677+
outpoints.push(ClaimRequest { absolute_timelock: htlc.cltv_expiry, aggregable, outpoint: BitcoinOutPoint { txid: commitment_txid, vout: transaction_output_index }, witness_data });
16531678
}
16541679
}
16551680
}
@@ -1671,7 +1696,7 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
16711696
}
16721697

16731698
/// Attempts to claim a remote HTLC-Success/HTLC-Timeout's outputs using the revocation key
1674-
fn check_spend_remote_htlc(&mut self, tx: &Transaction, commitment_number: u64, height: u32) -> HashMap<Sha256dHash, Vec<(u32, bool, BitcoinOutPoint, InputMaterial)>> {
1699+
fn check_spend_remote_htlc(&mut self, tx: &Transaction, commitment_number: u64, height: u32) -> HashMap<Sha256dHash, Vec<ClaimRequest>> {
16751700
//TODO: send back new outputs to guarantee pending_claim_request consistency
16761701
if tx.input.len() != 1 || tx.output.len() != 1 || tx.input[0].witness.len() != 5 {
16771702
return HashMap::new()
@@ -1704,7 +1729,8 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
17041729
let htlc_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
17051730

17061731
log_trace!(self, "Remote HTLC broadcast {}:{}", htlc_txid, 0);
1707-
let outpoints = vec!((height + self.our_to_self_delay as u32, true, BitcoinOutPoint { txid: htlc_txid, vout: 0}, InputMaterial::Revoked { script: redeemscript, pubkey: Some(revocation_pubkey), key: revocation_key, is_htlc: false, amount: tx.output[0].value }));
1732+
let witness_data = InputMaterial::Revoked { script: redeemscript, pubkey: Some(revocation_pubkey), key: revocation_key, is_htlc: false, amount: tx.output[0].value };
1733+
let outpoints = vec!(ClaimRequest { absolute_timelock: height + self.our_to_self_delay as u32, aggregable: true, outpoint: BitcoinOutPoint { txid: htlc_txid, vout: 0}, witness_data });
17081734
let mut claimable_outpoints = HashMap::with_capacity(1);
17091735
claimable_outpoints.insert(htlc_txid, outpoints);
17101736
claimable_outpoints
@@ -1980,7 +2006,7 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
19802006
log_trace!(self, "Block {} at height {} connected with {} txn matched", block_hash, height, txn_matched.len());
19812007
let mut watch_outputs = Vec::new();
19822008
let mut spendable_outputs = Vec::new();
1983-
let mut claimable_outpoints = HashMap::new();
2009+
let mut claim_requests = HashMap::new();
19842010
for tx in txn_matched {
19852011
if tx.input.len() == 1 {
19862012
// Assuming our keys were not leaked (in which case we're screwed no matter what),
@@ -1998,12 +2024,12 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
19982024
};
19992025
if funding_txo.is_none() || (prevout.txid == funding_txo.as_ref().unwrap().0.txid && prevout.vout == funding_txo.as_ref().unwrap().0.index as u32) {
20002026
if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
2001-
let (mut new_outpoints, new_outputs, mut spendable_output) = self.check_spend_remote_transaction(&tx, height);
2027+
let (mut new_claim_requests, new_outputs, mut spendable_output) = self.check_spend_remote_transaction(&tx, height);
20022028
spendable_outputs.append(&mut spendable_output);
20032029
if !new_outputs.1.is_empty() {
20042030
watch_outputs.push(new_outputs);
20052031
}
2006-
if new_outpoints.is_empty() {
2032+
if new_claim_requests.is_empty() {
20072033
let (local_txn, mut spendable_output, new_outputs) = self.check_spend_local_transaction(&tx, height);
20082034
spendable_outputs.append(&mut spendable_output);
20092035
for tx in local_txn.iter() {
@@ -2014,20 +2040,20 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
20142040
watch_outputs.push(new_outputs);
20152041
}
20162042
}
2017-
for (k, v) in new_outpoints.drain() {
2018-
claimable_outpoints.insert(k, v);
2043+
for (k, v) in new_claim_requests.drain() {
2044+
claim_requests.insert(k, v);
20192045
}
20202046
}
2021-
if !funding_txo.is_none() && claimable_outpoints.is_empty() {
2047+
if !funding_txo.is_none() && claim_requests.is_empty() {
20222048
if let Some(spendable_output) = self.check_spend_closing_transaction(&tx) {
20232049
spendable_outputs.push(spendable_output);
20242050
}
20252051
}
20262052
} else {
20272053
if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
2028-
let mut new_outpoints = self.check_spend_remote_htlc(&tx, commitment_number, height);
2029-
for (k, v) in new_outpoints.drain() {
2030-
claimable_outpoints.insert(k, v);
2054+
let mut new_claim_requests = self.check_spend_remote_htlc(&tx, commitment_number, height);
2055+
for (k, v) in new_claim_requests.drain() {
2056+
claim_requests.insert(k, v);
20312057
}
20322058
}
20332059
}
@@ -2084,7 +2110,7 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
20842110
}
20852111
}
20862112
}
2087-
let mut spendable_output = self.onchain_tx_handler.block_connected(txn_matched, claimable_outpoints, height, broadcaster, &*fee_estimator);
2113+
let mut spendable_output = self.onchain_tx_handler.block_connected(txn_matched, claim_requests, height, &*broadcaster, &*fee_estimator);
20882114
spendable_outputs.append(&mut spendable_output);
20892115

20902116
self.last_block_hash = block_hash.clone();

lightning/src/ln/onchaintx.rs

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use secp256k1::Secp256k1;
1414
use secp256k1;
1515

1616
use ln::msgs::DecodeError;
17-
use ln::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER, InputMaterial};
17+
use ln::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER, InputMaterial, ClaimRequest};
1818
use ln::chan_utils::HTLCType;
1919
use chain::chaininterface::{FeeEstimator, BroadcasterInterface, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT};
2020
use chain::keysinterface::SpendableOutputDescriptor;
@@ -471,32 +471,32 @@ impl OnchainTxHandler {
471471
Some((new_timer, new_feerate, bumped_tx))
472472
}
473473

474-
pub(super) fn block_connected<B: Deref, F: Deref>(&mut self, txn_matched: &[&Transaction], claimable_outpoints: HashMap<Sha256dHash, Vec<(u32, bool, BitcoinOutPoint, InputMaterial)>>, height: u32, broadcaster: B, fee_estimator: F) -> Vec<SpendableOutputDescriptor>
474+
pub(super) fn block_connected<B: Deref, F: Deref>(&mut self, txn_matched: &[&Transaction], claim_requests: HashMap<Sha256dHash, Vec<ClaimRequest>>, height: u32, broadcaster: B, fee_estimator: F) -> Vec<SpendableOutputDescriptor>
475475
where B::Target: BroadcasterInterface,
476476
F::Target: FeeEstimator
477477
{
478478
let mut new_claims = Vec::new();
479479
let mut aggregated_claim = HashMap::new();
480480
let mut aggregated_soonest = ::std::u32::MAX;
481481
let mut new_pending_claim_requests = HashMap::with_capacity(new_claims.len());
482-
let mut new_claimable_outpoints = HashMap::with_capacity(claimable_outpoints.len());
482+
let mut new_claimable_outpoints = HashMap::with_capacity(claim_requests.len());
483483
let mut spendable_outputs = Vec::new();
484484

485485
// Try to aggregate outputs if they're 1) belong to same parent tx, 2) their
486486
// timelock expiration isn't imminent (<= CLTV_SHARED_CLAIM_BUFFER).
487-
for (_, siblings_outpoints) in claimable_outpoints {
488-
for outp in siblings_outpoints {
487+
for (_, siblings_requests) in claim_requests {
488+
for req in siblings_requests {
489489
// Don't claim a outpoint twice that would be bad for privacy and may uselessly lock a CPFP input for a while
490-
if let Some(_) = self.claimable_outpoints.get(&outp.2) { log_trace!(self, "Bouncing off outpoint {}:{}, already registered its claiming request", outp.2.txid, outp.2.vout); } else {
491-
log_trace!(self, "Test if outpoint can be aggregated with expiration {} against {}", outp.0, height + CLTV_SHARED_CLAIM_BUFFER);
492-
if outp.0 <= height + CLTV_SHARED_CLAIM_BUFFER || !outp.1 { // Don't aggregate if outpoint absolute timelock is soon or marked as non-aggregable
490+
if let Some(_) = self.claimable_outpoints.get(&req.outpoint) { log_trace!(self, "Bouncing off outpoint {}:{}, already registered its claiming request", req.outpoint.txid, req.outpoint.vout); } else {
491+
log_trace!(self, "Test if outpoint can be aggregated with expiration {} against {}", req.absolute_timelock, height + CLTV_SHARED_CLAIM_BUFFER);
492+
if req.absolute_timelock <= height + CLTV_SHARED_CLAIM_BUFFER || !req.aggregable { // Don't aggregate if outpoint absolute timelock is soon or marked as non-aggregable
493493
let mut single_input = HashMap::new();
494-
single_input.insert(outp.2, outp.3);
495-
new_claims.push((outp.0, single_input));
494+
single_input.insert(req.outpoint, req.witness_data);
495+
new_claims.push((req.absolute_timelock, single_input));
496496
} else {
497-
aggregated_claim.insert(outp.2, outp.3);
498-
if outp.0 < aggregated_soonest {
499-
aggregated_soonest = outp.0;
497+
aggregated_claim.insert(req.outpoint, req.witness_data);
498+
if req.absolute_timelock < aggregated_soonest {
499+
aggregated_soonest = req.absolute_timelock;
500500
}
501501
}
502502
}

0 commit comments

Comments
 (0)