Skip to content

Commit 96ed4da

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 7fd2372 commit 96ed4da

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.
@@ -1417,9 +1433,9 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
14171433
/// balance, or until our counterparty has claimed the balance and accrued several
14181434
/// confirmations on the claim transaction.
14191435
///
1420-
/// Note that the balances available when you or your counterparty have broadcasted revoked
1421-
/// state(s) may not be fully captured here.
1422-
// TODO, fix that ^
1436+
/// Note that for `ChannelMonitors` which track a channel which went on-chain with versions of
1437+
/// LDK prior to 0.0.108, balances may not be fully captured if our counterparty broadcasted
1438+
/// a revoked state.
14231439
///
14241440
/// See [`Balance`] for additional details on the types of claimable balances which
14251441
/// may be returned here and their meanings.
@@ -1428,9 +1444,13 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
14281444
let us = self.inner.lock().unwrap();
14291445

14301446
let mut confirmed_txid = us.funding_spend_confirmed;
1447+
let mut confirmed_counterparty_output = us.confirmed_commitment_tx_counterparty_output;
14311448
let mut pending_commitment_tx_conf_thresh = None;
14321449
let funding_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1433-
if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
1450+
if let OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } =
1451+
event.event
1452+
{
1453+
confirmed_counterparty_output = commitment_tx_to_counterparty_output;
14341454
Some((event.txid, event.confirmation_threshold()))
14351455
} else { None }
14361456
});
@@ -1442,22 +1462,27 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
14421462
}
14431463

14441464
macro_rules! walk_htlcs {
1445-
($holder_commitment: expr, $htlc_iter: expr) => {
1465+
($holder_commitment: expr, $counterparty_revoked_commitment: expr, $htlc_iter: expr) => {
14461466
for htlc in $htlc_iter {
14471467
if let Some(htlc_commitment_tx_output_idx) = htlc.transaction_output_index {
1468+
let mut htlc_spend_txid_opt = None;
14481469
let mut htlc_update_pending = None;
14491470
let mut htlc_spend_pending = None;
14501471
let mut delayed_output_pending = None;
14511472
for event in us.onchain_events_awaiting_threshold_conf.iter() {
14521473
match event.event {
14531474
OnchainEvent::HTLCUpdate { commitment_tx_output_idx, htlc_value_satoshis, .. }
14541475
if commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) => {
1476+
debug_assert!(htlc_spend_txid_opt.is_none());
1477+
htlc_spend_txid_opt = event.transaction.as_ref().map(|tx| tx.txid());
14551478
debug_assert!(htlc_update_pending.is_none());
14561479
debug_assert_eq!(htlc_value_satoshis.unwrap(), htlc.amount_msat / 1000);
14571480
htlc_update_pending = Some(event.confirmation_threshold());
14581481
},
14591482
OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. }
14601483
if commitment_tx_output_idx == htlc_commitment_tx_output_idx => {
1484+
debug_assert!(htlc_spend_txid_opt.is_none());
1485+
htlc_spend_txid_opt = event.transaction.as_ref().map(|tx| tx.txid());
14611486
debug_assert!(htlc_spend_pending.is_none());
14621487
htlc_spend_pending = Some((event.confirmation_threshold(), preimage.is_some()));
14631488
},
@@ -1471,22 +1496,69 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
14711496
}
14721497
}
14731498
let htlc_resolved = us.htlcs_resolved_on_chain.iter()
1474-
.find(|v| v.commitment_tx_output_idx == htlc_commitment_tx_output_idx);
1499+
.find(|v| if v.commitment_tx_output_idx == htlc_commitment_tx_output_idx {
1500+
debug_assert!(htlc_spend_txid_opt.is_none());
1501+
htlc_spend_txid_opt = v.resolving_txid;
1502+
true
1503+
} else { false });
14751504
debug_assert!(htlc_update_pending.is_some() as u8 + htlc_spend_pending.is_some() as u8 + htlc_resolved.is_some() as u8 <= 1);
14761505

1506+
let htlc_output_to_spend =
1507+
if let Some(txid) = htlc_spend_txid_opt {
1508+
debug_assert!(
1509+
us.onchain_tx_handler.channel_transaction_parameters.opt_anchors.is_none(),
1510+
"This code needs updating for anchors");
1511+
BitcoinOutPoint::new(txid, 0)
1512+
} else {
1513+
BitcoinOutPoint::new(confirmed_txid.unwrap(), htlc_commitment_tx_output_idx)
1514+
};
1515+
let htlc_output_needs_spending = us.onchain_tx_handler.is_output_spend_pending(&htlc_output_to_spend);
1516+
14771517
if let Some(conf_thresh) = delayed_output_pending {
14781518
debug_assert!($holder_commitment);
14791519
res.push(Balance::ClaimableAwaitingConfirmations {
14801520
claimable_amount_satoshis: htlc.amount_msat / 1000,
14811521
confirmation_height: conf_thresh,
14821522
});
1483-
} else if htlc_resolved.is_some() {
1523+
} else if htlc_resolved.is_some() && !htlc_output_needs_spending {
14841524
// Funding transaction spends should be fully confirmed by the time any
14851525
// HTLC transactions are resolved, unless we're talking about a holder
14861526
// commitment tx, whose resolution is delayed until the CSV timeout is
14871527
// reached, even though HTLCs may be resolved after only
14881528
// ANTI_REORG_DELAY confirmations.
14891529
debug_assert!($holder_commitment || us.funding_spend_confirmed.is_some());
1530+
} else if $counterparty_revoked_commitment {
1531+
let htlc_output_claim_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1532+
if let OnchainEvent::MaturingOutput {
1533+
descriptor: SpendableOutputDescriptor::StaticOutput { .. }
1534+
} = &event.event {
1535+
if event.transaction.as_ref().map(|tx| tx.input.iter().any(|inp| {
1536+
if let Some(htlc_spend_txid) = htlc_spend_txid_opt {
1537+
Some(tx.txid()) == htlc_spend_txid_opt ||
1538+
inp.previous_output.txid == htlc_spend_txid
1539+
} else {
1540+
Some(inp.previous_output.txid) == confirmed_txid &&
1541+
inp.previous_output.vout == htlc_commitment_tx_output_idx
1542+
}
1543+
})).unwrap_or(false) {
1544+
Some(())
1545+
} else { None }
1546+
} else { None }
1547+
});
1548+
if htlc_output_claim_pending.is_some() {
1549+
// We already push `Balance`s onto the `res` list for every
1550+
// `StaticOutput` in a `MaturingOutput` in the revoked
1551+
// counterparty commitment transaction case generally, so don't
1552+
// need to do so again here.
1553+
} else {
1554+
debug_assert!(htlc_update_pending.is_none(),
1555+
"HTLCUpdate OnchainEvents should never appear for preimage claims");
1556+
debug_assert!(!htlc.offered || 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+
}
14901562
} else {
14911563
if htlc.offered == $holder_commitment {
14921564
// If the payment was outbound, check if there's an HTLCUpdate
@@ -1530,8 +1602,8 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
15301602

15311603
if let Some(txid) = confirmed_txid {
15321604
let mut found_commitment_tx = false;
1533-
if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1534-
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.
15351607
if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
15361608
if let Some(value) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
15371609
if let OnchainEvent::MaturingOutput {
@@ -1550,9 +1622,50 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
15501622
// confirmation with the same height or have never met our dust amount.
15511623
}
15521624
}
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 any StaticOutputs first, generating claimable balances for those.
1631+
// If any match the confirmed counterparty revoked to_self output, skip
1632+
// generating a CounterpartyRevokedOutputClaimable.
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+
}
15531666
found_commitment_tx = true;
15541667
} else if txid == us.current_holder_commitment_tx.txid {
1555-
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));
15561669
if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
15571670
res.push(Balance::ClaimableAwaitingConfirmations {
15581671
claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
@@ -1562,7 +1675,7 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
15621675
found_commitment_tx = true;
15631676
} else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
15641677
if txid == prev_commitment.txid {
1565-
walk_htlcs!(true, prev_commitment.htlc_outputs.iter().map(|(a, _, _)| a));
1678+
walk_htlcs!(true, false, prev_commitment.htlc_outputs.iter().map(|(a, _, _)| a));
15661679
if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
15671680
res.push(Balance::ClaimableAwaitingConfirmations {
15681681
claimable_amount_satoshis: prev_commitment.to_self_value_sat,
@@ -1583,8 +1696,6 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
15831696
});
15841697
}
15851698
}
1586-
// TODO: Add logic to provide claimable balances for counterparty broadcasting revoked
1587-
// outputs.
15881699
} else {
15891700
let mut claimable_inbound_htlc_value_sat = 0;
15901701
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
@@ -1533,13 +1533,11 @@ macro_rules! expect_payment_failed {
15331533
};
15341534
}
15351535

