Skip to content

Commit 1868f99

Browse files
committed
Move create_blinded_path_using_absolute_expiry to flow.rs
1 parent 546da37 commit 1868f99

File tree

7 files changed

+239
-207
lines changed

7 files changed

+239
-207
lines changed

lightning-background-processor/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -647,7 +647,7 @@ use futures_util::{dummy_waker, OptionalSelector, Selector, SelectorOutput};
647647
/// # type NetworkGraph = lightning::routing::gossip::NetworkGraph<Arc<Logger>>;
648648
/// # type P2PGossipSync<UL> = lightning::routing::gossip::P2PGossipSync<Arc<NetworkGraph>, Arc<UL>, Arc<Logger>>;
649649
/// # type ChannelManager<B, F, FE> = lightning::ln::channelmanager::SimpleArcChannelManager<ChainMonitor<B, F, FE>, B, FE, Logger>;
650-
/// # type OffersMessageFlow<B, F, FE> = lightning::offers::flow::OffersMessageFlow<Arc<lightning::sign::KeysManager>, Arc<ChannelManager<B, F, FE>>, Arc<Logger>>;
650+
/// # type OffersMessageFlow<B, F, FE> = lightning::offers::flow::OffersMessageFlow<Arc<lightning::sign::KeysManager>, Arc<ChannelManager<B, F, FE>>, Arc<lightning::onion_message::messenger::DefaultMessageRouter<Arc<NetworkGraph>, Arc<Logger>, Arc<lightning::sign::KeysManager>>>, Arc<Logger>>;
651651
/// # type OnionMessenger<B, F, FE> = lightning::onion_message::messenger::OnionMessenger<Arc<lightning::sign::KeysManager>, Arc<lightning::sign::KeysManager>, Arc<Logger>, Arc<ChannelManager<B, F, FE>>, Arc<lightning::onion_message::messenger::DefaultMessageRouter<Arc<NetworkGraph>, Arc<Logger>, Arc<lightning::sign::KeysManager>>>, Arc<OffersMessageFlow<B, F, FE>>, lightning::ln::peer_handler::IgnoringMessageHandler, lightning::ln::peer_handler::IgnoringMessageHandler, lightning::ln::peer_handler::IgnoringMessageHandler>;
652652
/// # type Scorer = RwLock<lightning::routing::scoring::ProbabilisticScorer<Arc<NetworkGraph>, Arc<Logger>>>;
653653
/// # type PeerManager<B, F, FE, UL> = lightning::ln::peer_handler::SimpleArcPeerManager<SocketDescriptor, ChainMonitor<B, F, FE>, B, FE, Arc<UL>, Logger>;

