Merge pull request #3060 from TheBlueMatt/2024-05-parallel-async-om-events
[rust-lightning] / lightning / src / ln / channelmanager.rs
index 7bfeeac6def5cef5144c5a0fe536073ac2bd7c45..921ea03b8cae781df32165ebfaaae6919288433b 100644 (file)
@@ -46,7 +46,7 @@ use crate::events::{Event, EventHandler, EventsProvider, MessageSendEvent, Messa
 use crate::ln::inbound_payment;
 use crate::ln::types::{ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
 use crate::ln::channel::{self, Channel, ChannelPhase, ChannelContext, ChannelError, ChannelUpdateStatus, ShutdownResult, UnfundedChannelContext, UpdateFulfillCommitFetch, OutboundV1Channel, InboundV1Channel, WithChannelContext};
-pub use crate::ln::channel::{InboundHTLCDetails, InboundHTLCStateDetails, OutboundHTLCDetails, OutboundHTLCStateDetails};
+use crate::ln::channel_state::{ChannelCounterparty, ChannelDetails, ChannelShutdownState, CounterpartyForwardingInfo};
 use crate::ln::features::{Bolt12InvoiceFeatures, ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
 #[cfg(any(feature = "_test_utils", test))]
 use crate::ln::features::Bolt11InvoiceFeatures;
@@ -1356,11 +1356,12 @@ where
 /// #
 /// # fn example<T: AChannelManager>(channel_manager: T) {
 /// # let channel_manager = channel_manager.get_cm();
+/// # let error_message = "Channel force-closed";
 /// channel_manager.process_pending_events(&|event| match event {
 ///     Event::OpenChannelRequest { temporary_channel_id, counterparty_node_id, ..  } => {
 ///         if !is_trusted(counterparty_node_id) {
 ///             match channel_manager.force_close_without_broadcasting_txn(
-///                 &temporary_channel_id, &counterparty_node_id
+///                 &temporary_channel_id, &counterparty_node_id, error_message.to_string()
 ///             ) {
 ///                 Ok(()) => println!("Rejecting channel {}", temporary_channel_id),
 ///                 Err(e) => println!("Error rejecting channel {}: {:?}", temporary_channel_id, e),
@@ -2286,338 +2287,6 @@ const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
 /// many peers we reject new (inbound) connections.
 const MAX_NO_CHANNEL_PEERS: usize = 250;
 
-/// Information needed for constructing an invoice route hint for this channel.
-#[derive(Clone, Debug, PartialEq)]
-pub struct CounterpartyForwardingInfo {
-       /// Base routing fee in millisatoshis.
-       pub fee_base_msat: u32,
-       /// Amount in millionths of a satoshi the channel will charge per transferred satoshi.
-       pub fee_proportional_millionths: u32,
-       /// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart,
-       /// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s
-       /// `cltv_expiry_delta` for more details.
-       pub cltv_expiry_delta: u16,
-}
-
-/// Channel parameters which apply to our counterparty. These are split out from [`ChannelDetails`]
-/// to better separate parameters.
-#[derive(Clone, Debug, PartialEq)]
-pub struct ChannelCounterparty {
-       /// The node_id of our counterparty
-       pub node_id: PublicKey,
-       /// The Features the channel counterparty provided upon last connection.
-       /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
-       /// many routing-relevant features are present in the init context.
-       pub features: InitFeatures,
-       /// The value, in satoshis, that must always be held in the channel for our counterparty. This
-       /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
-       /// claiming at least this value on chain.
-       ///
-       /// This value is not included in [`inbound_capacity_msat`] as it can never be spent.
-       ///
-       /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
-       pub unspendable_punishment_reserve: u64,
-       /// Information on the fees and requirements that the counterparty requires when forwarding
-       /// payments to us through this channel.
-       pub forwarding_info: Option<CounterpartyForwardingInfo>,
-       /// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field
-       /// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message
-       /// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107.
-       pub outbound_htlc_minimum_msat: Option<u64>,
-       /// The largest value HTLC (in msat) the remote peer currently will accept, for this channel.
-       pub outbound_htlc_maximum_msat: Option<u64>,
-}
-
-/// Details of a channel, as returned by [`ChannelManager::list_channels`] and [`ChannelManager::list_usable_channels`]
-#[derive(Clone, Debug, PartialEq)]
-pub struct ChannelDetails {
-       /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
-       /// thereafter this is the txid of the funding transaction xor the funding transaction output).
-       /// Note that this means this value is *not* persistent - it can change once during the
-       /// lifetime of the channel.
-       pub channel_id: ChannelId,
-       /// Parameters which apply to our counterparty. See individual fields for more information.
-       pub counterparty: ChannelCounterparty,
-       /// The Channel's funding transaction output, if we've negotiated the funding transaction with
-       /// our counterparty already.
-       pub funding_txo: Option<OutPoint>,
-       /// The features which this channel operates with. See individual features for more info.
-       ///
-       /// `None` until negotiation completes and the channel type is finalized.
-       pub channel_type: Option<ChannelTypeFeatures>,
-       /// The position of the funding transaction in the chain. None if the funding transaction has
-       /// not yet been confirmed and the channel fully opened.
-       ///
-       /// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound
-       /// payments instead of this. See [`get_inbound_payment_scid`].
-       ///
-       /// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may
-       /// be used in place of this in outbound routes. See [`get_outbound_payment_scid`].
-       ///
-       /// [`inbound_scid_alias`]: Self::inbound_scid_alias
-       /// [`outbound_scid_alias`]: Self::outbound_scid_alias
-       /// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid
-       /// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid
-       /// [`confirmations_required`]: Self::confirmations_required
-       pub short_channel_id: Option<u64>,
-       /// An optional [`short_channel_id`] alias for this channel, randomly generated by us and
-       /// usable in place of [`short_channel_id`] to reference the channel in outbound routes when
-       /// the channel has not yet been confirmed (as long as [`confirmations_required`] is
-       /// `Some(0)`).
-       ///
-       /// This will be `None` as long as the channel is not available for routing outbound payments.
-       ///
-       /// [`short_channel_id`]: Self::short_channel_id
-       /// [`confirmations_required`]: Self::confirmations_required
-       pub outbound_scid_alias: Option<u64>,
-       /// An optional [`short_channel_id`] alias for this channel, randomly generated by our
-       /// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our
-       /// counterparty will recognize the alias provided here in place of the [`short_channel_id`]
-       /// when they see a payment to be routed to us.
-       ///
-       /// Our counterparty may choose to rotate this value at any time, though will always recognize
-       /// previous values for inbound payment forwarding.
-       ///
-       /// [`short_channel_id`]: Self::short_channel_id
-       pub inbound_scid_alias: Option<u64>,
-       /// The value, in satoshis, of this channel as appears in the funding output
-       pub channel_value_satoshis: u64,
-       /// The value, in satoshis, that must always be held in the channel for us. This value ensures
-       /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least
-       /// this value on chain.
-       ///
-       /// This value is not included in [`outbound_capacity_msat`] as it can never be spent.
-       ///
-       /// This value will be `None` for outbound channels until the counterparty accepts the channel.
-       ///
-       /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
-       pub unspendable_punishment_reserve: Option<u64>,
-       /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
-       /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
-       /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
-       /// `user_channel_id` will be randomized for an inbound channel.  This may be zero for objects
-       /// serialized with LDK versions prior to 0.0.113.
-       ///
-       /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
-       /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
-       /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
-       pub user_channel_id: u128,
-       /// The currently negotiated fee rate denominated in satoshi per 1000 weight units,
-       /// which is applied to commitment and HTLC transactions.
-       ///
-       /// This value will be `None` for objects serialized with LDK versions prior to 0.0.115.
-       pub feerate_sat_per_1000_weight: Option<u32>,
-       /// Our total balance.  This is the amount we would get if we close the channel.
-       /// This value is not exact. Due to various in-flight changes and feerate changes, exactly this
-       /// amount is not likely to be recoverable on close.
-       ///
-       /// This does not include any pending HTLCs which are not yet fully resolved (and, thus, whose
-       /// balance is not available for inclusion in new outbound HTLCs). This further does not include
-       /// any pending outgoing HTLCs which are awaiting some other resolution to be sent.
-       /// This does not consider any on-chain fees.
-       ///
-       /// See also [`ChannelDetails::outbound_capacity_msat`]
-       pub balance_msat: u64,
-       /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
-       /// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
-       /// available for inclusion in new outbound HTLCs). This further does not include any pending
-       /// outgoing HTLCs which are awaiting some other resolution to be sent.
-       ///
-       /// See also [`ChannelDetails::balance_msat`]
-       ///
-       /// This value is not exact. Due to various in-flight changes, feerate changes, and our
-       /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we
-       /// should be able to spend nearly this amount.
-       pub outbound_capacity_msat: u64,
-       /// The available outbound capacity for sending a single HTLC to the remote peer. This is
-       /// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by
-       /// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us
-       /// to use a limit as close as possible to the HTLC limit we can currently send.
-       ///
-       /// See also [`ChannelDetails::next_outbound_htlc_minimum_msat`],
-       /// [`ChannelDetails::balance_msat`], and [`ChannelDetails::outbound_capacity_msat`].
-       pub next_outbound_htlc_limit_msat: u64,
-       /// The minimum value for sending a single HTLC to the remote peer. This is the equivalent of
-       /// [`ChannelDetails::next_outbound_htlc_limit_msat`] but represents a lower-bound, rather than
-       /// an upper-bound. This is intended for use when routing, allowing us to ensure we pick a
-       /// route which is valid.
-       pub next_outbound_htlc_minimum_msat: u64,
-       /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
-       /// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
-       /// available for inclusion in new inbound HTLCs).
-       /// Note that there are some corner cases not fully handled here, so the actual available
-       /// inbound capacity may be slightly higher than this.
-       ///
-       /// This value is not exact. Due to various in-flight changes, feerate changes, and our
-       /// counterparty's conflict-avoidance policy, exactly this amount is not likely to be spendable.
-       /// However, our counterparty should be able to spend nearly this amount.
-       pub inbound_capacity_msat: u64,
-       /// The number of required confirmations on the funding transaction before the funding will be
-       /// considered "locked". This number is selected by the channel fundee (i.e. us if
-       /// [`is_outbound`] is *not* set), and can be selected for inbound channels with
-       /// [`ChannelHandshakeConfig::minimum_depth`] or limited for outbound channels with
-       /// [`ChannelHandshakeLimits::max_minimum_depth`].
-       ///
-       /// This value will be `None` for outbound channels until the counterparty accepts the channel.
-       ///
-       /// [`is_outbound`]: ChannelDetails::is_outbound
-       /// [`ChannelHandshakeConfig::minimum_depth`]: crate::util::config::ChannelHandshakeConfig::minimum_depth
-       /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth
-       pub confirmations_required: Option<u32>,
-       /// The current number of confirmations on the funding transaction.
-       ///
-       /// This value will be `None` for objects serialized with LDK versions prior to 0.0.113.
-       pub confirmations: Option<u32>,
-       /// The number of blocks (after our commitment transaction confirms) that we will need to wait
-       /// until we can claim our funds after we force-close the channel. During this time our
-       /// counterparty is allowed to punish us if we broadcasted a stale state. If our counterparty
-       /// force-closes the channel and broadcasts a commitment transaction we do not have to wait any
-       /// time to claim our non-HTLC-encumbered funds.
-       ///
-       /// This value will be `None` for outbound channels until the counterparty accepts the channel.
-       pub force_close_spend_delay: Option<u16>,
-       /// True if the channel was initiated (and thus funded) by us.
-       pub is_outbound: bool,
-       /// True if the channel is confirmed, channel_ready messages have been exchanged, and the
-       /// channel is not currently being shut down. `channel_ready` message exchange implies the
-       /// required confirmation count has been reached (and we were connected to the peer at some
-       /// point after the funding transaction received enough confirmations). The required
-       /// confirmation count is provided in [`confirmations_required`].
-       ///
-       /// [`confirmations_required`]: ChannelDetails::confirmations_required
-       pub is_channel_ready: bool,
-       /// The stage of the channel's shutdown.
-       /// `None` for `ChannelDetails` serialized on LDK versions prior to 0.0.116.
-       pub channel_shutdown_state: Option<ChannelShutdownState>,
-       /// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b)
-       /// the peer is connected, and (c) the channel is not currently negotiating a shutdown.
-       ///
-       /// This is a strict superset of `is_channel_ready`.
-       pub is_usable: bool,
-       /// True if this channel is (or will be) publicly-announced.
-       pub is_public: bool,
-       /// The smallest value HTLC (in msat) we will accept, for this channel. This field
-       /// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107
-       pub inbound_htlc_minimum_msat: Option<u64>,
-       /// The largest value HTLC (in msat) we currently will accept, for this channel.
-       pub inbound_htlc_maximum_msat: Option<u64>,
-       /// Set of configurable parameters that affect channel operation.
-       ///
-       /// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109.
-       pub config: Option<ChannelConfig>,
-       /// Pending inbound HTLCs.
-       ///
-       /// This field is empty for objects serialized with LDK versions prior to 0.0.122.
-       pub pending_inbound_htlcs: Vec<InboundHTLCDetails>,
-       /// Pending outbound HTLCs.
-       ///
-       /// This field is empty for objects serialized with LDK versions prior to 0.0.122.
-       pub pending_outbound_htlcs: Vec<OutboundHTLCDetails>,
-}
-
-impl ChannelDetails {
-       /// Gets the current SCID which should be used to identify this channel for inbound payments.
-       /// This should be used for providing invoice hints or in any other context where our
-       /// counterparty will forward a payment to us.
-       ///
-       /// This is either the [`ChannelDetails::inbound_scid_alias`], if set, or the
-       /// [`ChannelDetails::short_channel_id`]. See those for more information.
-       pub fn get_inbound_payment_scid(&self) -> Option<u64> {
-               self.inbound_scid_alias.or(self.short_channel_id)
-       }
-
-       /// Gets the current SCID which should be used to identify this channel for outbound payments.
-       /// This should be used in [`Route`]s to describe the first hop or in other contexts where
-       /// we're sending or forwarding a payment outbound over this channel.
-       ///
-       /// This is either the [`ChannelDetails::short_channel_id`], if set, or the
-       /// [`ChannelDetails::outbound_scid_alias`]. See those for more information.
-       pub fn get_outbound_payment_scid(&self) -> Option<u64> {
-               self.short_channel_id.or(self.outbound_scid_alias)
-       }
-
-       fn from_channel_context<SP: Deref, F: Deref>(
-               context: &ChannelContext<SP>, best_block_height: u32, latest_features: InitFeatures,
-               fee_estimator: &LowerBoundedFeeEstimator<F>
-       ) -> Self
-       where
-               SP::Target: SignerProvider,
-               F::Target: FeeEstimator
-       {
-               let balance = context.get_available_balances(fee_estimator);
-               let (to_remote_reserve_satoshis, to_self_reserve_satoshis) =
-                       context.get_holder_counterparty_selected_channel_reserve_satoshis();
-               ChannelDetails {
-                       channel_id: context.channel_id(),
-                       counterparty: ChannelCounterparty {
-                               node_id: context.get_counterparty_node_id(),
-                               features: latest_features,
-                               unspendable_punishment_reserve: to_remote_reserve_satoshis,
-                               forwarding_info: context.counterparty_forwarding_info(),
-                               // Ensures that we have actually received the `htlc_minimum_msat` value
-                               // from the counterparty through the `OpenChannel` or `AcceptChannel`
-                               // message (as they are always the first message from the counterparty).
-                               // Else `Channel::get_counterparty_htlc_minimum_msat` could return the
-                               // default `0` value set by `Channel::new_outbound`.
-                               outbound_htlc_minimum_msat: if context.have_received_message() {
-                                       Some(context.get_counterparty_htlc_minimum_msat()) } else { None },
-                               outbound_htlc_maximum_msat: context.get_counterparty_htlc_maximum_msat(),
-                       },
-                       funding_txo: context.get_funding_txo(),
-                       // Note that accept_channel (or open_channel) is always the first message, so
-                       // `have_received_message` indicates that type negotiation has completed.
-                       channel_type: if context.have_received_message() { Some(context.get_channel_type().clone()) } else { None },
-                       short_channel_id: context.get_short_channel_id(),
-                       outbound_scid_alias: if context.is_usable() { Some(context.outbound_scid_alias()) } else { None },
-                       inbound_scid_alias: context.latest_inbound_scid_alias(),
-                       channel_value_satoshis: context.get_value_satoshis(),
-                       feerate_sat_per_1000_weight: Some(context.get_feerate_sat_per_1000_weight()),
-                       unspendable_punishment_reserve: to_self_reserve_satoshis,
-                       balance_msat: balance.balance_msat,
-                       inbound_capacity_msat: balance.inbound_capacity_msat,
-                       outbound_capacity_msat: balance.outbound_capacity_msat,
-                       next_outbound_htlc_limit_msat: balance.next_outbound_htlc_limit_msat,
-                       next_outbound_htlc_minimum_msat: balance.next_outbound_htlc_minimum_msat,
-                       user_channel_id: context.get_user_id(),
-                       confirmations_required: context.minimum_depth(),
-                       confirmations: Some(context.get_funding_tx_confirmations(best_block_height)),
-                       force_close_spend_delay: context.get_counterparty_selected_contest_delay(),
-                       is_outbound: context.is_outbound(),
-                       is_channel_ready: context.is_usable(),
-                       is_usable: context.is_live(),
-                       is_public: context.should_announce(),
-                       inbound_htlc_minimum_msat: Some(context.get_holder_htlc_minimum_msat()),
-                       inbound_htlc_maximum_msat: context.get_holder_htlc_maximum_msat(),
-                       config: Some(context.config()),
-                       channel_shutdown_state: Some(context.shutdown_state()),
-                       pending_inbound_htlcs: context.get_pending_inbound_htlc_details(),
-                       pending_outbound_htlcs: context.get_pending_outbound_htlc_details(),
-               }
-       }
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-/// Further information on the details of the channel shutdown.
-/// Upon channels being forced closed (i.e. commitment transaction confirmation detected
-/// by `ChainMonitor`), ChannelShutdownState will be set to `ShutdownComplete` or
-/// the channel will be removed shortly.
-/// Also note, that in normal operation, peers could disconnect at any of these states
-/// and require peer re-connection before making progress onto other states
-pub enum ChannelShutdownState {
-       /// Channel has not sent or received a shutdown message.
-       NotShuttingDown,
-       /// Local node has sent a shutdown message for this channel.
-       ShutdownInitiated,
-       /// Shutdown message exchanges have concluded and the channels are in the midst of
-       /// resolving all existing open HTLCs before closing can continue.
-       ResolvingHTLCs,
-       /// All HTLCs have been resolved, nodes are currently negotiating channel close onchain fee rates.
-       NegotiatingClosingFee,
-       /// We've successfully negotiated a closing_signed dance. At this point `ChannelManager` is about
-       /// to drop the channel.
-       ShutdownComplete,
-}
-
 /// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
 /// These include payments that have yet to find a successful path, or have unresolved HTLCs.
 #[derive(Debug, PartialEq)]
@@ -3700,8 +3369,11 @@ where
                Ok(counterparty_node_id)
        }
 
-       fn force_close_sending_error(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, broadcast: bool) -> Result<(), APIError> {
+       fn force_close_sending_error(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, broadcast: bool, error_message: String)
+       -> Result<(), APIError> {
                let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
+               log_debug!(self.logger,
+                       "Force-closing channel, The error message sent to the peer : {}", error_message);
                match self.force_close_channel_with_peer(channel_id, counterparty_node_id, None, broadcast) {
                        Ok(counterparty_node_id) => {
                                let per_peer_state = self.per_peer_state.read().unwrap();
@@ -3710,8 +3382,8 @@ where
                                        peer_state.pending_msg_events.push(
                                                events::MessageSendEvent::HandleError {
                                                        node_id: counterparty_node_id,
-                                                       action: msgs::ErrorAction::DisconnectPeer {
-                                                               msg: Some(msgs::ErrorMessage { channel_id: *channel_id, data: "Channel force-closed".to_owned() })
+                                                       action: msgs::ErrorAction::SendErrorMessage {
+                                                               msg: msgs::ErrorMessage { channel_id: *channel_id, data: error_message }
                                                        },
                                                }
                                        );
@@ -3722,39 +3394,53 @@ where
                }
        }
 
-       /// Force closes a channel, immediately broadcasting the latest local transaction(s) and
-       /// rejecting new HTLCs on the given channel. Fails if `channel_id` is unknown to
-       /// the manager, or if the `counterparty_node_id` isn't the counterparty of the corresponding
-       /// channel.
-       pub fn force_close_broadcasting_latest_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
+       /// Force closes a channel, immediately broadcasting the latest local transaction(s),
+       /// rejecting new HTLCs.
+       ///
+       /// The provided `error_message` is sent to connected peers for closing
+       /// channels and should be a human-readable description of what went wrong.
+       ///
+       /// Fails if `channel_id` is unknown to the manager, or if the `counterparty_node_id`
+       /// isn't the counterparty of the corresponding channel.
+       pub fn force_close_broadcasting_latest_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, error_message: String)
        -> Result<(), APIError> {
-               self.force_close_sending_error(channel_id, counterparty_node_id, true)
+               self.force_close_sending_error(channel_id, counterparty_node_id, true, error_message)
        }
 
        /// Force closes a channel, rejecting new HTLCs on the given channel but skips broadcasting
-       /// the latest local transaction(s). Fails if `channel_id` is unknown to the manager, or if the
-       /// `counterparty_node_id` isn't the counterparty of the corresponding channel.
+       /// the latest local transaction(s).
        ///
+       /// The provided `error_message` is sent to connected peers for closing channels and should
+       /// be a human-readable description of what went wrong.
+       ///
+       /// Fails if `channel_id` is unknown to the manager, or if the
+       /// `counterparty_node_id` isn't the counterparty of the corresponding channel.
        /// You can always broadcast the latest local transaction(s) via
        /// [`ChannelMonitor::broadcast_latest_holder_commitment_txn`].
-       pub fn force_close_without_broadcasting_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
+       pub fn force_close_without_broadcasting_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, error_message: String)
        -> Result<(), APIError> {
-               self.force_close_sending_error(channel_id, counterparty_node_id, false)
+               self.force_close_sending_error(channel_id, counterparty_node_id, false, error_message)
        }
 
        /// Force close all channels, immediately broadcasting the latest local commitment transaction
        /// for each to the chain and rejecting new HTLCs on each.
-       pub fn force_close_all_channels_broadcasting_latest_txn(&self) {
+       ///
+       /// The provided `error_message` is sent to connected peers for closing channels and should
+       /// be a human-readable description of what went wrong.
+       pub fn force_close_all_channels_broadcasting_latest_txn(&self, error_message: String) {
                for chan in self.list_channels() {
-                       let _ = self.force_close_broadcasting_latest_txn(&chan.channel_id, &chan.counterparty.node_id);
+                       let _ = self.force_close_broadcasting_latest_txn(&chan.channel_id, &chan.counterparty.node_id, error_message.clone());
                }
        }
 
        /// Force close all channels rejecting new HTLCs on each but without broadcasting the latest
        /// local transaction(s).
-       pub fn force_close_all_channels_without_broadcasting_txn(&self) {
+       ///
+       /// The provided `error_message` is sent to connected peers for closing channels and
+       /// should be a human-readable description of what went wrong.
+       pub fn force_close_all_channels_without_broadcasting_txn(&self, error_message: String) {
                for chan in self.list_channels() {
-                       let _ = self.force_close_without_broadcasting_txn(&chan.channel_id, &chan.counterparty.node_id);
+                       let _ = self.force_close_without_broadcasting_txn(&chan.channel_id, &chan.counterparty.node_id, error_message.clone());
                }
        }
 
@@ -12969,8 +12655,8 @@ mod tests {
 
                nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
                nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
-
-               nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
+               let error_message = "Channel force-closed";
+               nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id(), error_message.to_string()).unwrap();
                check_closed_broadcast!(nodes[0], true);
                check_added_monitors!(nodes[0], 1);
                check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
@@ -13187,6 +12873,7 @@ mod tests {
                let channel_id = ChannelId::from_bytes([4; 32]);
                let unkown_public_key = PublicKey::from_secret_key(&Secp256k1::signing_only(), &SecretKey::from_slice(&[42; 32]).unwrap());
                let intercept_id = InterceptId([0; 32]);
+               let error_message = "Channel force-closed";
 
                // Test the API functions.
                check_not_connected_to_peer_error(nodes[0].node.create_channel(unkown_public_key, 1_000_000, 500_000_000, 42, None, None), unkown_public_key);
@@ -13195,9 +12882,9 @@ mod tests {
 
                check_unkown_peer_error(nodes[0].node.close_channel(&channel_id, &unkown_public_key), unkown_public_key);
 
-               check_unkown_peer_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &unkown_public_key), unkown_public_key);
+               check_unkown_peer_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &unkown_public_key, error_message.to_string()), unkown_public_key);
 
-               check_unkown_peer_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &unkown_public_key), unkown_public_key);
+               check_unkown_peer_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &unkown_public_key, error_message.to_string()), unkown_public_key);
 
                check_unkown_peer_error(nodes[0].node.forward_intercepted_htlc(intercept_id, &channel_id, unkown_public_key, 1_000_000), unkown_public_key);
 
