@@ -33,9 +33,9 @@ use bitcoin::secp256k1::Secp256k1;
3333use bitcoin::{secp256k1, Sequence, Weight};
3434
3535use crate::events::FundingInfo;
36- use crate::blinded_path::message::{AsyncPaymentsContext, MessageContext, OffersContext };
36+ use crate::blinded_path::message::{AsyncPaymentsContext, MessageContext, MessageForwardNode };
3737use crate::blinded_path::NodeIdLookUp;
38- use crate::blinded_path::message::{ BlindedMessagePath, MessageForwardNode} ;
38+ use crate::blinded_path::message::BlindedMessagePath;
3939use crate::blinded_path::payment::{BlindedPaymentPath, PaymentConstraints, PaymentContext, UnauthenticatedReceiveTlvs};
4040use crate::chain;
4141use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock};
@@ -47,7 +47,6 @@ use crate::events::{self, Event, EventHandler, EventsProvider, InboundChannelFun
4747// construct one themselves.
4848use crate::ln::inbound_payment;
4949use crate::ln::types::ChannelId;
50- use crate::offers::offer::Offer;
5150use crate::offers::flow::OffersMessageCommons;
5251use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
5352use crate::ln::channel::{self, Channel, ChannelError, ChannelUpdateStatus, FundedChannel, ShutdownResult, UpdateFulfillCommitFetch, OutboundV1Channel, ReconnectionMsg, InboundV1Channel, WithChannelContext};
@@ -68,12 +67,11 @@ use crate::ln::outbound_payment;
6867use crate::ln::outbound_payment::{OutboundPayments, PendingOutboundPayment, RetryableInvoiceRequest, SendAlongPathArgs, StaleExpiration};
6968use crate::offers::invoice::Bolt12Invoice;
7069use crate::offers::invoice::UnsignedBolt12Invoice;
71- use crate::offers::invoice_request::{ InvoiceRequest, InvoiceRequestBuilder} ;
70+ use crate::offers::invoice_request::InvoiceRequest;
7271use crate::offers::nonce::Nonce;
7372use crate::offers::parse::Bolt12SemanticError;
7473use crate::offers::signer;
7574use crate::onion_message::async_payments::{AsyncPaymentsMessage, HeldHtlcAvailable, ReleaseHeldHtlc, AsyncPaymentsMessageHandler};
76- use crate::onion_message::dns_resolution::HumanReadableName;
7775use crate::onion_message::messenger::{DefaultMessageRouter, Destination, MessageRouter, MessageSendInstructions, Responder, ResponseInstruction};
7876use crate::onion_message::offers::OffersMessage;
7977use crate::sign::{EntropySource, NodeSigner, Recipient, SignerProvider};
@@ -461,11 +459,15 @@ impl Ord for ClaimableHTLC {
461459pub trait Verification {
462460 /// Constructs an HMAC to include in [`OffersContext`] for the data along with the given
463461 /// [`Nonce`].
462+ ///
463+ /// [`OffersContext`]: crate::blinded_path::message::OffersContext
464464 fn hmac_for_offer_payment(
465465 &self, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
466466 ) -> Hmac<Sha256>;
467467
468468 /// Authenticates the data using an HMAC and a [`Nonce`] taken from an [`OffersContext`].
469+ ///
470+ /// [`OffersContext`]: crate::blinded_path::message::OffersContext
469471 fn verify_for_offer_payment(
470472 &self, hmac: Hmac<Sha256>, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
471473 ) -> Result<(), ()>;
@@ -474,6 +476,8 @@ pub trait Verification {
474476impl Verification for PaymentHash {
475477 /// Constructs an HMAC to include in [`OffersContext::InboundPayment`] for the payment hash
476478 /// along with the given [`Nonce`].
479+ ///
480+ /// [`OffersContext::InboundPayment`]: crate::blinded_path::message::OffersContext::InboundPayment
477481 fn hmac_for_offer_payment(
478482 &self, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
479483 ) -> Hmac<Sha256> {
@@ -482,6 +486,8 @@ impl Verification for PaymentHash {
482486
483487 /// Authenticates the payment id using an HMAC and a [`Nonce`] taken from an
484488 /// [`OffersContext::InboundPayment`].
489+ ///
490+ /// [`OffersContext::InboundPayment`]: crate::blinded_path::message::OffersContext::InboundPayment
485491 fn verify_for_offer_payment(
486492 &self, hmac: Hmac<Sha256>, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
487493 ) -> Result<(), ()> {
@@ -536,6 +542,8 @@ impl PaymentId {
536542impl Verification for PaymentId {
537543 /// Constructs an HMAC to include in [`OffersContext::OutboundPayment`] for the payment id
538544 /// along with the given [`Nonce`].
545+ ///
546+ /// [`OffersContext::OutboundPayment`]: crate::blinded_path::message::OffersContext::OutboundPayment
539547 fn hmac_for_offer_payment(
540548 &self, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
541549 ) -> Hmac<Sha256> {
@@ -544,6 +552,8 @@ impl Verification for PaymentId {
544552
545553 /// Authenticates the payment id using an HMAC and a [`Nonce`] taken from an
546554 /// [`OffersContext::OutboundPayment`].
555+ ///
556+ /// [`OffersContext::OutboundPayment`]: crate::blinded_path::message::OffersContext::OutboundPayment
547557 fn verify_for_offer_payment(
548558 &self, hmac: Hmac<Sha256>, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
549559 ) -> Result<(), ()> {
@@ -2633,26 +2643,6 @@ const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
26332643/// many peers we reject new (inbound) connections.
26342644const MAX_NO_CHANNEL_PEERS: usize = 250;
26352645
2636- /// The maximum expiration from the current time where an [`Offer`] or [`Refund`] is considered
2637- /// short-lived, while anything with a greater expiration is considered long-lived.
2638- ///
2639- /// Using [`OffersMessageFlow::create_offer_builder`] or [`OffersMessageFlow::create_refund_builder`],
2640- /// will included a [`BlindedMessagePath`] created using:
2641- /// - [`MessageRouter::create_compact_blinded_paths`] when short-lived, and
2642- /// - [`MessageRouter::create_blinded_paths`] when long-lived.
2643- ///
2644- /// [`OffersMessageFlow::create_offer_builder`]: crate::offers::flow::OffersMessageFlow::create_offer_builder
2645- /// [`OffersMessageFlow::create_refund_builder`]: crate::offers::flow::OffersMessageFlow::create_refund_builder
2646- ///
2647- ///
2648- /// Using compact [`BlindedMessagePath`]s may provide better privacy as the [`MessageRouter`] could select
2649- /// more hops. However, since they use short channel ids instead of pubkeys, they are more likely to
2650- /// become invalid over time as channels are closed. Thus, they are only suitable for short-term use.
2651- ///
2652- /// [`Offer`]: crate::offers::offer
2653- /// [`Refund`]: crate::offers::refund
2654- pub const MAX_SHORT_LIVED_RELATIVE_EXPIRY: Duration = Duration::from_secs(60 * 60 * 24);
2655-
26562646/// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
26572647/// These include payments that have yet to find a successful path, or have unresolved HTLCs.
26582648#[derive(Debug, PartialEq)]
@@ -9515,6 +9505,23 @@ where
95159505 self.create_blinded_payment_paths(amount_msats, payment_secret, payment_context, relative_expiry_time)
95169506 }
95179507
9508+ fn get_peer_for_blinded_path(&self) -> Vec<MessageForwardNode> {
9509+ self.per_peer_state.read().unwrap()
9510+ .iter()
9511+ .map(|(node_id, peer_state)| (node_id, peer_state.lock().unwrap()))
9512+ .filter(|(_, peer)| peer.is_connected)
9513+ .filter(|(_, peer)| peer.latest_features.supports_onion_messages())
9514+ .map(|(node_id, peer)| MessageForwardNode {
9515+ node_id: *node_id,
9516+ short_channel_id: peer.channel_by_id
9517+ .iter()
9518+ .filter(|(_, channel)| channel.context().is_usable())
9519+ .min_by_key(|(_, channel)| channel.context().channel_creation_height)
9520+ .and_then(|(_, channel)| channel.context().get_short_channel_id()),
9521+ })
9522+ .collect::<Vec<_>>()
9523+ }
9524+
95189525 fn send_payment_for_verified_bolt12_invoice(&self, invoice: &Bolt12Invoice, payment_id: PaymentId) -> Result<(), Bolt12PaymentError> {
95199526 self.send_payment_for_verified_bolt12_invoice(invoice, payment_id)
95209527 }
@@ -9546,12 +9553,6 @@ where
95469553 self.initiate_async_payment(invoice, payment_id)
95479554 }
95489555
9549- fn create_blinded_paths_using_absolute_expiry(
9550- &self, context: OffersContext, absolute_expiry: Option<Duration>,
9551- ) -> Result<Vec<BlindedMessagePath>, ()> {
9552- self.create_blinded_paths_using_absolute_expiry(context, absolute_expiry)
9553- }
9554-
95559556 fn get_chain_hash(&self) -> ChainHash {
95569557 self.chain_hash
95579558 }
@@ -9575,14 +9576,6 @@ where
95759576 self.pending_outbound_payments.add_new_awaiting_offer(payment_id, expiration, retry_strategy, max_total_routing_fee_msat, amount_msats)
95769577 }
95779578
9578- fn pay_for_offer_intern<CPP: FnOnce(&InvoiceRequest, Nonce) -> Result<(), Bolt12SemanticError>>(
9579- &self, offer: &Offer, quantity: Option<u64>, amount_msats: Option<u64>,
9580- payer_note: Option<String>, payment_id: PaymentId,
9581- human_readable_name: Option<HumanReadableName>, create_pending_payment: CPP,
9582- ) -> Result<(), Bolt12SemanticError> {
9583- self.pay_for_offer_intern(offer, quantity, amount_msats, payer_note, payment_id, human_readable_name, create_pending_payment)
9584- }
9585-
95869579 #[cfg(feature = "dnssec")]
95879580 fn amt_msats_for_payment_awaiting_offer(&self, payment_id: PaymentId) -> Result<u64, ()> {
95889581 self.pending_outbound_payments.amt_msats_for_payment_awaiting_offer(payment_id)
@@ -9614,54 +9607,6 @@ where
96149607 MR::Target: MessageRouter,
96159608 L::Target: Logger,
96169609{
9617- /// Internal pay_for_offer
9618- pub fn pay_for_offer_intern<CPP: FnOnce(&InvoiceRequest, Nonce) -> Result<(), Bolt12SemanticError>>(
9619- &self, offer: &Offer, quantity: Option<u64>, amount_msats: Option<u64>,
9620- payer_note: Option<String>, payment_id: PaymentId,
9621- human_readable_name: Option<HumanReadableName>, create_pending_payment: CPP,
9622- ) -> Result<(), Bolt12SemanticError> {
9623- let expanded_key = &self.inbound_payment_key;
9624- let entropy = &*self.entropy_source;
9625- let secp_ctx = &self.secp_ctx;
9626-
9627- let nonce = Nonce::from_entropy_source(entropy);
9628- let builder: InvoiceRequestBuilder<secp256k1::All> = offer
9629- .request_invoice(expanded_key, nonce, secp_ctx, payment_id)?
9630- .into();
9631- let builder = builder.chain_hash(self.chain_hash)?;
9632-
9633- let builder = match quantity {
9634- None => builder,
9635- Some(quantity) => builder.quantity(quantity)?,
9636- };
9637- let builder = match amount_msats {
9638- None => builder,
9639- Some(amount_msats) => builder.amount_msats(amount_msats)?,
9640- };
9641- let builder = match payer_note {
9642- None => builder,
9643- Some(payer_note) => builder.payer_note(payer_note),
9644- };
9645- let builder = match human_readable_name {
9646- None => builder,
9647- Some(hrn) => builder.sourced_from_human_readable_name(hrn),
9648- };
9649- let invoice_request = builder.build_and_sign()?;
9650-
9651- let hmac = payment_id.hmac_for_offer_payment(nonce, expanded_key);
9652- let context = MessageContext::Offers(
9653- OffersContext::OutboundPayment { payment_id, nonce, hmac: Some(hmac) }
9654- );
9655- let reply_paths = self.create_blinded_paths(context)
9656- .map_err(|_| Bolt12SemanticError::MissingPaths)?;
9657-
9658- let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
9659-
9660- create_pending_payment(&invoice_request, nonce)?;
9661-
9662- self.enqueue_invoice_request(invoice_request, reply_paths)
9663- }
9664-
96659610 fn enqueue_invoice_request(
96669611 &self,
96679612 invoice_request: InvoiceRequest,
@@ -9697,6 +9642,19 @@ where
96979642 Ok(())
96989643 }
96999644
9645+ #[cfg(async_payments)]
9646+ pub(super) fn duration_since_epoch(&self) -> Duration {
9647+ #[cfg(not(feature = "std"))]
9648+ let now = Duration::from_secs(
9649+ self.highest_seen_timestamp.load(Ordering::Acquire) as u64
9650+ );
9651+ #[cfg(feature = "std")]
9652+ let now = std::time::SystemTime::now()
9653+ .duration_since(std::time::SystemTime::UNIX_EPOCH)
9654+ .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
9655+ now
9656+ }
9657+
97009658 /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
97019659 /// to pay us.
97029660 ///
@@ -9795,86 +9753,25 @@ where
97959753 inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
97969754 }
97979755
9798- /// Creates a collection of blinded paths by delegating to [`MessageRouter`] based on
9799- /// the path's intended lifetime.
9800- ///
9801- /// Whether or not the path is compact depends on whether the path is short-lived or long-lived,
9802- /// respectively, based on the given `absolute_expiry` as seconds since the Unix epoch. See
9803- /// [`MAX_SHORT_LIVED_RELATIVE_EXPIRY`].
9804- pub fn create_blinded_paths_using_absolute_expiry(
9805- &self, context: OffersContext, absolute_expiry: Option<Duration>,
9806- ) -> Result<Vec<BlindedMessagePath>, ()> {
9807- let now = self.duration_since_epoch();
9808- let max_short_lived_absolute_expiry = now.saturating_add(MAX_SHORT_LIVED_RELATIVE_EXPIRY);
9809- if absolute_expiry.unwrap_or(Duration::MAX) <= max_short_lived_absolute_expiry {
9810- self.create_compact_blinded_paths(context)
9811- } else {
9812- self.create_blinded_paths(MessageContext::Offers(context))
9813- }
9814- }
9815-
9816- pub(super) fn duration_since_epoch(&self) -> Duration {
9817- #[cfg(not(feature = "std"))]
9818- let now = Duration::from_secs(
9819- self.highest_seen_timestamp.load(Ordering::Acquire) as u64
9820- );
9821- #[cfg(feature = "std")]
9822- let now = std::time::SystemTime::now()
9823- .duration_since(std::time::SystemTime::UNIX_EPOCH)
9824- .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
9825-
9826- now
9827- }
9828-
98299756 /// Creates a collection of blinded paths by delegating to
98309757 /// [`MessageRouter::create_blinded_paths`].
98319758 ///
98329759 /// Errors if the `MessageRouter` errors.
98339760 fn create_blinded_paths(&self, context: MessageContext) -> Result<Vec<BlindedMessagePath>, ()> {
98349761 let recipient = self.get_our_node_id();
98359762 let secp_ctx = &self.secp_ctx;
9836-
98379763 let peers = self.per_peer_state.read().unwrap()
98389764 .iter()
98399765 .map(|(node_id, peer_state)| (node_id, peer_state.lock().unwrap()))
98409766 .filter(|(_, peer)| peer.is_connected)
98419767 .filter(|(_, peer)| peer.latest_features.supports_onion_messages())
98429768 .map(|(node_id, _)| *node_id)
98439769 .collect::<Vec<_>>();
9844-
98459770 self.message_router
98469771 .create_blinded_paths(recipient, context, peers, secp_ctx)
98479772 .and_then(|paths| (!paths.is_empty()).then(|| paths).ok_or(()))
98489773 }
98499774
9850- /// Creates a collection of blinded paths by delegating to
9851- /// [`MessageRouter::create_compact_blinded_paths`].
9852- ///
9853- /// Errors if the `MessageRouter` errors.
9854- fn create_compact_blinded_paths(&self, context: OffersContext) -> Result<Vec<BlindedMessagePath>, ()> {
9855- let recipient = self.get_our_node_id();
9856- let secp_ctx = &self.secp_ctx;
9857-
9858- let peers = self.per_peer_state.read().unwrap()
9859- .iter()
9860- .map(|(node_id, peer_state)| (node_id, peer_state.lock().unwrap()))
9861- .filter(|(_, peer)| peer.is_connected)
9862- .filter(|(_, peer)| peer.latest_features.supports_onion_messages())
9863- .map(|(node_id, peer)| MessageForwardNode {
9864- node_id: *node_id,
9865- short_channel_id: peer.channel_by_id
9866- .iter()
9867- .filter(|(_, channel)| channel.context().is_usable())
9868- .min_by_key(|(_, channel)| channel.context().channel_creation_height)
9869- .and_then(|(_, channel)| channel.context().get_short_channel_id()),
9870- })
9871- .collect::<Vec<_>>();
9872-
9873- self.message_router
9874- .create_compact_blinded_paths(recipient, MessageContext::Offers(context), peers, secp_ctx)
9875- .and_then(|paths| (!paths.is_empty()).then(|| paths).ok_or(()))
9876- }
9877-
98789775 /// Creates multi-hop blinded payment paths for the given `amount_msats` by delegating to
98799776 /// [`Router::create_blinded_payment_paths`].
98809777 fn create_blinded_payment_paths(
@@ -9884,7 +9781,6 @@ where
98849781 let expanded_key = &self.inbound_payment_key;
98859782 let entropy = &*self.entropy_source;
98869783 let secp_ctx = &self.secp_ctx;
9887-
98889784 let first_hops = self.list_usable_channels();
98899785 let payee_node_id = self.get_our_node_id();
98909786
@@ -9905,7 +9801,6 @@ where
99059801 };
99069802 let nonce = Nonce::from_entropy_source(entropy);
99079803 let payee_tlvs = payee_tlvs.authenticate(nonce, expanded_key);
9908-
99099804 self.router.create_blinded_payment_paths(
99109805 payee_node_id, first_hops, payee_tlvs, amount_msats, secp_ctx
99119806 )
@@ -12161,6 +12056,7 @@ where
1216112056 /// The [`MessageRouter`] used for constructing [`BlindedMessagePath`]s for [`Offer`]s,
1216212057 /// [`Refund`]s, and any reply paths.
1216312058 ///
12059+ /// [`BlindedMessagePath`]: crate::blinded_path::message::BlindedMessagePath
1216412060 /// [`Offer`]: crate::offers::offer
1216512061 /// [`Refund`]: crate::offers::refund
1216612062 pub message_router: MR,
0 commit comments