Skip to content

Commit bb56a38

Browse files
committed
Expose the amount of funds available for claim in ChannelMonitor
In general, we should always allow users to query for how much is currently in-flight being claimed on-chain at any time. This does so by examining the confirmed claims on-chain and breaking down what is left to be claimed into a new `ClaimableBalance` enum. Fixes lightningdevkit#995.
1 parent 9d8197e commit bb56a38

File tree

2 files changed

+468
-2
lines changed

2 files changed

+468
-2
lines changed

lightning/src/chain/channelmonitor.rs

+151
Original file line numberDiff line numberDiff line change
@@ -527,6 +527,56 @@ impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep,
527527
},
528528
);
529529

530+
/// Details about the balance available for claim once the channel appears on chain.
531+
#[derive(Clone, Debug, PartialEq, Eq)]
532+
#[cfg_attr(test, derive(PartialOrd, Ord))]
533+
pub enum ClaimableBalance {
534+
/// The channel is not yet closed (or the initial commitment or closing transaction has not yet
535+
/// been confirmed). The given balance is claimable (less on-chain fees) if the channel is
536+
/// force-closed now.
537+
ClaimableOnChannelClose {
538+
/// The amount available to claim, in satoshis, ignoring the on-chain fees which will be
539+
/// required to do so.
540+
claimable_amount_satoshis: u64,
541+
},
542+
/// The channel has been closed, and the given balance is ours but awaiting confirmations until
543+
/// we consider it spendable.
544+
ClaimableAwaitingConfirmations {
545+
/// The amount available to claim, in satoshis, possibly ignoring the on-chain fees which
546+
/// were spent in broadcasting the transaction.
547+
claimable_amount_satoshis: u64,
548+
/// The height at which an [`Event::SpendableOutputs`] event will be generated for this
549+
/// amount.
550+
confirmation_height: u32,
551+
},
552+
/// The channel has been closed, and the given balance should be ours but awaiting spending
553+
/// transaction confirmation. If the spending transaction does not confirm in time, it is
554+
/// possible our counterparty can take the funds by broadcasting an HTLC timeout on-chain.
555+
///
556+
/// Once the spending transaction confirms, before it has reached enough confirmations to be
557+
/// considered safe from chain reorganizations, the balance will instead be provided via
558+
/// [`ClaimableBalance::ClaimableAwaitingConfirmations`].
559+
ContentiousClaimable {
560+
/// The amount available to claim, in satoshis, ignoring the on-chain fees which will be
561+
/// required to do so.
562+
claimable_amount_satoshis: u64,
563+
/// The height at which the counterparty may be able to claim the balance if we have not
564+
/// done so.
565+
timeout_height: u32,
566+
},
567+
/// HTLCs which we sent to our counterparty which are claimable after a timeout (less on-chain
568+
/// fees) if the counterparty does not know the preimage for the HTLCs. These are somewhat
569+
/// likely to be claimed by our counterparty before we do.
570+
PossiblyClaimableHTLCAwaitingTimeout {
571+
/// The amount available to claim, in satoshis, ignoring the on-chain fees which will be
572+
/// required to do so.
573+
claimable_amount_satoshis: u64,
574+
/// The height at which we will be able to claim the balance if our counterparty has not
575+
/// done so.
576+
claimable_height: u32,
577+
},
578+
}
579+
530580
/// An HTLC which has been irrevocably resolved on-chain, and has reached ANTI_REORG_DELAY.
531581
#[derive(PartialEq)]
532582
struct HTLCIrrevocablyResolved {
@@ -1293,6 +1343,107 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
12931343
pub fn current_best_block(&self) -> BestBlock {
12941344
self.inner.lock().unwrap().best_block.clone()
12951345
}
1346+
1347+
/// Gets the balances in this channel which are either claimable by us if we were to
1348+
/// force-close the channel now or which are claimable on-chain or claims which are awaiting
1349+
/// confirmation.
1350+
///
1351+
/// Any balances in the channel which are available on-chain (ignoring on-chain fees) are
1352+
/// included here until an [`Event::SpendableOutputs`] event has been generated for the
1353+
/// balance, or until our counterparty has claimed the balance and accrued several
1354+
/// confirmations on the claim transaction.
1355+
///
1356+
/// See [`ClaimableBalance`] for additional details on the types of claimable balances which
1357+
/// may be returned here and their meanings.
1358+
pub fn get_claimable_balances(&self) -> Vec<ClaimableBalance> {
1359+
let mut res = Vec::new();
1360+
let us = self.inner.lock().unwrap();
1361+
1362+
let mut confirmed_txid = us.funding_spend_confirmed;
1363+
if let Some((txid, conf_thresh)) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1364+
if let OnchainEvent::FundingSpendConfirmation { txid, .. } = event.event {
1365+
Some((txid, event.confirmation_threshold()))
1366+
} else { None }
1367+
}) {
1368+
debug_assert!(us.funding_spend_confirmed.is_none(), "We have a pending funding spend awaiting confirmation, we can't have confirmed it already!");
1369+
confirmed_txid = Some(txid);
1370+
res.push(ClaimableBalance::ClaimableAwaitingConfirmations {
1371+
claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
1372+
confirmation_height: conf_thresh,
1373+
});
1374+
}
1375+
1376+
macro_rules! walk_htlcs {
1377+
($holder_commitment: expr, $htlc_iter: expr) => {
1378+
for htlc in $htlc_iter {
1379+
if let Some(htlc_input_idx) = htlc.transaction_output_index {
1380+
if us.htlcs_resolved_on_chain.iter().any(|v| v.input_idx == htlc_input_idx) {
1381+
assert!(us.funding_spend_confirmed.is_some());
1382+
} else if htlc.offered == $holder_commitment {
1383+
res.push(ClaimableBalance::PossiblyClaimableHTLCAwaitingTimeout {
1384+
claimable_amount_satoshis: htlc.amount_msat / 1000,
1385+
claimable_height: htlc.cltv_expiry,
1386+
});
1387+
} else {
1388+
if us.payment_preimages.get(&htlc.payment_hash).is_some() {
1389+
if let Some(conf_thresh) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1390+
if let OnchainEvent::HTLCSpendConfirmation { input_idx, .. } = event.event {
1391+
if input_idx == htlc_input_idx { Some(event.confirmation_threshold()) } else { None }
1392+
} else { None }
1393+
}) {
1394+
res.push(ClaimableBalance::ClaimableAwaitingConfirmations {
1395+
claimable_amount_satoshis: htlc.amount_msat / 1000,
1396+
confirmation_height: conf_thresh,
1397+
});
1398+
} else {
1399+
res.push(ClaimableBalance::ContentiousClaimable {
1400+
claimable_amount_satoshis: htlc.amount_msat / 1000,
1401+
timeout_height: htlc.cltv_expiry,
1402+
});
1403+
}
1404+
}
1405+
}
1406+
}
1407+
}
1408+
}
1409+
}
1410+
1411+
if let Some(txid) = confirmed_txid {
1412+
if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1413+
walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().map(|(a, _)| a));
1414+
} else if txid == us.current_holder_commitment_tx.txid {
1415+
walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, _)| a));
1416+
} else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
1417+
if txid == prev_commitment.txid {
1418+
walk_htlcs!(true, prev_commitment.htlc_outputs.iter().map(|(a, _, _)| a));
1419+
}
1420+
}
1421+
// TODO: Add logic to provide claimable balances for counterparty broadcasting revoked
1422+
// outputs.
1423+
// Otherwise assume we closed with a cooperative close which only needs the
1424+
// `ClaimableAwaitingConfirmations` balance pushed first.
1425+
} else {
1426+
let mut claimable_inbound_htlc_value_sat = 0;
1427+
for (htlc, _, _) in us.current_holder_commitment_tx.htlc_outputs.iter() {
1428+
if htlc.transaction_output_index.is_none() { continue; }
1429+
if htlc.offered {
1430+
res.push(ClaimableBalance::PossiblyClaimableHTLCAwaitingTimeout {
1431+
claimable_amount_satoshis: htlc.amount_msat / 1000,
1432+
claimable_height: htlc.cltv_expiry,
1433+
});
1434+
} else {
1435+
if us.payment_preimages.get(&htlc.payment_hash).is_some() {
1436+
claimable_inbound_htlc_value_sat += htlc.amount_msat / 1000;
1437+
}
1438+
}
1439+
}
1440+
res.push(ClaimableBalance::ClaimableOnChannelClose {
1441+
claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat + claimable_inbound_htlc_value_sat,
1442+
});
1443+
}
1444+
1445+
res
1446+
}
12961447
}
12971448

12981449
/// Compares a broadcasted commitment transaction's HTLCs with those in the latest state,

0 commit comments

Comments
 (0)