Skip to content

Commit 57cc3a0

Browse files
committed
Update tests to test re-claiming of forwarded HTLCs on startup
1 parent efc63e8 commit 57cc3a0

File tree

4 files changed

+210
-42
lines changed

4 files changed

+210
-42
lines changed

lightning/src/chain/channelmonitor.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ use crate::sync::{Mutex, LockTestExt};
6666
/// much smaller than a full [`ChannelMonitor`]. However, for large single commitment transaction
6767
/// updates (e.g. ones during which there are hundreds of HTLCs pending on the commitment
6868
/// transaction), a single update may reach upwards of 1 MiB in serialized size.
69-
#[derive(Clone, PartialEq, Eq)]
69+
#[derive(Clone, Debug, PartialEq, Eq)]
7070
#[must_use]
7171
pub struct ChannelMonitorUpdate {
7272
pub(crate) updates: Vec<ChannelMonitorUpdateStep>,
@@ -486,7 +486,7 @@ impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
486486

487487
);
488488

489-
#[derive(Clone, PartialEq, Eq)]
489+
#[derive(Clone, Debug, PartialEq, Eq)]
490490
pub(crate) enum ChannelMonitorUpdateStep {
491491
LatestHolderCommitmentTXInfo {
492492
commitment_tx: HolderCommitmentTransaction,

lightning/src/ln/chan_utils.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -448,7 +448,7 @@ pub fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp2
448448
/// channel basepoints via the new function, or they were obtained via
449449
/// CommitmentTransaction.trust().keys() because we trusted the source of the
450450
/// pre-calculated keys.
451-
#[derive(PartialEq, Eq, Clone)]
451+
#[derive(PartialEq, Eq, Clone, Debug)]
452452
pub struct TxCreationKeys {
453453
/// The broadcaster's per-commitment public key which was used to derive the other keys.
454454
pub per_commitment_point: PublicKey,
@@ -1026,7 +1026,7 @@ impl<'a> DirectedChannelTransactionParameters<'a> {
10261026
/// Information needed to build and sign a holder's commitment transaction.
10271027
///
10281028
/// The transaction is only signed once we are ready to broadcast.
1029-
#[derive(Clone)]
1029+
#[derive(Clone, Debug)]
10301030
pub struct HolderCommitmentTransaction {
10311031
inner: CommitmentTransaction,
10321032
/// Our counterparty's signature for the transaction
@@ -1132,7 +1132,7 @@ impl HolderCommitmentTransaction {
11321132
}
11331133

11341134
/// A pre-built Bitcoin commitment transaction and its txid.
1135-
#[derive(Clone)]
1135+
#[derive(Clone, Debug)]
11361136
pub struct BuiltCommitmentTransaction {
11371137
/// The commitment transaction
11381138
pub transaction: Transaction,
@@ -1303,7 +1303,7 @@ impl<'a> TrustedClosingTransaction<'a> {
13031303
///
13041304
/// This class can be used inside a signer implementation to generate a signature given the relevant
13051305
/// secret key.
1306-
#[derive(Clone)]
1306+
#[derive(Clone, Debug)]
13071307
pub struct CommitmentTransaction {
13081308
commitment_number: u64,
13091309
to_broadcaster_value_sat: u64,

lightning/src/ln/chanmon_update_fail_tests.rs

Lines changed: 201 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -3099,7 +3099,7 @@ fn test_blocked_chan_preimage_release() {
30993099
expect_payment_sent(&nodes[2], payment_preimage_2, None, true, true);
31003100
}
31013101

3102-
fn do_test_inverted_mon_completion_order(complete_bc_commitment_dance: bool) {
3102+
fn do_test_inverted_mon_completion_order(with_latest_manager: bool, complete_bc_commitment_dance: bool) {
31033103
// When we forward a payment and receive an `update_fulfill_htlc` message from the downstream
31043104
// channel, we immediately claim the HTLC on the upstream channel, before even doing a
31053105
// `commitment_signed` dance on the downstream channel. This implies that our
@@ -3127,6 +3127,10 @@ fn do_test_inverted_mon_completion_order(complete_bc_commitment_dance: bool) {
31273127
let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100_000);
31283128

31293129
let mon_ab = get_monitor!(nodes[1], chan_id_ab).encode();
3130+
let mut manager_b = Vec::new();
3131+
if !with_latest_manager {
3132+
manager_b = nodes[1].node.encode();
3133+
}
31303134

31313135
nodes[2].node.claim_funds(payment_preimage);
31323136
check_added_monitors(&nodes[2], 1);
@@ -3163,61 +3167,225 @@ fn do_test_inverted_mon_completion_order(complete_bc_commitment_dance: bool) {
31633167
}
31643168

31653169
// Now reload node B
3166-
let manager_b = nodes[1].node.encode();
3170+
if with_latest_manager {
3171+
manager_b = nodes[1].node.encode();
3172+
}
31673173

31683174
let mon_bc = get_monitor!(nodes[1], chan_id_bc).encode();
31693175
reload_node!(nodes[1], &manager_b, &[&mon_ab, &mon_bc], persister, new_chain_monitor, nodes_1_deserialized);
31703176

31713177
nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
31723178
nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
31733179

3174-
// If we used the latest ChannelManager to reload from, we should have both channels still
3175-
// live. The B <-> C channel's final RAA ChannelMonitorUpdate must still be blocked as
3176-
// before - the ChannelMonitorUpdate for the A <-> B channel hasn't completed.
3177-
// When we call `timer_tick_occurred` we will get that monitor update back, which we'll
3178-
// complete after reconnecting to our peers.
3179-
persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
3180-
nodes[1].node.timer_tick_occurred();
3181-
check_added_monitors(&nodes[1], 1);
3182-
assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3180+
if with_latest_manager {
3181+
// If we used the latest ChannelManager to reload from, we should have both channels still
3182+
// live. The B <-> C channel's final RAA ChannelMonitorUpdate must still be blocked as
3183+
// before - the ChannelMonitorUpdate for the A <-> B channel hasn't completed.
3184+
// When we call `timer_tick_occurred` we will get that monitor update back, which we'll
3185+
// complete after reconnecting to our peers.
3186+
persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
3187+
nodes[1].node.timer_tick_occurred();
3188+
check_added_monitors(&nodes[1], 1);
3189+
assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
31833190

3184-
// Now reconnect B to both A and C. If the B <-> C commitment signed dance wasn't run to
3185-
// the end go ahead and do that, though the -2 in `reconnect_nodes` indicates that we
3186-
// expect to *not* receive the final RAA ChannelMonitorUpdate.
3187-
if complete_bc_commitment_dance {
3188-
reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[2]));
3191+
// Now reconnect B to both A and C. If the B <-> C commitment signed dance wasn't run to
3192+
// the end go ahead and do that, though the -2 in `reconnect_nodes` indicates that we
3193+
// expect to *not* receive the final RAA ChannelMonitorUpdate.
3194+
if complete_bc_commitment_dance {
3195+
reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[2]));
3196+
} else {
3197+
let mut reconnect_args = ReconnectArgs::new(&nodes[1], &nodes[2]);
3198+
reconnect_args.pending_htlc_adds = (0, -2);
3199+
reconnect_args.pending_raa = (false, true);
3200+
reconnect_nodes(reconnect_args);
3201+
}
3202+
3203+
reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3204+
3205+
// (Finally) complete the A <-> B ChannelMonitorUpdate, ensuring the preimage is durably on
3206+
// disk in the proper ChannelMonitor, unblocking the B <-> C ChannelMonitor updating
3207+
// process.
3208+
let (outpoint, _, ab_update_id) = nodes[1].chain_monitor.latest_monitor_update_id.lock().unwrap().get(&chan_id_ab).unwrap().clone();
3209+
nodes[1].chain_monitor.chain_monitor.channel_monitor_updated(outpoint, ab_update_id).unwrap();
3210+
3211+
// When we fetch B's HTLC update messages next (now that the ChannelMonitorUpdate has
3212+
// completed), it will also release the final RAA ChannelMonitorUpdate on the B <-> C
3213+
// channel.
31893214
} else {
3190-
let mut reconnect_args = ReconnectArgs::new(&nodes[1], &nodes[2]);
3191-
reconnect_args.pending_htlc_adds = (0, -2);
3192-
reconnect_args.pending_raa = (false, true);
3193-
reconnect_nodes(reconnect_args);
3194-
}
3215+
// If the ChannelManager used in the reload was stale, check that the B <-> C channel was
3216+
// closed.
3217+
//
3218+
// Note that this will also process the ChannelMonitorUpdates which were queued up when we
3219+
// reloaded the ChannelManager. This will re-emit the A<->B preimage as well as the B<->C
3220+
// force-closure ChannelMonitorUpdate. Once the A<->B preimage update completes, the claim
3221+
// commitment update will be allowed to go out.
3222+
check_added_monitors(&nodes[1], 0);
3223+
persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
3224+
persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
3225+
check_closed_event(&nodes[1], 1, ClosureReason::OutdatedChannelManager, false, &[nodes[2].node.get_our_node_id()], 100_000);
3226+
check_added_monitors(&nodes[1], 2);
3227+
3228+
nodes[1].node.timer_tick_occurred();
3229+
check_added_monitors(&nodes[1], 0);
31953230

3196-
reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3231+
// Don't bother to reconnect B to C - that channel has been closed. We don't need to
3232+
// exchange any messages here even though there's a pending commitment update because the
3233+
// ChannelMonitorUpdate hasn't yet completed.
3234+
reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3235+
3236+
let (outpoint, _, ab_update_id) = nodes[1].chain_monitor.latest_monitor_update_id.lock().unwrap().get(&chan_id_ab).unwrap().clone();
3237+
nodes[1].chain_monitor.chain_monitor.channel_monitor_updated(outpoint, ab_update_id).unwrap();
31973238

3198-
// (Finally) complete the A <-> B ChannelMonitorUpdate, ensuring the preimage is durably on
3199-
// disk in the proper ChannelMonitor, unblocking the B <-> C ChannelMonitor updating
3200-
// process.
3201-
let (outpoint, _, ab_update_id) = nodes[1].chain_monitor.latest_monitor_update_id.lock().unwrap().get(&chan_id_ab).unwrap().clone();
3202-
nodes[1].chain_monitor.chain_monitor.channel_monitor_updated(outpoint, ab_update_id).unwrap();
3239+
// The ChannelMonitorUpdate which was completed prior to the reconnect only contained the
3240+
// preimage (as it was a replay of the original ChannelMonitorUpdate from before we
3241+
// restarted). When we go to fetch the commitment transaction updates we'll poll the
3242+
// ChannelMonitorUpdate completion, then generate (and complete) a new ChannelMonitorUpdate
3243+
// with the actual commitment transaction, which will allow us to fulfill the HTLC with
3244+
// node A.
3245+
}
32033246

3204-
// When we fetch B's HTLC update messages here (now that the ChannelMonitorUpdate has
3205-
// completed), it will also release the final RAA ChannelMonitorUpdate on the B <-> C
3206-
// channel.
32073247
let bs_updates = get_htlc_update_msgs(&nodes[1], &nodes[0].node.get_our_node_id());
32083248
check_added_monitors(&nodes[1], 1);
32093249

32103250
nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
32113251
do_commitment_signed_dance(&nodes[0], &nodes[1], &bs_updates.commitment_signed, false, false);
32123252

3213-
expect_payment_forwarded!(nodes[1], &nodes[0], &nodes[2], Some(1_000), false, false);
3253+
expect_payment_forwarded!(nodes[1], &nodes[0], &nodes[2], Some(1_000), false, !with_latest_manager);
32143254

32153255
// Finally, check that the payment was, ultimately, seen as sent by node A.
32163256
expect_payment_sent(&nodes[0], payment_preimage, None, true, true);
32173257
}
32183258

32193259
#[test]
32203260
fn test_inverted_mon_completion_order() {
3221-
do_test_inverted_mon_completion_order(true);
3222-
do_test_inverted_mon_completion_order(false);
3261+
do_test_inverted_mon_completion_order(true, true);
3262+
do_test_inverted_mon_completion_order(true, false);
3263+
do_test_inverted_mon_completion_order(false, true);
3264+
do_test_inverted_mon_completion_order(false, false);
3265+
}
3266+
3267+
fn do_test_durable_preimages_on_closed_channel(close_chans_before_reload: bool, close_only_a: bool) {
3268+
// Test that we can apply a `ChannelMonitorUpdate` with a payment preimage even if the channel
3269+
// is force-closed between when we generate the update on reload and when we go to handle the
3270+
// update or prior to generating the update at all.
3271+
3272+
if !close_chans_before_reload && close_only_a {
3273+
// If we're not closing, it makes no sense to "only close A"
3274+
panic!();
3275+
}
3276+
3277+
let chanmon_cfgs = create_chanmon_cfgs(3);
3278+
let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3279+
3280+
let persister;
3281+
let new_chain_monitor;
3282+
let nodes_1_deserialized;
3283+
3284+
let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3285+
let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3286+
3287+
let chan_id_ab = create_announced_chan_between_nodes(&nodes, 0, 1).2;
3288+
let chan_id_bc = create_announced_chan_between_nodes(&nodes, 1, 2).2;
3289+
3290+
// Route a payment from A, through B, to C, then claim it on C. Once we pass B the
3291+
// `update_fulfill_htlc` we have a monitor update for both of B's channels. We complete the one
3292+
// on the B<->C channel but leave the A<->B monitor update pending, then reload B.
3293+
let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
3294+
3295+
let mon_ab = get_monitor!(nodes[1], chan_id_ab).encode();
3296+
3297+
nodes[2].node.claim_funds(payment_preimage);
3298+
check_added_monitors(&nodes[2], 1);
3299+
expect_payment_claimed!(nodes[2], payment_hash, 1_000_000);
3300+
3301+
chanmon_cfgs[1].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
3302+
let cs_updates = get_htlc_update_msgs(&nodes[2], &nodes[1].node.get_our_node_id());
3303+
nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
3304+
3305+
// B generates a new monitor update for the A <-> B channel, but doesn't send the new messages
3306+
// for it since the monitor update is marked in-progress.
3307+
check_added_monitors(&nodes[1], 1);
3308+
assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3309+
3310+
// Now step the Commitment Signed Dance between B and C forward a bit, ensuring we won't get
3311+
// the preimage when the nodes reconnect, at which point we have to ensure we get it from the
3312+
// ChannelMonitor.
3313+
nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &cs_updates.commitment_signed);
3314+
check_added_monitors(&nodes[1], 1);
3315+
let _ = get_revoke_commit_msgs!(nodes[1], nodes[2].node.get_our_node_id());
3316+
3317+
let mon_bc = get_monitor!(nodes[1], chan_id_bc).encode();
3318+
3319+
if close_chans_before_reload {
3320+
if !close_only_a {
3321+
chanmon_cfgs[1].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
3322+
nodes[1].node.force_close_broadcasting_latest_txn(&chan_id_bc, &nodes[2].node.get_our_node_id()).unwrap();
3323+
check_closed_broadcast(&nodes[1], 1, true);
3324+
check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[2].node.get_our_node_id()], 100000);
3325+
}
3326+
3327+
chanmon_cfgs[1].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
3328+
nodes[1].node.force_close_broadcasting_latest_txn(&chan_id_ab, &nodes[0].node.get_our_node_id()).unwrap();
3329+
check_closed_broadcast(&nodes[1], 1, true);
3330+
check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
3331+
}
3332+
3333+
// Now reload node B
3334+
let manager_b = nodes[1].node.encode();
3335+
reload_node!(nodes[1], &manager_b, &[&mon_ab, &mon_bc], persister, new_chain_monitor, nodes_1_deserialized);
3336+
3337+
nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3338+
nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3339+
3340+
if close_chans_before_reload {
3341+
// If the channels were already closed, B will rebroadcast its closing transactions here.
3342+
let bs_close_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3343+
if close_only_a {
3344+
assert_eq!(bs_close_txn.len(), 2);
3345+
} else {
3346+
assert_eq!(bs_close_txn.len(), 3);
3347+
}
3348+
}
3349+
3350+
nodes[0].node.force_close_broadcasting_latest_txn(&chan_id_ab, &nodes[1].node.get_our_node_id()).unwrap();
3351+
check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
3352+
let as_closing_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3353+
assert_eq!(as_closing_tx.len(), 1);
3354+
3355+
// In order to give B A's closing transaction without processing background events first, use
3356+
// the _without_checks utility method. This is similar to connecting blocks during startup
3357+
// prior to the node being full initialized.
3358+
mine_transaction_without_checks(&nodes[1], &as_closing_tx[0]);
3359+
3360+
// After a timer tick a payment preimage ChannelMonitorUpdate is applied to the A<->B
3361+
// ChannelMonitor (possible twice), even though the channel has since been closed.
3362+
check_added_monitors(&nodes[1], 0);
3363+
nodes[1].node.timer_tick_occurred();
3364+
check_added_monitors(&nodes[1], if close_chans_before_reload { if !close_only_a { 4 } else { 3 } } else { 2 });
3365+
3366+
// Finally, check that B created a payment preimage transaction and close out the payment.
3367+
let bs_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3368+
assert_eq!(bs_txn.len(), if close_chans_before_reload && !close_only_a { 2 } else { 1 });
3369+
let bs_preimage_tx = &bs_txn[0];
3370+
check_spends!(bs_preimage_tx, as_closing_tx[0]);
3371+
3372+
if !close_chans_before_reload {
3373+
check_closed_broadcast(&nodes[1], 1, true);
3374+
check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false, &[nodes[0].node.get_our_node_id()], 100000);
3375+
} else {
3376+
// While we forwarded the payment a while ago, we don't want to process events too early or
3377+
// we'll run background tasks we wanted to test individually.
3378+
expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, !close_only_a);
3379+
}
3380+
3381+
mine_transactions(&nodes[0], &[&as_closing_tx[0], bs_preimage_tx]);
3382+
check_closed_broadcast(&nodes[0], 1, true);
3383+
expect_payment_sent(&nodes[0], payment_preimage, None, true, true);
3384+
}
3385+
3386+
#[test]
3387+
fn test_durable_preimages_on_closed_channel() {
3388+
do_test_durable_preimages_on_closed_channel(true, true);
3389+
do_test_durable_preimages_on_closed_channel(true, false);
3390+
do_test_durable_preimages_on_closed_channel(false, false);
32233391
}

