Move `[u8; 32]` wrapper types to a common module
[rust-lightning] / lightning / src / ln / channelmanager.rs
index 130eab49384ce884c99cc637422c61729dd1617f..7bc62463b36feb7a271294f309edf34a9ec8367e 100644 (file)
@@ -42,7 +42,8 @@ use crate::events;
 use crate::events::{Event, EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination, PaymentFailureReason};
 // Since this struct is returned in `list_channels` methods, expose it here in case users want to
 // construct one themselves.
-use crate::ln::{inbound_payment, ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
+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::features::{Bolt12InvoiceFeatures, ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
@@ -357,11 +358,6 @@ enum OnionPayload {
                /// This is only here for backwards-compatibility in serialization, in the future it can be
                /// removed, breaking clients running 0.0.106 and earlier.
                _legacy_hop_data: Option<msgs::FinalOnionHopData>,
-               /// The context of the payment included by the recipient in a blinded path, or `None` if a
-               /// blinded path was not used.
-               ///
-               /// Used in part to determine the [`events::PaymentPurpose`].
-               payment_context: Option<PaymentContext>,
        },
        /// Contains the payer-provided preimage.
        Spontaneous(PaymentPreimage),
@@ -1392,7 +1388,7 @@ where
 ///
 /// ```
 /// # use bitcoin::secp256k1::PublicKey;
-/// # use lightning::ln::ChannelId;
+/// # use lightning::ln::types::ChannelId;
 /// # use lightning::ln::channelmanager::AChannelManager;
 /// # use lightning::events::{Event, EventsProvider};
 /// #
@@ -1495,7 +1491,7 @@ where
 ///
 /// ```
 /// # use lightning::events::{Event, EventsProvider};
-/// # use lightning::ln::PaymentHash;
+/// # use lightning::ln::types::PaymentHash;
 /// # use lightning::ln::channelmanager::{AChannelManager, PaymentId, RecentPaymentDetails, RecipientOnionFields, Retry};
 /// # use lightning::routing::router::RouteParameters;
 /// #
@@ -5346,7 +5342,7 @@ where
                                                                }
                                                        }) => {
                                                                let blinded_failure = routing.blinded_failure();
-                                                               let (cltv_expiry, onion_payload, payment_data, phantom_shared_secret, mut onion_fields) = match routing {
+                                                               let (cltv_expiry, onion_payload, payment_data, payment_context, phantom_shared_secret, mut onion_fields) = match routing {
                                                                        PendingHTLCRouting::Receive {
                                                                                payment_data, payment_metadata, payment_context,
                                                                                incoming_cltv_expiry, phantom_shared_secret, custom_tlvs,
@@ -5355,8 +5351,8 @@ where
                                                                                let _legacy_hop_data = Some(payment_data.clone());
                                                                                let onion_fields = RecipientOnionFields { payment_secret: Some(payment_data.payment_secret),
                                                                                                payment_metadata, custom_tlvs };
-                                                                               (incoming_cltv_expiry, OnionPayload::Invoice { _legacy_hop_data, payment_context },
-                                                                                       Some(payment_data), phantom_shared_secret, onion_fields)
+                                                                               (incoming_cltv_expiry, OnionPayload::Invoice { _legacy_hop_data },
+                                                                                       Some(payment_data), payment_context, phantom_shared_secret, onion_fields)
                                                                        },
                                                                        PendingHTLCRouting::ReceiveKeysend {
                                                                                payment_data, payment_preimage, payment_metadata,
@@ -5368,7 +5364,7 @@ where
                                                                                        custom_tlvs,
                                                                                };
                                                                                (incoming_cltv_expiry, OnionPayload::Spontaneous(payment_preimage),
-                                                                                       payment_data, None, onion_fields)
+                                                                                       payment_data, None, None, onion_fields)
                                                                        },
                                                                        _ => {
                                                                                panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
@@ -5530,7 +5526,7 @@ where
                                                                match payment_secrets.entry(payment_hash) {
                                                                        hash_map::Entry::Vacant(_) => {
                                                                                match claimable_htlc.onion_payload {
-                                                                                       OnionPayload::Invoice { ref payment_context, .. } => {
+                                                                                       OnionPayload::Invoice { .. } => {
                                                                                                let payment_data = payment_data.unwrap();
                                                                                                let (payment_preimage, min_final_cltv_expiry_delta) = match inbound_payment::verify(payment_hash, &payment_data, self.highest_seen_timestamp.load(Ordering::Acquire) as u64, &self.inbound_payment_key, &self.logger) {
                                                                                                        Ok(result) => result,
@@ -5548,9 +5544,9 @@ where
                                                                                                        }
                                                                                                }
                                                                                                let purpose = events::PaymentPurpose::from_parts(
-                                                                                                       payment_preimage.clone(),
+                                                                                                       payment_preimage,
                                                                                                        payment_data.payment_secret,
-                                                                                                       payment_context.clone(),
+                                                                                                       payment_context,
                                                                                                );
                                                                                                check_total_value!(purpose);
                                                                                        },
@@ -5561,13 +5557,10 @@ where
                                                                                }
                                                                        },
                                                                        hash_map::Entry::Occupied(inbound_payment) => {
-                                                                               let payment_context = match claimable_htlc.onion_payload {
-                                                                                       OnionPayload::Spontaneous(_) => {
-                                                                                               log_trace!(self.logger, "Failing new keysend HTLC with payment_hash {} because we already have an inbound payment with the same payment hash", &payment_hash);
-                                                                                               fail_htlc!(claimable_htlc, payment_hash);
-                                                                                       },
-                                                                                       OnionPayload::Invoice { ref payment_context, .. } => payment_context,
-                                                                               };
+                                                                               if let OnionPayload::Spontaneous(_) = claimable_htlc.onion_payload {
+                                                                                       log_trace!(self.logger, "Failing new keysend HTLC with payment_hash {} because we already have an inbound payment with the same payment hash", &payment_hash);
+                                                                                       fail_htlc!(claimable_htlc, payment_hash);
+                                                                               }
                                                                                let payment_data = payment_data.unwrap();
                                                                                if inbound_payment.get().payment_secret != payment_data.payment_secret {
                                                                                        log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our expected payment secret.", &payment_hash);
@@ -5580,7 +5573,7 @@ where
                                                                                        let purpose = events::PaymentPurpose::from_parts(
                                                                                                inbound_payment.get().payment_preimage,
                                                                                                payment_data.payment_secret,
-                                                                                               payment_context.clone(),
+                                                                                               payment_context,
                                                                                        );
                                                                                        let payment_claimable_generated = check_total_value!(purpose);
                                                                                        if payment_claimable_generated {
@@ -8765,14 +8758,7 @@ where
                        .map_err(|_| Bolt12SemanticError::DuplicatePaymentId)?;
 
                let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
-               if offer.paths().is_empty() {
-                       let message = new_pending_onion_message(
-                               OffersMessage::InvoiceRequest(invoice_request),
-                               Destination::Node(offer.signing_pubkey()),
-                               Some(reply_path),
-                       );
-                       pending_offers_messages.push(message);
-               } else {
+               if !offer.paths().is_empty() {
                        // Send as many invoice requests as there are paths in the offer (with an upper bound).
                        // Using only one path could result in a failure if the path no longer exists. But only
                        // one invoice for a given payment id will be paid, even if more than one is received.
@@ -8785,6 +8771,16 @@ where
                                );
                                pending_offers_messages.push(message);
                        }
+               } else if let Some(signing_pubkey) = offer.signing_pubkey() {
+                       let message = new_pending_onion_message(
+                               OffersMessage::InvoiceRequest(invoice_request),
+                               Destination::Node(signing_pubkey),
+                               Some(reply_path),
+                       );
+                       pending_offers_messages.push(message);
+               } else {
+                       debug_assert!(false);
+                       return Err(Bolt12SemanticError::MissingSigningPubkey);
                }
 
                Ok(())
@@ -10815,11 +10811,11 @@ impl_writeable_tlv_based!(HTLCPreviousHopData, {
 
 impl Writeable for ClaimableHTLC {
        fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
-               let (payment_data, keysend_preimage, payment_context) = match &self.onion_payload {
-                       OnionPayload::Invoice { _legacy_hop_data, payment_context } => {
-                               (_legacy_hop_data.as_ref(), None, payment_context.as_ref())
+               let (payment_data, keysend_preimage) = match &self.onion_payload {
+                       OnionPayload::Invoice { _legacy_hop_data } => {
+                               (_legacy_hop_data.as_ref(), None)
                        },
-                       OnionPayload::Spontaneous(preimage) => (None, Some(preimage), None),
+                       OnionPayload::Spontaneous(preimage) => (None, Some(preimage)),
                };
                write_tlv_fields!(writer, {
                        (0, self.prev_hop, required),
@@ -10831,7 +10827,6 @@ impl Writeable for ClaimableHTLC {
                        (6, self.cltv_expiry, required),
                        (8, keysend_preimage, option),
                        (10, self.counterparty_skimmed_fee_msat, option),
-                       (11, payment_context, option),
                });
                Ok(())
        }
@@ -10849,7 +10844,6 @@ impl Readable for ClaimableHTLC {
                        (6, cltv_expiry, required),
                        (8, keysend_preimage, option),
                        (10, counterparty_skimmed_fee_msat, option),
-                       (11, payment_context, option),
                });
                let payment_data: Option<msgs::FinalOnionHopData> = payment_data_opt;
                let value = value_ser.0.unwrap();
@@ -10870,7 +10864,7 @@ impl Readable for ClaimableHTLC {
                                        }
                                        total_msat = Some(payment_data.as_ref().unwrap().total_msat);
                                }
-                               OnionPayload::Invoice { _legacy_hop_data: payment_data, payment_context }
+                               OnionPayload::Invoice { _legacy_hop_data: payment_data }
                        },
                };
                Ok(Self {
@@ -11561,9 +11555,10 @@ where
                                                }
                                        }
                                } else {
-                                       log_info!(logger, "Successfully loaded channel {} at update_id {} against monitor at update id {}",
+                                       channel.on_startup_drop_completed_blocked_mon_updates_through(&logger, monitor.get_latest_update_id());
+                                       log_info!(logger, "Successfully loaded channel {} at update_id {} against monitor at update id {} with {} blocked updates",
                                                &channel.context.channel_id(), channel.context.get_latest_monitor_update_id(),
-                                               monitor.get_latest_update_id());
+                                               monitor.get_latest_update_id(), channel.blocked_monitor_updates_pending());
                                        if let Some(short_channel_id) = channel.context.get_short_channel_id() {
                                                short_to_chan_info.insert(short_channel_id, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
                                        }
@@ -11888,6 +11883,7 @@ where
                                        log_error!(logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
                                        log_error!(logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
                                        log_error!(logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
+                                       log_error!(logger, " Pending in-flight updates are: {:?}", chan_in_flight_updates);
                                        return Err(DecodeError::InvalidValue);
                                }
                        }
@@ -12106,7 +12102,7 @@ where
                                        return Err(DecodeError::InvalidValue);
                                }
                                let purpose = match &htlcs[0].onion_payload {
-                                       OnionPayload::Invoice { _legacy_hop_data, payment_context: _ } => {
+                                       OnionPayload::Invoice { _legacy_hop_data } => {
                                                if let Some(hop_data) = _legacy_hop_data {
                                                        events::PaymentPurpose::Bolt11InvoicePayment {
                                                                payment_preimage: match pending_inbound_payments.get(&payment_hash) {
@@ -12363,8 +12359,7 @@ mod tests {
        use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
        use core::sync::atomic::Ordering;
        use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
-       use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
-       use crate::ln::ChannelId;
+       use crate::ln::types::{ChannelId, PaymentPreimage, PaymentHash, PaymentSecret};
        use crate::ln::channelmanager::{create_recv_pending_htlc_info, HTLCForwardInfo, inbound_payment, PaymentId, PaymentSendFailure, RecipientOnionFields, InterceptId};
        use crate::ln::functional_test_utils::*;
        use crate::ln::msgs::{self, ErrorAction};