Skip to content

Commit 839e69a

Browse files
committed
Move create_refund_builder to flow.rs
Move create_refund_builder documentation to flow.rs
1 parent ea4ebac commit 839e69a

File tree

5 files changed

+243
-216
lines changed

5 files changed

+243
-216
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 57 additions & 192 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ use crate::offers::invoice_request::{InvoiceRequest, InvoiceRequestBuilder};
6969
use crate::offers::nonce::Nonce;
7070
use crate::offers::offer::Offer;
7171
use crate::offers::parse::Bolt12SemanticError;
72-
use crate::offers::refund::{Refund, RefundBuilder};
72+
use crate::offers::refund::Refund;
7373
use crate::offers::signer;
7474
#[cfg(async_payments)]
7575
use crate::offers::static_invoice::StaticInvoice;
@@ -1949,7 +1949,7 @@ where
19491949
/// ```
19501950
/// # use lightning::events::{Event, EventsProvider};
19511951
/// # use lightning::types::payment::PaymentHash;
1952-
/// # use lightning::ln::channelmanager::{AChannelManager, PaymentId, RecentPaymentDetails, RecipientOnionFields, Retry};
1952+
/// # use lightning::ln::channelmanager::{AChannelManager, OffersMessageCommons, PaymentId, RecentPaymentDetails, RecipientOnionFields, Retry};
19531953
/// # use lightning::routing::router::RouteParameters;
19541954
/// #
19551955
/// # fn example<T: AChannelManager>(
@@ -2001,7 +2001,7 @@ where
20012001
///
20022002
/// ```
20032003
/// # use lightning::events::{Event, EventsProvider};
2004-
/// # use lightning::ln::channelmanager::{AChannelManager, PaymentId, RecentPaymentDetails, Retry};
2004+
/// # use lightning::ln::channelmanager::{AChannelManager, OffersMessageCommons, PaymentId, RecentPaymentDetails, Retry};
20052005
/// # use lightning::offers::offer::Offer;
20062006
/// #
20072007
/// # fn example<T: AChannelManager>(
@@ -2049,67 +2049,6 @@ where
20492049
///
20502050
/// ## BOLT 12 Refunds
20512051
///
2052-
/// A [`Refund`] is a request for an invoice to be paid. Like *paying* for an [`Offer`], *creating*
2053-
/// a [`Refund`] involves maintaining state since it represents a future outbound payment.
2054-
/// Therefore, use [`create_refund_builder`] when creating one, otherwise [`ChannelManager`] will
2055-
/// refuse to pay any corresponding [`Bolt12Invoice`] that it receives.
2056-
///
2057-
/// ```
2058-
/// # use core::time::Duration;
2059-
/// # use lightning::events::{Event, EventsProvider};
2060-
/// # use lightning::ln::channelmanager::{AChannelManager, PaymentId, RecentPaymentDetails, Retry};
2061-
/// # use lightning::offers::parse::Bolt12SemanticError;
2062-
/// #
2063-
/// # fn example<T: AChannelManager>(
2064-
/// # channel_manager: T, amount_msats: u64, absolute_expiry: Duration, retry: Retry,
2065-
/// # max_total_routing_fee_msat: Option<u64>
2066-
/// # ) -> Result<(), Bolt12SemanticError> {
2067-
/// # let channel_manager = channel_manager.get_cm();
2068-
/// let payment_id = PaymentId([42; 32]);
2069-
/// let refund = channel_manager
2070-
/// .create_refund_builder(
2071-
/// amount_msats, absolute_expiry, payment_id, retry, max_total_routing_fee_msat
2072-
/// )?
2073-
/// # ;
2074-
/// # // Needed for compiling for c_bindings
2075-
/// # let builder: lightning::offers::refund::RefundBuilder<_> = refund.into();
2076-
/// # let refund = builder
2077-
/// .description("coffee".to_string())
2078-
/// .payer_note("refund for order 1234".to_string())
2079-
/// .build()?;
2080-
/// let bech32_refund = refund.to_string();
2081-
///
2082-
/// // First the payment will be waiting on an invoice
2083-
/// let expected_payment_id = payment_id;
2084-
/// assert!(
2085-
/// channel_manager.list_recent_payments().iter().find(|details| matches!(
2086-
/// details,
2087-
/// RecentPaymentDetails::AwaitingInvoice { payment_id: expected_payment_id }
2088-
/// )).is_some()
2089-
/// );
2090-
///
2091-
/// // Once the invoice is received, a payment will be sent
2092-
/// assert!(
2093-
/// channel_manager.list_recent_payments().iter().find(|details| matches!(
2094-
/// details,
2095-
/// RecentPaymentDetails::Pending { payment_id: expected_payment_id, .. }
2096-
/// )).is_some()
2097-
/// );
2098-
///
2099-
/// // On the event processing thread
2100-
/// channel_manager.process_pending_events(&|event| {
2101-
/// match event {
2102-
/// Event::PaymentSent { payment_id: Some(payment_id), .. } => println!("Paid {}", payment_id),
2103-
/// Event::PaymentFailed { payment_id, .. } => println!("Failed paying {}", payment_id),
2104-
/// // ...
2105-
/// # _ => {},
2106-
/// }
2107-
/// Ok(())
2108-
/// });
2109-
/// # Ok(())
2110-
/// # }
2111-
/// ```
2112-
///
21132052
/// Use [`request_refund_payment`] to send a [`Bolt12Invoice`] for receiving the refund. Similar to
21142053
/// *creating* an [`Offer`], this is stateless as it represents an inbound payment.
21152054
///
@@ -2236,7 +2175,6 @@ where
22362175
/// [`offers`]: crate::offers
22372176
/// [`pay_for_offer`]: Self::pay_for_offer
22382177
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
2239-
/// [`create_refund_builder`]: Self::create_refund_builder
22402178
/// [`request_refund_payment`]: Self::request_refund_payment
22412179
/// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
22422180
/// [`funding_created`]: msgs::FundingCreated
@@ -2735,12 +2673,14 @@ const MAX_NO_CHANNEL_PEERS: usize = 250;
27352673
/// The maximum expiration from the current time where an [`Offer`] or [`Refund`] is considered
27362674
/// short-lived, while anything with a greater expiration is considered long-lived.
27372675
///
2738-
/// Using [`OffersMessageFlow::create_offer_builder`] or [`ChannelManager::create_refund_builder`],
2676+
/// Using [`OffersMessageFlow::create_offer_builder`] or [`OffersMessageFlow::create_refund_builder`],
27392677
/// will included a [`BlindedMessagePath`] created using:
27402678
/// - [`MessageRouter::create_compact_blinded_paths`] when short-lived, and
27412679
/// - [`MessageRouter::create_blinded_paths`] when long-lived.
27422680
///
27432681
/// [`OffersMessageFlow::create_offer_builder`]: crate::offers::flow::OffersMessageFlow::create_offer_builder
2682+
/// [`OffersMessageFlow::create_refund_builder`]: crate::offers::flow::OffersMessageFlow::create_refund_builder
2683+
///
27442684
///
27452685
/// Using compact [`BlindedMessagePath`]s may provide better privacy as the [`MessageRouter`] could select
27462686
/// more hops. However, since they use short channel ids instead of pubkeys, they are more likely to
@@ -3610,45 +3550,6 @@ where
36103550
vec![]
36113551
}
36123552

