Skip to content

Commit 0a31c12

Browse files
authored
Merge pull request #1104 from TheBlueMatt/2021-10-payment-id-in-monitors
Reload pending outbound payments from ChannelMonitors on startup
2 parents 107c6c7 + 7af5d12 commit 0a31c12

8 files changed

+868
-219
lines changed

lightning/src/chain/channelmonitor.rs

+95
Original file line numberDiff line numberDiff line change
@@ -1515,6 +1515,101 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
15151515

15161516
res
15171517
}
1518+
1519+
/// Gets the set of outbound HTLCs which are pending resolution in this channel.
1520+
/// This is used to reconstruct pending outbound payments on restart in the ChannelManager.
1521+
pub(crate) fn get_pending_outbound_htlcs(&self) -> HashMap<HTLCSource, HTLCOutputInCommitment> {
1522+
let mut res = HashMap::new();
1523+
let us = self.inner.lock().unwrap();
1524+
1525+
macro_rules! walk_htlcs {
1526+
($holder_commitment: expr, $htlc_iter: expr) => {
1527+
for (htlc, source) in $htlc_iter {
1528+
if us.htlcs_resolved_on_chain.iter().any(|v| Some(v.input_idx) == htlc.transaction_output_index) {
1529+
// We should assert that funding_spend_confirmed is_some() here, but we
1530+
// have some unit tests which violate HTLC transaction CSVs entirely and
1531+
// would fail.
1532+
// TODO: Once tests all connect transactions at consensus-valid times, we
1533+
// should assert here like we do in `get_claimable_balances`.
1534+
} else if htlc.offered == $holder_commitment {
1535+
// If the payment was outbound, check if there's an HTLCUpdate
1536+
// indicating we have spent this HTLC with a timeout, claiming it back
1537+
// and awaiting confirmations on it.
1538+
let htlc_update_confd = us.onchain_events_awaiting_threshold_conf.iter().any(|event| {
1539+
if let OnchainEvent::HTLCUpdate { input_idx: Some(input_idx), .. } = event.event {
1540+
// If the HTLC was timed out, we wait for ANTI_REORG_DELAY blocks
1541+
// before considering it "no longer pending" - this matches when we
1542+
// provide the ChannelManager an HTLC failure event.
1543+
Some(input_idx) == htlc.transaction_output_index &&
1544+
us.best_block.height() >= event.height + ANTI_REORG_DELAY - 1
1545+
} else if let OnchainEvent::HTLCSpendConfirmation { input_idx, .. } = event.event {
1546+
// If the HTLC was fulfilled with a preimage, we consider the HTLC
1547+
// immediately non-pending, matching when we provide ChannelManager
1548+
// the preimage.
1549+
Some(input_idx) == htlc.transaction_output_index
1550+
} else { false }
1551+
});
1552+
if !htlc_update_confd {
1553+
res.insert(source.clone(), htlc.clone());
1554+
}
1555+
}
1556+
}
1557+
}
1558+
}
1559+
1560+
// We're only concerned with the confirmation count of HTLC transactions, and don't
1561+
// actually care how many confirmations a commitment transaction may or may not have. Thus,
1562+
// we look for either a FundingSpendConfirmation event or a funding_spend_confirmed.
1563+
let confirmed_txid = us.funding_spend_confirmed.or_else(|| {
1564+
us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1565+
if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
1566+
Some(event.txid)
1567+
} else { None }
1568+
})
1569+
});
1570+
if let Some(txid) = confirmed_txid {
1571+
if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1572+
walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().filter_map(|(a, b)| {
1573+
if let &Some(ref source) = b {
1574+
Some((a, &**source))
1575+
} else { None }
1576+
}));
1577+
} else if txid == us.current_holder_commitment_tx.txid {
1578+
walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().filter_map(|(a, _, c)| {
1579+
if let Some(source) = c { Some((a, source)) } else { None }
1580+
}));
1581+
} else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
1582+
if txid == prev_commitment.txid {
1583+
walk_htlcs!(true, prev_commitment.htlc_outputs.iter().filter_map(|(a, _, c)| {
1584+
if let Some(source) = c { Some((a, source)) } else { None }
1585+
}));
1586+
}
1587+
}
1588+
} else {
1589+
// If we have not seen a commitment transaction on-chain (ie the channel is not yet
1590+
// closed), just examine the available counterparty commitment transactions. See docs
1591+
// on `fail_unbroadcast_htlcs`, below, for justification.
1592+
macro_rules! walk_counterparty_commitment {
1593+
($txid: expr) => {
1594+
if let Some(ref latest_outpoints) = us.counterparty_claimable_outpoints.get($txid) {
1595+
for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1596+
if let &Some(ref source) = source_option {
1597+
res.insert((**source).clone(), htlc.clone());
1598+
}
1599+
}
1600+
}
1601+
}
1602+
}
1603+
if let Some(ref txid) = us.current_counterparty_commitment_txid {
1604+
walk_counterparty_commitment!(txid);
1605+
}
1606+
if let Some(ref txid) = us.prev_counterparty_commitment_txid {
1607+
walk_counterparty_commitment!(txid);
1608+
}
1609+
}
1610+
1611+
res
1612+
}
15181613
}
15191614

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

