Skip to content

Commit 52efad1

Browse files
committed
Move request_refund_payment to OffersMessageFlow
1 parent 2cd728e commit 52efad1

File tree

3 files changed

+201
-169
lines changed

3 files changed

+201
-169
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 9 additions & 152 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ use crate::events::FundingInfo;
3636
use crate::blinded_path::message::{AsyncPaymentsContext, MessageContext, OffersContext};
3737
use crate::blinded_path::NodeIdLookUp;
3838
use crate::blinded_path::message::{BlindedMessagePath, MessageForwardNode};
39-
use crate::blinded_path::payment::{BlindedPaymentPath, Bolt12RefundContext, PaymentConstraints, PaymentContext, ReceiveTlvs};
39+
use crate::blinded_path::payment::{BlindedPaymentPath, PaymentConstraints, PaymentContext, ReceiveTlvs};
4040
use crate::chain;
4141
use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock};
4242
use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator};
@@ -64,11 +64,11 @@ use crate::ln::msgs::{ChannelMessageHandler, CommitmentUpdate, DecodeError, Ligh
6464
#[cfg(test)]
6565
use crate::ln::outbound_payment;
6666
use crate::ln::outbound_payment::{OutboundPayments, PendingOutboundPayment, RetryableInvoiceRequest, SendAlongPathArgs, StaleExpiration};
67-
use crate::offers::invoice::{Bolt12Invoice, DerivedSigningPubkey, InvoiceBuilder, UnsignedBolt12Invoice, DEFAULT_RELATIVE_EXPIRY};
67+
use crate::offers::invoice::Bolt12Invoice;
68+
use crate::offers::invoice::UnsignedBolt12Invoice;
6869
use crate::offers::invoice_request::{InvoiceRequest, InvoiceRequestBuilder};
6970
use crate::offers::nonce::Nonce;
7071
use crate::offers::parse::Bolt12SemanticError;
71-
use crate::offers::refund::Refund;
7272
use crate::offers::signer;
7373
#[cfg(async_payments)]
7474
use crate::offers::static_invoice::StaticInvoice;
@@ -2010,53 +2010,8 @@ where
20102010
///
20112011
/// For more information on creating refunds, see [`create_refund_builder`].
20122012
///
2013-
/// Use [`request_refund_payment`] to send a [`Bolt12Invoice`] for receiving the refund. Similar to
2014-
/// *creating* an [`Offer`], this is stateless as it represents an inbound payment.
2015-
///
2016-
/// ```
2017-
/// # use lightning::events::{Event, EventsProvider, PaymentPurpose};
2018-
/// # use lightning::ln::channelmanager::AChannelManager;
2019-
/// # use lightning::offers::flow::OffersMessageCommons;
2020-
/// # use lightning::offers::refund::Refund;
2021-
/// #
2022-
/// # fn example<T: AChannelManager>(channel_manager: T, refund: &Refund) {
2023-
/// # let channel_manager = channel_manager.get_cm();
2024-
/// let known_payment_hash = match channel_manager.request_refund_payment(refund) {
2025-
/// Ok(invoice) => {
2026-
/// let payment_hash = invoice.payment_hash();
2027-
/// println!("Requesting refund payment {}", payment_hash);
2028-
/// payment_hash
2029-
/// },
2030-
/// Err(e) => panic!("Unable to request payment for refund: {:?}", e),
2031-
/// };
2032-
///
2033-
/// // On the event processing thread
2034-
/// channel_manager.process_pending_events(&|event| {
2035-
/// match event {
2036-
/// Event::PaymentClaimable { payment_hash, purpose, .. } => match purpose {
2037-
/// PaymentPurpose::Bolt12RefundPayment { payment_preimage: Some(payment_preimage), .. } => {
2038-
/// assert_eq!(payment_hash, known_payment_hash);
2039-
/// println!("Claiming payment {}", payment_hash);
2040-
/// channel_manager.claim_funds(payment_preimage);
2041-
/// },
2042-
/// PaymentPurpose::Bolt12RefundPayment { payment_preimage: None, .. } => {
2043-
/// println!("Unknown payment hash: {}", payment_hash);
2044-
/// },
2045-
/// // ...
2046-
/// # _ => {},
2047-
/// },
2048-
/// Event::PaymentClaimed { payment_hash, amount_msat, .. } => {
2049-
/// assert_eq!(payment_hash, known_payment_hash);
2050-
/// println!("Claimed {} msats", amount_msat);
2051-
/// },
2052-
/// // ...
2053-
/// # _ => {},
2054-
/// }
2055-
/// Ok(())
2056-
/// });
2057-
/// # }
2058-
/// ```
2059-
///
2013+
/// For requesting refund payments, see [`request_refund_payment`].
2014+
///
20602015
/// # Persistence
20612016
///
20622017
/// Implements [`Writeable`] to write out all channel state to disk. Implies [`peer_disconnected`] for
@@ -2137,7 +2092,7 @@ where
21372092
/// [`offers`]: crate::offers
21382093
/// [`Offer`]: crate::offers::offer
21392094
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
2140-
/// [`request_refund_payment`]: Self::request_refund_payment
2095+
/// [`request_refund_payment`]: crate::offers::flow::OffersMessageFlow::request_refund_payment
21412096
/// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
21422097
/// [`funding_created`]: msgs::FundingCreated
21432098
/// [`funding_transaction_generated`]: Self::funding_transaction_generated
@@ -2658,6 +2613,7 @@ const MAX_NO_CHANNEL_PEERS: usize = 250;
26582613
/// become invalid over time as channels are closed. Thus, they are only suitable for short-term use.
26592614
///
26602615
/// [`Offer`]: crate::offers::offer
2616+
/// [`Refund`]: crate::offers::refund
26612617
pub const MAX_SHORT_LIVED_RELATIVE_EXPIRY: Duration = Duration::from_secs(60 * 60 * 24);
26622618

26632619
/// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
@@ -9775,7 +9731,7 @@ where
97759731
/// Sending multiple requests increases the chances of successful delivery in case some
97769732
/// paths are unavailable. However, only one invoice for a given [`PaymentId`] will be paid,
97779733
/// even if multiple invoices are received.
9778-
const OFFERS_MESSAGE_REQUEST_LIMIT: usize = 10;
9734+
pub const OFFERS_MESSAGE_REQUEST_LIMIT: usize = 10;
97799735

97809736
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>
97819737
where
@@ -9789,106 +9745,6 @@ where
97899745
MR::Target: MessageRouter,
97909746
L::Target: Logger,
97919747
{
9792-
/// Creates a [`Bolt12Invoice`] for a [`Refund`] and enqueues it to be sent via an onion
9793-
/// message.
9794-
///
9795-
/// The resulting invoice uses a [`PaymentHash`] recognized by the [`ChannelManager`] and a
9796-
/// [`BlindedPaymentPath`] containing the [`PaymentSecret`] needed to reconstruct the
9797-
/// corresponding [`PaymentPreimage`]. It is returned purely for informational purposes.
9798-
///
9799-
/// # Limitations
9800-
///
9801-
/// Requires a direct connection to an introduction node in [`Refund::paths`] or to
9802-
/// [`Refund::payer_signing_pubkey`], if empty. This request is best effort; an invoice will be
9803-
/// sent to each node meeting the aforementioned criteria, but there's no guarantee that they
9804-
/// will be received and no retries will be made.
9805-
///
9806-
/// # Errors
9807-
///
9808-
/// Errors if:
9809-
/// - the refund is for an unsupported chain, or
9810-
/// - the parameterized [`Router`] is unable to create a blinded payment path or reply path for
9811-
/// the invoice.
9812-
///
9813-
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
9814-
pub fn request_refund_payment(
9815-
&self, refund: &Refund
9816-
) -> Result<Bolt12Invoice, Bolt12SemanticError> {
9817-
let expanded_key = &self.inbound_payment_key;
9818-
let entropy = &*self.entropy_source;
9819-
let secp_ctx = &self.secp_ctx;
9820-
9821-
let amount_msats = refund.amount_msats();
9822-
let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
9823-
9824-
if refund.chain() != self.chain_hash {
9825-
return Err(Bolt12SemanticError::UnsupportedChain);
9826-
}
9827-
9828-
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
9829-
9830-
match self.create_inbound_payment(Some(amount_msats), relative_expiry, None) {
9831-
Ok((payment_hash, payment_secret)) => {
9832-
let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
9833-
let payment_paths = self.create_blinded_payment_paths(
9834-
amount_msats, payment_secret, payment_context
9835-
)
9836-
.map_err(|_| Bolt12SemanticError::MissingPaths)?;
9837-
9838-
#[cfg(feature = "std")]
9839-
let builder = refund.respond_using_derived_keys(
9840-
payment_paths, payment_hash, expanded_key, entropy
9841-
)?;
9842-
#[cfg(not(feature = "std"))]
9843-
let created_at = Duration::from_secs(
9844-
self.highest_seen_timestamp.load(Ordering::Acquire) as u64
9845-
);
9846-
#[cfg(not(feature = "std"))]
9847-
let builder = refund.respond_using_derived_keys_no_std(
9848-
payment_paths, payment_hash, created_at, expanded_key, entropy
9849-
)?;
9850-
let builder: InvoiceBuilder<DerivedSigningPubkey> = builder.into();
9851-
let invoice = builder.allow_mpp().build_and_sign(secp_ctx)?;
9852-
9853-
let nonce = Nonce::from_entropy_source(entropy);
9854-
let hmac = payment_hash.hmac_for_offer_payment(nonce, expanded_key);
9855-
let context = MessageContext::Offers(OffersContext::InboundPayment {
9856-
payment_hash: invoice.payment_hash(), nonce, hmac
9857-
});
9858-
let reply_paths = self.create_blinded_paths(context)
9859-
.map_err(|_| Bolt12SemanticError::MissingPaths)?;
9860-
9861-
let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
9862-
if refund.paths().is_empty() {
9863-
for reply_path in reply_paths {
9864-
let instructions = MessageSendInstructions::WithSpecifiedReplyPath {
9865-
destination: Destination::Node(refund.payer_signing_pubkey()),
9866-
reply_path,
9867-
};
9868-
let message = OffersMessage::Invoice(invoice.clone());
9869-
pending_offers_messages.push((message, instructions));
9870-
}
9871-
} else {
9872-
reply_paths
9873-
.iter()
9874-
.flat_map(|reply_path| refund.paths().iter().map(move |path| (path, reply_path)))
9875-
.take(OFFERS_MESSAGE_REQUEST_LIMIT)
9876-
.for_each(|(path, reply_path)| {
9877-
let instructions = MessageSendInstructions::WithSpecifiedReplyPath {
9878-
destination: Destination::BlindedPath(path.clone()),
9879-
reply_path: reply_path.clone(),
9880-
};
9881-
let message = OffersMessage::Invoice(invoice.clone());
9882-
pending_offers_messages.push((message, instructions));
9883-
});
9884-
}
9885-
9886-
Ok(invoice)
9887-
},
9888-
Err(()) => Err(Bolt12SemanticError::InvalidAmount),
9889-
}
9890-
}
9891-
98929748
/// Pays for an [`Offer`] looked up using [BIP 353] Human Readable Names resolved by the DNS
98939749
/// resolver(s) at `dns_resolvers` which resolve names according to bLIP 32.
98949750
///
@@ -12354,6 +12210,7 @@ where
1235412210
/// [`Refund`]s, and any reply paths.
1235512211
///
1235612212
/// [`Offer`]: crate::offers::offer
12213+
/// [`Refund`]: crate::offers::refund
1235712214
pub message_router: MR,
1235812215
/// The Logger for use in the ChannelManager and which may be used to log information during
1235912216
/// deserialization.

lightning/src/ln/offers_tests.rs

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -654,7 +654,7 @@ fn creates_and_pays_for_refund_using_two_hop_blinded_path() {
654654
expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
655655

656656
let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
657-
let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();
657+
let expected_invoice = alice.offers_handler.request_refund_payment(&refund).unwrap();
658658

659659
connect_peers(alice, charlie);
660660

@@ -783,7 +783,7 @@ fn creates_and_pays_for_refund_using_one_hop_blinded_path() {
783783
expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);
784784

785785
let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
786-
let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();
786+
let expected_invoice = alice.offers_handler.request_refund_payment(&refund).unwrap();
787787

788788
let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
789789
bob.onion_messenger.handle_onion_message(alice_id, &onion_message);
@@ -888,7 +888,7 @@ fn pays_for_refund_without_blinded_paths() {
888888
expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);
889889

890890
let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
891-
let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();
891+
let expected_invoice = alice.offers_handler.request_refund_payment(&refund).unwrap();
892892

893893
let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
894894
bob.onion_messenger.handle_onion_message(alice_id, &onion_message);
@@ -1043,7 +1043,7 @@ fn send_invoice_for_refund_with_distinct_reply_path() {
10431043
}
10441044
expect_recent_payment!(alice, RecentPaymentDetails::AwaitingInvoice, payment_id);
10451045

1046-
let _expected_invoice = david.node.request_refund_payment(&refund).unwrap();
1046+
let _expected_invoice = david.offers_handler.request_refund_payment(&refund).unwrap();
10471047

10481048
connect_peers(david, bob);
10491049

@@ -1247,7 +1247,7 @@ fn creates_refund_with_blinded_path_using_unannounced_introduction_node() {
12471247
}
12481248
expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);
12491249

1250-
let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();
1250+
let expected_invoice = alice.offers_handler.request_refund_payment(&refund).unwrap();
12511251

12521252
let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
12531253

@@ -1531,7 +1531,7 @@ fn fails_authentication_when_handling_invoice_for_refund() {
15311531
expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
15321532

15331533
// Send the invoice directly to David instead of using a blinded path.
1534-
let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();
1534+
let expected_invoice = alice.offers_handler.request_refund_payment(&refund).unwrap();
15351535

15361536
connect_peers(david, alice);
15371537
match &mut alice.node.pending_offers_messages.lock().unwrap().first_mut().unwrap().1 {
@@ -1563,7 +1563,7 @@ fn fails_authentication_when_handling_invoice_for_refund() {
15631563
assert_eq!(path.introduction_node(), &IntroductionNode::NodeId(charlie_id));
15641564
}
15651565

1566-
let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();
1566+
let expected_invoice = alice.offers_handler.request_refund_payment(&refund).unwrap();
15671567

15681568
match &mut alice.node.pending_offers_messages.lock().unwrap().first_mut().unwrap().1 {
15691569
MessageSendInstructions::WithSpecifiedReplyPath { destination, .. } =>
@@ -1696,7 +1696,7 @@ fn fails_creating_refund_or_sending_invoice_without_connected_peers() {
16961696
.unwrap()
16971697
.build().unwrap();
16981698

1699-
match alice.node.request_refund_payment(&refund) {
1699+
match alice.offers_handler.request_refund_payment(&refund) {
17001700
Ok(_) => panic!("Expected error"),
17011701
Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
17021702
}
@@ -1705,7 +1705,7 @@ fn fails_creating_refund_or_sending_invoice_without_connected_peers() {
17051705
args.send_channel_ready = (true, true);
17061706
reconnect_nodes(args);
17071707

1708-
assert!(alice.node.request_refund_payment(&refund).is_ok());
1708+
assert!(alice.offers_handler.request_refund_payment(&refund).is_ok());
17091709
}
17101710

17111711
/// Fails creating an invoice request when the offer contains an unsupported chain.
@@ -1755,7 +1755,7 @@ fn fails_sending_invoice_with_unsupported_chain_for_refund() {
17551755
.chain(Network::Signet)
17561756
.build().unwrap();
17571757

1758-
match alice.node.request_refund_payment(&refund) {
1758+
match alice.offers_handler.request_refund_payment(&refund) {
17591759
Ok(_) => panic!("Expected error"),
17601760
Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
17611761
}
@@ -1978,7 +1978,7 @@ fn fails_sending_invoice_without_blinded_payment_paths_for_refund() {
19781978
.unwrap()
19791979
.build().unwrap();
19801980

1981-
match alice.node.request_refund_payment(&refund) {
1981+
match alice.offers_handler.request_refund_payment(&refund) {
19821982
Ok(_) => panic!("Expected error"),
19831983
Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
19841984
}
@@ -2029,7 +2029,7 @@ fn fails_paying_invoice_more_than_once() {
20292029
expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
20302030

20312031
// Alice sends the first invoice
2032-
alice.node.request_refund_payment(&refund).unwrap();
2032+
alice.offers_handler.request_refund_payment(&refund).unwrap();
20332033

20342034
connect_peers(alice, charlie);
20352035

@@ -2049,7 +2049,7 @@ fn fails_paying_invoice_more_than_once() {
20492049
disconnect_peers(alice, &[charlie]);
20502050

20512051
// Alice sends the second invoice
2052-
alice.node.request_refund_payment(&refund).unwrap();
2052+
alice.offers_handler.request_refund_payment(&refund).unwrap();
20532053

20542054
connect_peers(alice, charlie);
20552055
connect_peers(david, bob);

0 commit comments

Comments
 (0)