Handle sign_counterparty_commitment failing during inb funding
[rust-lightning] / lightning / src / ln / channelmanager.rs
index e71d7124aaafcfb16492006d7ad19bfc8ee90f58..56820a6c480f93c1acb1aaebf3306bd156ff0889 100644 (file)
@@ -63,7 +63,7 @@ use crate::offers::merkle::SignError;
 use crate::offers::offer::{DerivedMetadata, Offer, OfferBuilder};
 use crate::offers::parse::Bolt12SemanticError;
 use crate::offers::refund::{Refund, RefundBuilder};
-use crate::onion_message::{Destination, OffersMessage, OffersMessageHandler, PendingOnionMessage};
+use crate::onion_message::{Destination, OffersMessage, OffersMessageHandler, PendingOnionMessage, new_pending_onion_message};
 use crate::sign::{EntropySource, KeysManager, NodeSigner, Recipient, SignerProvider, WriteableEcdsaChannelSigner};
 use crate::util::config::{UserConfig, ChannelConfig, ChannelConfigUpdate};
 use crate::util::wakers::{Future, Notifier};
@@ -827,7 +827,8 @@ struct PendingInboundPayment {
 /// or, respectively, [`Router`] for its router, but this type alias chooses the concrete types
 /// of [`KeysManager`] and [`DefaultRouter`].
 ///
-/// This is not exported to bindings users as Arcs don't make sense in bindings
+/// This is not exported to bindings users as type aliases aren't supported in most languages.
+#[cfg(not(c_bindings))]
 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<
        Arc<M>,
        Arc<T>,
@@ -855,7 +856,8 @@ pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<
 /// or, respectively, [`Router`]  for its router, but this type alias chooses the concrete types
 /// of [`KeysManager`] and [`DefaultRouter`].
 ///
-/// This is not exported to bindings users as Arcs don't make sense in bindings
+/// This is not exported to bindings users as type aliases aren't supported in most languages.
+#[cfg(not(c_bindings))]
 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L> =
        ChannelManager<
                &'a M,
@@ -2681,11 +2683,11 @@ where
        /// will be accepted on the given channel, and after additional timeout/the closing of all
        /// pending HTLCs, the channel will be closed on chain.
        ///
-       ///  * If we are the channel initiator, we will pay between our [`Background`] and
-       ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
-       ///    estimate.
+       ///  * If we are the channel initiator, we will pay between our [`ChannelCloseMinimum`] and
+       ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`]
+       ///    fee estimate.
        ///  * If our counterparty is the channel initiator, we will require a channel closing
-       ///    transaction feerate of at least our [`Background`] feerate or the feerate which
+       ///    transaction feerate of at least our [`ChannelCloseMinimum`] feerate or the feerate which
        ///    would appear on a force-closure transaction, whichever is lower. We will allow our
        ///    counterparty to pay as much fee as they'd like, however.
        ///
@@ -2697,8 +2699,8 @@ where
        /// channel.
        ///
        /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
-       /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
-       /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
+       /// [`ChannelCloseMinimum`]: crate::chain::chaininterface::ConfirmationTarget::ChannelCloseMinimum
+       /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
        /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
        pub fn close_channel(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey) -> Result<(), APIError> {
                self.close_channel_internal(channel_id, counterparty_node_id, None, None)
@@ -2712,8 +2714,8 @@ where
        /// the channel being closed or not:
        ///  * If we are the channel initiator, we will pay at least this feerate on the closing
        ///    transaction. The upper-bound is set by
-       ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
-       ///    estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
+       ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`]
+       ///    fee estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
        ///  * If our counterparty is the channel initiator, we will refuse to accept a channel closure
        ///    transaction feerate below `target_feerate_sat_per_1000_weight` (or the feerate which
        ///    will appear on a force-closure transaction, whichever is lower).
@@ -2731,8 +2733,7 @@ where
        /// channel.
        ///
        /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
