Skip to content

Commit dee10c5

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 fa1c6e2 commit dee10c5

File tree

3 files changed

+556
-13
lines changed

3 files changed

+556
-13
lines changed

lightning/src/chain/channelmonitor.rs

Lines changed: 130 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

@@ -588,6 +589,15 @@ pub enum Balance {
588589
/// done so.
589590
claimable_height: u32,
590591
},
592+
/// The channel has been closed, and our counterparty broadcasted a revoked commitment
593+
/// transaction.
594+
///
595+
/// Thus, we're able to claim all outputs in the commitment transaction, one of which has the
596+
/// following amount.
597+
CounterpartyRevokedOutputClaimable {
598+
/// The amount, in satoshis, of the output which we can claim.
599+
claimable_amount_satoshis: u64,
600+
},
591601
}
592602

593603
/// An HTLC which has been irrevocably resolved on-chain, and has reached ANTI_REORG_DELAY.
@@ -1403,9 +1413,9 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
14031413
/// balance, or until our counterparty has claimed the balance and accrued several
14041414
/// confirmations on the claim transaction.
14051415
///
1406-
/// Note that the balances available when you or your counterparty have broadcasted revoked
1407-
/// state(s) may not be fully captured here.
1408-
// TODO, fix that ^
1416+
/// Note that for `ChannelMonitors` which track a channel which went on-chain with versions of
1417+
/// LDK prior to 0.0.108, balances may not be fully captured if our counterparty broadcasted
1418+
/// a revoked state.
14091419
///
14101420
/// See [`Balance`] for additional details on the types of claimable balances which
14111421
/// may be returned here and their meanings.
@@ -1414,9 +1424,13 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
14141424
let us = self.inner.lock().unwrap();
14151425

14161426
let mut confirmed_txid = us.funding_spend_confirmed;
1427+
let mut confirmed_counterparty_output = us.confirmed_commitment_tx_counterparty_output;
14171428
let mut pending_commitment_tx_conf_thresh = None;
14181429
let funding_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1419-
if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
1430+
if let OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } =
1431+
event.event
1432+
{
1433+
confirmed_counterparty_output = commitment_tx_to_counterparty_output;
14201434
Some((event.txid, event.confirmation_threshold()))
14211435
} else { None }
14221436
});
@@ -1428,9 +1442,10 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
14281442
}
14291443