lightning/src/ln/blinded_payment_tests.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1238,7 +1238,7 @@ fn blinded_keysend() {
12381238

12391239
let inbound_payment_key = nodes[2].keys_manager.get_inbound_payment_key();
12401240
let payment_secret = inbound_payment::create_for_spontaneous_payment(
1241-
&inbound_payment_key, None, u32::MAX, nodes[2].node.duration_since_epoch().as_secs(), None
1241+
&inbound_payment_key, None, u32::MAX, nodes[2].offers_handler.duration_since_epoch().as_secs(), None
12421242
).unwrap();
12431243

12441244
let amt_msat = 5000;
@@ -1277,7 +1277,7 @@ fn blinded_mpp_keysend() {
12771277

12781278
let inbound_payment_key = nodes[3].keys_manager.get_inbound_payment_key();
12791279
let payment_secret = inbound_payment::create_for_spontaneous_payment(
1280-
&inbound_payment_key, None, u32::MAX, nodes[3].node.duration_since_epoch().as_secs(), None
1280+
&inbound_payment_key, None, u32::MAX, nodes[3].offers_handler.duration_since_epoch().as_secs(), None
12811281
).unwrap();
12821282

12831283
let amt_msat = 15_000_000;

lightning/src/ln/channelmanager.rs

Lines changed: 38 additions & 151 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,9 @@ use bitcoin::secp256k1::Secp256k1;
3333
use bitcoin::{secp256k1, Sequence, Weight};
3434

3535
use crate::events::FundingInfo;
36-
use crate::blinded_path::message::{AsyncPaymentsContext, MessageContext, OffersContext};
36+
use crate::blinded_path::message::{AsyncPaymentsContext, MessageContext, MessageForwardNode};
3737
use crate::blinded_path::NodeIdLookUp;
38-
use crate::blinded_path::message::{BlindedMessagePath, MessageForwardNode};
38+
use crate::blinded_path::message::BlindedMessagePath;
3939
use crate::blinded_path::payment::{BlindedPaymentPath, PaymentConstraints, PaymentContext, UnauthenticatedReceiveTlvs};
4040
use crate::chain;
4141
use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock};
@@ -47,7 +47,6 @@ use crate::events::{self, Event, EventHandler, EventsProvider, InboundChannelFun
4747
// construct one themselves.
4848
use crate::ln::inbound_payment;
4949
use crate::ln::types::ChannelId;
50-
use crate::offers::offer::Offer;
5150
use crate::offers::flow::OffersMessageCommons;
5251
use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
5352
use crate::ln::channel::{self, Channel, ChannelPhase, ChannelError, ChannelUpdateStatus, ShutdownResult, UpdateFulfillCommitFetch, OutboundV1Channel, InboundV1Channel, WithChannelContext, InboundV2Channel, InteractivelyFunded as _};
@@ -68,14 +67,13 @@ use crate::ln::outbound_payment;
6867
use crate::ln::outbound_payment::{OutboundPayments, PendingOutboundPayment, RetryableInvoiceRequest, SendAlongPathArgs, StaleExpiration};
6968
use crate::offers::invoice::Bolt12Invoice;
7069
use crate::offers::invoice::UnsignedBolt12Invoice;
71-
use crate::offers::invoice_request::{InvoiceRequest, InvoiceRequestBuilder};
70+
use crate::offers::invoice_request::InvoiceRequest;
7271
use crate::offers::nonce::Nonce;
7372
use crate::offers::parse::Bolt12SemanticError;
7473
use crate::offers::signer;
7574
#[cfg(async_payments)]
7675
use crate::offers::static_invoice::StaticInvoice;
7776
use crate::onion_message::async_payments::{AsyncPaymentsMessage, HeldHtlcAvailable, ReleaseHeldHtlc, AsyncPaymentsMessageHandler};
78-
use crate::onion_message::dns_resolution::HumanReadableName;
7977
use crate::onion_message::messenger::{DefaultMessageRouter, Destination, MessageRouter, MessageSendInstructions, Responder, ResponseInstruction};
8078
use crate::onion_message::offers::OffersMessage;
8179
use crate::sign::{EntropySource, NodeSigner, Recipient, SignerProvider};
@@ -443,11 +441,15 @@ impl Ord for ClaimableHTLC {
443441
pub trait Verification {
444442
/// Constructs an HMAC to include in [`OffersContext`] for the data along with the given
445443
/// [`Nonce`].
444+
///
445+
/// [`OffersContext`]: crate::blinded_path::message::OffersContext
446446
fn hmac_for_offer_payment(
447447
&self, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
448448
) -> Hmac<Sha256>;
449449

450450
/// Authenticates the data using an HMAC and a [`Nonce`] taken from an [`OffersContext`].
451+
///
452+
/// [`OffersContext`]: crate::blinded_path::message::OffersContext
451453
fn verify_for_offer_payment(
452454
&self, hmac: Hmac<Sha256>, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
453455
) -> Result<(), ()>;
@@ -456,6 +458,8 @@ pub trait Verification {
456458
impl Verification for PaymentHash {
457459
/// Constructs an HMAC to include in [`OffersContext::InboundPayment`] for the payment hash
458460
/// along with the given [`Nonce`].
461+
///
462+
/// [`OffersContext::InboundPayment`]: crate::blinded_path::message::OffersContext::InboundPayment
459463
fn hmac_for_offer_payment(
460464
&self, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
461465
) -> Hmac<Sha256> {
@@ -464,6 +468,8 @@ impl Verification for PaymentHash {
464468

465469
/// Authenticates the payment id using an HMAC and a [`Nonce`] taken from an
466470
/// [`OffersContext::InboundPayment`].
471+
///
472+
/// [`OffersContext::InboundPayment`]: crate::blinded_path::message::OffersContext::InboundPayment
467473
fn verify_for_offer_payment(
468474
&self, hmac: Hmac<Sha256>, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
469475
) -> Result<(), ()> {
@@ -518,6 +524,8 @@ impl PaymentId {
518524
impl Verification for PaymentId {
519525
/// Constructs an HMAC to include in [`OffersContext::OutboundPayment`] for the payment id
520526
/// along with the given [`Nonce`].
527+
///
528+
/// [`OffersContext::OutboundPayment`]: crate::blinded_path::message::OffersContext::OutboundPayment
521529
fn hmac_for_offer_payment(
522530
&self, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
523531
) -> Hmac<Sha256> {
@@ -526,6 +534,8 @@ impl Verification for PaymentId {
526534

527535
/// Authenticates the payment id using an HMAC and a [`Nonce`] taken from an
528536
/// [`OffersContext::OutboundPayment`].
537+
///
538+
/// [`OffersContext::OutboundPayment`]: crate::blinded_path::message::OffersContext::OutboundPayment
529539
fn verify_for_offer_payment(
530540
&self, hmac: Hmac<Sha256>, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
531541
) -> Result<(), ()> {
@@ -2612,26 +2622,6 @@ const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
26122622
/// many peers we reject new (inbound) connections.
26132623
const MAX_NO_CHANNEL_PEERS: usize = 250;
26142624

2615-
/// The maximum expiration from the current time where an [`Offer`] or [`Refund`] is considered
2616-
/// short-lived, while anything with a greater expiration is considered long-lived.
2617-
///
2618-
/// Using [`OffersMessageFlow::create_offer_builder`] or [`OffersMessageFlow::create_refund_builder`],
2619-
/// will included a [`BlindedMessagePath`] created using:
2620-
/// - [`MessageRouter::create_compact_blinded_paths`] when short-lived, and
2621-
/// - [`MessageRouter::create_blinded_paths`] when long-lived.
2622-
///
2623-
/// [`OffersMessageFlow::create_offer_builder`]: crate::offers::flow::OffersMessageFlow::create_offer_builder
2624-
/// [`OffersMessageFlow::create_refund_builder`]: crate::offers::flow::OffersMessageFlow::create_refund_builder
2625-
///
2626-
///
2627-
/// Using compact [`BlindedMessagePath`]s may provide better privacy as the [`MessageRouter`] could select
2628-
/// more hops. However, since they use short channel ids instead of pubkeys, they are more likely to
2629-
/// become invalid over time as channels are closed. Thus, they are only suitable for short-term use.
2630-
///
2631-
/// [`Offer`]: crate::offers::offer
2632-
/// [`Refund`]: crate::offers::refund
2633-
pub const MAX_SHORT_LIVED_RELATIVE_EXPIRY: Duration = Duration::from_secs(60 * 60 * 24);
2634-
26352625
/// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
26362626
/// These include payments that have yet to find a successful path, or have unresolved HTLCs.
26372627
#[derive(Debug, PartialEq)]
@@ -9640,6 +9630,23 @@ where
96409630
self.create_blinded_payment_paths(amount_msats, payment_secret, payment_context)
96419631
}
96429632

9633+
fn get_peer_for_blinded_path(&self) -> Vec<MessageForwardNode> {
9634+
self.per_peer_state.read().unwrap()
9635+
.iter()
9636+
.map(|(node_id, peer_state)| (node_id, peer_state.lock().unwrap()))
9637+
.filter(|(_, peer)| peer.is_connected)
9638+
.filter(|(_, peer)| peer.latest_features.supports_onion_messages())
9639+
.map(|(node_id, peer)| MessageForwardNode {
9640+
node_id: *node_id,
9641+
short_channel_id: peer.channel_by_id
9642+
.iter()
9643+
.filter(|(_, channel)| channel.context().is_usable())
9644+
.min_by_key(|(_, channel)| channel.context().channel_creation_height)
9645+
.and_then(|(_, channel)| channel.context().get_short_channel_id()),
9646+
})
9647+
.collect::<Vec<_>>()
9648+
}
9649+
96439650
fn send_payment_for_verified_bolt12_invoice(&self, invoice: &Bolt12Invoice, payment_id: PaymentId) -> Result<(), Bolt12PaymentError> {
96449651
self.send_payment_for_verified_bolt12_invoice(invoice, payment_id)
96459652
}
@@ -9671,12 +9678,6 @@ where
96719678
self.initiate_async_payment(invoice, payment_id)
96729679
}
96739680

9674-
fn create_blinded_paths_using_absolute_expiry(
9675-
&self, context: OffersContext, absolute_expiry: Option<Duration>,
9676-
) -> Result<Vec<BlindedMessagePath>, ()> {
9677-
self.create_blinded_paths_using_absolute_expiry(context, absolute_expiry)
9678-
}
9679-
96809681
fn get_chain_hash(&self) -> ChainHash {
96819682
self.chain_hash
96829683
}
@@ -9695,14 +9696,6 @@ where
96959696
self.pending_outbound_payments.add_new_awaiting_offer(payment_id, expiration, retry_strategy, max_total_routing_fee_msat, amount_msats)
96969697
}
96979698

9698-
fn pay_for_offer_intern<CPP: FnOnce(&InvoiceRequest, Nonce) -> Result<(), Bolt12SemanticError>>(
9699-
&self, offer: &Offer, quantity: Option<u64>, amount_msats: Option<u64>,
9700-
payer_note: Option<String>, payment_id: PaymentId,
9701-
human_readable_name: Option<HumanReadableName>, create_pending_payment: CPP,
9702-
) -> Result<(), Bolt12SemanticError> {
9703-
self.pay_for_offer_intern(offer, quantity, amount_msats, payer_note, payment_id, human_readable_name, create_pending_payment)
9704-
}
9705-
97069699
#[cfg(feature = "dnssec")]
97079700
fn amt_msats_for_payment_awaiting_offer(&self, payment_id: PaymentId) -> Result<u64, ()> {
97089701
self.pending_outbound_payments.amt_msats_for_payment_awaiting_offer(payment_id)
@@ -9713,6 +9706,11 @@ where
97139706
) -> Result<(), ()> {
97149707
self.pending_outbound_payments.received_offer(payment_id, retryable_invoice_request)
97159708
}
9709+
9710+
#[cfg(not(feature = "std"))]
9711+
fn get_highest_seen_timestamp(&self) -> Duration {
9712+
Duration::from_secs(self.highest_seen_timestamp.load(Ordering::Acquire) as u64)
9713+
}
97169714
}
97179715

97189716
/// Defines the maximum number of [`OffersMessage`] including different reply paths to be sent
@@ -9734,54 +9732,6 @@ where
97349732
MR::Target: MessageRouter,
97359733
L::Target: Logger,
97369734
{
9737-
/// Internal pay_for_offer
9738-
pub fn pay_for_offer_intern<CPP: FnOnce(&InvoiceRequest, Nonce) -> Result<(), Bolt12SemanticError>>(
9739-
&self, offer: &Offer, quantity: Option<u64>, amount_msats: Option<u64>,
9740-
payer_note: Option<String>, payment_id: PaymentId,
9741-
human_readable_name: Option<HumanReadableName>, create_pending_payment: CPP,
9742-
) -> Result<(), Bolt12SemanticError> {
9743-
let expanded_key = &self.inbound_payment_key;
9744-
let entropy = &*self.entropy_source;
9745-
let secp_ctx = &self.secp_ctx;
9746-
9747-
let nonce = Nonce::from_entropy_source(entropy);
9748-
let builder: InvoiceRequestBuilder<secp256k1::All> = offer
9749-
.request_invoice(expanded_key, nonce, secp_ctx, payment_id)?
9750-
.into();
9751-
let builder = builder.chain_hash(self.chain_hash)?;
9752-
9753-
let builder = match quantity {
9754-
None => builder,
9755-
Some(quantity) => builder.quantity(quantity)?,
9756-
};
9757-
let builder = match amount_msats {
9758-
None => builder,
9759-
Some(amount_msats) => builder.amount_msats(amount_msats)?,
9760-
};
9761-
let builder = match payer_note {
9762-
None => builder,
9763-
Some(payer_note) => builder.payer_note(payer_note),
9764-
};
9765-
let builder = match human_readable_name {
9766-
None => builder,
9767-
Some(hrn) => builder.sourced_from_human_readable_name(hrn),
9768-
};
9769-
let invoice_request = builder.build_and_sign()?;
9770-
9771-
let hmac = payment_id.hmac_for_offer_payment(nonce, expanded_key);
9772-
let context = MessageContext::Offers(
9773-
OffersContext::OutboundPayment { payment_id, nonce, hmac: Some(hmac) }
9774-
);
9775-
let reply_paths = self.create_blinded_paths(context)
9776-
.map_err(|_| Bolt12SemanticError::MissingPaths)?;
9777-
9778-
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
9779-
9780-
create_pending_payment(&invoice_request, nonce)?;
9781-
9782-
self.enqueue_invoice_request(invoice_request, reply_paths)
9783-
}
9784-
97859735
fn enqueue_invoice_request(
97869736
&self,
97879737
invoice_request: InvoiceRequest,
@@ -9915,86 +9865,25 @@ where
99159865
inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
99169866
}
99179867

9918-
/// Creates a collection of blinded paths by delegating to [`MessageRouter`] based on
9919-
/// the path's intended lifetime.
9920-
///
9921-
/// Whether or not the path is compact depends on whether the path is short-lived or long-lived,
9922-
/// respectively, based on the given `absolute_expiry` as seconds since the Unix epoch. See
9923-
/// [`MAX_SHORT_LIVED_RELATIVE_EXPIRY`].
9924-
pub fn create_blinded_paths_using_absolute_expiry(
9925-
&self, context: OffersContext, absolute_expiry: Option<Duration>,
9926-
) -> Result<Vec<BlindedMessagePath>, ()> {
9927-
let now = self.duration_since_epoch();
9928-
let max_short_lived_absolute_expiry = now.saturating_add(MAX_SHORT_LIVED_RELATIVE_EXPIRY);
9929-
if absolute_expiry.unwrap_or(Duration::MAX) <= max_short_lived_absolute_expiry {
9930-
self.create_compact_blinded_paths(context)
9931-
} else {
9932-
self.create_blinded_paths(MessageContext::Offers(context))
9933-
}
9934-
}
9935-
9936-
pub(super) fn duration_since_epoch(&self) -> Duration {
9937-
#[cfg(not(feature = "std"))]
9938-
let now = Duration::from_secs(
9939-
self.highest_seen_timestamp.load(Ordering::Acquire) as u64
9940-
);
9941-
#[cfg(feature = "std")]
9942-
let now = std::time::SystemTime::now()
9943-
.duration_since(std::time::SystemTime::UNIX_EPOCH)
9944-
.expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
9945-
9946-
now
9947-
}
9948-
99499868
/// Creates a collection of blinded paths by delegating to
99509869
/// [`MessageRouter::create_blinded_paths`].
99519870
///
99529871
/// Errors if the `MessageRouter` errors.
99539872
fn create_blinded_paths(&self, context: MessageContext) -> Result<Vec<BlindedMessagePath>, ()> {
99549873
let recipient = self.get_our_node_id();
99559874
let secp_ctx = &self.secp_ctx;
9956-
99579875
let peers = self.per_peer_state.read().unwrap()
99589876
.iter()
99599877
.map(|(node_id, peer_state)| (node_id, peer_state.lock().unwrap()))
99609878
.filter(|(_, peer)| peer.is_connected)
99619879
.filter(|(_, peer)| peer.latest_features.supports_onion_messages())
99629880
.map(|(node_id, _)| *node_id)
99639881
.collect::<Vec<_>>();
9964-
99659882
self.message_router
99669883
.create_blinded_paths(recipient, context, peers, secp_ctx)
99679884
.and_then(|paths| (!paths.is_empty()).then(|| paths).ok_or(()))
99689885
}
99699886

9970-
/// Creates a collection of blinded paths by delegating to
9971-
/// [`MessageRouter::create_compact_blinded_paths`].
9972-
///
9973-
/// Errors if the `MessageRouter` errors.
9974-
fn create_compact_blinded_paths(&self, context: OffersContext) -> Result<Vec<BlindedMessagePath>, ()> {
9975-
let recipient = self.get_our_node_id();
9976-
let secp_ctx = &self.secp_ctx;
9977-
9978-
let peers = self.per_peer_state.read().unwrap()
9979-
.iter()
9980-
.map(|(node_id, peer_state)| (node_id, peer_state.lock().unwrap()))
9981-
.filter(|(_, peer)| peer.is_connected)
9982-
.filter(|(_, peer)| peer.latest_features.supports_onion_messages())
9983-
.map(|(node_id, peer)| MessageForwardNode {
9984-
node_id: *node_id,
9985-
short_channel_id: peer.channel_by_id
9986-
.iter()
9987-
.filter(|(_, channel)| channel.context().is_usable())
9988-
.min_by_key(|(_, channel)| channel.context().channel_creation_height)
9989-
.and_then(|(_, channel)| channel.context().get_short_channel_id()),
9990-
})
9991-
.collect::<Vec<_>>();
9992-
9993-
self.message_router
9994-
.create_compact_blinded_paths(recipient, MessageContext::Offers(context), peers, secp_ctx)
9995-
.and_then(|paths| (!paths.is_empty()).then(|| paths).ok_or(()))
9996-
}
9997-
99989887
/// Creates multi-hop blinded payment paths for the given `amount_msats` by delegating to
99999888
/// [`Router::create_blinded_payment_paths`].
100009889
fn create_blinded_payment_paths(
@@ -10003,12 +9892,10 @@ where
100039892
let expanded_key = &self.inbound_payment_key;
100049893
let entropy = &*self.entropy_source;
100059894
let secp_ctx = &self.secp_ctx;
10006-
100079895
let first_hops = self.list_usable_channels();
100089896
let payee_node_id = self.get_our_node_id();
100099897
let max_cltv_expiry = self.best_block.read().unwrap().height + CLTV_FAR_FAR_AWAY
100109898
+ LATENCY_GRACE_PERIOD_BLOCKS;
10011-
100129899
let payee_tlvs = UnauthenticatedReceiveTlvs {
100139900
payment_secret,
100149901
payment_constraints: PaymentConstraints {
@@ -10019,7 +9906,6 @@ where
100199906
};
100209907
let nonce = Nonce::from_entropy_source(entropy);
100219908
let payee_tlvs = payee_tlvs.authenticate(nonce, expanded_key);
10022-
100239909
self.router.create_blinded_payment_paths(
100249910
payee_node_id, first_hops, payee_tlvs, amount_msats, secp_ctx
100259911
)
@@ -12265,6 +12151,7 @@ where
1226512151
/// The [`MessageRouter`] used for constructing [`BlindedMessagePath`]s for [`Offer`]s,
1226612152
/// [`Refund`]s, and any reply paths.
1226712153
///
12154+
/// [`BlindedMessagePath`]: crate::blinded_path::message::BlindedMessagePath
1226812155
/// [`Offer`]: crate::offers::offer
1226912156
/// [`Refund`]: crate::offers::refund
1227012157
pub message_router: MR,

0 commit comments

Comments
 (0)