Skip to content

Commit 43a3d52

Browse files
committed
Move request_refund_payment to OffersMessageFlow
1 parent 5af7a66 commit 43a3d52

File tree

3 files changed

+203
-169
lines changed

3 files changed

+203
-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, UnauthenticatedReceiveTlvs};
39+
use crate::blinded_path::payment::{BlindedPaymentPath, PaymentConstraints, PaymentContext, UnauthenticatedReceiveTlvs};
4040
use crate::chain;
4141
use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock};
4242
use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator};
@@ -66,11 +66,11 @@ use crate::ln::msgs::{ChannelMessageHandler, CommitmentUpdate, DecodeError, Ligh
6666
#[cfg(test)]
6767
use crate::ln::outbound_payment;
6868
use crate::ln::outbound_payment::{OutboundPayments, PendingOutboundPayment, RetryableInvoiceRequest, SendAlongPathArgs, StaleExpiration};
69-
use crate::offers::invoice::{Bolt12Invoice, DerivedSigningPubkey, InvoiceBuilder, UnsignedBolt12Invoice, DEFAULT_RELATIVE_EXPIRY};
69+
use crate::offers::invoice::Bolt12Invoice;
70+
use crate::offers::invoice::UnsignedBolt12Invoice;
7071
use crate::offers::invoice_request::{InvoiceRequest, InvoiceRequestBuilder};
7172
use crate::offers::nonce::Nonce;
7273
use crate::offers::parse::Bolt12SemanticError;
73-
use crate::offers::refund::Refund;
7474
use crate::offers::signer;
7575
use crate::onion_message::async_payments::{AsyncPaymentsMessage, HeldHtlcAvailable, ReleaseHeldHtlc, AsyncPaymentsMessageHandler};
7676
use crate::onion_message::dns_resolution::HumanReadableName;
@@ -2059,53 +2059,8 @@ where
20592059
///
20602060
/// For more information on creating refunds, see [`create_refund_builder`].
20612061
///
2062-
/// Use [`request_refund_payment`] to send a [`Bolt12Invoice`] for receiving the refund. Similar to
2063-
/// *creating* an [`Offer`], this is stateless as it represents an inbound payment.
2064-
///
2065-
/// ```
2066-
/// # use lightning::events::{Event, EventsProvider, PaymentPurpose};
2067-
/// # use lightning::ln::channelmanager::AChannelManager;
2068-
/// # use lightning::offers::flow::OffersMessageCommons;
2069-
/// # use lightning::offers::refund::Refund;
2070-
/// #
2071-
/// # fn example<T: AChannelManager>(channel_manager: T, refund: &Refund) {
2072-
/// # let channel_manager = channel_manager.get_cm();
2073-
/// let known_payment_hash = match channel_manager.request_refund_payment(refund) {
2074-
/// Ok(invoice) => {
2075-
/// let payment_hash = invoice.payment_hash();
2076-
/// println!("Requesting refund payment {}", payment_hash);
2077-
/// payment_hash
2078-
/// },
2079-
/// Err(e) => panic!("Unable to request payment for refund: {:?}", e),
2080-
/// };
2081-
///
2082-
/// // On the event processing thread
2083-
/// channel_manager.process_pending_events(&|event| {
2084-
/// match event {
2085-
/// Event::PaymentClaimable { payment_hash, purpose, .. } => match purpose {
2086-
/// PaymentPurpose::Bolt12RefundPayment { payment_preimage: Some(payment_preimage), .. } => {
2087-
/// assert_eq!(payment_hash, known_payment_hash);
2088-
/// println!("Claiming payment {}", payment_hash);
2089-
/// channel_manager.claim_funds(payment_preimage);
2090-
/// },
2091-
/// PaymentPurpose::Bolt12RefundPayment { payment_preimage: None, .. } => {
2092-
/// println!("Unknown payment hash: {}", payment_hash);
2093-
/// },
2094-
/// // ...
2095-
/// # _ => {},
2096-
/// },
2097-
/// Event::PaymentClaimed { payment_hash, amount_msat, .. } => {
2098-
/// assert_eq!(payment_hash, known_payment_hash);
2099-
/// println!("Claimed {} msats", amount_msat);
2100-
/// },
2101-
/// // ...
2102-
/// # _ => {},
2103-
/// }
2104-
/// Ok(())
2105-
/// });
2106-
/// # }
2107-
/// ```
2108-
///
2062+
/// For requesting refund payments, see [`request_refund_payment`].
2063+
///
21092064
/// # Persistence
21102065
///
21112066
/// Implements [`Writeable`] to write out all channel state to disk. Implies [`peer_disconnected`] for
@@ -2186,7 +2141,7 @@ where
21862141
/// [`offers`]: crate::offers
21872142
/// [`Offer`]: crate::offers::offer
21882143
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
2189-
/// [`request_refund_payment`]: Self::request_refund_payment
2144+
/// [`request_refund_payment`]: crate::offers::flow::OffersMessageFlow::request_refund_payment
21902145
/// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
21912146
/// [`funding_created`]: msgs::FundingCreated
21922147
/// [`funding_transaction_generated`]: Self::funding_transaction_generated
@@ -2706,6 +2661,7 @@ const MAX_NO_CHANNEL_PEERS: usize = 250;
27062661
/// become invalid over time as channels are closed. Thus, they are only suitable for short-term use.
27072662
///
27082663
/// [`Offer`]: crate::offers::offer
2664+
/// [`Refund`]: crate::offers::refund
27092665
pub const MAX_SHORT_LIVED_RELATIVE_EXPIRY: Duration = Duration::from_secs(60 * 60 * 24);
27102666

27112667
/// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
@@ -9629,7 +9585,7 @@ where
96299585
/// Sending multiple requests increases the chances of successful delivery in case some
96309586
/// paths are unavailable. However, only one invoice for a given [`PaymentId`] will be paid,
96319587
/// even if multiple invoices are received.
9632-
const OFFERS_MESSAGE_REQUEST_LIMIT: usize = 10;
9588+
pub const OFFERS_MESSAGE_REQUEST_LIMIT: usize = 10;
96339589

96349590
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>
96359591
where
@@ -9726,106 +9682,6 @@ where
97269682
Ok(())
97279683
}
97289684