-       /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
-       /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
+       /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
        /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
        pub fn close_channel_with_feerate_and_script(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, target_feerate_sats_per_1000_weight: Option<u32>, shutdown_script: Option<ShutdownScript>) -> Result<(), APIError> {
                self.close_channel_internal(channel_id, counterparty_node_id, target_feerate_sats_per_1000_weight, shutdown_script)
@@ -3802,7 +3803,7 @@ where
 
                let mut peer_state_lock = peer_state_mutex.lock().unwrap();
                let peer_state = &mut *peer_state_lock;
-               let (chan, msg) = match peer_state.channel_by_id.remove(temporary_channel_id) {
+               let (chan, msg_opt) = match peer_state.channel_by_id.remove(temporary_channel_id) {
                        Some(ChannelPhase::UnfundedOutboundV1(chan)) => {
                                let funding_txo = find_funding_output(&chan, &funding_transaction)?;
 
@@ -3841,10 +3842,12 @@ where
                                }),
                };
 
-               peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
-                       node_id: chan.context.get_counterparty_node_id(),
-                       msg,
-               });
+               if let Some(msg) = msg_opt {
+                       peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
+                               node_id: chan.context.get_counterparty_node_id(),
+                               msg,
+                       });
+               }
                match peer_state.channel_by_id.entry(chan.context.channel_id()) {
                        hash_map::Entry::Occupied(_) => {
                                panic!("Generated duplicate funding txid?");
@@ -4817,8 +4820,8 @@ where
                PersistenceNotifierGuard::optionally_notify(self, || {
                        let mut should_persist = NotifyOption::SkipPersistNoEvents;
 
-                       let normal_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
-                       let min_mempool_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::MempoolMinimum);
+                       let non_anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
+                       let anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee);
 
                        let per_peer_state = self.per_peer_state.read().unwrap();
                        for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
@@ -4828,9 +4831,9 @@ where
                                        |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
                                ) {
                                        let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
-                                               min_mempool_feerate
+                                               anchor_feerate
                                        } else {
-                                               normal_feerate
+                                               non_anchor_feerate
                                        };
                                        let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
                                        if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
@@ -4866,8 +4869,8 @@ where
                PersistenceNotifierGuard::optionally_notify(self, || {
                        let mut should_persist = NotifyOption::SkipPersistNoEvents;
 
-                       let normal_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
-                       let min_mempool_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::MempoolMinimum);
+                       let non_anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
+                       let anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee);
 
                        let mut handle_errors: Vec<(Result<(), _>, _)> = Vec::new();
                        let mut timed_out_mpp_htlcs = Vec::new();
@@ -4914,9 +4917,9 @@ where
                                                match phase {
                                                        ChannelPhase::Funded(chan) => {
                                                                let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
-                                                                       min_mempool_feerate
+                                                                       anchor_feerate
                                                                } else {
-                                                                       normal_feerate
+                                                                       non_anchor_feerate
                                                                };
                                                                let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
                                                                if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
@@ -6229,7 +6232,7 @@ where
 
                let mut peer_state_lock = peer_state_mutex.lock().unwrap();
                let peer_state = &mut *peer_state_lock;
-               let (chan, funding_msg, monitor) =
+               let (chan, funding_msg_opt, monitor) =
                        match peer_state.channel_by_id.remove(&msg.temporary_channel_id) {
                                Some(ChannelPhase::UnfundedInboundV1(inbound_chan)) => {
                                        match inbound_chan.funding_created(msg, best_block, &self.signer_provider, &self.logger) {
@@ -6252,9 +6255,12 @@ where
                                None => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.temporary_channel_id))
                        };
 
-               match peer_state.channel_by_id.entry(funding_msg.channel_id) {
+               match peer_state.channel_by_id.entry(chan.context.channel_id()) {
                        hash_map::Entry::Occupied(_) => {
-                               Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id".to_owned(), funding_msg.channel_id))
+                               Err(MsgHandleErrInternal::send_err_msg_no_close(
+                                       "Already had channel with the new channel_id".to_owned(),
+                                       chan.context.channel_id()
+                               ))
                        },
                        hash_map::Entry::Vacant(e) => {
                                let mut id_to_peer_lock = self.id_to_peer.lock().unwrap();
@@ -6262,7 +6268,7 @@ where
                                        hash_map::Entry::Occupied(_) => {
                                                return Err(MsgHandleErrInternal::send_err_msg_no_close(
                                                        "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
-                                                       funding_msg.channel_id))
+                                                       chan.context.channel_id()))
                                        },
                                        hash_map::Entry::Vacant(i_e) => {
                                                let monitor_res = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor);
@@ -6274,10 +6280,12 @@ where
                                                        // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
                                                        // accepted payment from yet. We do, however, need to wait to send our channel_ready
                                                        // until we have persisted our monitor.
-                                                       peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
-                                                               node_id: counterparty_node_id.clone(),
-                                                               msg: funding_msg,
-                                                       });
+                                                       if let Some(msg) = funding_msg_opt {
+                                                               peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
+                                                                       node_id: counterparty_node_id.clone(),
+                                                                       msg,
+                                                               });
+                                                       }
 
                                                        if let ChannelPhase::Funded(chan) = e.insert(ChannelPhase::Funded(chan)) {
                                                                handle_new_monitor_update!(self, persist_state, peer_state_lock, peer_state,
@@ -6288,9 +6296,13 @@ where
                                                        Ok(())
                                                } else {
                                                        log_error!(self.logger, "Persisting initial ChannelMonitor failed, implying the funding outpoint was duplicated");
+                                                       let channel_id = match funding_msg_opt {
+                                                               Some(msg) => msg.channel_id,
+                                                               None => chan.context.channel_id(),
+                                                       };
                                                        return Err(MsgHandleErrInternal::send_err_msg_no_close(
                                                                "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
-                                                               funding_msg.channel_id));
+                                                               channel_id));
                                                }
                                        }
                                }
