Merge pull request #3125 from valentinewallace/2024-06-async-payments-prefactor
[rust-lightning] / lightning / src / ln / monitor_tests.rs
index 74740a6f2279d6549ba57b443b473410e26fbef6..af65d0cc6c40c2ba01cad6bd6f7db8c4731fc356 100644 (file)
@@ -9,17 +9,17 @@
 
 //! Further functional tests which test blockchain reorganizations.
 
-use crate::sign::{ecdsa::EcdsaChannelSigner, SpendableOutputDescriptor};
+use crate::sign::{ecdsa::EcdsaChannelSigner, OutputSpender, SpendableOutputDescriptor};
 use crate::chain::channelmonitor::{ANTI_REORG_DELAY, LATENCY_GRACE_PERIOD_BLOCKS, Balance};
 use crate::chain::transaction::OutPoint;
 use crate::chain::chaininterface::{LowerBoundedFeeEstimator, compute_feerate_sat_per_1000_weight};
 use crate::events::bump_transaction::{BumpTransactionEvent, WalletSource};
 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination};
 use crate::ln::channel;
+use crate::ln::types::ChannelId;
 use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, PaymentId, RecipientOnionFields};
 use crate::ln::msgs::ChannelMessageHandler;
-use crate::util::config::UserConfig;
-use crate::util::crypto::sign;
+use crate::crypto::utils::sign;
 use crate::util::ser::Writeable;
 use crate::util::scid_utils::block_from_scid;
 use crate::util::test_utils;
@@ -31,6 +31,7 @@ use bitcoin::blockdata::opcodes;
 use bitcoin::hashes::hex::FromHex;
 use bitcoin::secp256k1::{Secp256k1, SecretKey};
 use bitcoin::sighash::{SighashCache, EcdsaSighashType};
+use bitcoin::transaction::Version;
 
 use crate::prelude::*;
 
@@ -158,6 +159,60 @@ fn revoked_output_htlc_resolution_timing() {
        expect_payment_failed!(nodes[1], payment_hash_1, false);
 }
 
+#[test]
+fn archive_fully_resolved_monitors() {
+       // Test we can archive fully resolved channel monitor.
+       let chanmon_cfgs = create_chanmon_cfgs(2);
+       let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
+       let mut user_config = test_default_channel_config();
+       let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(user_config), Some(user_config)]);
+       let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
+
+       let (_, _, chan_id, funding_tx) =
+               create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 1_000_000);
+
+       nodes[0].node.close_channel(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
+       let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
+       nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
+       let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
+       nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
+
+       let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
+       nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
+       let node_1_closing_signed = get_event_msg!(nodes[1], MessageSendEvent::SendClosingSigned, nodes[0].node.get_our_node_id());
+       nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed);
+       let (_, node_0_2nd_closing_signed) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
+       nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed.unwrap());
+       let (_, _) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
+
+       let shutdown_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
+
+       mine_transaction(&nodes[0], &shutdown_tx[0]);
+       mine_transaction(&nodes[1], &shutdown_tx[0]);
+
+       connect_blocks(&nodes[0], 6);
+       connect_blocks(&nodes[1], 6);
+
+       check_closed_event!(nodes[0], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 1000000);
+       check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 1000000);
+
+       assert_eq!(nodes[0].chain_monitor.chain_monitor.list_monitors().len(), 1);
+       // First archive should set balances_empty_height to current block height
+       nodes[0].chain_monitor.chain_monitor.archive_fully_resolved_channel_monitors();
+       assert_eq!(nodes[0].chain_monitor.chain_monitor.list_monitors().len(), 1);
+       connect_blocks(&nodes[0], 4032);
+       // Second call after 4032 blocks, should archive the monitor
+       nodes[0].chain_monitor.chain_monitor.archive_fully_resolved_channel_monitors();
+       // Should have no monitors left
+       assert_eq!(nodes[0].chain_monitor.chain_monitor.list_monitors().len(), 0);
+       // Remove the corresponding outputs and transactions the chain source is
+       // watching. This is to make sure the `Drop` function assertions pass.
+       nodes.get_mut(0).unwrap().chain_source.remove_watched_txn_and_outputs(
+               OutPoint { txid: funding_tx.txid(), index: 0 },
+               funding_tx.output[0].script_pubkey.clone()
+       );
+}
+
 fn do_chanmon_claim_value_coop_close(anchors: bool) {
        // Tests `get_claimable_balances` returns the correct values across a simple cooperative claim.
        // Specifically, this tests that the channel non-HTLC balances show up in
@@ -176,7 +231,7 @@ fn do_chanmon_claim_value_coop_close(anchors: bool) {
        let (_, _, chan_id, funding_tx) =
                create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 1_000_000);
        let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
-       assert_eq!(funding_outpoint.to_channel_id(), chan_id);
+       assert_eq!(ChannelId::v1_from_funding_outpoint(funding_outpoint), chan_id);
 
        let chan_feerate = get_feerate!(nodes[0], nodes[1], chan_id) as u64;
        let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_id);