1536-
pub fn expect_payment_failed_conditions<'a, 'b, 'c, 'd, 'e>(
1537-
node: &'a Node<'b, 'c, 'd>, expected_payment_hash: PaymentHash, expected_rejected_by_dest: bool,
1538-
conditions: PaymentFailedConditions<'e>
1536+
pub fn expect_payment_failed_conditions_event<'a, 'b, 'c, 'd, 'e>(
1537+
node: &'a Node<'b, 'c, 'd>, payment_failed_event: Event, expected_payment_hash: PaymentHash,
1538+
expected_rejected_by_dest: bool, conditions: PaymentFailedConditions<'e>
15391539
) {
1540-
let mut events = node.node.get_and_clear_pending_events();
1541-
assert_eq!(events.len(), 1);
1542-
let expected_payment_id = match events.pop().unwrap() {
1540+
let expected_payment_id = match payment_failed_event {
15431541
Event::PaymentPathFailed { payment_hash, rejected_by_dest, path, retry, payment_id, network_update, short_channel_id,
15441542
#[cfg(test)]
15451543
error_code,
@@ -1602,6 +1600,15 @@ pub fn expect_payment_failed_conditions<'a, 'b, 'c, 'd, 'e>(
16021600
}
16031601
}
16041602

1603+
pub fn expect_payment_failed_conditions<'a, 'b, 'c, 'd, 'e>(
1604+
node: &'a Node<'b, 'c, 'd>, expected_payment_hash: PaymentHash, expected_rejected_by_dest: bool,
1605+
conditions: PaymentFailedConditions<'e>
1606+
) {
1607+
let mut events = node.node.get_and_clear_pending_events();
1608+
assert_eq!(events.len(), 1);
1609+
expect_payment_failed_conditions_event(node, events.pop().unwrap(), expected_payment_hash, expected_rejected_by_dest, conditions);
1610+
}
1611+
16051612
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 {
16061613
let payment_id = origin_node.node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
16071614
check_added_monitors!(origin_node, expected_paths.len());

0 commit comments

Comments
 (0)