Skip to content

Commit 0c89682

Browse files
author
Antoine Riard
committed
Structurify claim request handed between detection/reaction
1 parent 5d69595 commit 0c89682

File tree

2 files changed

+57
-31
lines changed

2 files changed

+57
-31
lines changed

lightning/src/ln/channelmonitor.rs

Lines changed: 44 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -499,6 +499,28 @@ impl<R: ::std::io::Read> Readable<R> for InputMaterial {
499499
}
500500
}
501501

502+
/// ClaimRequest is a descriptor structure to communicate between detection
503+
/// and reaction module. They are generated by ChannelMonitor while parsing
504+
/// onchain txn leaked from a channel and handed over to OnchainTxHandler which
505+
/// is responsible for opportunistic aggregation, selecting and enforcing
506+
/// bumping logic, building and signing transactions.
507+
pub(crate) struct ClaimRequest {
508+
// Block height before which claiming is exclusive to one party,
509+
// after reaching it, claiming may be contentious.
510+
pub(crate) absolute_timelock: u32,
511+
// Timeout tx must have nLocktime set which means aggregating multiple
512+
// ones must take the higher nLocktime among them to satisfy all of them.
513+
// Sadly it has few pitfalls, a) it takes longuer to get fund back b) CLTV_DELTA
514+
// of a sooner-HTLC could be swallowed by the highest nLocktime of the HTLC set.
515+
// Do simplify we mark them as non-aggregable.
516+
pub(crate) aggregable: bool,
517+
// Basic bitcoin outpoint (txid, vout)
518+
pub(crate) outpoint: BitcoinOutPoint,
519+
// Following outpoint type, set of data needed to generate transaction digest
520+
// and satisfy witness program.
521+
pub(crate) witness_data: InputMaterial
522+
}
523+
502524
/// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
503525
/// once they mature to enough confirmations (ANTI_REORG_DELAY)
504526
#[derive(Clone, PartialEq)]
@@ -1231,7 +1253,7 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
12311253
/// HTLC-Success/HTLC-Timeout transactions.
12321254
/// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
12331255
/// revoked remote commitment tx
1234-
fn check_spend_remote_transaction(&mut self, tx: &Transaction, height: u32) -> (HashMap<Sha256dHash, Vec<(u32, bool, BitcoinOutPoint, InputMaterial)>>, (Sha256dHash, Vec<TxOut>), Option<SpendableOutputDescriptor>) {
1256+
fn check_spend_remote_transaction(&mut self, tx: &Transaction, height: u32) -> (HashMap<Sha256dHash, Vec<ClaimRequest>>, (Sha256dHash, Vec<TxOut>), Option<SpendableOutputDescriptor>) {
12351257
// Most secp and related errors trying to create keys means we have no hope of constructing
12361258
// a spend transaction...so we return no transactions to broadcast
12371259
let mut claimable_outpoints = HashMap::new();
@@ -1286,7 +1308,8 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
12861308
// First, process non-htlc outputs (to_local & to_remote)
12871309
for (idx, outp) in tx.output.iter().enumerate() {
12881310
if outp.script_pubkey == revokeable_p2wsh {
1289-
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 }));
1311+
let witness_data = InputMaterial::Revoked { script: revokeable_redeemscript.clone(), pubkey: Some(revocation_pubkey), key: revocation_key, is_htlc: false, amount: outp.value };
1312+
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});
12901313
} else if Some(&outp.script_pubkey) == local_payment_p2wpkh.as_ref() {
12911314
spendable_descriptor = Some(SpendableOutputDescriptor::DynamicOutputP2WPKH {
12921315
outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
@@ -1306,7 +1329,8 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
13061329
tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
13071330
return (claimable_outpoints, (commitment_txid, watch_outputs), spendable_descriptor); // Corrupted per_commitment_data, fuck this user
13081331
}
1309-
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 }));
1332+
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 };
1333+
outpoints.push(ClaimRequest { absolute_timelock: htlc.cltv_expiry, aggregable: true, outpoint: BitcoinOutPoint { txid: commitment_txid, vout: transaction_output_index }, witness_data });
13101334
}
13111335
}
13121336
}
@@ -1469,7 +1493,8 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
14691493
let preimage = if htlc.offered { if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
14701494
let aggregable = if !htlc.offered { false } else { true };
14711495
if preimage.is_some() || !htlc.offered {
1472-
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 }));
1496+
let witness_data = InputMaterial::RemoteHTLC { script: expected_script, key: htlc_privkey, preimage, amount: htlc.amount_msat / 1000, locktime: htlc.cltv_expiry };
1497+
outpoints.push(ClaimRequest { absolute_timelock: htlc.cltv_expiry, aggregable, outpoint: BitcoinOutPoint { txid: commitment_txid, vout: transaction_output_index }, witness_data });
14731498
}
14741499
}
14751500
}
@@ -1491,7 +1516,7 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
14911516
}
14921517

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