@@ -13219,15 +12906,16 @@ mod tests {
 
                // Dummy values
                let channel_id = ChannelId::from_bytes([4; 32]);
+               let error_message = "Channel force-closed";
 
                // Test the API functions.
                check_api_misuse_error(nodes[0].node.accept_inbound_channel(&channel_id, &counterparty_node_id, 42));
 
                check_channel_unavailable_error(nodes[0].node.close_channel(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
 
-               check_channel_unavailable_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
+               check_channel_unavailable_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &counterparty_node_id, error_message.to_string()), channel_id, counterparty_node_id);
 
-               check_channel_unavailable_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
+               check_channel_unavailable_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &counterparty_node_id, error_message.to_string()), channel_id, counterparty_node_id);
 
                check_channel_unavailable_error(nodes[0].node.forward_intercepted_htlc(InterceptId([0; 32]), &channel_id, counterparty_node_id, 1_000_000), channel_id, counterparty_node_id);
 
@@ -13581,6 +13269,7 @@ mod tests {
                anchors_config.manually_accept_inbound_channels = true;
                let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config.clone()), Some(anchors_config.clone())]);
                let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
+               let error_message = "Channel force-closed";
 
                nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 0, None, None).unwrap();
                let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
@@ -13590,7 +13279,7 @@ mod tests {
                let events = nodes[1].node.get_and_clear_pending_events();
                match events[0] {
                        Event::OpenChannelRequest { temporary_channel_id, .. } => {
-                               nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
+                               nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id(), error_message.to_string()).unwrap();
                        }
                        _ => panic!("Unexpected event"),
                }
@@ -13698,12 +13387,13 @@ mod tests {
                let user_config = test_default_channel_config();
                let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
                let nodes = create_network(2, &node_cfg, &node_chanmgr);
+               let error_message = "Channel force-closed";
 
                // Open a channel, immediately disconnect each other, and broadcast Alice's latest state.
                let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
                nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
                nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
-               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_closed_broadcast(&nodes[0], 1, true);
                check_added_monitors(&nodes[0], 1);
                check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);