@@ -209,8 +264,8 @@ fn do_chanmon_claim_value_coop_close(anchors: bool) {
        assert_eq!(shutdown_tx, nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0));
        assert_eq!(shutdown_tx.len(), 1);
 
-       let shutdown_tx_conf_height_a = block_from_scid(&mine_transaction(&nodes[0], &shutdown_tx[0]));
-       let shutdown_tx_conf_height_b = block_from_scid(&mine_transaction(&nodes[1], &shutdown_tx[0]));
+       let shutdown_tx_conf_height_a = block_from_scid(mine_transaction(&nodes[0], &shutdown_tx[0]));
+       let shutdown_tx_conf_height_b = block_from_scid(mine_transaction(&nodes[1], &shutdown_tx[0]));
 
        assert!(nodes[0].node.list_channels().is_empty());
        assert!(nodes[1].node.list_channels().is_empty());
@@ -257,8 +312,8 @@ fn do_chanmon_claim_value_coop_close(anchors: bool) {
                spendable_outputs_b
        );
 
-       check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 1000000);
-       check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 1000000);
+       check_closed_event!(nodes[0], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 1000000);
+       check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 1000000);
 }
 
 #[test]
@@ -305,16 +360,16 @@ fn do_test_claim_value_force_close(anchors: bool, prev_commitment_tx: bool) {
        let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
 
        let coinbase_tx = Transaction {
-               version: 2,
+               version: Version::TWO,
                lock_time: LockTime::ZERO,
                input: vec![TxIn { ..Default::default() }],
                output: vec![
                        TxOut {
-                               value: Amount::ONE_BTC.to_sat(),
+                               value: Amount::ONE_BTC,
                                script_pubkey: nodes[0].wallet_source.get_change_script().unwrap(),
                        },
                        TxOut {
-                               value: Amount::ONE_BTC.to_sat(),
+                               value: Amount::ONE_BTC,
                                script_pubkey: nodes[1].wallet_source.get_change_script().unwrap(),
                        },
                ],
@@ -327,7 +382,7 @@ fn do_test_claim_value_force_close(anchors: bool, prev_commitment_tx: bool) {
        let (_, _, chan_id, funding_tx) =
                create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 1_000_000);
        let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
-       assert_eq!(funding_outpoint.to_channel_id(), chan_id);
+       assert_eq!(ChannelId::v1_from_funding_outpoint(funding_outpoint), chan_id);
 
        // This HTLC is immediately claimed, giving node B the preimage
        let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
@@ -481,8 +536,8 @@ fn do_test_claim_value_force_close(anchors: bool, prev_commitment_tx: bool) {
        check_spends!(b_broadcast_txn[1], remote_txn[0], coinbase_tx);
        assert_eq!(b_broadcast_txn[0].input.len(), if anchors { 2 } else { 1 });
        assert_eq!(b_broadcast_txn[1].input.len(), if anchors { 2 } else { 1 });
-       assert_eq!(remote_txn[0].output[b_broadcast_txn[0].input[0].previous_output.vout as usize].value, 3_000);
-       assert_eq!(remote_txn[0].output[b_broadcast_txn[1].input[0].previous_output.vout as usize].value, 4_000);
+       assert_eq!(remote_txn[0].output[b_broadcast_txn[0].input[0].previous_output.vout as usize].value.to_sat(), 3_000);
+       assert_eq!(remote_txn[0].output[b_broadcast_txn[1].input[0].previous_output.vout as usize].value.to_sat(), 4_000);
 
        assert!(nodes[0].node.list_channels().is_empty());
        check_closed_broadcast!(nodes[0], true);
@@ -561,8 +616,8 @@ fn do_test_claim_value_force_close(anchors: bool, prev_commitment_tx: bool) {
        assert_ne!(a_broadcast_txn[0].input[0].previous_output.vout,
                   a_broadcast_txn[1].input[0].previous_output.vout);
        // a_broadcast_txn [0] and [1] should spend the HTLC outputs of the commitment tx
-       assert_eq!(remote_txn[0].output[a_broadcast_txn[0].input[0].previous_output.vout as usize].value, 3_000);
-       assert_eq!(remote_txn[0].output[a_broadcast_txn[1].input[0].previous_output.vout as usize].value, 4_000);
+       assert_eq!(remote_txn[0].output[a_broadcast_txn[0].input[0].previous_output.vout as usize].value.to_sat(), 3_000);
+       assert_eq!(remote_txn[0].output[a_broadcast_txn[1].input[0].previous_output.vout as usize].value.to_sat(), 4_000);
 
        // Once the HTLC-Timeout transaction confirms, A will no longer consider the HTLC
        // "MaybeClaimable", but instead move it to "AwaitingConfirmations".
@@ -666,16 +721,16 @@ fn do_test_balances_on_local_commitment_htlcs(anchors: bool) {
        let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
 
        let coinbase_tx = Transaction {
-               version: 2,
+               version: Version::TWO,
                lock_time: LockTime::ZERO,
                input: vec![TxIn { ..Default::default() }],
                output: vec![
                        TxOut {
-                               value: Amount::ONE_BTC.to_sat(),
+                               value: Amount::ONE_BTC,
                                script_pubkey: nodes[0].wallet_source.get_change_script().unwrap(),
                        },
                        TxOut {
-                               value: Amount::ONE_BTC.to_sat(),
+                               value: Amount::ONE_BTC,
                                script_pubkey: nodes[1].wallet_source.get_change_script().unwrap(),
                        },
                ],
@@ -724,11 +779,12 @@ fn do_test_balances_on_local_commitment_htlcs(anchors: bool) {
 
        // First confirm the commitment transaction on nodes[0], which should leave us with three
        // claimable balances.
+       let error_message = "Channel force-closed";
        let node_a_commitment_claimable = nodes[0].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
-       nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
+       nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id(), error_message.to_string()).unwrap();
        check_added_monitors!(nodes[0], 1);
        check_closed_broadcast!(nodes[0], true);
-       check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 1000000);
+       check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true) }, [nodes[1].node.get_our_node_id()], 1000000);
        let commitment_tx = {
                let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
                assert_eq!(txn.len(), 1);
@@ -736,7 +792,7 @@ fn do_test_balances_on_local_commitment_htlcs(anchors: bool) {
                check_spends!(commitment_tx, funding_tx);
                commitment_tx
        };
-       let commitment_tx_conf_height_a = block_from_scid(&mine_transaction(&nodes[0], &commitment_tx));
+       let commitment_tx_conf_height_a = block_from_scid(mine_transaction(&nodes[0], &commitment_tx));
        if nodes[0].connect_style.borrow().updates_best_block_first() {
                let mut txn = nodes[0].tx_broadcaster.txn_broadcast();
                assert_eq!(txn.len(), 1);
@@ -1121,7 +1177,7 @@ fn do_test_revoked_counterparty_commitment_balances(anchors: bool, confirm_htlc_
        let (_, _, chan_id, funding_tx) =
                create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 100_000_000);
        let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
-       assert_eq!(funding_outpoint.to_channel_id(), chan_id);
+       assert_eq!(ChannelId::v1_from_funding_outpoint(funding_outpoint), chan_id);
 
        // We create five HTLCs for B to claim against A's revoked commitment transaction:
        //
@@ -1188,14 +1244,14 @@ fn do_test_revoked_counterparty_commitment_balances(anchors: bool, confirm_htlc_
        assert!(failed_payments.is_empty());
        if let Event::PendingHTLCsForwardable { .. } = events[0] {} else { panic!(); }
        match &events[1] {
-               Event::ChannelClosed { reason: ClosureReason::HolderForceClosed, .. } => {},
+               Event::ChannelClosed { reason: ClosureReason::HTLCsTimedOut, .. } => {},
                _ => panic!(),
        }
 
        connect_blocks(&nodes[1], htlc_cltv_timeout + 1 - 10);
        check_closed_broadcast!(nodes[1], true);
        check_added_monitors!(nodes[1], 1);
-       check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 1000000);
+       check_closed_event!(nodes[1], 1, ClosureReason::HTLCsTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
 
        // Prior to channel closure, B considers the preimage HTLC as its own, and otherwise only
        // lists the two on-chain timeout-able HTLCs as claimable balances.
@@ -1221,7 +1277,7 @@ fn do_test_revoked_counterparty_commitment_balances(anchors: bool, confirm_htlc_
        // Currently the revoked commitment is claimed in four transactions as the HTLCs all expire
        // quite soon.
        assert_eq!(claim_txn.len(), 4);
-       claim_txn.sort_unstable_by_key(|tx| tx.output.iter().map(|output| output.value).sum::<u64>());
+       claim_txn.sort_unstable_by_key(|tx| tx.output.iter().map(|output| output.value.to_sat()).sum::<u64>());
 
        // The following constants were determined experimentally
        const BS_TO_SELF_CLAIM_EXP_WEIGHT: u64 = 483;
@@ -1380,16 +1436,16 @@ fn do_test_revoked_counterparty_htlc_tx_balances(anchors: bool) {
        let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
 
        let coinbase_tx = Transaction {
-               version: 2,
+               version: Version::TWO,
                lock_time: LockTime::ZERO,
                input: vec![TxIn { ..Default::default() }],
                output: vec![
                        TxOut {
-                               value: Amount::ONE_BTC.to_sat(),
+                               value: Amount::ONE_BTC,
                                script_pubkey: nodes[0].wallet_source.get_change_script().unwrap(),
                        },
                        TxOut {
-                               value: Amount::ONE_BTC.to_sat(),
+                               value: Amount::ONE_BTC,
                                script_pubkey: nodes[1].wallet_source.get_change_script().unwrap(),
                        },
                ],
@@ -1403,7 +1459,7 @@ fn do_test_revoked_counterparty_htlc_tx_balances(anchors: bool) {
        let (_, _, chan_id, funding_tx) =
                create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 12_000_000);
        let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
-       assert_eq!(funding_outpoint.to_channel_id(), chan_id);
+       assert_eq!(ChannelId::v1_from_funding_outpoint(funding_outpoint), chan_id);
 
        let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
        let failed_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 1_000_000).1;
@@ -1411,9 +1467,9 @@ fn do_test_revoked_counterparty_htlc_tx_balances(anchors: bool) {
        assert_eq!(revoked_local_txn[0].input.len(), 1);
        assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, funding_tx.txid());
        if anchors {
-               assert_eq!(revoked_local_txn[0].output[4].value, 11000); // to_self output
+               assert_eq!(revoked_local_txn[0].output[4].value.to_sat(), 11000); // to_self output
        } else {
-               assert_eq!(revoked_local_txn[0].output[2].value, 11000); // to_self output
+               assert_eq!(revoked_local_txn[0].output[2].value.to_sat(), 11000); // to_self output
        }
 
        // The to-be-revoked commitment tx should have two HTLCs, an output for each side, and an
@@ -1535,10 +1591,10 @@ fn do_test_revoked_counterparty_htlc_tx_balances(anchors: bool) {
        if anchors {
                // With anchors, B can pay for revoked_htlc_success's fee with additional inputs, rather
                // than with the HTLC itself.
-               fuzzy_assert_eq(as_htlc_claim_tx[0].output[0].value,
+               fuzzy_assert_eq(as_htlc_claim_tx[0].output[0].value.to_sat(),
                        3_000 - as_revoked_htlc_success_claim_fee);
        } else {
-               fuzzy_assert_eq(as_htlc_claim_tx[0].output[0].value,
+               fuzzy_assert_eq(as_htlc_claim_tx[0].output[0].value.to_sat(),
                        3_000 - revoked_htlc_success_fee - as_revoked_htlc_success_claim_fee);
        }
 
@@ -1553,7 +1609,7 @@ fn do_test_revoked_counterparty_htlc_tx_balances(anchors: bool) {
                }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
                        amount_satoshis: 1_000,
                }, Balance::ClaimableAwaitingConfirmations {
-                       amount_satoshis: as_htlc_claim_tx[0].output[0].value,
+                       amount_satoshis: as_htlc_claim_tx[0].output[0].value.to_sat(),
                        confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
                }]),
                sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
@@ -1566,7 +1622,7 @@ fn do_test_revoked_counterparty_htlc_tx_balances(anchors: bool) {
                }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
                        amount_satoshis: 1_000,
                }, Balance::ClaimableAwaitingConfirmations {
-                       amount_satoshis: as_htlc_claim_tx[0].output[0].value,
+                       amount_satoshis: as_htlc_claim_tx[0].output[0].value.to_sat(),
                        confirmation_height: nodes[0].best_block_info().1 + 2,
                }]),
                sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
@@ -1635,7 +1691,7 @@ fn do_test_revoked_counterparty_htlc_tx_balances(anchors: bool) {
                        // to_self output in B's revoked commitment
                        amount_satoshis: 11_000,
                }, Balance::ClaimableAwaitingConfirmations {
-                       amount_satoshis: revoked_htlc_timeout_claim.output[0].value,
+                       amount_satoshis: revoked_htlc_timeout_claim.output[0].value.to_sat(),
                        confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
                }]),
                sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
@@ -1643,10 +1699,10 @@ fn do_test_revoked_counterparty_htlc_tx_balances(anchors: bool) {
        mine_transaction(&nodes[0], &revoked_to_self_claim);
        assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
                        // to_self output in B's revoked commitment
-                       amount_satoshis: revoked_to_self_claim.output[0].value,
+                       amount_satoshis: revoked_to_self_claim.output[0].value.to_sat(),
                        confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
                }, Balance::ClaimableAwaitingConfirmations {
-                       amount_satoshis: revoked_htlc_timeout_claim.output[0].value,
+                       amount_satoshis: revoked_htlc_timeout_claim.output[0].value.to_sat(),
                        confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 2,
                }]),
                sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