9729-
/// Creates a [`Bolt12Invoice`] for a [`Refund`] and enqueues it to be sent via an onion
9730-
/// message.
9731-
///
9732-
/// The resulting invoice uses a [`PaymentHash`] recognized by the [`ChannelManager`] and a
9733-
/// [`BlindedPaymentPath`] containing the [`PaymentSecret`] needed to reconstruct the
9734-
/// corresponding [`PaymentPreimage`]. It is returned purely for informational purposes.
9735-
///
9736-
/// # Limitations
9737-
///
9738-
/// Requires a direct connection to an introduction node in [`Refund::paths`] or to
9739-
/// [`Refund::payer_signing_pubkey`], if empty. This request is best effort; an invoice will be
9740-
/// sent to each node meeting the aforementioned criteria, but there's no guarantee that they
9741-
/// will be received and no retries will be made.
9742-
///
9743-
/// # Errors
9744-
///
9745-
/// Errors if:
9746-
/// - the refund is for an unsupported chain, or
9747-
/// - the parameterized [`Router`] is unable to create a blinded payment path or reply path for
9748-
/// the invoice.
9749-
///
9750-
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
9751-
pub fn request_refund_payment(
9752-
&self, refund: &Refund
9753-
) -> Result<Bolt12Invoice, Bolt12SemanticError> {
9754-
let expanded_key = &self.inbound_payment_key;
9755-
let entropy = &*self.entropy_source;
9756-
let secp_ctx = &self.secp_ctx;
9757-
9758-
let amount_msats = refund.amount_msats();
9759-
let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
9760-
9761-
if refund.chain() != self.chain_hash {
9762-
return Err(Bolt12SemanticError::UnsupportedChain);
9763-
}
9764-
9765-
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
9766-
9767-
match self.create_inbound_payment(Some(amount_msats), relative_expiry, None) {
9768-
Ok((payment_hash, payment_secret)) => {
9769-
let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
9770-
let payment_paths = self.create_blinded_payment_paths(
9771-
Some(amount_msats), payment_secret, payment_context, relative_expiry,
9772-
)
9773-
.map_err(|_| Bolt12SemanticError::MissingPaths)?;
9774-
9775-
#[cfg(feature = "std")]
9776-
let builder = refund.respond_using_derived_keys(
9777-
payment_paths, payment_hash, expanded_key, entropy
9778-
)?;
9779-
#[cfg(not(feature = "std"))]
9780-
let created_at = Duration::from_secs(
9781-
self.highest_seen_timestamp.load(Ordering::Acquire) as u64
9782-
);
9783-
#[cfg(not(feature = "std"))]
9784-
let builder = refund.respond_using_derived_keys_no_std(
9785-
payment_paths, payment_hash, created_at, expanded_key, entropy
9786-
)?;
9787-
let builder: InvoiceBuilder<DerivedSigningPubkey> = builder.into();
9788-
let invoice = builder.allow_mpp().build_and_sign(secp_ctx)?;
9789-
9790-
let nonce = Nonce::from_entropy_source(entropy);
9791-
let hmac = payment_hash.hmac_for_offer_payment(nonce, expanded_key);
9792-
let context = MessageContext::Offers(OffersContext::InboundPayment {
9793-
payment_hash: invoice.payment_hash(), nonce, hmac
9794-
});
9795-
let reply_paths = self.create_blinded_paths(context)
9796-
.map_err(|_| Bolt12SemanticError::MissingPaths)?;
9797-
9798-
let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
9799-
if refund.paths().is_empty() {
9800-
for reply_path in reply_paths {
9801-
let instructions = MessageSendInstructions::WithSpecifiedReplyPath {
9802-
destination: Destination::Node(refund.payer_signing_pubkey()),
9803-
reply_path,
9804-
};
9805-
let message = OffersMessage::Invoice(invoice.clone());
9806-
pending_offers_messages.push((message, instructions));
9807-
}
9808-
} else {
9809-
reply_paths
9810-
.iter()
9811-
.flat_map(|reply_path| refund.paths().iter().map(move |path| (path, reply_path)))
9812-
.take(OFFERS_MESSAGE_REQUEST_LIMIT)
9813-
.for_each(|(path, reply_path)| {
9814-
let instructions = MessageSendInstructions::WithSpecifiedReplyPath {
9815-
destination: Destination::BlindedPath(path.clone()),
9816-
reply_path: reply_path.clone(),
9817-
};
9818-
let message = OffersMessage::Invoice(invoice.clone());
9819-
pending_offers_messages.push((message, instructions));
9820-
});
9821-
}
9822-
9823-
Ok(invoice)
9824-
},
9825-
Err(()) => Err(Bolt12SemanticError::InvalidAmount),
9826-
}
9827-
}
9828-
98299685
/// Pays for an [`Offer`] looked up using [BIP 353] Human Readable Names resolved by the DNS
98309686
/// resolver(s) at `dns_resolvers` which resolve names according to bLIP 32.
98319687
///
@@ -12422,6 +12278,7 @@ where
1242212278
/// [`Refund`]s, and any reply paths.
1242312279
///
1242412280
/// [`Offer`]: crate::offers::offer
12281+
/// [`Refund`]: crate::offers::refund
1242512282
pub message_router: MR,
1242612283
/// The Logger for use in the ChannelManager and which may be used to log information during
1242712284
/// deserialization.

lightning/src/ln/offers_tests.rs

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

657657
let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
658-
let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();
658+
let expected_invoice = alice.offers_handler.request_refund_payment(&refund).unwrap();
659659

660660
connect_peers(alice, charlie);
661661

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

786786
let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
787-
let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();
787+
let expected_invoice = alice.offers_handler.request_refund_payment(&refund).unwrap();
788788

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

891891
let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
892-
let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();
892+
let expected_invoice = alice.offers_handler.request_refund_payment(&refund).unwrap();
893893

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

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

10491049
connect_peers(david, bob);
10501050

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

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

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

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

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

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

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

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

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

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

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

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

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

20322032
// Alice sends the first invoice
2033-
alice.node.request_refund_payment(&refund).unwrap();
2033+
alice.offers_handler.request_refund_payment(&refund).unwrap();
20342034

20352035
connect_peers(alice, charlie);
20362036

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

20522052
// Alice sends the second invoice
2053-
alice.node.request_refund_payment(&refund).unwrap();
2053+
alice.offers_handler.request_refund_payment(&refund).unwrap();
20542054

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

0 commit comments

Comments
 (0)