Skip to content

Commit 66640cb

Browse files
committed
Move pay_for_offer to OffersMessageFlow
1 parent 592a4c2 commit 66640cb

File tree

4 files changed

+208
-174
lines changed

4 files changed

+208
-174
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 43 additions & 151 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ 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;
5051
use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
5152
use crate::ln::channel::{self, Channel, ChannelPhase, ChannelError, ChannelUpdateStatus, ShutdownResult, UpdateFulfillCommitFetch, OutboundV1Channel, InboundV1Channel, WithChannelContext, InboundV2Channel, InteractivelyFunded as _};
5253
use crate::ln::channel_state::ChannelDetails;
@@ -65,7 +66,6 @@ use crate::ln::outbound_payment::{OutboundPayments, PendingOutboundPayment, Retr
6566
use crate::offers::invoice::{Bolt12Invoice, DerivedSigningPubkey, InvoiceBuilder, UnsignedBolt12Invoice, DEFAULT_RELATIVE_EXPIRY};
6667
use crate::offers::invoice_request::{InvoiceRequest, InvoiceRequestBuilder};
6768
use crate::offers::nonce::Nonce;
68-
use crate::offers::offer::Offer;
6969
use crate::offers::parse::Bolt12SemanticError;
7070
use crate::offers::refund::Refund;
7171
use crate::offers::signer;
@@ -2009,56 +2009,7 @@ where
20092009
///
20102010
/// For more information on creating offers, see [`create_offer_builder`].
20112011
///
2012-
/// Use [`pay_for_offer`] to initiated payment, which sends an [`InvoiceRequest`] for an [`Offer`]
2013-
/// and pays the [`Bolt12Invoice`] response.
2014-
///
2015-
/// ```
2016-
/// # use lightning::events::{Event, EventsProvider};
2017-
/// # use lightning::ln::channelmanager::{AChannelManager, OffersMessageCommons, PaymentId, RecentPaymentDetails, Retry};
2018-
/// # use lightning::offers::offer::Offer;
2019-
/// #
2020-
/// # fn example<T: AChannelManager>(
2021-
/// # channel_manager: T, offer: &Offer, quantity: Option<u64>, amount_msats: Option<u64>,
2022-
/// # payer_note: Option<String>, retry: Retry, max_total_routing_fee_msat: Option<u64>
2023-
/// # ) {
2024-
/// # let channel_manager = channel_manager.get_cm();
2025-
/// let payment_id = PaymentId([42; 32]);
2026-
/// match channel_manager.pay_for_offer(
2027-
/// offer, quantity, amount_msats, payer_note, payment_id, retry, max_total_routing_fee_msat
2028-
/// ) {
2029-
/// Ok(()) => println!("Requesting invoice for offer"),
2030-
/// Err(e) => println!("Unable to request invoice for offer: {:?}", e),
2031-
/// }
2032-
///
2033-
/// // First the payment will be waiting on an invoice
2034-
/// let expected_payment_id = payment_id;
2035-
/// assert!(
2036-
/// channel_manager.list_recent_payments().iter().find(|details| matches!(
2037-
/// details,
2038-
/// RecentPaymentDetails::AwaitingInvoice { payment_id: expected_payment_id }
2039-
/// )).is_some()
2040-
/// );
2041-
///
2042-
/// // Once the invoice is received, a payment will be sent
2043-
/// assert!(
2044-
/// channel_manager.list_recent_payments().iter().find(|details| matches!(
2045-
/// details,
2046-
/// RecentPaymentDetails::Pending { payment_id: expected_payment_id, .. }
2047-
/// )).is_some()
2048-
/// );
2049-
///
2050-
/// // On the event processing thread
2051-
/// channel_manager.process_pending_events(&|event| {
2052-
/// match event {
2053-
/// Event::PaymentSent { payment_id: Some(payment_id), .. } => println!("Paid {}", payment_id),
2054-
/// Event::PaymentFailed { payment_id, .. } => println!("Failed paying {}", payment_id),
2055-
/// // ...
2056-
/// # _ => {},
2057-
/// }
2058-
/// Ok(())
2059-
/// });
2060-
/// # }
2061-
/// ```
2012+
/// For details on initiating payments for offers, see [`pay_for_offer`].
20622013
///
20632014
/// ## BOLT 12 Refunds
20642015
///
@@ -2188,7 +2139,7 @@ where
21882139
/// [`claim_funds`]: Self::claim_funds
21892140
/// [`send_payment`]: Self::send_payment
21902141
/// [`offers`]: crate::offers
2191-
/// [`pay_for_offer`]: Self::pay_for_offer
2142+
/// [`Offer`]: crate::offers::offer
21922143
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
21932144
/// [`request_refund_payment`]: Self::request_refund_payment
21942145
/// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
@@ -2199,6 +2150,7 @@ where
21992150
/// [`ChannelUpdate`]: msgs::ChannelUpdate
22002151
/// [`read`]: ReadableArgs::read
22012152
/// [`create_offer_builder`]: crate::offers::flow::OffersMessageFlow::create_offer_builder
2153+
/// [`pay_for_offer`]: crate::offers::flow::OffersMessageFlow::pay_for_offer
22022154
/// [`create_refund_builder`]: crate::offers::flow::OffersMessageFlow::create_refund_builder
22032155
//
22042156
// Lock order:
@@ -2708,6 +2660,8 @@ const MAX_NO_CHANNEL_PEERS: usize = 250;
27082660
/// Using compact [`BlindedMessagePath`]s may provide better privacy as the [`MessageRouter`] could select
27092661
/// more hops. However, since they use short channel ids instead of pubkeys, they are more likely to
27102662
/// become invalid over time as channels are closed. Thus, they are only suitable for short-term use.
2663+
///
2664+
/// [`Offer`]: crate::offers::offer
27112665
pub const MAX_SHORT_LIVED_RELATIVE_EXPIRY: Duration = Duration::from_secs(60 * 60 * 24);
27122666

27132667
/// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
@@ -2716,8 +2670,10 @@ pub const MAX_SHORT_LIVED_RELATIVE_EXPIRY: Duration = Duration::from_secs(60 * 6
27162670
pub enum RecentPaymentDetails {
27172671
/// When an invoice was requested and thus a payment has not yet been sent.
27182672
AwaitingInvoice {
2719-
/// A user-provided identifier in [`ChannelManager::pay_for_offer`] used to uniquely identify a
2673+
/// A user-provided identifier in [`OffersMessageFlow::pay_for_offer`] used to uniquely identify a
27202674
/// payment and ensure idempotency in LDK.
2675+
///
2676+
/// [`OffersMessageFlow::pay_for_offer`]: crate::offers::flow::OffersMessageFlow::pay_for_offer
27212677
payment_id: PaymentId,
27222678
},
27232679
/// When a payment is still being sent and awaiting successful delivery.
@@ -2726,7 +2682,7 @@ pub enum RecentPaymentDetails {
27262682
/// identify a payment and ensure idempotency in LDK.
27272683
///
27282684
/// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
2729-
/// [`pay_for_offer`]: crate::ln::channelmanager::ChannelManager::pay_for_offer
2685+
/// [`pay_for_offer`]: crate::offers::flow::OffersMessageFlow::pay_for_offer
27302686
payment_id: PaymentId,
27312687
/// Hash of the payment that is currently being sent but has yet to be fulfilled or
27322688
/// abandoned.
@@ -2743,7 +2699,7 @@ pub enum RecentPaymentDetails {
27432699
/// identify a payment and ensure idempotency in LDK.
27442700
///
27452701
/// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
2746-
/// [`pay_for_offer`]: crate::ln::channelmanager::ChannelManager::pay_for_offer
2702+
/// [`pay_for_offer`]: crate::offers::flow::OffersMessageFlow::pay_for_offer
27472703
payment_id: PaymentId,
27482704
/// Hash of the payment that was claimed. `None` for serializations of [`ChannelManager`]
27492705
/// made before LDK version 0.0.104.
@@ -2757,7 +2713,7 @@ pub enum RecentPaymentDetails {
27572713
/// identify a payment and ensure idempotency in LDK.
27582714
///
27592715
/// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
2760-
/// [`pay_for_offer`]: crate::ln::channelmanager::ChannelManager::pay_for_offer
2716+
/// [`pay_for_offer`]: crate::offers::flow::OffersMessageFlow::pay_for_offer
27612717
payment_id: PaymentId,
27622718
/// Hash of the payment that we have given up trying to send.
27632719
payment_hash: PaymentHash,
@@ -4643,7 +4599,7 @@ where
46434599
///
46444600
/// # Requested Invoices
46454601
///
4646-
/// In the case of paying a [`Bolt12Invoice`] via [`ChannelManager::pay_for_offer`], abandoning
4602+
/// In the case of paying a [`Bolt12Invoice`] via [`OffersMessageFlow::pay_for_offer`], abandoning
46474603
/// the payment prior to receiving the invoice will result in an [`Event::PaymentFailed`] and
46484604
/// prevent any attempts at paying it once received.
46494605
///
@@ -4653,6 +4609,7 @@ where
46534609
/// [`ChannelManager`], another [`Event::PaymentFailed`] may be generated.
46544610
///
46554611
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
4612+
/// [`OffersMessageFlow::pay_for_offer`]: crate::offers::flow::OffersMessageFlow::pay_for_offer
46564613
pub fn abandon_payment(&self, payment_id: PaymentId) {
46574614
self.abandon_payment_with_reason(payment_id, PaymentFailureReason::UserAbandoned)
46584615
}
@@ -9711,6 +9668,13 @@ pub trait OffersMessageCommons {
97119668

97129669
/// Add new awaiting invoice
97139670
fn add_new_awaiting_invoice(&self, payment_id: PaymentId, expiration: StaleExpiration, retry_strategy: Retry, max_total_routing_fee_msat: Option<u64>, retryable_invoice_request: Option<RetryableInvoiceRequest>) -> Result<(), ()>;
9671+
9672+
/// Internal pay_for_offer
9673+
fn pay_for_offer_intern<CPP: FnOnce(&InvoiceRequest, Nonce) -> Result<(), Bolt12SemanticError>> (
9674+
&self, offer: &Offer, quantity: Option<u64>, amount_msats: Option<u64>,
9675+
payer_note: Option<String>, payment_id: PaymentId,
9676+
human_readable_name: Option<HumanReadableName>, create_pending_payment: CPP,
9677+
) -> Result<(), Bolt12SemanticError>;
97149678
}
97159679

97169680
impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, MR: Deref, L: Deref> OffersMessageCommons for ChannelManager<M, T, ES, NS, SP, F, R, MR, L>
@@ -9894,104 +9858,10 @@ where
98949858
}
98959859

98969860
fn add_new_awaiting_invoice(&self, payment_id: PaymentId, expiration: StaleExpiration, retry_strategy: Retry, max_total_routing_fee_msat: Option<u64>, retryable_invoice_request: Option<RetryableInvoiceRequest>) -> Result<(), ()> {
9897-
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
98989861
self.pending_outbound_payments.add_new_awaiting_invoice (
98999862
payment_id, expiration, retry_strategy, max_total_routing_fee_msat, retryable_invoice_request,
99009863
)
99019864
}
9902-
}
9903-
9904-
/// Defines the maximum number of [`OffersMessage`] including different reply paths to be sent
9905-
/// along different paths.
9906-
/// Sending multiple requests increases the chances of successful delivery in case some
9907-
/// paths are unavailable. However, only one invoice for a given [`PaymentId`] will be paid,
9908-
/// even if multiple invoices are received.
9909-
const OFFERS_MESSAGE_REQUEST_LIMIT: usize = 10;
9910-
9911-
impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, MR: Deref, L: Deref> ChannelManager<M, T, ES, NS, SP, F, R, MR, L>
9912-
where
9913-
M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
9914-
T::Target: BroadcasterInterface,
9915-
ES::Target: EntropySource,
9916-
NS::Target: NodeSigner,
9917-
SP::Target: SignerProvider,
9918-
F::Target: FeeEstimator,
9919-
R::Target: Router,
9920-
MR::Target: MessageRouter,
9921-
L::Target: Logger,
9922-
{
9923-
/// Pays for an [`Offer`] using the given parameters by creating an [`InvoiceRequest`] and
9924-
/// enqueuing it to be sent via an onion message. [`ChannelManager`] will pay the actual
9925-
/// [`Bolt12Invoice`] once it is received.
9926-
///
9927-
/// Uses [`InvoiceRequestBuilder`] such that the [`InvoiceRequest`] it builds is recognized by
9928-
/// the [`ChannelManager`] when handling a [`Bolt12Invoice`] message in response to the request.
9929-
/// The optional parameters are used in the builder, if `Some`:
9930-
/// - `quantity` for [`InvoiceRequest::quantity`] which must be set if
9931-
/// [`Offer::expects_quantity`] is `true`.
9932-
/// - `amount_msats` if overpaying what is required for the given `quantity` is desired, and
9933-
/// - `payer_note` for [`InvoiceRequest::payer_note`].
9934-
///
9935-
/// If `max_total_routing_fee_msat` is not specified, The default from
9936-
/// [`RouteParameters::from_payment_params_and_value`] is applied.
9937-
///
9938-
/// # Payment
9939-
///
9940-
/// The provided `payment_id` is used to ensure that only one invoice is paid for the request
9941-
/// when received. See [Avoiding Duplicate Payments] for other requirements once the payment has
9942-
/// been sent.
9943-
///
9944-
/// To revoke the request, use [`ChannelManager::abandon_payment`] prior to receiving the
9945-
/// invoice. If abandoned, or an invoice isn't received in a reasonable amount of time, the
9946-
/// payment will fail with an [`Event::PaymentFailed`].
9947-
///
9948-
/// # Privacy
9949-
///
9950-
/// For payer privacy, uses a derived payer id and uses [`MessageRouter::create_blinded_paths`]
9951-
/// to construct a [`BlindedMessagePath`] for the reply path. For further privacy implications, see the
9952-
/// docs of the parameterized [`Router`], which implements [`MessageRouter`].
9953-
///
9954-
/// # Limitations
9955-
///
9956-
/// Requires a direct connection to an introduction node in [`Offer::paths`] or to
9957-
/// [`Offer::issuer_signing_pubkey`], if empty. A similar restriction applies to the responding
9958-
/// [`Bolt12Invoice::payment_paths`].
9959-
///
9960-
/// # Errors
9961-
///
9962-
/// Errors if:
9963-
/// - a duplicate `payment_id` is provided given the caveats in the aforementioned link,
9964-
/// - the provided parameters are invalid for the offer,
9965-
/// - the offer is for an unsupported chain, or
9966-
/// - the parameterized [`Router`] is unable to create a blinded reply path for the invoice
9967-
/// request.
9968-
///
9969-
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
9970-
/// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
9971-
/// [`InvoiceRequest::payer_note`]: crate::offers::invoice_request::InvoiceRequest::payer_note
9972-
/// [`InvoiceRequestBuilder`]: crate::offers::invoice_request::InvoiceRequestBuilder
9973-
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
9974-
/// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths
9975-
/// [Avoiding Duplicate Payments]: #avoiding-duplicate-payments
9976-
pub fn pay_for_offer(
9977-
&self, offer: &Offer, quantity: Option<u64>, amount_msats: Option<u64>,
9978-
payer_note: Option<String>, payment_id: PaymentId, retry_strategy: Retry,
9979-
max_total_routing_fee_msat: Option<u64>
9980-
) -> Result<(), Bolt12SemanticError> {
9981-
self.pay_for_offer_intern(offer, quantity, amount_msats, payer_note, payment_id, None, |invoice_request, nonce| {
9982-
let expiration = StaleExpiration::TimerTicks(1);
9983-
let retryable_invoice_request = RetryableInvoiceRequest {
9984-
invoice_request: invoice_request.clone(),
9985-
nonce,
9986-
};
9987-
self.pending_outbound_payments
9988-
.add_new_awaiting_invoice(
9989-
payment_id, expiration, retry_strategy, max_total_routing_fee_msat,
9990-
Some(retryable_invoice_request)
9991-
)
9992-
.map_err(|_| Bolt12SemanticError::DuplicatePaymentId)
9993-
})
9994-
}
99959865

99969866
fn pay_for_offer_intern<CPP: FnOnce(&InvoiceRequest, Nonce) -> Result<(), Bolt12SemanticError>>(
99979867
&self, offer: &Offer, quantity: Option<u64>, amount_msats: Option<u64>,
@@ -10039,7 +9909,27 @@ where
100399909

100409910
self.enqueue_invoice_request(invoice_request, reply_paths)
100419911
}
9912+
}
100429913

9914+
/// Defines the maximum number of [`OffersMessage`] including different reply paths to be sent
9915+
/// along different paths.
9916+
/// Sending multiple requests increases the chances of successful delivery in case some
9917+
/// paths are unavailable. However, only one invoice for a given [`PaymentId`] will be paid,
9918+
/// even if multiple invoices are received.
9919+
const OFFERS_MESSAGE_REQUEST_LIMIT: usize = 10;
9920+
9921+
impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, MR: Deref, L: Deref> ChannelManager<M, T, ES, NS, SP, F, R, MR, L>
9922+
where
9923+
M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
9924+
T::Target: BroadcasterInterface,
9925+
ES::Target: EntropySource,
9926+
NS::Target: NodeSigner,
9927+
SP::Target: SignerProvider,
9928+
F::Target: FeeEstimator,
9929+
R::Target: Router,
9930+
MR::Target: MessageRouter,
9931+
L::Target: Logger,
9932+
{
100439933
/// Creates a [`Bolt12Invoice`] for a [`Refund`] and enqueues it to be sent via an onion
100449934
/// message.
100459935
///
@@ -12603,6 +12493,8 @@ where
1260312493
pub router: R,
1260412494
/// The [`MessageRouter`] used for constructing [`BlindedMessagePath`]s for [`Offer`]s,
1260512495
/// [`Refund`]s, and any reply paths.
12496+
///
12497+
/// [`Offer`]: crate::offers::offer
1260612498
pub message_router: MR,
1260712499
/// The Logger for use in the ChannelManager and which may be used to log information during
1260812500
/// deserialization.

lightning/src/ln/max_payment_path_len_tests.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -387,7 +387,7 @@ fn bolt12_invoice_too_large_blinded_paths() {
387387

388388
let offer = nodes[1].offers_handler.create_offer_builder(None).unwrap().build().unwrap();
389389
let payment_id = PaymentId([1; 32]);
390-
nodes[0].node.pay_for_offer(&offer, None, Some(5000), None, payment_id, Retry::Attempts(0), None).unwrap();
390+
nodes[0].offers_handler.pay_for_offer(&offer, None, Some(5000), None, payment_id, Retry::Attempts(0), None).unwrap();
391391
let invreq_om = nodes[0].onion_messenger.next_onion_message_for_peer(nodes[1].node.get_our_node_id()).unwrap();
392392
nodes[1].onion_messenger.handle_onion_message(nodes[0].node.get_our_node_id(), &invreq_om);
393393

0 commit comments

Comments
 (0)