@@ -1692,11 +1748,11 @@ fn do_test_revoked_counterparty_aggregated_claims(anchors: bool) {
        let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
 
        let coinbase_tx = Transaction {
-               version: 2,
+               version: Version::TWO,
                lock_time: LockTime::ZERO,
                input: vec![TxIn { ..Default::default() }],
                output: vec![TxOut {
-                       value: Amount::ONE_BTC.to_sat(),
+                       value: Amount::ONE_BTC,
                        script_pubkey: nodes[0].wallet_source.get_change_script().unwrap(),
                }],
        };
@@ -1705,7 +1761,7 @@ fn do_test_revoked_counterparty_aggregated_claims(anchors: bool) {
        let (_, _, chan_id, funding_tx) =
                create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 100_000_000);
        let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
-       assert_eq!(funding_outpoint.to_channel_id(), chan_id);
+       assert_eq!(ChannelId::v1_from_funding_outpoint(funding_outpoint), chan_id);
 
        // We create two HTLCs, one which we will give A the preimage to to generate an HTLC-Success
        // transaction, and one which we will not, allowing B to claim the HTLC output in an aggregated
@@ -1889,7 +1945,7 @@ fn do_test_revoked_counterparty_aggregated_claims(anchors: bool) {
                }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
                        amount_satoshis: 4_000,
                }, Balance::ClaimableAwaitingConfirmations { // HTLC 2
-                       amount_satoshis: claim_txn_2[0].output[0].value,
+                       amount_satoshis: claim_txn_2[0].output[0].value.to_sat(),
                        confirmation_height: htlc_2_claim_maturity,
                }]),
                sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
