Skip to content

Commit 2b78fde

Browse files
TheBlueMattvalentinewallace
authored andcommitted
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. f drop/tweak debug assertions f make comment more factual
1 parent df785d1 commit 2b78fde

File tree

2 files changed

+635
-2
lines changed

2 files changed

+635
-2
lines changed

lightning/src/chain/channelmonitor.rs

+219
Original file line numberDiff line numberDiff line change
@@ -535,6 +535,59 @@ impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep,
535535
},
536536
);
537537

538+
/// Details about the balance(s) available for spending once the channel appears on chain.
539+
///
540+
/// See [`ChannelMonitor::get_claimable_balances`] for more details on when these will or will not
541+
/// be provided.
542+
#[derive(Clone, Debug, PartialEq, Eq)]
543+
#[cfg_attr(test, derive(PartialOrd, Ord))]
544+
pub enum ClaimableBalance {
545+
/// The channel is not yet closed (or the commitment or closing transaction has not yet
546+
/// appeared in a block). The given balance is claimable (less on-chain fees) if the channel is
547+
/// force-closed now.
548+
ClaimableOnChannelClose {
549+
/// The amount available to claim, in satoshis, ignoring the on-chain fees which will be
550+
/// required to do so.
551+
claimable_amount_satoshis: u64,
552+
},
553+
/// The channel has been closed, and the given balance is ours but awaiting confirmations until
554+
/// we consider it spendable.
555+
ClaimableAwaitingConfirmations {
556+
/// The amount available to claim, in satoshis, possibly ignoring the on-chain fees which
557+
/// were spent in broadcasting the transaction.
558+
claimable_amount_satoshis: u64,
559+
/// The height at which an [`Event::SpendableOutputs`] event will be generated for this
560+
/// amount.
561+
confirmation_height: u32,
562+
},
563+
/// The channel has been closed, and the given balance should be ours but awaiting spending
564+
/// transaction confirmation. If the spending transaction does not confirm in time, it is
565+
/// possible our counterparty can take the funds by broadcasting an HTLC timeout on-chain.
566+
///
567+
/// Once the spending transaction confirms, before it has reached enough confirmations to be
568+
/// considered safe from chain reorganizations, the balance will instead be provided via
569+
/// [`ClaimableBalance::ClaimableAwaitingConfirmations`].
570+
ContentiousClaimable {
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 the counterparty may be able to claim the balance if we have not
575+
/// done so.
576+
timeout_height: u32,
577+
},
578+
/// HTLCs which we sent to our counterparty which are claimable after a timeout (less on-chain
579+
/// fees) if the counterparty does not know the preimage for the HTLCs. These are somewhat
580+
/// likely to be claimed by our counterparty before we do.
581+
MaybeClaimableHTLCAwaitingTimeout {
582+
/// The amount available to claim, in satoshis, ignoring the on-chain fees which will be
583+
/// required to do so.
584+
claimable_amount_satoshis: u64,
585+
/// The height at which we will be able to claim the balance if our counterparty has not
586+
/// done so.
587+
claimable_height: u32,
588+
},
589+
}
590+
538591
/// An HTLC which has been irrevocably resolved on-chain, and has reached ANTI_REORG_DELAY.
539592
#[derive(PartialEq)]
540593
struct HTLCIrrevocablyResolved {
@@ -1302,6 +1355,172 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
13021355
pub fn current_best_block(&self) -> BestBlock {
13031356
self.inner.lock().unwrap().best_block.clone()
13041357
}
1358+
1359+
/// Gets the balances in this channel which are either claimable by us if we were to
1360+
/// force-close the channel now or which are claimable on-chain or claims which are awaiting
1361+
/// confirmation.
1362+
///
1363+
/// Any balances in the channel which are available on-chain (ignoring on-chain fees) are
1364+
/// included here until an [`Event::SpendableOutputs`] event has been generated for the
1365+
/// balance, or until our counterparty has claimed the balance and accrued several
1366+
/// confirmations on the claim transaction.
1367+
///
1368+
/// Note that the balances available when you or your counterparty have broadcasted revoked
1369+
/// state(s) may not be fully captured here.
1370+
// TODO, fix that ^
1371+
///
1372+
/// See [`ClaimableBalance`] for additional details on the types of claimable balances which
1373+
/// may be returned here and their meanings.
1374+
pub fn get_claimable_balances(&self) -> Vec<ClaimableBalance> {
1375+
let mut res = Vec::new();
1376+
let us = self.inner.lock().unwrap();
1377+
1378+
let mut confirmed_txid = us.funding_spend_confirmed;
1379+
let mut pending_commitment_tx_conf_thresh = None;
1380+
if let Some((txid, conf_thresh)) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1381+
if let OnchainEvent::FundingSpendConfirmation { txid, .. } = event.event {
1382+
Some((txid, event.confirmation_threshold()))
1383+
} else { None }
1384+
}) {
1385+
debug_assert!(us.funding_spend_confirmed.is_none(),
1386+
"We have a pending funding spend awaiting anti-reorg confirmation, we can't have confirmed it already!");
1387+
confirmed_txid = Some(txid);
1388+
pending_commitment_tx_conf_thresh = Some(conf_thresh);
1389+
}
1390+
1391+
macro_rules! walk_htlcs {
1392+
($holder_commitment: expr, $htlc_iter: expr) => {
1393+
for htlc in $htlc_iter {
1394+
if let Some(htlc_input_idx) = htlc.transaction_output_index {
1395+
if us.htlcs_resolved_on_chain.iter().any(|v| v.input_idx == htlc_input_idx) {
1396+
assert!(us.funding_spend_confirmed.is_some());
1397+
} else if htlc.offered == $holder_commitment {
1398+
// If the payment was outbound, check if there's an HTLCUpdate
1399+
// indicating we have spent this HTLC with a timeout, claiming it back
1400+
// and awaiting confirmations on it.
1401+
if let Some(conf_thresh) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1402+
if let OnchainEvent::HTLCUpdate { input_idx: Some(input_idx), .. } = event.event {
1403+
if input_idx == htlc_input_idx { Some(event.confirmation_threshold()) } else { None }
1404+
} else { None }
1405+
}) {
1406+
res.push(ClaimableBalance::ClaimableAwaitingConfirmations {
1407+
claimable_amount_satoshis: htlc.amount_msat / 1000,
1408+
confirmation_height: conf_thresh,
1409+
});
1410+
} else {
1411+
res.push(ClaimableBalance::MaybeClaimableHTLCAwaitingTimeout {
1412+
claimable_amount_satoshis: htlc.amount_msat / 1000,
1413+
claimable_height: htlc.cltv_expiry,
1414+
});
1415+
}
1416+
} else if us.payment_preimages.get(&htlc.payment_hash).is_some() {
1417+
// Otherwise (the payment was inbound), only expose it as claimable if
1418+
// we know the preimage.
1419+
// Note that if there is a pending claim, but it did not use the
1420+
// preimage, we lost funds to our counterparty! We will then continue
1421+
// to show it as ContentiousClaimable until ANTI_REORG_DELAY.
1422+
if let Some((conf_thresh, true)) =
1423+
us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1424+
if let OnchainEvent::HTLCSpendConfirmation { input_idx, preimage, .. } = event.event {
1425+
if input_idx == htlc_input_idx {
1426+
Some((event.confirmation_threshold(), preimage.is_some()))
1427+
} else { None }
1428+
} else { None }
1429+
}
1430+
) {
1431+
res.push(ClaimableBalance::ClaimableAwaitingConfirmations {
1432+
claimable_amount_satoshis: htlc.amount_msat / 1000,
1433+
confirmation_height: conf_thresh,
1434+
});
1435+
} else {
1436+
res.push(ClaimableBalance::ContentiousClaimable {
1437+
claimable_amount_satoshis: htlc.amount_msat / 1000,
1438+
timeout_height: htlc.cltv_expiry,
1439+
});
1440+
}
1441+
}
1442+
}
1443+
}
1444+
}
1445+
}
1446+
1447+
if let Some(txid) = confirmed_txid {
1448+
let mut found_commitment_tx = false;
1449+
if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1450+
walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().map(|(a, _)| a));
1451+
if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1452+
if let Some(value) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1453+
if let OnchainEvent::MaturingOutput {
1454+
descriptor: SpendableOutputDescriptor::StaticPaymentOutput(descriptor)
1455+
} = &event.event {
1456+
Some(descriptor.output.value)
1457+
} else { None }
1458+
}) {
1459+
res.push(ClaimableBalance::ClaimableAwaitingConfirmations {
1460+
claimable_amount_satoshis: value,
1461+
confirmation_height: conf_thresh,
1462+
});
1463+
} else {
1464+
// If a counterparty commitment transaction is awaiting confirmation, we
1465+
// should either have a StaticPaymentOutput MaturingOutput event awaiting
1466+
// confirmation with the same height or have never met our dust amount.
1467+
}
1468+
}
1469+
found_commitment_tx = true;
1470+
} else if txid == us.current_holder_commitment_tx.txid {
1471+
walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, _)| a));
1472+
if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1473+
res.push(ClaimableBalance::ClaimableAwaitingConfirmations {
1474+
claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
1475+
confirmation_height: conf_thresh,
1476+
});
1477+
}
1478+
found_commitment_tx = true;
1479+
} else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
1480+
if txid == prev_commitment.txid {
1481+
walk_htlcs!(true, prev_commitment.htlc_outputs.iter().map(|(a, _, _)| a));
1482+
if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1483+
res.push(ClaimableBalance::ClaimableAwaitingConfirmations {
1484+
claimable_amount_satoshis: prev_commitment.to_self_value_sat,
1485+
confirmation_height: conf_thresh,
1486+
});
1487+
}
1488+
found_commitment_tx = true;
1489+
}
1490+
}
1491+
if !found_commitment_tx {
1492+
if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1493+
// We blindly assume this is a cooperative close transaction here, and that
1494+
// neither us nor our counterparty misbehaved. At worst we've under-estimated
1495+
// the amount we can claim as we'll punish a misbehaving counterparty.
1496+
res.push(ClaimableBalance::ClaimableAwaitingConfirmations {
1497+
claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
1498+
confirmation_height: conf_thresh,
1499+
});
1500+
}
1501+
}
1502+
// TODO: Add logic to provide claimable balances for counterparty broadcasting revoked
1503+
// outputs.
1504+
} else {
1505+
let mut claimable_inbound_htlc_value_sat = 0;
1506+
for (htlc, _, _) in us.current_holder_commitment_tx.htlc_outputs.iter() {
1507+
if htlc.transaction_output_index.is_none() { continue; }
1508+
if htlc.offered {
1509+
res.push(ClaimableBalance::MaybeClaimableHTLCAwaitingTimeout {
1510+
claimable_amount_satoshis: htlc.amount_msat / 1000,
1511+
claimable_height: htlc.cltv_expiry,
1512+
});
1513+
} else if us.payment_preimages.get(&htlc.payment_hash).is_some() {
1514+
claimable_inbound_htlc_value_sat += htlc.amount_msat / 1000;
1515+
}
1516+
}
1517+
res.push(ClaimableBalance::ClaimableOnChannelClose {
1518+
claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat + claimable_inbound_htlc_value_sat,
1519+
});
1520+
}
1521+
1522+
res
1523+
}
13051524
}
13061525

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

0 commit comments

Comments
 (0)