15261551
log_trace!(self, "Remote HTLC broadcast {}:{}", htlc_txid, 0);
1527-
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 }));
1552+
let witness_data = InputMaterial::Revoked { script: redeemscript, pubkey: Some(revocation_pubkey), key: revocation_key, is_htlc: false, amount: tx.output[0].value };
1553+
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 });
15281554
let mut claimable_outpoints = HashMap::with_capacity(1);
15291555
claimable_outpoints.insert(htlc_txid, outpoints);
15301556
claimable_outpoints
@@ -1793,7 +1819,7 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
17931819
let mut watch_outputs = Vec::new();
17941820
let mut spendable_outputs = Vec::new();
17951821
let mut htlc_updated = Vec::new();
1796-
let mut claimable_outpoints = HashMap::new();
1822+
let mut claim_requests = HashMap::new();
17971823
for tx in txn_matched {
17981824
if tx.input.len() == 1 {
17991825
// Assuming our keys were not leaked (in which case we're screwed no matter what),
@@ -1811,14 +1837,14 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
18111837
};
18121838
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) {
18131839
if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
1814-
let (mut new_outpoints, new_outputs, spendable_output) = self.check_spend_remote_transaction(&tx, height);
1840+
let (mut new_claim_requests, new_outputs, spendable_output) = self.check_spend_remote_transaction(&tx, height);
18151841
if !new_outputs.1.is_empty() {
18161842
watch_outputs.push(new_outputs);
18171843
}
18181844
if let Some(spendable_output) = spendable_output {
18191845
spendable_outputs.push(spendable_output);
18201846
}
1821-
if new_outpoints.is_empty() {
1847+
if new_claim_requests.is_empty() {
18221848
let (local_txn, mut spendable_output, new_outputs) = self.check_spend_local_transaction(&tx, height);
18231849
spendable_outputs.append(&mut spendable_output);
18241850
for tx in local_txn.iter() {
@@ -1829,23 +1855,23 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
18291855
watch_outputs.push(new_outputs);
18301856
}
18311857
}
1832-
for (k, v) in new_outpoints.drain() {
1833-
claimable_outpoints.insert(k, v);
1858+
for (k, v) in new_claim_requests.drain() {
1859+
claim_requests.insert(k, v);
18341860
}
18351861
}
1836-
if !funding_txo.is_none() && claimable_outpoints.is_empty() {
1862+
if !funding_txo.is_none() && claim_requests.is_empty() {
18371863
if let Some(spendable_output) = self.check_spend_closing_transaction(&tx) {
18381864
spendable_outputs.push(spendable_output);
18391865
}
18401866
}
18411867
} else {
18421868
if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
1843-
let mut new_outpoints = self.check_spend_remote_htlc(&tx, commitment_number, height);
1844-
for (k, v) in new_outpoints.drain() {
1845-
claimable_outpoints.insert(k, v);
1869+
let mut new_claim_requests = self.check_spend_remote_htlc(&tx, commitment_number, height);
1870+
for (k, v) in new_claim_requests.drain() {
1871+
claim_requests.insert(k, v);
18461872
}
1847-
for (k, v) in new_outpoints.drain() {
1848-
claimable_outpoints.insert(k, v);
1873+
for (k, v) in new_claim_requests.drain() {
1874+
claim_requests.insert(k, v);
18491875
}
18501876
}
18511877
}
@@ -1902,7 +1928,7 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
19021928
}
19031929
}
19041930

1905-
let mut spendable_output = self.onchain_tx_handler.block_connected(txn_matched, claimable_outpoints, height, broadcaster, fee_estimator);
1931+
let mut spendable_output = self.onchain_tx_handler.block_connected(txn_matched, claim_requests, height, broadcaster, fee_estimator);
19061932
spendable_outputs.append(&mut spendable_output);
19071933

19081934
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
@@ -13,7 +13,7 @@ use bitcoin_hashes::sha256d::Hash as Sha256dHash;
1313
use secp256k1::Secp256k1;
1414

1515
use ln::msgs::DecodeError;
16-
use ln::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER, InputMaterial};
16+
use ln::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER, InputMaterial, ClaimRequest};
1717
use ln::chan_utils::HTLCType;
1818
use chain::chaininterface::{FeeEstimator, BroadcasterInterface, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT};
1919
use chain::keysinterface::SpendableOutputDescriptor;
@@ -467,29 +467,29 @@ impl OnchainTxHandler {
467467
Some((new_timer, new_feerate, bumped_tx))
468468
}
469469