@@ -1914,16 +1970,16 @@ fn do_test_revoked_counterparty_aggregated_claims(anchors: bool) {
 
        if anchors {
                assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
-                               amount_satoshis: claim_txn_2[1].output[0].value,
+                               amount_satoshis: claim_txn_2[1].output[0].value.to_sat(),
                                confirmation_height: rest_claim_maturity,
                        }, Balance::ClaimableAwaitingConfirmations {
-                               amount_satoshis: revoked_to_self_claim.as_ref().unwrap().output[0].value,
+                               amount_satoshis: revoked_to_self_claim.as_ref().unwrap().output[0].value.to_sat(),
                                confirmation_height: rest_claim_maturity,
                        }],
                        nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
        } else {
                assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
-                               amount_satoshis: claim_txn_2[1].output[0].value,
+                               amount_satoshis: claim_txn_2[1].output[0].value.to_sat(),
                                confirmation_height: rest_claim_maturity,
                        }],
                        nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
@@ -1982,11 +2038,11 @@ fn do_test_restored_packages_retry(check_old_monitor_retries_after_upgrade: bool
        // ensures that the HTLC timeout package is held until we reach its expiration height.
        let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 50_000_000);
        route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
-
-       nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
+       let error_message = "Channel force-closed";
+       nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id(), error_message.to_string()).unwrap();
        check_added_monitors(&nodes[0], 1);
        check_closed_broadcast(&nodes[0], 1, true);