14301444
macro_rules! walk_htlcs {
1431-
($holder_commitment: expr, $htlc_iter: expr) => {
1445+
($holder_commitment: expr, $counterparty_revoked_commitment: expr, $htlc_iter: expr) => {
14321446
for htlc in $htlc_iter {
14331447
if let Some(htlc_commitment_tx_output_idx) = htlc.transaction_output_index {
1448+
let mut htlc_spend_txid_opt = None;
14341449
let mut htlc_update_pending = None;
14351450
let mut htlc_spend_pending = None;
14361451
let mut delayed_output_pending = None;
@@ -1439,6 +1454,7 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
14391454
OnchainEvent::HTLCUpdate {
14401455
commitment_tx_output_idx, onchain_value_satoshis, htlc_value_satoshis, .. }
14411456
if commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) => {
1457+
htlc_spend_txid_opt = event.transaction.as_ref().map(|tx| tx.txid());
14421458
debug_assert!(htlc_update_pending.is_none());
14431459
htlc_update_pending = Some((
14441460
onchain_value_satoshis.unwrap_or(htlc_value_satoshis.unwrap()),
@@ -1447,6 +1463,7 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
14471463
OnchainEvent::HTLCSpendConfirmation {
14481464
commitment_tx_output_idx, preimage, onchain_value_satoshis, .. }
14491465
if commitment_tx_output_idx == htlc_commitment_tx_output_idx => {
1466+
htlc_spend_txid_opt = event.transaction.as_ref().map(|tx| tx.txid());
14501467
debug_assert!(htlc_spend_pending.is_none());
14511468
htlc_spend_pending = Some((event.confirmation_threshold(),
14521469
preimage.is_some(), onchain_value_satoshis));
@@ -1461,22 +1478,80 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
14611478
}
14621479
}
14631480
let htlc_resolved = us.htlcs_resolved_on_chain.iter()
1464-
.find(|v| v.commitment_tx_output_idx == htlc_commitment_tx_output_idx);
1481+
.find(|v| if v.commitment_tx_output_idx == htlc_commitment_tx_output_idx {
1482+
if v.resolving_txid != confirmed_txid {
1483+
htlc_spend_txid_opt = v.resolving_txid;
1484+
}
1485+
true
1486+
} else { false });
14651487
debug_assert!(htlc_update_pending.is_some() as u8 + htlc_spend_pending.is_some() as u8 + htlc_resolved.is_some() as u8 <= 1);
14661488

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

15211596
if let Some(txid) = confirmed_txid {
15221597
let mut found_commitment_tx = false;
1523-
if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1524-
walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().map(|(a, _)| a));
1598+
if let Some(counterparty_tx_htlcs) = us.counterparty_claimable_outpoints.get(&txid) {
1599+
// First look for the to_remote output back to us.
15251600
if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
15261601
if let Some(value) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
15271602
if let OnchainEvent::MaturingOutput {
@@ -1540,9 +1615,53 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
15401615
// confirmation with the same height or have never met our dust amount.
15411616
}
15421617
}
1618+
if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1619+
walk_htlcs!(false, false, counterparty_tx_htlcs.iter().map(|(a, _)| a));
1620+
} else {
1621+
walk_htlcs!(true, true, counterparty_tx_htlcs.iter().map(|(a, _)| a));
1622+
// The counterparty broadcasted a revoked state!
1623+
// Look for a StaticOutput spend first, as it should be spending the full set
1624+
// of commitment transaction outputs, if we see one, assume that it did and
1625+
// just return that.
1626+
let mut spent_counterparty_output = false;
1627+
for event in us.onchain_events_awaiting_threshold_conf.iter() {
1628+
if let OnchainEvent::MaturingOutput {
1629+
descriptor: SpendableOutputDescriptor::StaticOutput { output, .. }
1630+
} = &event.event {
1631+
res.push(Balance::ClaimableAwaitingConfirmations {
1632+
claimable_amount_satoshis: output.value,
1633+
confirmation_height: event.confirmation_threshold(),
1634+
});
1635+
if let Some(confirmed_to_self_idx) = confirmed_counterparty_output.map(|(idx, _)| idx) {
1636+
if event.transaction.as_ref().map(|tx|
1637+
tx.input.iter().any(|inp| inp.previous_output.vout == confirmed_to_self_idx)
1638+
).unwrap_or(false) {
1639+
spent_counterparty_output = true;
1640+
}
1641+
}
1642+
}
1643+
}
1644+
1645+
if spent_counterparty_output {
1646+
} else if let Some((_, amt)) = confirmed_counterparty_output {
1647+
debug_assert!(confirmed_counterparty_output.is_some());
1648+
if let Some(confirmed_to_self_idx) = confirmed_counterparty_output.map(|(idx, _)| idx) {
1649+
let output_spendable = us.onchain_tx_handler
1650+
.is_output_spend_pending(&BitcoinOutPoint::new(txid, confirmed_to_self_idx));
1651+
if output_spendable {
1652+
res.push(Balance::CounterpartyRevokedOutputClaimable {
1653+
claimable_amount_satoshis: amt,
1654+
});
1655+
}
1656+
}
1657+
} else {
1658+
// Counterparty output is missing, either it was broadcasted on a
1659+
// previous version of LDK or the counterparty hadn't met dust.
1660+
}
1661+
}
15431662
found_commitment_tx = true;
15441663
} else if txid == us.current_holder_commitment_tx.txid {
1545-
walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, _)| a));
1664+
walk_htlcs!(true, false, us.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, _)| a));
15461665
if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
15471666
res.push(Balance::ClaimableAwaitingConfirmations {
15481667
claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
@@ -1552,7 +1671,7 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
15521671
found_commitment_tx = true;
15531672
} else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
15541673
if txid == prev_commitment.txid {
1555-
walk_htlcs!(true, prev_commitment.htlc_outputs.iter().map(|(a, _, _)| a));
1674+
walk_htlcs!(true, false, prev_commitment.htlc_outputs.iter().map(|(a, _, _)| a));
15561675
if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
15571676
res.push(Balance::ClaimableAwaitingConfirmations {
15581677
claimable_amount_satoshis: prev_commitment.to_self_value_sat,
@@ -1573,8 +1692,6 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
15731692
});
15741693
}
15751694
}
1576-
// TODO: Add logic to provide claimable balances for counterparty broadcasting revoked
1577-
// outputs.
15781695
} else {
15791696
let mut claimable_inbound_htlc_value_sat = 0;
15801697
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)