3613-
/// Returns in an undefined order recent payments that -- if not fulfilled -- have yet to find a
3614-
/// successful path, or have unresolved HTLCs.
3615-
///
3616-
/// This can be useful for payments that may have been prepared, but ultimately not sent, as a
3617-
/// result of a crash. If such a payment exists, is not listed here, and an
3618-
/// [`Event::PaymentSent`] has not been received, you may consider resending the payment.
3619-
///
3620-
/// [`Event::PaymentSent`]: events::Event::PaymentSent
3621-
pub fn list_recent_payments(&self) -> Vec<RecentPaymentDetails> {
3622-
self.pending_outbound_payments.pending_outbound_payments.lock().unwrap().iter()
3623-
.filter_map(|(payment_id, pending_outbound_payment)| match pending_outbound_payment {
3624-
PendingOutboundPayment::AwaitingInvoice { .. }
3625-
| PendingOutboundPayment::AwaitingOffer { .. }
3626-
// InvoiceReceived is an intermediate state and doesn't need to be exposed
3627-
| PendingOutboundPayment::InvoiceReceived { .. } =>
3628-
{
3629-
Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
3630-
},
3631-
PendingOutboundPayment::StaticInvoiceReceived { .. } => {
3632-
Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
3633-
},
3634-
PendingOutboundPayment::Retryable { payment_hash, total_msat, .. } => {
3635-
Some(RecentPaymentDetails::Pending {
3636-
payment_id: *payment_id,
3637-
payment_hash: *payment_hash,
3638-
total_msat: *total_msat,
3639-
})
3640-
},
3641-
PendingOutboundPayment::Abandoned { payment_hash, .. } => {
3642-
Some(RecentPaymentDetails::Abandoned { payment_id: *payment_id, payment_hash: *payment_hash })
3643-
},
3644-
PendingOutboundPayment::Fulfilled { payment_hash, .. } => {
3645-
Some(RecentPaymentDetails::Fulfilled { payment_id: *payment_id, payment_hash: *payment_hash })
3646-
},
3647-
PendingOutboundPayment::Legacy { .. } => None
3648-
})
3649-
.collect()
3650-
}
3651-
36523553
fn close_channel_internal(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, target_feerate_sats_per_1000_weight: Option<u32>, override_shutdown_script: Option<ShutdownScript>) -> Result<(), APIError> {
36533554
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
36543555

@@ -9309,87 +9210,6 @@ impl Default for Bolt11InvoiceParameters {
93099210
}
93109211
}
93119212