-       check_closed_event!(&nodes[0], 1, ClosureReason::HolderForceClosed, false,
+       check_closed_event!(&nodes[0], 1, ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true) }, false,
                 [nodes[1].node.get_our_node_id()], 100000);
 
        let commitment_tx = {
@@ -2081,11 +2137,11 @@ fn do_test_monitor_rebroadcast_pending_claims(anchors: bool) {
        check_added_monitors(&nodes[0], 1);
 
        let coinbase_tx = Transaction {
-               version: 2,
+               version: Version::TWO,
                lock_time: LockTime::ZERO,
                input: vec![TxIn { ..Default::default() }],
                output: vec![TxOut { // UTXO to attach fees to `htlc_tx` on anchors
-                       value: Amount::ONE_BTC.to_sat(),
+                       value: Amount::ONE_BTC,
                        script_pubkey: nodes[0].wallet_source.get_change_script().unwrap(),
                }],
        };
@@ -2110,8 +2166,8 @@ fn do_test_monitor_rebroadcast_pending_claims(anchors: bool) {
                                        assert_eq!(txn.len(), 1);
                                        let htlc_tx = txn.pop().unwrap();
                                        check_spends!(&htlc_tx, &commitment_txn[0], &coinbase_tx);
-                                       let htlc_tx_fee = HTLC_AMT_SAT + coinbase_tx.output[0].value -
-                                               htlc_tx.output.iter().map(|output| output.value).sum::<u64>();
+                                       let htlc_tx_fee = HTLC_AMT_SAT + coinbase_tx.output[0].value.to_sat() -
+                                               htlc_tx.output.iter().map(|output| output.value.to_sat()).sum::<u64>();
                                        let htlc_tx_weight = htlc_tx.weight().to_wu();
                                        (htlc_tx, compute_feerate_sat_per_1000_weight(htlc_tx_fee, htlc_tx_weight))
                                }
@@ -2126,7 +2182,7 @@ fn do_test_monitor_rebroadcast_pending_claims(anchors: bool) {
                        }
                        let htlc_tx = txn.pop().unwrap();
                        check_spends!(htlc_tx, commitment_txn[0]);
-                       let htlc_tx_fee = HTLC_AMT_SAT - htlc_tx.output[0].value;
+                       let htlc_tx_fee = HTLC_AMT_SAT - htlc_tx.output[0].value.to_sat();
                        let htlc_tx_weight = htlc_tx.weight().to_wu();
                        (htlc_tx, compute_feerate_sat_per_1000_weight(htlc_tx_fee, htlc_tx_weight))
                };
@@ -2195,7 +2251,7 @@ fn test_yield_anchors_events() {
        // emitted by LDK, such that the consumer can attach fees to the zero fee HTLC transactions.
        let mut chanmon_cfgs = create_chanmon_cfgs(2);
        let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
-       let mut anchors_config = UserConfig::default();
+       let mut anchors_config = test_default_channel_config();
        anchors_config.channel_handshake_config.announced_channel = true;
        anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
        anchors_config.manually_accept_inbound_channels = true;
@@ -2237,11 +2293,11 @@ fn test_yield_anchors_events() {
        let (commitment_tx, anchor_tx) = match holder_events.pop().unwrap() {
                Event::BumpTransaction(event) => {
                        let coinbase_tx = Transaction {
-                               version: 2,
+                               version: Version::TWO,
                                lock_time: LockTime::ZERO,
                                input: vec![TxIn { ..Default::default() }],
                                output: vec![TxOut { // UTXO to attach fees to `anchor_tx`
-                                       value: Amount::ONE_BTC.to_sat(),
+                                       value: Amount::ONE_BTC,
                                        script_pubkey: nodes[0].wallet_source.get_change_script().unwrap(),
                                }],
                        };
@@ -2258,8 +2314,8 @@ fn test_yield_anchors_events() {
                _ => panic!("Unexpected event"),
        };
 
-       assert_eq!(commitment_tx.output[2].value, 1_000); // HTLC A -> B
-       assert_eq!(commitment_tx.output[3].value, 2_000); // HTLC B -> A
+       assert_eq!(commitment_tx.output[2].value.to_sat(), 1_000); // HTLC A -> B
+       assert_eq!(commitment_tx.output[3].value.to_sat(), 2_000); // HTLC B -> A
 
        mine_transactions(&nodes[0], &[&commitment_tx, &anchor_tx]);
        check_added_monitors!(nodes[0], 1);
@@ -2346,7 +2402,7 @@ fn test_anchors_aggregated_revoked_htlc_tx() {
        let bob_persister;
        let bob_chain_monitor;
 
-       let mut anchors_config = UserConfig::default();
+       let mut anchors_config = test_default_channel_config();
        anchors_config.channel_handshake_config.announced_channel = true;
        anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
        anchors_config.manually_accept_inbound_channels = true;
@@ -2414,9 +2470,9 @@ fn test_anchors_aggregated_revoked_htlc_tx() {
        let mut revoked_commitment_txs = Vec::with_capacity(events.len());
        let mut anchor_txs = Vec::with_capacity(events.len());
        for (idx, event) in events.into_iter().enumerate() {
-               let utxo_value = Amount::ONE_BTC.to_sat() * (idx + 1) as u64;
+               let utxo_value = Amount::ONE_BTC * (idx + 1) as u64;
                let coinbase_tx = Transaction {
-                       version: 2,
+                       version: Version::TWO,
                        lock_time: LockTime::ZERO,
                        input: vec![TxIn { ..Default::default() }],
                        output: vec![TxOut { // UTXO to attach fees to `anchor_tx`
@@ -2491,18 +2547,18 @@ fn test_anchors_aggregated_revoked_htlc_tx() {
        let htlc_tx = {
                let secret_key = SecretKey::from_slice(&[1; 32]).unwrap();
                let public_key = PublicKey::new(secret_key.public_key(&secp));
-               let fee_utxo_script = ScriptBuf::new_v0_p2wpkh(&public_key.wpubkey_hash().unwrap());
+               let fee_utxo_script = ScriptBuf::new_p2wpkh(&public_key.wpubkey_hash().unwrap());
                let coinbase_tx = Transaction {
-                       version: 2,
+                       version: Version::TWO,
                        lock_time: LockTime::ZERO,
                        input: vec![TxIn { ..Default::default() }],
                        output: vec![TxOut { // UTXO to attach fees to `htlc_tx`
-                               value: Amount::ONE_BTC.to_sat(),
+                               value: Amount::ONE_BTC,
                                script_pubkey: fee_utxo_script.clone(),
                        }],
                };
                let mut htlc_tx = Transaction {
-                       version: 2,
+                       version: Version::TWO,
                        lock_time: LockTime::ZERO,
                        input: vec![TxIn { // Fee input
                                previous_output: bitcoin::OutPoint { txid: coinbase_tx.txid(), vout: 0 },
@@ -2539,7 +2595,7 @@ fn test_anchors_aggregated_revoked_htlc_tx() {
                }
                let fee_utxo_sig = {
                        let witness_script = ScriptBuf::new_p2pkh(&public_key.pubkey_hash());
-                       let sighash = hash_to_message!(&SighashCache::new(&htlc_tx).segwit_signature_hash(
+                       let sighash = hash_to_message!(&SighashCache::new(&htlc_tx).p2wsh_signature_hash(
                                0, &witness_script, coinbase_tx.output[0].value, EcdsaSighashType::All
                        ).unwrap()[..]);
                        let sig = sign(&secp, &sighash, &secret_key);
@@ -2572,7 +2628,7 @@ fn test_anchors_aggregated_revoked_htlc_tx() {
                        check_spends!(revoked_htlc_claim, htlc_tx);
                }
 
-               let mut revoked_claim_transaction_map = HashMap::new();
+               let mut revoked_claim_transaction_map = new_hash_map();
                for current_tx in txn.into_iter() {
                        revoked_claim_transaction_map.insert(current_tx.txid(), current_tx);
                }
@@ -2649,16 +2705,17 @@ fn do_test_anchors_monitor_fixes_counterparty_payment_script_on_reload(confirm_c
        let secp = Secp256k1::new();
        let privkey = bitcoin::PrivateKey::from_slice(&[1; 32], bitcoin::Network::Testnet).unwrap();
        let pubkey = bitcoin::PublicKey::from_private_key(&secp, &privkey);
-       let p2wpkh_script = ScriptBuf::new_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap());
+       let p2wpkh_script = ScriptBuf::new_p2wpkh(&pubkey.wpubkey_hash().unwrap());
        get_monitor!(nodes[1], chan_id).set_counterparty_payment_script(p2wpkh_script.clone());
        assert_eq!(get_monitor!(nodes[1], chan_id).get_counterparty_payment_script(), p2wpkh_script);
 
        // Confirm the counterparty's commitment and reload the monitor (either before or after) such
        // that we arrive at the correct `counterparty_payment_script` after the reload.
-       nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
+       let error_message = "Channel force-closed";
+       nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id(), error_message.to_string()).unwrap();
        check_added_monitors(&nodes[0], 1);
        check_closed_broadcast(&nodes[0], 1, true);
-       check_closed_event!(&nodes[0], 1, ClosureReason::HolderForceClosed, false,
+       check_closed_event!(&nodes[0], 1, ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true) }, false,
                 [nodes[1].node.get_our_node_id()], 100000);
 
        let commitment_tx = {
@@ -2674,21 +2731,21 @@ fn do_test_anchors_monitor_fixes_counterparty_payment_script_on_reload(confirm_c
                // We should expect our round trip serialization check to fail as we're writing the monitor
                // with the incorrect P2WPKH script but reading it with the correct P2WSH script.
                *nodes[1].chain_monitor.expect_monitor_round_trip_fail.lock().unwrap() = Some(chan_id);
-               let commitment_tx_conf_height = block_from_scid(&mine_transaction(&nodes[1], &commitment_tx));
+               let commitment_tx_conf_height = block_from_scid(mine_transaction(&nodes[1], &commitment_tx));
                let serialized_monitor = get_monitor!(nodes[1], chan_id).encode();
                reload_node!(nodes[1], user_config, &nodes[1].node.encode(), &[&serialized_monitor], persister, chain_monitor, node_deserialized);
                commitment_tx_conf_height
        } else {
                let serialized_monitor = get_monitor!(nodes[1], chan_id).encode();
                reload_node!(nodes[1], user_config, &nodes[1].node.encode(), &[&serialized_monitor], persister, chain_monitor, node_deserialized);
-               let commitment_tx_conf_height = block_from_scid(&mine_transaction(&nodes[1], &commitment_tx));
+               let commitment_tx_conf_height = block_from_scid(mine_transaction(&nodes[1], &commitment_tx));
                check_added_monitors(&nodes[1], 1);
                check_closed_broadcast(&nodes[1], 1, true);
                commitment_tx_conf_height
        };
        check_closed_event!(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false,
                 [nodes[0].node.get_our_node_id()], 100000);
-       assert!(get_monitor!(nodes[1], chan_id).get_counterparty_payment_script().is_v0_p2wsh());
+       assert!(get_monitor!(nodes[1], chan_id).get_counterparty_payment_script().is_p2wsh());
 
        connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
        connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
@@ -2731,12 +2788,12 @@ fn do_test_monitor_claims_with_random_signatures(anchors: bool, confirm_counterp
        let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
 
        let coinbase_tx = Transaction {
-               version: 2,
+               version: Version::TWO,
                lock_time: LockTime::ZERO,
                input: vec![TxIn { ..Default::default() }],
                output: vec![
                        TxOut {
-                               value: Amount::ONE_BTC.to_sat(),
+                               value: Amount::ONE_BTC,
                                script_pubkey: nodes[0].wallet_source.get_change_script().unwrap(),
                        },
                ],
@@ -2755,7 +2812,9 @@ fn do_test_monitor_claims_with_random_signatures(anchors: bool, confirm_counterp
                (&nodes[0], &nodes[1])
        };
 
-       closing_node.node.force_close_broadcasting_latest_txn(&chan_id, &other_node.node.get_our_node_id()).unwrap();
+       get_monitor!(closing_node, chan_id).broadcast_latest_holder_commitment_txn(
+               &closing_node.tx_broadcaster, &closing_node.fee_estimator, &closing_node.logger
+       );
 
        // The commitment transaction comes first.
        let commitment_tx = {
@@ -2768,7 +2827,7 @@ fn do_test_monitor_claims_with_random_signatures(anchors: bool, confirm_counterp
        mine_transaction(closing_node, &commitment_tx);
        check_added_monitors!(closing_node, 1);
        check_closed_broadcast!(closing_node, true);
-       check_closed_event!(closing_node, 1, ClosureReason::HolderForceClosed, [other_node.node.get_our_node_id()], 1_000_000);
+       check_closed_event!(closing_node, 1, ClosureReason::CommitmentTxConfirmed, [other_node.node.get_our_node_id()], 1_000_000);
 
        mine_transaction(other_node, &commitment_tx);
        check_added_monitors!(other_node, 1);
@@ -2821,3 +2880,42 @@ fn test_monitor_claims_with_random_signatures() {
        do_test_monitor_claims_with_random_signatures(true, false);
        do_test_monitor_claims_with_random_signatures(true, true);
 }
+
+#[test]
+fn test_event_replay_causing_monitor_replay() {
+       // In LDK 0.0.121 there was a bug where if a `PaymentSent` event caused an RAA
+       // `ChannelMonitorUpdate` hold and then the node was restarted after the `PaymentSent` event
+       // and `ChannelMonitorUpdate` both completed but without persisting the `ChannelManager` we'd
+       // replay the `ChannelMonitorUpdate` on restart (which is fine, but triggered a safety panic).
+       let chanmon_cfgs = create_chanmon_cfgs(2);
+       let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
+       let persister;
+       let new_chain_monitor;
+       let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
+       let node_deserialized;
+       let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
+
+       let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
+
+       let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1_000_000).0;
+
+       do_claim_payment_along_route(
+               ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1]]], payment_preimage)
+       );
+
+       // At this point the `PaymentSent` event has not been processed but the full commitment signed
+       // dance has completed.
+       let serialized_channel_manager = nodes[0].node.encode();
+
+       // Now process the `PaymentSent` to get the final RAA `ChannelMonitorUpdate`, checking that it
+       // resulted in a `ChannelManager` persistence request.
+       nodes[0].node.get_and_clear_needs_persistence();
+       expect_payment_sent(&nodes[0], payment_preimage, None, true, true /* expected post-event monitor update*/);
+       assert!(nodes[0].node.get_and_clear_needs_persistence());
+
+       let serialized_monitor = get_monitor!(nodes[0], chan.2).encode();
+       reload_node!(nodes[0], &serialized_channel_manager, &[&serialized_monitor], persister, new_chain_monitor, node_deserialized);
+
+       // Expect the `PaymentSent` to get replayed, this time without the duplicate monitor update
+       expect_payment_sent(&nodes[0], payment_preimage, None, false, false /* expected post-event monitor update*/);
+}