lightning/src/ln/channelmanager.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ pub(super) enum HTLCForwardInfo {
177177
}
178178

179179
/// Tracks the inbound corresponding to an outbound HTLC
180-
#[derive(Clone, Hash, PartialEq, Eq)]
180+
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
181181
pub(crate) struct HTLCPreviousHopData {
182182
// Note that this may be an outbound SCID alias for the associated channel.
183183
short_channel_id: u64,
@@ -259,7 +259,7 @@ impl Readable for InterceptId {
259259
}
260260
}
261261

262-
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
262+
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
263263
/// Uniquely describes an HTLC by its source. Just the guaranteed-unique subset of [`HTLCSource`].
264264
pub(crate) enum SentHTLCId {
265265
PreviousHopData { short_channel_id: u64, htlc_id: u64 },
@@ -290,7 +290,7 @@ impl_writeable_tlv_based_enum!(SentHTLCId,
290290

291291
/// Tracks the inbound corresponding to an outbound HTLC
292292
#[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
293-
#[derive(Clone, PartialEq, Eq)]
293+
#[derive(Clone, Debug, PartialEq, Eq)]
294294
pub(crate) enum HTLCSource {
295295
PreviousHopData(HTLCPreviousHopData),
296296
OutboundRoute {

0 commit comments

Comments
 (0)