lightning/src/ln/channel.rs

+88-20
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,29 @@ pub enum UpdateFulfillCommitFetch {
339339
DuplicateClaim {},
340340
}
341341

342+
/// The return value of `revoke_and_ack` on success, primarily updates to other channels or HTLC
343+
/// state.
344+
pub(super) struct RAAUpdates {
345+
pub commitment_update: Option<msgs::CommitmentUpdate>,
346+
pub accepted_htlcs: Vec<(PendingHTLCInfo, u64)>,
347+
pub failed_htlcs: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>,
348+
pub finalized_claimed_htlcs: Vec<HTLCSource>,
349+
pub monitor_update: ChannelMonitorUpdate,
350+
pub holding_cell_failed_htlcs: Vec<(HTLCSource, PaymentHash)>,
351+
}
352+
353+
/// The return value of `monitor_updating_restored`
354+
pub(super) struct MonitorRestoreUpdates {
355+
pub raa: Option<msgs::RevokeAndACK>,
356+
pub commitment_update: Option<msgs::CommitmentUpdate>,
357+
pub order: RAACommitmentOrder,
358+
pub accepted_htlcs: Vec<(PendingHTLCInfo, u64)>,
359+
pub failed_htlcs: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>,
360+
pub finalized_claimed_htlcs: Vec<HTLCSource>,
361+
pub funding_broadcastable: Option<Transaction>,
362+
pub funding_locked: Option<msgs::FundingLocked>,
363+
}
364+
342365
/// If the majority of the channels funds are to the fundee and the initiator holds only just
343366
/// enough funds to cover their reserve value, channels are at risk of getting "stuck". Because the
344367
/// initiator controls the feerate, if they then go to increase the channel fee, they may have no
@@ -406,6 +429,7 @@ pub(super) struct Channel<Signer: Sign> {
406429
monitor_pending_commitment_signed: bool,
407430
monitor_pending_forwards: Vec<(PendingHTLCInfo, u64)>,
408431
monitor_pending_failures: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>,
432+
monitor_pending_finalized_fulfills: Vec<HTLCSource>,
409433

410434
// pending_update_fee is filled when sending and receiving update_fee.
411435
//
@@ -692,6 +716,7 @@ impl<Signer: Sign> Channel<Signer> {
692716
monitor_pending_commitment_signed: false,
693717
monitor_pending_forwards: Vec::new(),
694718
monitor_pending_failures: Vec::new(),
719+
monitor_pending_finalized_fulfills: Vec::new(),
695720

696721
#[cfg(debug_assertions)]
697722
holder_max_commitment_tx_output: Mutex::new((channel_value_satoshis * 1000 - push_msat, push_msat)),
@@ -955,6 +980,7 @@ impl<Signer: Sign> Channel<Signer> {
955980
monitor_pending_commitment_signed: false,
956981
monitor_pending_forwards: Vec::new(),
957982
monitor_pending_failures: Vec::new(),
983+
monitor_pending_finalized_fulfills: Vec::new(),
958984

959985
#[cfg(debug_assertions)]
960986
holder_max_commitment_tx_output: Mutex::new((msg.push_msat, msg.funding_satoshis * 1000 - msg.push_msat)),
@@ -2711,7 +2737,7 @@ impl<Signer: Sign> Channel<Signer> {
27112737
/// waiting on this revoke_and_ack. The generation of this new commitment_signed may also fail,
27122738
/// generating an appropriate error *after* the channel state has been updated based on the
27132739
/// revoke_and_ack message.
2714-
pub fn revoke_and_ack<L: Deref>(&mut self, msg: &msgs::RevokeAndACK, logger: &L) -> Result<(Option<msgs::CommitmentUpdate>, Vec<(PendingHTLCInfo, u64)>, Vec<(HTLCSource, PaymentHash, HTLCFailReason)>, ChannelMonitorUpdate, Vec<(HTLCSource, PaymentHash)>), ChannelError>
2740+
pub fn revoke_and_ack<L: Deref>(&mut self, msg: &msgs::RevokeAndACK, logger: &L) -> Result<RAAUpdates, ChannelError>
27152741
where L::Target: Logger,
27162742
{
27172743
if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) {
@@ -2777,6 +2803,7 @@ impl<Signer: Sign> Channel<Signer> {
27772803
log_trace!(logger, "Updating HTLCs on receipt of RAA in channel {}...", log_bytes!(self.channel_id()));
27782804
let mut to_forward_infos = Vec::new();
27792805
let mut revoked_htlcs = Vec::new();
2806+
let mut finalized_claimed_htlcs = Vec::new();
27802807
let mut update_fail_htlcs = Vec::new();
27812808
let mut update_fail_malformed_htlcs = Vec::new();
27822809
let mut require_commitment = false;
@@ -2803,6 +2830,7 @@ impl<Signer: Sign> Channel<Signer> {
28032830
if let Some(reason) = fail_reason.clone() { // We really want take() here, but, again, non-mut ref :(
28042831
revoked_htlcs.push((htlc.source.clone(), htlc.payment_hash, reason));
28052832
} else {
2833+
finalized_claimed_htlcs.push(htlc.source.clone());
28062834
// They fulfilled, so we sent them money
28072835
value_to_self_msat_diff -= htlc.amount_msat as i64;
28082836
}
@@ -2899,8 +2927,14 @@ impl<Signer: Sign> Channel<Signer> {
28992927
}
29002928
self.monitor_pending_forwards.append(&mut to_forward_infos);
29012929
self.monitor_pending_failures.append(&mut revoked_htlcs);
2930+
self.monitor_pending_finalized_fulfills.append(&mut finalized_claimed_htlcs);
29022931
log_debug!(logger, "Received a valid revoke_and_ack for channel {} but awaiting a monitor update resolution to reply.", log_bytes!(self.channel_id()));
2903-
return Ok((None, Vec::new(), Vec::new(), monitor_update, Vec::new()))
2932+
return Ok(RAAUpdates {
2933+
commitment_update: None, finalized_claimed_htlcs: Vec::new(),
2934+
accepted_htlcs: Vec::new(), failed_htlcs: Vec::new(),
2935+
monitor_update,
2936+
holding_cell_failed_htlcs: Vec::new()
2937+
});
29042938
}
29052939

29062940
match self.free_holding_cell_htlcs(logger)? {
@@ -2919,7 +2953,14 @@ impl<Signer: Sign> Channel<Signer> {
29192953
self.latest_monitor_update_id = monitor_update.update_id;
29202954
monitor_update.updates.append(&mut additional_update.updates);
29212955

2922-
Ok((Some(commitment_update), to_forward_infos, revoked_htlcs, monitor_update, htlcs_to_fail))
2956+
Ok(RAAUpdates {
2957+
commitment_update: Some(commitment_update),
2958+
finalized_claimed_htlcs,
2959+
accepted_htlcs: to_forward_infos,
2960+
failed_htlcs: revoked_htlcs,
2961+
monitor_update,
2962+
holding_cell_failed_htlcs: htlcs_to_fail
2963+
})
29232964
},
29242965
(None, htlcs_to_fail) => {
29252966
if require_commitment {
@@ -2932,17 +2973,27 @@ impl<Signer: Sign> Channel<Signer> {
29322973

29332974
log_debug!(logger, "Received a valid revoke_and_ack for channel {}. Responding with a commitment update with {} HTLCs failed.",
29342975
log_bytes!(self.channel_id()), update_fail_htlcs.len() + update_fail_malformed_htlcs.len());
2935-
Ok((Some(msgs::CommitmentUpdate {
2936-
update_add_htlcs: Vec::new(),
2937-
update_fulfill_htlcs: Vec::new(),
2938-
update_fail_htlcs,
2939-
update_fail_malformed_htlcs,
2940-
update_fee: None,
2941-
commitment_signed
2942-
}), to_forward_infos, revoked_htlcs, monitor_update, htlcs_to_fail))
2976+
Ok(RAAUpdates {
2977+
commitment_update: Some(msgs::CommitmentUpdate {
2978+
update_add_htlcs: Vec::new(),
2979+
update_fulfill_htlcs: Vec::new(),
2980+
update_fail_htlcs,
2981+
update_fail_malformed_htlcs,
2982+
update_fee: None,
2983+
commitment_signed
2984+
}),
2985+
finalized_claimed_htlcs,
2986+
accepted_htlcs: to_forward_infos, failed_htlcs: revoked_htlcs,
2987+
monitor_update, holding_cell_failed_htlcs: htlcs_to_fail
2988+
})
29432989
} else {
29442990
log_debug!(logger, "Received a valid revoke_and_ack for channel {} with no reply necessary.", log_bytes!(self.channel_id()));
2945-
Ok((None, to_forward_infos, revoked_htlcs, monitor_update, htlcs_to_fail))
2991+
Ok(RAAUpdates {
2992+
commitment_update: None,
2993+
finalized_claimed_htlcs,
2994+
accepted_htlcs: to_forward_infos, failed_htlcs: revoked_htlcs,
2995+
monitor_update, holding_cell_failed_htlcs: htlcs_to_fail
2996+
})
29462997
}
29472998
}
29482999
}
@@ -3057,18 +3108,23 @@ impl<Signer: Sign> Channel<Signer> {
30573108
/// which failed. The messages which were generated from that call which generated the
30583109
/// monitor update failure must *not* have been sent to the remote end, and must instead
30593110
/// have been dropped. They will be regenerated when monitor_updating_restored is called.
3060-
pub fn monitor_update_failed(&mut self, resend_raa: bool, resend_commitment: bool, mut pending_forwards: Vec<(PendingHTLCInfo, u64)>, mut pending_fails: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>) {
3111+
pub fn monitor_update_failed(&mut self, resend_raa: bool, resend_commitment: bool,
3112+
mut pending_forwards: Vec<(PendingHTLCInfo, u64)>,
3113+
mut pending_fails: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>,
3114+
mut pending_finalized_claimed_htlcs: Vec<HTLCSource>
3115+
) {
30613116
self.monitor_pending_revoke_and_ack |= resend_raa;
30623117
self.monitor_pending_commitment_signed |= resend_commitment;
30633118
self.monitor_pending_forwards.append(&mut pending_forwards);
30643119
self.monitor_pending_failures.append(&mut pending_fails);
3120+
self.monitor_pending_finalized_fulfills.append(&mut pending_finalized_claimed_htlcs);
30653121
self.channel_state |= ChannelState::MonitorUpdateFailed as u32;
30663122
}
30673123

30683124
/// Indicates that the latest ChannelMonitor update has been committed by the client
30693125
/// successfully and we should restore normal operation. Returns messages which should be sent
30703126
/// to the remote side.
3071-
pub fn monitor_updating_restored<L: Deref>(&mut self, logger: &L) -> (Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder, Vec<(PendingHTLCInfo, u64)>, Vec<(HTLCSource, PaymentHash, HTLCFailReason)>, Option<Transaction>, Option<msgs::FundingLocked>) where L::Target: Logger {
3127+
pub fn monitor_updating_restored<L: Deref>(&mut self, logger: &L) -> MonitorRestoreUpdates where L::Target: Logger {
30723128
assert_eq!(self.channel_state & ChannelState::MonitorUpdateFailed as u32, ChannelState::MonitorUpdateFailed as u32);
30733129
self.channel_state &= !(ChannelState::MonitorUpdateFailed as u32);
30743130

@@ -3091,15 +3147,20 @@ impl<Signer: Sign> Channel<Signer> {
30913147
})
30923148
} else { None };
30933149

3094-
let mut forwards = Vec::new();
3095-
mem::swap(&mut forwards, &mut self.monitor_pending_forwards);
3096-
let mut failures = Vec::new();
3097-
mem::swap(&mut failures, &mut self.monitor_pending_failures);
3150+
let mut accepted_htlcs = Vec::new();
3151+
mem::swap(&mut accepted_htlcs, &mut self.monitor_pending_forwards);
3152+
let mut failed_htlcs = Vec::new();
3153+
mem::swap(&mut failed_htlcs, &mut self.monitor_pending_failures);
3154+
let mut finalized_claimed_htlcs = Vec::new();
3155+
mem::swap(&mut finalized_claimed_htlcs, &mut self.monitor_pending_finalized_fulfills);
30983156

30993157
if self.channel_state & (ChannelState::PeerDisconnected as u32) != 0 {
31003158
self.monitor_pending_revoke_and_ack = false;
31013159
self.monitor_pending_commitment_signed = false;
3102-
return (None, None, RAACommitmentOrder::RevokeAndACKFirst, forwards, failures, funding_broadcastable, funding_locked);
3160+
return MonitorRestoreUpdates {
3161+
raa: None, commitment_update: None, order: RAACommitmentOrder::RevokeAndACKFirst,
3162+
accepted_htlcs, failed_htlcs, finalized_claimed_htlcs, funding_broadcastable, funding_locked
3163+
};
31033164
}
31043165

31053166
let raa = if self.monitor_pending_revoke_and_ack {
@@ -3116,7 +3177,9 @@ impl<Signer: Sign> Channel<Signer> {
31163177
log_bytes!(self.channel_id()), if funding_broadcastable.is_some() { "a funding broadcastable, " } else { "" },
31173178
if commitment_update.is_some() { "a" } else { "no" }, if raa.is_some() { "an" } else { "no" },
31183179
match order { RAACommitmentOrder::CommitmentFirst => "commitment", RAACommitmentOrder::RevokeAndACKFirst => "RAA"});
3119-
(raa, commitment_update, order, forwards, failures, funding_broadcastable, funding_locked)
3180+
MonitorRestoreUpdates {
3181+
raa, commitment_update, order, accepted_htlcs, failed_htlcs, finalized_claimed_htlcs, funding_broadcastable, funding_locked
3182+
}
31203183
}
31213184

31223185
pub fn update_fee<F: Deref>(&mut self, fee_estimator: &F, msg: &msgs::UpdateFee) -> Result<(), ChannelError>
@@ -5176,6 +5239,7 @@ impl<Signer: Sign> Writeable for Channel<Signer> {
51765239
(5, self.config, required),
51775240
(7, self.shutdown_scriptpubkey, option),
51785241
(9, self.target_closing_feerate_sats_per_kw, option),
5242+
(11, self.monitor_pending_finalized_fulfills, vec_type),
51795243
});
51805244

51815245
Ok(())
@@ -5409,13 +5473,15 @@ impl<'a, Signer: Sign, K: Deref> ReadableArgs<&'a K> for Channel<Signer>
54095473

54105474
let mut announcement_sigs = None;
54115475
let mut target_closing_feerate_sats_per_kw = None;
5476+
let mut monitor_pending_finalized_fulfills = Some(Vec::new());
54125477
read_tlv_fields!(reader, {
54135478
(0, announcement_sigs, option),
54145479
(1, minimum_depth, option),
54155480
(3, counterparty_selected_channel_reserve_satoshis, option),
54165481
(5, config, option), // Note that if none is provided we will *not* overwrite the existing one.
54175482
(7, shutdown_scriptpubkey, option),
54185483
(9, target_closing_feerate_sats_per_kw, option),
5484+
(11, monitor_pending_finalized_fulfills, vec_type),
54195485
});
54205486

54215487
let mut secp_ctx = Secp256k1::new();
@@ -5451,6 +5517,7 @@ impl<'a, Signer: Sign, K: Deref> ReadableArgs<&'a K> for Channel<Signer>
54515517
monitor_pending_commitment_signed,
54525518
monitor_pending_forwards,
54535519
monitor_pending_failures,
5520+
monitor_pending_finalized_fulfills: monitor_pending_finalized_fulfills.unwrap(),
54545521

54555522
pending_update_fee,
54565523
holding_cell_update_fee,
@@ -5700,6 +5767,7 @@ mod tests {
57005767
session_priv: SecretKey::from_slice(&hex::decode("0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()[..]).unwrap(),
57015768
first_hop_htlc_msat: 548,
57025769
payment_id: PaymentId([42; 32]),
5770+
payment_secret: None,
57035771
}
57045772
});
57055773

0 commit comments

Comments
 (0)