9312-
macro_rules! create_refund_builder { ($self: ident, $builder: ty) => {
9313-
/// Creates a [`RefundBuilder`] such that the [`Refund`] it builds is recognized by the
9314-
/// [`ChannelManager`] when handling [`Bolt12Invoice`] messages for the refund.
9315-
///
9316-
/// # Payment
9317-
///
9318-
/// The provided `payment_id` is used to ensure that only one invoice is paid for the refund.
9319-
/// See [Avoiding Duplicate Payments] for other requirements once the payment has been sent.
9320-
///
9321-
/// The builder will have the provided expiration set. Any changes to the expiration on the
9322-
/// returned builder will not be honored by [`ChannelManager`]. For non-`std`, the highest seen
9323-
/// block time minus two hours is used for the current time when determining if the refund has
9324-
/// expired.
9325-
///
9326-
/// To revoke the refund, use [`ChannelManager::abandon_payment`] prior to receiving the
9327-
/// invoice. If abandoned, or an invoice isn't received before expiration, the payment will fail
9328-
/// with an [`Event::PaymentFailed`].
9329-
///
9330-
/// If `max_total_routing_fee_msat` is not specified, The default from
9331-
/// [`RouteParameters::from_payment_params_and_value`] is applied.
9332-
///
9333-
/// # Privacy
9334-
///
9335-
/// Uses [`MessageRouter`] to construct a [`BlindedMessagePath`] for the refund based on the given
9336-
/// `absolute_expiry` according to [`MAX_SHORT_LIVED_RELATIVE_EXPIRY`]. See those docs for
9337-
/// privacy implications as well as those of the parameterized [`Router`], which implements
9338-
/// [`MessageRouter`].
9339-
///
9340-
/// Also, uses a derived payer id in the refund for payer privacy.
9341-
///
9342-
/// # Limitations
9343-
///
9344-
/// Requires a direct connection to an introduction node in the responding
9345-
/// [`Bolt12Invoice::payment_paths`].
9346-
///
9347-
/// # Errors
9348-
///
9349-
/// Errors if:
9350-
/// - a duplicate `payment_id` is provided given the caveats in the aforementioned link,
9351-
/// - `amount_msats` is invalid, or
9352-
/// - the parameterized [`Router`] is unable to create a blinded path for the refund.
9353-
///
9354-
/// [`Refund`]: crate::offers::refund::Refund
9355-
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
9356-
/// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths
9357-
/// [Avoiding Duplicate Payments]: #avoiding-duplicate-payments
9358-
pub fn create_refund_builder(
9359-
&$self, amount_msats: u64, absolute_expiry: Duration, payment_id: PaymentId,
9360-
retry_strategy: Retry, max_total_routing_fee_msat: Option<u64>
9361-
) -> Result<$builder, Bolt12SemanticError> {
9362-
let node_id = $self.get_our_node_id();
9363-
let expanded_key = &$self.inbound_payment_key;
9364-
let entropy = &*$self.entropy_source;
9365-
let secp_ctx = &$self.secp_ctx;
9366-
9367-
let nonce = Nonce::from_entropy_source(entropy);
9368-
let context = OffersContext::OutboundPayment { payment_id, nonce, hmac: None };
9369-
let path = $self.create_blinded_paths_using_absolute_expiry(context, Some(absolute_expiry))
9370-
.and_then(|paths| paths.into_iter().next().ok_or(()))
9371-
.map_err(|_| Bolt12SemanticError::MissingPaths)?;
9372-
9373-
let builder = RefundBuilder::deriving_signing_pubkey(
9374-
node_id, expanded_key, nonce, secp_ctx, amount_msats, payment_id
9375-
)?
9376-
.chain_hash($self.chain_hash)
9377-
.absolute_expiry(absolute_expiry)
9378-
.path(path);
9379-
9380-
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop($self);
9381-
9382-
let expiration = StaleExpiration::AbsoluteTimeout(absolute_expiry);
9383-
$self.pending_outbound_payments
9384-
.add_new_awaiting_invoice(
9385-
payment_id, expiration, retry_strategy, max_total_routing_fee_msat, None,
9386-
)
9387-
.map_err(|_| Bolt12SemanticError::DuplicatePaymentId)?;
9388-
9389-
Ok(builder.into())
9390-
}
9391-
} }
9392-
93939213
/// Functions commonly shared in usage between [`ChannelManager`] & [`OffersMessageFlow`]
93949214
///
93959215
/// [`OffersMessageFlow`]: crate::offers::flow::OffersMessageFlow
@@ -9513,6 +9333,19 @@ pub trait OffersMessageCommons {
95139333
/// [`create_inbound_payment_for_hash`]: ChannelManager::create_inbound_payment_for_hash
95149334
/// [`claim_funds_with_known_custom_tlvs`]: ChannelManager::claim_funds_with_known_custom_tlvs
95159335
fn claim_funds(&self, payment_preimage: PaymentPreimage);
9336+
9337+
/// Add new awaiting invoice
9338+
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<(), ()>;
9339+
9340+
/// Returns in an undefined order recent payments that -- if not fulfilled -- have yet to find a
9341+
/// successful path, or have unresolved HTLCs.
9342+
///
9343+
/// This can be useful for payments that may have been prepared, but ultimately not sent, as a
9344+
/// result of a crash. If such a payment exists, is not listed here, and an
9345+
/// [`Event::PaymentSent`] has not been received, you may consider resending the payment.
9346+
///
9347+
/// [`Event::PaymentSent`]: events::Event::PaymentSent
9348+
fn list_recent_payments(&self) -> Vec<RecentPaymentDetails>;
95169349
}
95179350

