Skip to content

Commit 0acaca7

Browse files
committed
Expose counterparty-revoked-outputs in get_claimable_balance
This uses the various new tracking added in the prior commits to expose a new `Balance` type - `CounterpartyRevokedOutputClaimable`. Some nontrivial work is required, however, as we now have to track HTLC outputs as spendable in a transaction that comes *after* an HTLC-Success/HTLC-Timeout transaction, which we previously didn't need to do. Thus, we have to check if an `onchain_events_awaiting_threshold_conf` event spends a commitment transaction's HTLC output while walking events. Further, because we now need to track HTLC outputs after the HTLC-Success/HTLC-Timeout confirms, and because we have to track the counterparty's `to_self` output as a contentious output which could be claimed by either party, we have to examine the `OnchainTxHandler`'s set of outputs to spend when determining if certain outputs are still spendable. Two new tests are added which test various different transaction formats, and hopefully provide good test coverage of the various revoked output paths.
1 parent 3b21f2b commit 0acaca7

File tree

3 files changed

+554
-13
lines changed

3 files changed

+554
-13
lines changed

lightning/src/chain/channelmonitor.rs

Lines changed: 127 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
2323
use bitcoin::blockdata::block::BlockHeader;
2424
use bitcoin::blockdata::transaction::{TxOut,Transaction};
25+
use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
2526
use bitcoin::blockdata::script::{Script, Builder};
2627
use bitcoin::blockdata::opcodes;
2728

@@ -590,6 +591,15 @@ pub enum Balance {
590591
/// done so.
591592
claimable_height: u32,
592593
},
594+
/// The channel has been closed, and our counterparty broadcasted a revoked commitment
595+
/// transaction.
596+
///
597+
/// Thus, we're able to claim all outputs in the commitment transaction, one of which has the
598+
/// following amount.
599+
CounterpartyRevokedOutputClaimable {
600+
/// The amount, in satoshis, of the output which we can claim.
601+
claimable_amount_satoshis: u64,
602+
},
593603
}
594604

595605
/// An HTLC which has been irrevocably resolved on-chain, and has reached ANTI_REORG_DELAY.
@@ -1410,9 +1420,9 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
14101420
/// balance, or until our counterparty has claimed the balance and accrued several
14111421
/// confirmations on the claim transaction.
14121422
///
1413-
/// Note that the balances available when you or your counterparty have broadcasted revoked
1414-
/// state(s) may not be fully captured here.
1415-
// TODO, fix that ^
1423+
/// Note that for `ChannelMonitors` which track a channel which went on-chain with versions of
1424+
/// LDK prior to 0.0.108, balances may not be fully captured if our counterparty broadcasted
1425+
/// a revoked state.
14161426
///
14171427
/// See [`Balance`] for additional details on the types of claimable balances which
14181428
/// may be returned here and their meanings.
@@ -1421,9 +1431,13 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
14211431
let us = self.inner.lock().unwrap();
14221432

14231433
let mut confirmed_txid = us.funding_spend_confirmed;
1434+
let mut confirmed_counterparty_output = us.confirmed_commitment_tx_counterparty_output;
14241435
let mut pending_commitment_tx_conf_thresh = None;
14251436
let funding_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1426-
if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
1437+
if let OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } =
1438+
event.event
1439+
{
1440+
confirmed_counterparty_output = commitment_tx_to_counterparty_output;
14271441
Some((event.txid, event.confirmation_threshold()))
14281442
} else { None }
14291443
});
@@ -1435,9 +1449,10 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
14351449
}
14361450

