Skip to content

Commit 2cd728e

Browse files
committed
Move pay_for_offer to OffersMessageFlow
1 parent 6768e36 commit 2cd728e

File tree

4 files changed

+211
-174
lines changed

4 files changed

+211
-174
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 36 additions & 152 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::offers::flow::OffersMessageCommons;
5152
use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
5253
use crate::ln::channel::{self, Channel, ChannelPhase, ChannelError, ChannelUpdateStatus, ShutdownResult, UpdateFulfillCommitFetch, OutboundV1Channel, InboundV1Channel, WithChannelContext, InboundV2Channel, InteractivelyFunded as _};
@@ -66,7 +67,6 @@ use crate::ln::outbound_payment::{OutboundPayments, PendingOutboundPayment, Retr
6667
use crate::offers::invoice::{Bolt12Invoice, DerivedSigningPubkey, InvoiceBuilder, UnsignedBolt12Invoice, DEFAULT_RELATIVE_EXPIRY};
6768
use crate::offers::invoice_request::{InvoiceRequest, InvoiceRequestBuilder};
6869
use crate::offers::nonce::Nonce;
69-
use crate::offers::offer::Offer;
7070
use crate::offers::parse::Bolt12SemanticError;
7171
use crate::offers::refund::Refund;
7272
use crate::offers::signer;
@@ -2004,57 +2004,7 @@ where
20042004
///
20052005
/// For more information on creating offers, see [`create_offer_builder`].
20062006
///
2007-
/// Use [`pay_for_offer`] to initiated payment, which sends an [`InvoiceRequest`] for an [`Offer`]
2008-
/// and pays the [`Bolt12Invoice`] response.
2009-
///
2010-
/// ```
2011-
/// # use lightning::events::{Event, EventsProvider};
2012-
/// # use lightning::ln::channelmanager::{AChannelManager, PaymentId, RecentPaymentDetails, Retry};
2013-
/// # use lightning::offers::flow::OffersMessageCommons;
2014-
/// # use lightning::offers::offer::Offer;
2015-
/// #
2016-
/// # fn example<T: AChannelManager>(
2017-
/// # channel_manager: T, offer: &Offer, quantity: Option<u64>, amount_msats: Option<u64>,
2018-
/// # payer_note: Option<String>, retry: Retry, max_total_routing_fee_msat: Option<u64>
2019-
/// # ) {
2020-
/// # let channel_manager = channel_manager.get_cm();
2021-
/// let payment_id = PaymentId([42; 32]);
2022-
/// match channel_manager.pay_for_offer(
2023-
/// offer, quantity, amount_msats, payer_note, payment_id, retry, max_total_routing_fee_msat
2024-
/// ) {
2025-
/// Ok(()) => println!("Requesting invoice for offer"),
2026-
/// Err(e) => println!("Unable to request invoice for offer: {:?}", e),
2027-
/// }
2028-
///
2029-
/// // First the payment will be waiting on an invoice
2030-
/// let expected_payment_id = payment_id;
2031-
/// assert!(
2032-
/// channel_manager.list_recent_payments().iter().find(|details| matches!(
2033-
/// details,
2034-
/// RecentPaymentDetails::AwaitingInvoice { payment_id: expected_payment_id }
2035-
/// )).is_some()
2036-
/// );
2037-
///
2038-
/// // Once the invoice is received, a payment will be sent
2039-
/// assert!(
2040-
/// channel_manager.list_recent_payments().iter().find(|details| matches!(
2041-
/// details,
2042-
/// RecentPaymentDetails::Pending { payment_id: expected_payment_id, .. }
2043-
/// )).is_some()
2044-
/// );
2045-
///
2046-
/// // On the event processing thread
2047-
/// channel_manager.process_pending_events(&|event| {
2048-
/// match event {
2049-
/// Event::PaymentSent { payment_id: Some(payment_id), .. } => println!("Paid {}", payment_id),
2050-
/// Event::PaymentFailed { payment_id, .. } => println!("Failed paying {}", payment_id),
2051-
/// // ...
2052-
/// # _ => {},
2053-
/// }
2054-
/// Ok(())
2055-
/// });
2056-
/// # }
2057-
/// ```
2007+
/// For details on initiating payments for offers, see [`pay_for_offer`].
20582008
///
20592009
/// ## BOLT 12 Refunds
20602010
///
@@ -2185,7 +2135,7 @@ where
21852135
/// [`claim_funds`]: Self::claim_funds
21862136
/// [`send_payment`]: Self::send_payment
21872137
/// [`offers`]: crate::offers
2188-
/// [`pay_for_offer`]: Self::pay_for_offer
2138+
/// [`Offer`]: crate::offers::offer
21892139
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
21902140
/// [`request_refund_payment`]: Self::request_refund_payment
21912141
/// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
@@ -2196,6 +2146,7 @@ where
21962146
/// [`ChannelUpdate`]: msgs::ChannelUpdate
21972147
/// [`read`]: ReadableArgs::read
21982148
/// [`create_offer_builder`]: crate::offers::flow::OffersMessageFlow::create_offer_builder
2149+
/// [`pay_for_offer`]: crate::offers::flow::OffersMessageFlow::pay_for_offer
21992150
/// [`create_refund_builder`]: crate::offers::flow::OffersMessageFlow::create_refund_builder
22002151
//
22012152
// Lock order:
@@ -2705,6 +2656,8 @@ const MAX_NO_CHANNEL_PEERS: usize = 250;
27052656
/// Using compact [`BlindedMessagePath`]s may provide better privacy as the [`MessageRouter`] could select
27062657
/// more hops. However, since they use short channel ids instead of pubkeys, they are more likely to
27072658
/// become invalid over time as channels are closed. Thus, they are only suitable for short-term use.
2659+
///
2660+
/// [`Offer`]: crate::offers::offer
27082661
pub const MAX_SHORT_LIVED_RELATIVE_EXPIRY: Duration = Duration::from_secs(60 * 60 * 24);
27092662

27102663
/// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
@@ -2713,8 +2666,10 @@ pub const MAX_SHORT_LIVED_RELATIVE_EXPIRY: Duration = Duration::from_secs(60 * 6
27132666
pub enum RecentPaymentDetails {
27142667
/// When an invoice was requested and thus a payment has not yet been sent.
27152668
AwaitingInvoice {
2716-
/// A user-provided identifier in [`ChannelManager::pay_for_offer`] used to uniquely identify a
2669+
/// A user-provided identifier in [`OffersMessageFlow::pay_for_offer`] used to uniquely identify a
27172670
/// payment and ensure idempotency in LDK.
2671+
///
2672+
/// [`OffersMessageFlow::pay_for_offer`]: crate::offers::flow::OffersMessageFlow::pay_for_offer
27182673
payment_id: PaymentId,
27192674
},
27202675
/// When a payment is still being sent and awaiting successful delivery.
@@ -2723,7 +2678,7 @@ pub enum RecentPaymentDetails {
27232678
/// identify a payment and ensure idempotency in LDK.
27242679
///
27252680
/// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
2726-
/// [`pay_for_offer`]: crate::ln::channelmanager::ChannelManager::pay_for_offer
2681+
/// [`pay_for_offer`]: crate::offers::flow::OffersMessageFlow::pay_for_offer
27272682
payment_id: PaymentId,
27282683
/// Hash of the payment that is currently being sent but has yet to be fulfilled or
27292684
/// abandoned.
@@ -2740,7 +2695,7 @@ pub enum RecentPaymentDetails {
27402695
/// identify a payment and ensure idempotency in LDK.
27412696
///
27422697
/// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
2743-
/// [`pay_for_offer`]: crate::ln::channelmanager::ChannelManager::pay_for_offer
2698+
/// [`pay_for_offer`]: crate::offers::flow::OffersMessageFlow::pay_for_offer
27442699
payment_id: PaymentId,
27452700
/// Hash of the payment that was claimed. `None` for serializations of [`ChannelManager`]
27462701
/// made before LDK version 0.0.104.
@@ -2754,7 +2709,7 @@ pub enum RecentPaymentDetails {
27542709
/// identify a payment and ensure idempotency in LDK.
27552710
///
27562711
/// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
2757-
/// [`pay_for_offer`]: crate::ln::channelmanager::ChannelManager::pay_for_offer
2712+
/// [`pay_for_offer`]: crate::offers::flow::OffersMessageFlow::pay_for_offer
27582713
payment_id: PaymentId,
27592714
/// Hash of the payment that we have given up trying to send.
27602715
payment_hash: PaymentHash,
@@ -4585,7 +4540,7 @@ where
45854540
///
45864541
/// # Requested Invoices
45874542
///
4588-
/// In the case of paying a [`Bolt12Invoice`] via [`ChannelManager::pay_for_offer`], abandoning
4543+
/// In the case of paying a [`Bolt12Invoice`] via [`OffersMessageFlow::pay_for_offer`], abandoning
45894544
/// the payment prior to receiving the invoice will result in an [`Event::PaymentFailed`] and
45904545
/// prevent any attempts at paying it once received.
45914546
///
@@ -4595,6 +4550,7 @@ where
45954550
/// [`ChannelManager`], another [`Event::PaymentFailed`] may be generated.
45964551
///
45974552
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
4553+
/// [`OffersMessageFlow::pay_for_offer`]: crate::offers::flow::OffersMessageFlow::pay_for_offer
45984554
pub fn abandon_payment(&self, payment_id: PaymentId) {
45994555
self.abandon_payment_with_reason(payment_id, PaymentFailureReason::UserAbandoned)
46004556
}
@@ -9761,104 +9717,10 @@ where
97619717
}
97629718

97639719
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<(), ()> {
9764-
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
97659720
self.pending_outbound_payments.add_new_awaiting_invoice (
97669721
payment_id, expiration, retry_strategy, max_total_routing_fee_msat, retryable_invoice_request,
97679722
)
97689723
}
9769-
}
9770-
9771-
/// Defines the maximum number of [`OffersMessage`] including different reply paths to be sent
9772-
/// along different paths.
9773-
/// Sending multiple requests increases the chances of successful delivery in case some
9774-
/// paths are unavailable. However, only one invoice for a given [`PaymentId`] will be paid,
9775-
/// even if multiple invoices are received.
9776-
const OFFERS_MESSAGE_REQUEST_LIMIT: usize = 10;
9777-
9778-
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>
9779-
where
9780-
M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
9781-
T::Target: BroadcasterInterface,
9782-
ES::Target: EntropySource,
9783-
NS::Target: NodeSigner,
9784-
SP::Target: SignerProvider,
9785-
F::Target: FeeEstimator,
9786-
R::Target: Router,
9787-
MR::Target: MessageRouter,
9788-
L::Target: Logger,
9789-
{
9790-
/// Pays for an [`Offer`] using the given parameters by creating an [`InvoiceRequest`] and
9791-
/// enqueuing it to be sent via an onion message. [`ChannelManager`] will pay the actual
9792-
/// [`Bolt12Invoice`] once it is received.
9793-
///
9794-
/// Uses [`InvoiceRequestBuilder`] such that the [`InvoiceRequest`] it builds is recognized by
9795-
/// the [`ChannelManager`] when handling a [`Bolt12Invoice`] message in response to the request.
9796-
/// The optional parameters are used in the builder, if `Some`:
9797-
/// - `quantity` for [`InvoiceRequest::quantity`] which must be set if
9798-
/// [`Offer::expects_quantity`] is `true`.
9799-
/// - `amount_msats` if overpaying what is required for the given `quantity` is desired, and
9800-
/// - `payer_note` for [`InvoiceRequest::payer_note`].
9801-
///
9802-
/// If `max_total_routing_fee_msat` is not specified, The default from
9803-
/// [`RouteParameters::from_payment_params_and_value`] is applied.
9804-
///
9805-
/// # Payment
9806-
///
9807-
/// The provided `payment_id` is used to ensure that only one invoice is paid for the request
9808-
/// when received. See [Avoiding Duplicate Payments] for other requirements once the payment has
9809-
/// been sent.
9810-
///
9811-
/// To revoke the request, use [`ChannelManager::abandon_payment`] prior to receiving the
9812-
/// invoice. If abandoned, or an invoice isn't received in a reasonable amount of time, the
9813-
/// payment will fail with an [`Event::PaymentFailed`].
9814-
///
9815-
/// # Privacy
9816-
///
9817-
/// For payer privacy, uses a derived payer id and uses [`MessageRouter::create_blinded_paths`]
9818-
/// to construct a [`BlindedMessagePath`] for the reply path. For further privacy implications, see the
9819-
/// docs of the parameterized [`Router`], which implements [`MessageRouter`].
9820-
///
9821-
/// # Limitations
9822-
///
9823-
/// Requires a direct connection to an introduction node in [`Offer::paths`] or to
9824-
/// [`Offer::issuer_signing_pubkey`], if empty. A similar restriction applies to the responding
9825-
/// [`Bolt12Invoice::payment_paths`].
9826-
///
9827-
/// # Errors
9828-
///
9829-
/// Errors if:
9830-
/// - a duplicate `payment_id` is provided given the caveats in the aforementioned link,
9831-
/// - the provided parameters are invalid for the offer,
9832-
/// - the offer is for an unsupported chain, or
9833-
/// - the parameterized [`Router`] is unable to create a blinded reply path for the invoice
9834-
/// request.
9835-
///
9836-
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
9837-
/// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
9838-
/// [`InvoiceRequest::payer_note`]: crate::offers::invoice_request::InvoiceRequest::payer_note
9839-
/// [`InvoiceRequestBuilder`]: crate::offers::invoice_request::InvoiceRequestBuilder
9840-
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
9841-
/// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths
9842-
/// [Avoiding Duplicate Payments]: #avoiding-duplicate-payments
9843-
pub fn pay_for_offer(
9844-
&self, offer: &Offer, quantity: Option<u64>, amount_msats: Option<u64>,
9845-
payer_note: Option<String>, payment_id: PaymentId, retry_strategy: Retry,
9846-
max_total_routing_fee_msat: Option<u64>
9847-
) -> Result<(), Bolt12SemanticError> {
9848-
self.pay_for_offer_intern(offer, quantity, amount_msats, payer_note, payment_id, None, |invoice_request, nonce| {
9849-
let expiration = StaleExpiration::TimerTicks(1);
9850-
let retryable_invoice_request = RetryableInvoiceRequest {
9851-
invoice_request: invoice_request.clone(),
9852-
nonce,
9853-
};
9854-
self.pending_outbound_payments
9855-
.add_new_awaiting_invoice(
9856-
payment_id, expiration, retry_strategy, max_total_routing_fee_msat,
9857-
Some(retryable_invoice_request)
9858-
)
9859-
.map_err(|_| Bolt12SemanticError::DuplicatePaymentId)
9860-
})
9861-
}
98629724

98639725
fn pay_for_offer_intern<CPP: FnOnce(&InvoiceRequest, Nonce) -> Result<(), Bolt12SemanticError>>(
98649726
&self, offer: &Offer, quantity: Option<u64>, amount_msats: Option<u64>,
@@ -9906,7 +9768,27 @@ where
99069768

99079769
self.enqueue_invoice_request(invoice_request, reply_paths)
99089770
}
9771+
}
9772+
9773+
/// Defines the maximum number of [`OffersMessage`] including different reply paths to be sent
9774+
/// along different paths.
9775+
/// Sending multiple requests increases the chances of successful delivery in case some
9776+
/// paths are unavailable. However, only one invoice for a given [`PaymentId`] will be paid,
9777+
/// even if multiple invoices are received.
9778+
const OFFERS_MESSAGE_REQUEST_LIMIT: usize = 10;
99099779

9780+
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>
9781+
where
9782+
M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
9783+
T::Target: BroadcasterInterface,
9784+
ES::Target: EntropySource,
9785+
NS::Target: NodeSigner,
9786+
SP::Target: SignerProvider,
9787+
F::Target: FeeEstimator,
9788+
R::Target: Router,
9789+
MR::Target: MessageRouter,
9790+
L::Target: Logger,
9791+
{
99109792
/// Creates a [`Bolt12Invoice`] for a [`Refund`] and enqueues it to be sent via an onion
99119793
/// message.
99129794
///
@@ -12470,6 +12352,8 @@ where
1247012352
pub router: R,
1247112353
/// The [`MessageRouter`] used for constructing [`BlindedMessagePath`]s for [`Offer`]s,
1247212354
/// [`Refund`]s, and any reply paths.
12355+
///
12356+
/// [`Offer`]: crate::offers::offer
1247312357
pub message_router: MR,
1247412358
/// The Logger for use in the ChannelManager and which may be used to log information during
1247512359
/// 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)