470-
pub(crate) fn block_connected(&mut self, txn_matched: &[&Transaction], claimable_outpoints: HashMap<Sha256dHash, Vec<(u32, bool, BitcoinOutPoint, InputMaterial)>>, height: u32, broadcaster: &BroadcasterInterface, fee_estimator: &FeeEstimator) -> Vec<SpendableOutputDescriptor> {
470+
pub(crate) fn block_connected(&mut self, txn_matched: &[&Transaction], claim_requests: HashMap<Sha256dHash, Vec<ClaimRequest>>, height: u32, broadcaster: &BroadcasterInterface, fee_estimator: &FeeEstimator) -> Vec<SpendableOutputDescriptor> {
471471
let mut new_claims = Vec::new();
472472
let mut aggregated_claim = HashMap::new();
473473
let mut aggregated_soonest = ::std::u32::MAX;
474474
let mut new_pending_claim_requests = HashMap::with_capacity(new_claims.len());
475-
let mut new_claimable_outpoints = HashMap::with_capacity(claimable_outpoints.len());
475+
let mut new_claimable_outpoints = HashMap::with_capacity(claim_requests.len());
476476
let mut spendable_outputs = Vec::new();
477477

478478
// Try to aggregate outputs if they're 1) belong to same parent tx, 2) their
479479
// timelock expiration isn't imminent (<= CLTV_SHARED_CLAIM_BUFFER).
480-
for (_, siblings_outpoints) in claimable_outpoints {
481-
for outp in siblings_outpoints {
480+
for (_, siblings_requests) in claim_requests {
481+
for req in siblings_requests {
482482
// Don't claim a outpoint twice that would be bad for privacy and may uselessly lock a CPFP input for a while
483-
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 {
484-
log_trace!(self, "Test if outpoint can be aggregated with expiration {} against {}", outp.0, height + CLTV_SHARED_CLAIM_BUFFER);
485-
if outp.0 <= height + CLTV_SHARED_CLAIM_BUFFER || !outp.1 { // Don't aggregate if outpoint absolute timelock is soon or marked as non-aggregable
483+
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 {
484+
log_trace!(self, "Test if outpoint can be aggregated with expiration {} against {}", req.absolute_timelock, height + CLTV_SHARED_CLAIM_BUFFER);
485+
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
486486
let mut single_input = HashMap::new();
487-
single_input.insert(outp.2, outp.3);
488-
new_claims.push((outp.0, single_input));
487+
single_input.insert(req.outpoint, req.witness_data);
488+
new_claims.push((req.absolute_timelock, single_input));
489489
} else {
490-
aggregated_claim.insert(outp.2, outp.3);
491-
if outp.0 < aggregated_soonest {
492-
aggregated_soonest = outp.0;
490+
aggregated_claim.insert(req.outpoint, req.witness_data);
491+
if req.absolute_timelock < aggregated_soonest {
492+
aggregated_soonest = req.absolute_timelock;
493493
}
494494
}
495495
}

0 commit comments

Comments
 (0)