95189351
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>
@@ -9684,6 +9517,44 @@ where
96849517
fn claim_funds(&self, payment_preimage: PaymentPreimage) {
96859518
self.claim_payment_internal(payment_preimage, false);
96869519
}
9520+
9521+
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<(), ()> {
9522+
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
9523+
self.pending_outbound_payments.add_new_awaiting_invoice (
9524+
payment_id, expiration, retry_strategy, max_total_routing_fee_msat, retryable_invoice_request,
9525+
)
9526+
}
9527+
9528+
fn list_recent_payments(&self) -> Vec<RecentPaymentDetails> {
9529+
self.pending_outbound_payments.pending_outbound_payments.lock().unwrap().iter()
9530+
.filter_map(|(payment_id, pending_outbound_payment)| match pending_outbound_payment {
9531+
PendingOutboundPayment::AwaitingInvoice { .. }
9532+
| PendingOutboundPayment::AwaitingOffer { .. }
9533+
// InvoiceReceived is an intermediate state and doesn't need to be exposed
9534+
| PendingOutboundPayment::InvoiceReceived { .. } =>
9535+
{
9536+
Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
9537+
},
9538+
PendingOutboundPayment::StaticInvoiceReceived { .. } => {
9539+
Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
9540+
},
9541+
PendingOutboundPayment::Retryable { payment_hash, total_msat, .. } => {
9542+
Some(RecentPaymentDetails::Pending {
9543+
payment_id: *payment_id,
9544+
payment_hash: *payment_hash,
9545+
total_msat: *total_msat,
9546+
})
9547+
},
9548+
PendingOutboundPayment::Abandoned { payment_hash, .. } => {
9549+
Some(RecentPaymentDetails::Abandoned { payment_id: *payment_id, payment_hash: *payment_hash })
9550+
},
9551+
PendingOutboundPayment::Fulfilled { payment_hash, .. } => {
9552+
Some(RecentPaymentDetails::Fulfilled { payment_id: *payment_id, payment_hash: *payment_hash })
9553+
},
9554+
PendingOutboundPayment::Legacy { .. } => None
9555+
})
9556+
.collect()
9557+
}
96879558
}
96889559

96899560
/// Defines the maximum number of [`OffersMessage`] including different reply paths to be sent
@@ -9705,12 +9576,6 @@ where
97059576
MR::Target: MessageRouter,
97069577
L::Target: Logger,
97079578
{
9708-
#[cfg(not(c_bindings))]
9709-
create_refund_builder!(self, RefundBuilder<secp256k1::All>);
9710-
9711-
#[cfg(c_bindings)]
9712-
create_refund_builder!(self, RefundMaybeWithDerivedMetadataBuilder);
9713-
97149579
/// Pays for an [`Offer`] using the given parameters by creating an [`InvoiceRequest`] and
97159580
/// enqueuing it to be sent via an onion message. [`ChannelManager`] will pay the actual
97169581
/// [`Bolt12Invoice`] once it is received.

0 commit comments

Comments
 (0)