Skip to content

Commit f8bea88

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 ae93f00 commit f8bea88

File tree

4 files changed

+779
-19
lines changed

4 files changed

+779
-19
lines changed

lightning/src/chain/channelmonitor.rs

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

@@ -382,6 +383,9 @@ enum OnchainEvent {
382383
on_local_output_csv: Option<u16>,
383384
/// If the funding spend transaction was a known remote commitment transaction, we track
384385
/// the output index and amount of the counterparty's `to_self` output here.
386+
///
387+
/// This allows us to generate a [`Balance::CounterpartyRevokedOutputClaimable`] for the
388+
/// counterparty output.
385389
commitment_tx_to_counterparty_output: CommitmentTxCounterpartyOutputInfo,
386390
},
387391
/// A spend of a commitment transaction HTLC output, set in the cases where *no* `HTLCUpdate`
@@ -582,6 +586,18 @@ pub enum Balance {
582586
/// done so.
583587
claimable_height: u32,
584588
},
589+
/// The channel has been closed, and our counterparty broadcasted a revoked commitment
590+
/// transaction.
591+
///
592+
/// Thus, we're able to claim all outputs in the commitment transaction, one of which has the
593+
/// following amount.
594+
CounterpartyRevokedOutputClaimable {
595+
/// The amount, in satoshis, of the output which we can claim.
596+
///
597+
/// Note that for outputs from HTLC balances this may be excluding some on-chain fees that
598+
/// were already spent.
599+
claimable_amount_satoshis: u64,
600+
},
585601
}
586602

587603
/// An HTLC which has been irrevocably resolved on-chain, and has reached ANTI_REORG_DELAY.
@@ -1413,9 +1429,9 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
14131429
/// balance, or until our counterparty has claimed the balance and accrued several
14141430
/// confirmations on the claim transaction.
14151431
///
1416-
/// Note that the balances available when you or your counterparty have broadcasted revoked
1417-
/// state(s) may not be fully captured here.
1418-
// TODO, fix that ^
1432+
/// Note that for `ChannelMonitors` which track a channel which went on-chain with versions of
1433+
/// LDK prior to 0.0.108, balances may not be fully captured if our counterparty broadcasted
1434+
/// a revoked state.
14191435
///
14201436
/// See [`Balance`] for additional details on the types of claimable balances which
14211437
/// may be returned here and their meanings.
@@ -1424,9 +1440,13 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
14241440
let us = self.inner.lock().unwrap();
14251441

14261442
let mut confirmed_txid = us.funding_spend_confirmed;
1443+
let mut confirmed_counterparty_output = us.confirmed_commitment_tx_counterparty_output;
14271444
let mut pending_commitment_tx_conf_thresh = None;
14281445
let funding_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1429-
if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
1446+
if let OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } =
1447+
event.event
1448+
{
1449+
confirmed_counterparty_output = commitment_tx_to_counterparty_output;
14301450
Some((event.txid, event.confirmation_threshold()))
14311451
} else { None }
14321452
});
@@ -1438,22 +1458,27 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
14381458
}
14391459