@@ -7330,6 +7342,8 @@ where
        /// Requires a direct connection to the introduction node in the responding [`InvoiceRequest`]'s
        /// reply path.
        ///
+       /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
+       ///
        /// [`Offer`]: crate::offers::offer::Offer
        /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
        pub fn create_offer_builder(
@@ -7363,6 +7377,9 @@ where
        /// invoice. If abandoned, or an invoice isn't received before expiration, the payment will fail
        /// with an [`Event::InvoiceRequestFailed`].
        ///
+       /// If `max_total_routing_fee_msat` is not specified, The default from
+       /// [`RouteParameters::from_payment_params_and_value`] is applied.
+       ///
        /// # Privacy
        ///
        /// Uses a one-hop [`BlindedPath`] for the refund with [`ChannelManager::get_our_node_id`] as
@@ -7380,6 +7397,8 @@ where
        /// Errors if a duplicate `payment_id` is provided given the caveats in the aforementioned link
        /// or if `amount_msats` is invalid.
        ///
+       /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
+       ///
        /// [`Refund`]: crate::offers::refund::Refund
        /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
        /// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths
@@ -7422,6 +7441,9 @@ where
        /// - `amount_msats` if overpaying what is required for the given `quantity` is desired, and
        /// - `payer_note` for [`InvoiceRequest::payer_note`].
        ///
+       /// If `max_total_routing_fee_msat` is not specified, The default from
+       /// [`RouteParameters::from_payment_params_and_value`] is applied.
+       ///
        /// # Payment
        ///
        /// The provided `payment_id` is used to ensure that only one invoice is paid for the request
@@ -7494,11 +7516,11 @@ where
 
                let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
                if offer.paths().is_empty() {
-                       let message = PendingOnionMessage {
-                               contents: OffersMessage::InvoiceRequest(invoice_request),
-                               destination: Destination::Node(offer.signing_pubkey()),
-                               reply_path: Some(reply_path),
-                       };
+                       let message = new_pending_onion_message(
+                               OffersMessage::InvoiceRequest(invoice_request),
+                               Destination::Node(offer.signing_pubkey()),
+                               Some(reply_path),
+                       );
                        pending_offers_messages.push(message);
                } else {
                        // Send as many invoice requests as there are paths in the offer (with an upper bound).
@@ -7506,11 +7528,11 @@ where
                        // one invoice for a given payment id will be paid, even if more than one is received.
                        const REQUEST_LIMIT: usize = 10;
                        for path in offer.paths().into_iter().take(REQUEST_LIMIT) {
-                               let message = PendingOnionMessage {
-                                       contents: OffersMessage::InvoiceRequest(invoice_request.clone()),
-                                       destination: Destination::BlindedPath(path.clone()),
-                                       reply_path: Some(reply_path.clone()),
-                               };
+                               let message = new_pending_onion_message(
+                                       OffersMessage::InvoiceRequest(invoice_request.clone()),
+                                       Destination::BlindedPath(path.clone()),
+                                       Some(reply_path.clone()),
+                               );
                                pending_offers_messages.push(message);
                        }
                }
@@ -7528,7 +7550,9 @@ where
        /// # Limitations
        ///
        /// Requires a direct connection to an introduction node in [`Refund::paths`] or to
-       /// [`Refund::payer_id`], if empty.
+       /// [`Refund::payer_id`], if empty. This request is best effort; an invoice will be sent to each
+       /// node meeting the aforementioned criteria, but there's no guarantee that they will be
+       /// received and no retries will be made.
        ///
        /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
        pub fn request_refund_payment(&self, refund: &Refund) -> Result<(), Bolt12SemanticError> {
@@ -7561,19 +7585,19 @@ where
 
                                let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
                                if refund.paths().is_empty() {
-                                       let message = PendingOnionMessage {
-                                               contents: OffersMessage::Invoice(invoice),
-                                               destination: Destination::Node(refund.payer_id()),
-                                               reply_path: Some(reply_path),
-                                       };
+                                       let message = new_pending_onion_message(
+                                               OffersMessage::Invoice(invoice),
+                                               Destination::Node(refund.payer_id()),
+                                               Some(reply_path),
+                                       );
                                        pending_offers_messages.push(message);
                                } else {
                                        for path in refund.paths() {
-                                               let message = PendingOnionMessage {
-                                                       contents: OffersMessage::Invoice(invoice.clone()),
-                                                       destination: Destination::BlindedPath(path.clone()),
-                                                       reply_path: Some(reply_path.clone()),
-                                               };
+                                               let message = new_pending_onion_message(
+                                                       OffersMessage::Invoice(invoice.clone()),
+                                                       Destination::BlindedPath(path.clone()),
+                                                       Some(reply_path.clone()),
+                                               );
                                                pending_offers_messages.push(message);
                                        }
                                }
@@ -8960,10 +8984,10 @@ where
                                                                match invoice.sign(|invoice| self.node_signer.sign_bolt12_invoice(invoice)) {
                                                                        Ok(invoice) => Ok(OffersMessage::Invoice(invoice)),
                                                                        Err(SignError::Signing(())) => Err(OffersMessage::InvoiceError(
-                                                                                       InvoiceError::from_str("Failed signing invoice")
+                                                                                       InvoiceError::from_string("Failed signing invoice".to_string())
                                                                        )),
                                                                        Err(SignError::Verification(_)) => Err(OffersMessage::InvoiceError(
-                                                                                       InvoiceError::from_str("Failed invoice signature verification")
+                                                                                       InvoiceError::from_string("Failed invoice signature verification".to_string())
                                                                        )),
                                                                });
                                                match response {
@@ -8979,7 +9003,7 @@ where
                        OffersMessage::Invoice(invoice) => {
                                match invoice.verify(expanded_key, secp_ctx) {
                                        Err(()) => {
-                                               Some(OffersMessage::InvoiceError(InvoiceError::from_str("Unrecognized invoice")))
+                                               Some(OffersMessage::InvoiceError(InvoiceError::from_string("Unrecognized invoice".to_owned())))
                                        },
                                        Ok(_) if invoice.invoice_features().requires_unknown_bits_from(&self.bolt12_invoice_features()) => {
                                                Some(OffersMessage::InvoiceError(Bolt12SemanticError::UnknownRequiredFeatures.into()))
@@ -8987,7 +9011,7 @@ where
                                        Ok(payment_id) => {
                                                if let Err(e) = self.send_payment_for_bolt12_invoice(&invoice, payment_id) {
                                                        log_trace!(self.logger, "Failed paying invoice: {:?}", e);
-                                                       Some(OffersMessage::InvoiceError(InvoiceError::from_str(&format!("{:?}", e))))
+                                                       Some(OffersMessage::InvoiceError(InvoiceError::from_string(format!("{:?}", e))))
                                                } else {
                                                        None
                                                }