14371451
macro_rules! walk_htlcs {
1438-
($holder_commitment: expr, $htlc_iter: expr) => {
1452+
($holder_commitment: expr, $counterparty_revoked_commitment: expr, $htlc_iter: expr) => {
14391453
for htlc in $htlc_iter {
14401454
if let Some(htlc_commitment_tx_output_idx) = htlc.transaction_output_index {
1455+
let mut htlc_spend_txid_opt = None;
14411456
let mut htlc_update_pending = None;
14421457
let mut htlc_spend_pending = None;
14431458
let mut delayed_output_pending = None;
@@ -1446,6 +1461,7 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
14461461
OnchainEvent::HTLCUpdate {
14471462
commitment_tx_output_idx, onchain_value_satoshis, htlc_value_satoshis, .. }
14481463
if commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) => {
1464+
htlc_spend_txid_opt = event.transaction.as_ref().map(|tx| tx.txid());
14491465
debug_assert!(htlc_update_pending.is_none());
14501466
htlc_update_pending = Some((
14511467
onchain_value_satoshis.unwrap_or(htlc_value_satoshis.unwrap()),
@@ -1454,6 +1470,7 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
14541470
OnchainEvent::HTLCSpendConfirmation {
14551471
commitment_tx_output_idx, preimage, onchain_value_satoshis, .. }
14561472
if commitment_tx_output_idx == htlc_commitment_tx_output_idx => {
1473+
htlc_spend_txid_opt = event.transaction.as_ref().map(|tx| tx.txid());
14571474
debug_assert!(htlc_spend_pending.is_none());
14581475
htlc_spend_pending = Some((event.confirmation_threshold(),
14591476
preimage.is_some(), onchain_value_satoshis));
@@ -1468,22 +1485,80 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
14681485
}
14691486
}
14701487
let htlc_resolved = us.htlcs_resolved_on_chain.iter()
1471-
.find(|v| v.commitment_tx_output_idx == htlc_commitment_tx_output_idx);
1488+
.find(|v| if v.commitment_tx_output_idx == htlc_commitment_tx_output_idx {
1489+
if v.resolving_txid != confirmed_txid {
1490+
htlc_spend_txid_opt = v.resolving_txid;
1491+
}
1492+
true
1493+
} else { false });
14721494
debug_assert!(htlc_update_pending.is_some() as u8 + htlc_spend_pending.is_some() as u8 + htlc_resolved.is_some() as u8 <= 1);
14731495

1496+
let htlc_output_needs_spending =
1497+
us.onchain_tx_handler.is_output_spend_pending(&
1498+
if let Some(txid) = htlc_spend_txid_opt {
1499+
debug_assert!(
1500+
us.onchain_tx_handler.channel_transaction_parameters.opt_anchors.is_none(),
1501+
"This code needs updating for anchors");
1502+
BitcoinOutPoint::new(txid, 0)
1503+
} else {
1504+
BitcoinOutPoint::new(confirmed_txid.unwrap(), htlc_commitment_tx_output_idx)
1505+
});
1506+
14741507
if let Some(conf_thresh) = delayed_output_pending {
14751508
debug_assert!($holder_commitment);
14761509
res.push(Balance::ClaimableAwaitingConfirmations {
14771510
claimable_amount_satoshis: htlc.amount_msat / 1000,
14781511
confirmation_height: conf_thresh,
14791512
});
1480-
} else if htlc_resolved.is_some() {
1513+
} else if htlc_resolved.is_some() && !htlc_output_needs_spending {
14811514
// Funding transaction spends should be fully confirmed by the time any
14821515
// HTLC transactions are resolved, unless we're talking about a holder
14831516
// commitment tx, whose resolution is delayed until the CSV timeout is
14841517
// reached, even though HTLCs may be resolved after only
14851518
// ANTI_REORG_DELAY confirmations.
14861519
debug_assert!($holder_commitment || us.funding_spend_confirmed.is_some());
1520+
} else if $counterparty_revoked_commitment {
1521+
let htlc_output_claim_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1522+
if let OnchainEvent::MaturingOutput {
1523+
descriptor: SpendableOutputDescriptor::StaticOutput { .. }
1524+
} = &event.event {
1525+
if event.transaction.as_ref().map(|tx| tx.input.iter().any(|inp| {
1526+
if let Some(htlc_spend_txid) = htlc_spend_txid_opt {
1527+
Some(tx.txid()) == htlc_spend_txid_opt ||
1528+
inp.previous_output.txid == htlc_spend_txid
1529+
} else {
1530+
Some(inp.previous_output.txid) == confirmed_txid &&
1531+
inp.previous_output.vout == htlc_commitment_tx_output_idx
1532+
}
1533+
})).unwrap_or(false) {
1534+
Some(())
1535+
} else { None }
1536+
} else { None }
1537+
});
1538+
if htlc_output_claim_pending.is_some() {
1539+
// We already push `Balance`s onto the `res` list for every
1540+
// `StaticOutput` in a `MaturingOutput` in the revoked
1541+
// counterparty commitment transaction case generally, so don't
1542+
// need to do so again here.
1543+
} else if let Some((_, _, amount_sats_option)) = htlc_spend_pending {
1544+
if let Some(amount_sats) = amount_sats_option {
1545+
res.push(Balance::CounterpartyRevokedOutputClaimable {
1546+
claimable_amount_satoshis: amount_sats,
1547+
});
1548+
}
1549+
} else if let Some(Some(val)) = htlc_resolved.map(|v| v.onchain_value_satoshis) {
1550+
res.push(Balance::CounterpartyRevokedOutputClaimable {
1551+
claimable_amount_satoshis: val,
1552+
});
1553+
} else {
1554+
debug_assert!(htlc_update_pending.is_none(),
1555+
"HTLCUpdate OnchainEvents should never appear for preimage claims");
1556+
debug_assert!(htlc_spend_pending.is_none() || !htlc_spend_pending.unwrap().1,
1557+
"We don't (currently) generate preimage claims against revoked outputs, where did you get one?!");
1558+
res.push(Balance::CounterpartyRevokedOutputClaimable {
1559+
claimable_amount_satoshis: htlc.amount_msat / 1000,
1560+
});
1561+
}
14871562
} else {
14881563
if htlc.offered == $holder_commitment {
14891564
// If the payment was outbound, check if there's an HTLCUpdate
@@ -1527,8 +1602,8 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
15271602

15281603
if let Some(txid) = confirmed_txid {
15291604
let mut found_commitment_tx = false;
1530-
if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1531-
walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().map(|(a, _)| a));
1605+
if let Some(counterparty_tx_htlcs) = us.counterparty_claimable_outpoints.get(&txid) {
1606+
// First look for the to_remote output back to us.
15321607
if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
15331608
if let Some(value) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
15341609
if let OnchainEvent::MaturingOutput {
@@ -1547,9 +1622,50 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
15471622
// confirmation with the same height or have never met our dust amount.
15481623
}
15491624
}
1625+
if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1626+
walk_htlcs!(false, false, counterparty_tx_htlcs.iter().map(|(a, _)| a));
1627+
} else {
1628+
walk_htlcs!(false, true, counterparty_tx_htlcs.iter().map(|(a, _)| a));
1629+
// The counterparty broadcasted a revoked state!
1630+
// Look for a StaticOutput spend first, as it should be spending the full set
1631+
// of commitment transaction outputs, if we see one, assume that it did and
1632+
// just return that.
1633+
let mut spent_counterparty_output = false;
1634+
for event in us.onchain_events_awaiting_threshold_conf.iter() {
1635+
if let OnchainEvent::MaturingOutput {
1636+
descriptor: SpendableOutputDescriptor::StaticOutput { output, .. }
1637+
} = &event.event {
1638+
res.push(Balance::ClaimableAwaitingConfirmations {
1639+
claimable_amount_satoshis: output.value,
1640+
confirmation_height: event.confirmation_threshold(),
1641+
});
1642+
if let Some(confirmed_to_self_idx) = confirmed_counterparty_output.map(|(idx, _)| idx) {
1643+
if event.transaction.as_ref().map(|tx|
1644+
tx.input.iter().any(|inp| inp.previous_output.vout == confirmed_to_self_idx)
1645+
).unwrap_or(false) {
1646+
spent_counterparty_output = true;
1647+
}
1648+
}
1649+
}
1650+
}
1651+
1652+
if spent_counterparty_output {
1653+
} else if let Some((confirmed_to_self_idx, amt)) = confirmed_counterparty_output {
1654+
let output_spendable = us.onchain_tx_handler
1655+
.is_output_spend_pending(&BitcoinOutPoint::new(txid, confirmed_to_self_idx));
1656+
if output_spendable {
1657+
res.push(Balance::CounterpartyRevokedOutputClaimable {
1658+
claimable_amount_satoshis: amt,
1659+
});
1660+
}
1661+
} else {
1662+
// Counterparty output is missing, either it was broadcasted on a
1663+
// previous version of LDK or the counterparty hadn't met dust.
1664+
}
1665+
}
15501666
found_commitment_tx = true;
15511667
} else if txid == us.current_holder_commitment_tx.txid {
1552-
walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, _)| a));
1668+
walk_htlcs!(true, false, us.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, _)| a));
15531669
if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
15541670
res.push(Balance::ClaimableAwaitingConfirmations {
15551671
claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
@@ -1559,7 +1675,7 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
15591675
found_commitment_tx = true;
15601676
} else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
15611677
if txid == prev_commitment.txid {
1562-
walk_htlcs!(true, prev_commitment.htlc_outputs.iter().map(|(a, _, _)| a));
1678+
walk_htlcs!(true, false, prev_commitment.htlc_outputs.iter().map(|(a, _, _)| a));
15631679
if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
15641680
res.push(Balance::ClaimableAwaitingConfirmations {
15651681
claimable_amount_satoshis: prev_commitment.to_self_value_sat,
@@ -1580,8 +1696,6 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
15801696
});
15811697
}
15821698
}
1583-
// TODO: Add logic to provide claimable balances for counterparty broadcasting revoked
1584-
// outputs.
15851699
} else {
15861700
let mut claimable_inbound_htlc_value_sat = 0;
15871701
for (htlc, _, _) in us.current_holder_commitment_tx.htlc_outputs.iter() {

lightning/src/chain/onchaintx.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -690,6 +690,10 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
690690
}
691691
}
692692

693+
pub(crate) fn is_output_spend_pending(&self, outpoint: &BitcoinOutPoint) -> bool {
694+
self.claimable_outpoints.get(outpoint).is_some()
695+
}
696+
693697
pub(crate) fn get_relevant_txids(&self) -> Vec<Txid> {
694698
let mut txids: Vec<Txid> = self.onchain_events_awaiting_threshold_conf
695699
.iter()

0 commit comments

Comments
 (0)