14401460
macro_rules! walk_htlcs {
1441-
($holder_commitment: expr, $htlc_iter: expr) => {
1461+
($holder_commitment: expr, $counterparty_revoked_commitment: expr, $htlc_iter: expr) => {
14421462
for htlc in $htlc_iter {
14431463
if let Some(htlc_commitment_tx_output_idx) = htlc.transaction_output_index {
1464+
let mut htlc_spend_txid_opt = None;
14441465
let mut htlc_update_pending = None;
14451466
let mut htlc_spend_pending = None;
14461467
let mut delayed_output_pending = None;
14471468
for event in us.onchain_events_awaiting_threshold_conf.iter() {
14481469
match event.event {
14491470
OnchainEvent::HTLCUpdate { commitment_tx_output_idx, htlc_value_satoshis, .. }
14501471
if commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) => {
1472+
debug_assert!(htlc_spend_txid_opt.is_none());
1473+
htlc_spend_txid_opt = event.transaction.as_ref().map(|tx| tx.txid());
14511474
debug_assert!(htlc_update_pending.is_none());
14521475
debug_assert_eq!(htlc_value_satoshis.unwrap(), htlc.amount_msat / 1000);
14531476
htlc_update_pending = Some(event.confirmation_threshold());
14541477
},
14551478
OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. }
14561479
if commitment_tx_output_idx == htlc_commitment_tx_output_idx => {
1480+
debug_assert!(htlc_spend_txid_opt.is_none());
1481+
htlc_spend_txid_opt = event.transaction.as_ref().map(|tx| tx.txid());
14571482
debug_assert!(htlc_spend_pending.is_none());
14581483
htlc_spend_pending = Some((event.confirmation_threshold(), preimage.is_some()));
14591484
},
@@ -1467,22 +1492,69 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
14671492
}
14681493
}
14691494
let htlc_resolved = us.htlcs_resolved_on_chain.iter()
1470-
.find(|v| v.commitment_tx_output_idx == htlc_commitment_tx_output_idx);
1495+
.find(|v| if v.commitment_tx_output_idx == htlc_commitment_tx_output_idx {
1496+
debug_assert!(htlc_spend_txid_opt.is_none());
1497+
htlc_spend_txid_opt = v.resolving_txid;
1498+
true
1499+
} else { false });
14711500
debug_assert!(htlc_update_pending.is_some() as u8 + htlc_spend_pending.is_some() as u8 + htlc_resolved.is_some() as u8 <= 1);
14721501

1502+
let htlc_output_to_spend =
1503+
if let Some(txid) = htlc_spend_txid_opt {
1504+
debug_assert!(
1505+
us.onchain_tx_handler.channel_transaction_parameters.opt_anchors.is_none(),
1506+
"This code needs updating for anchors");
1507+
BitcoinOutPoint::new(txid, 0)
1508+
} else {
1509+
BitcoinOutPoint::new(confirmed_txid.unwrap(), htlc_commitment_tx_output_idx)
1510+
};
1511+
let htlc_output_needs_spending = us.onchain_tx_handler.is_output_spend_pending(&htlc_output_to_spend);
1512+
14731513
if let Some(conf_thresh) = delayed_output_pending {
14741514
debug_assert!($holder_commitment);
14751515
res.push(Balance::ClaimableAwaitingConfirmations {
14761516
claimable_amount_satoshis: htlc.amount_msat / 1000,
14771517
confirmation_height: conf_thresh,
14781518
});
1479-
} else if htlc_resolved.is_some() {
1519+
} else if htlc_resolved.is_some() && !htlc_output_needs_spending {
14801520
// Funding transaction spends should be fully confirmed by the time any
14811521
// HTLC transactions are resolved, unless we're talking about a holder
14821522
// commitment tx, whose resolution is delayed until the CSV timeout is
14831523
// reached, even though HTLCs may be resolved after only
14841524
// ANTI_REORG_DELAY confirmations.
14851525
debug_assert!($holder_commitment || us.funding_spend_confirmed.is_some());
1526+
} else if $counterparty_revoked_commitment {
1527+
let htlc_output_claim_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1528+
if let OnchainEvent::MaturingOutput {
1529+
descriptor: SpendableOutputDescriptor::StaticOutput { .. }
1530+
} = &event.event {
1531+
if event.transaction.as_ref().map(|tx| tx.input.iter().any(|inp| {
1532+
if let Some(htlc_spend_txid) = htlc_spend_txid_opt {
1533+
Some(tx.txid()) == htlc_spend_txid_opt ||
1534+
inp.previous_output.txid == htlc_spend_txid
1535+
} else {
1536+
Some(inp.previous_output.txid) == confirmed_txid &&
1537+
inp.previous_output.vout == htlc_commitment_tx_output_idx
1538+
}
1539+
})).unwrap_or(false) {
1540+
Some(())
1541+
} else { None }
1542+
} else { None }
1543+
});
1544+
if htlc_output_claim_pending.is_some() {
1545+
// We already push `Balance`s onto the `res` list for every
1546+
// `StaticOutput` in a `MaturingOutput` in the revoked
1547+
// counterparty commitment transaction case generally, so don't
1548+
// need to do so again here.
1549+
} else {
1550+
debug_assert!(htlc_update_pending.is_none(),
1551+
"HTLCUpdate OnchainEvents should never appear for preimage claims");
1552+
debug_assert!(!htlc.offered || htlc_spend_pending.is_none() || !htlc_spend_pending.unwrap().1,
1553+
"We don't (currently) generate preimage claims against revoked outputs, where did you get one?!");
1554+
res.push(Balance::CounterpartyRevokedOutputClaimable {
1555+
claimable_amount_satoshis: htlc.amount_msat / 1000,
1556+
});
1557+
}
14861558
} else {
14871559
if htlc.offered == $holder_commitment {
14881560
// If the payment was outbound, check if there's an HTLCUpdate
@@ -1526,8 +1598,8 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
15261598

15271599
if let Some(txid) = confirmed_txid {
15281600
let mut found_commitment_tx = false;
1529-
if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1530-
walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().map(|(a, _)| a));
1601+
if let Some(counterparty_tx_htlcs) = us.counterparty_claimable_outpoints.get(&txid) {
1602+
// First look for the to_remote output back to us.
15311603
if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
15321604
if let Some(value) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
15331605
if let OnchainEvent::MaturingOutput {
@@ -1546,9 +1618,50 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
15461618
// confirmation with the same height or have never met our dust amount.
15471619
}
15481620
}
1621+
if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1622+
walk_htlcs!(false, false, counterparty_tx_htlcs.iter().map(|(a, _)| a));
1623+
} else {
1624+
walk_htlcs!(false, true, counterparty_tx_htlcs.iter().map(|(a, _)| a));
1625+
// The counterparty broadcasted a revoked state!
1626+
// Look for any StaticOutputs first, generating claimable balances for those.
1627+
// If any match the confirmed counterparty revoked to_self output, skip
1628+
// generating a CounterpartyRevokedOutputClaimable.
1629+
let mut spent_counterparty_output = false;
1630+
for event in us.onchain_events_awaiting_threshold_conf.iter() {
1631+
if let OnchainEvent::MaturingOutput {
1632+
descriptor: SpendableOutputDescriptor::StaticOutput { output, .. }
1633+
} = &event.event {
1634+
res.push(Balance::ClaimableAwaitingConfirmations {
1635+
claimable_amount_satoshis: output.value,
1636+
confirmation_height: event.confirmation_threshold(),
1637+
});
1638+
if let Some(confirmed_to_self_idx) = confirmed_counterparty_output.map(|(idx, _)| idx) {
1639+
if event.transaction.as_ref().map(|tx|
1640+
tx.input.iter().any(|inp| inp.previous_output.vout == confirmed_to_self_idx)
1641+
).unwrap_or(false) {
1642+
spent_counterparty_output = true;
1643+
}
1644+
}
1645+
}
1646+
}
1647+
1648+
if spent_counterparty_output {
1649+
} else if let Some((confirmed_to_self_idx, amt)) = confirmed_counterparty_output {
1650+
let output_spendable = us.onchain_tx_handler
1651+
.is_output_spend_pending(&BitcoinOutPoint::new(txid, confirmed_to_self_idx));
1652+
if output_spendable {
1653+
res.push(Balance::CounterpartyRevokedOutputClaimable {
1654+
claimable_amount_satoshis: amt,
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+
}
15491662
found_commitment_tx = true;
15501663
} else if txid == us.current_holder_commitment_tx.txid {
1551-
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));
15521665
if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
15531666
res.push(Balance::ClaimableAwaitingConfirmations {
15541667
claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
@@ -1558,7 +1671,7 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
15581671
found_commitment_tx = true;
15591672
} else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
15601673
if txid == prev_commitment.txid {
1561-
walk_htlcs!(true, prev_commitment.htlc_outputs.iter().map(|(a, _, _)| a));
1674+
walk_htlcs!(true, false, prev_commitment.htlc_outputs.iter().map(|(a, _, _)| a));
15621675
if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
15631676
res.push(Balance::ClaimableAwaitingConfirmations {
15641677
claimable_amount_satoshis: prev_commitment.to_self_value_sat,
@@ -1579,8 +1692,6 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
15791692
});
15801693
}
15811694
}
1582-
// TODO: Add logic to provide claimable balances for counterparty broadcasting revoked
1583-
// outputs.
15841695
} else {
15851696
let mut claimable_inbound_htlc_value_sat = 0;
15861697
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()

lightning/src/ln/functional_test_utils.rs

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1483,13 +1483,11 @@ macro_rules! expect_payment_failed {
14831483
};
14841484
}
14851485

1486-
pub fn expect_payment_failed_conditions<'a, 'b, 'c, 'd, 'e>(
1487-
node: &'a Node<'b, 'c, 'd>, expected_payment_hash: PaymentHash, expected_rejected_by_dest: bool,
1488-
conditions: PaymentFailedConditions<'e>
1486+
pub fn expect_payment_failed_conditions_event<'a, 'b, 'c, 'd, 'e>(
1487+
node: &'a Node<'b, 'c, 'd>, payment_failed_event: Event, expected_payment_hash: PaymentHash,
1488+
expected_rejected_by_dest: bool, conditions: PaymentFailedConditions<'e>
14891489
) {
1490-
let mut events = node.node.get_and_clear_pending_events();
1491-
assert_eq!(events.len(), 1);
1492-
let expected_payment_id = match events.pop().unwrap() {
1490+
let expected_payment_id = match payment_failed_event {
14931491
Event::PaymentPathFailed { payment_hash, rejected_by_dest, path, retry, payment_id, network_update, short_channel_id,
14941492
#[cfg(test)]
14951493
error_code,
@@ -1552,6 +1550,15 @@ pub fn expect_payment_failed_conditions<'a, 'b, 'c, 'd, 'e>(
15521550
}
15531551
}
15541552

1553+
pub fn expect_payment_failed_conditions<'a, 'b, 'c, 'd, 'e>(
1554+
node: &'a Node<'b, 'c, 'd>, expected_payment_hash: PaymentHash, expected_rejected_by_dest: bool,
1555+
conditions: PaymentFailedConditions<'e>
1556+
) {
1557+
let mut events = node.node.get_and_clear_pending_events();
1558+
assert_eq!(events.len(), 1);
1559+
expect_payment_failed_conditions_event(node, events.pop().unwrap(), expected_payment_hash, expected_rejected_by_dest, conditions);
1560+
}
1561+
15551562
pub fn send_along_route_with_secret<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, route: Route, expected_paths: &[&[&Node<'a, 'b, 'c>]], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: PaymentSecret) -> PaymentId {
15561563
let payment_id = origin_node.node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
15571564
check_added_monitors!(origin_node, expected_paths.len());

0 commit comments

Comments
 (0)