Skip to content

Commit 287a88e

Browse files
committed
Move pending_offers_message to flows.rs
1 parent 0c2991f commit 287a88e

File tree

3 files changed

+76
-94
lines changed

3 files changed

+76
-94
lines changed

lightning/src/ln/channelmanager.rs

+9-65
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ use bitcoin::{secp256k1, Sequence, Weight};
3535
use crate::events::FundingInfo;
3636
use crate::blinded_path::message::{AsyncPaymentsContext, MessageForwardNode};
3737
use crate::blinded_path::NodeIdLookUp;
38-
use crate::blinded_path::message::BlindedMessagePath;
3938
use crate::blinded_path::payment::{BlindedPaymentPath, PaymentConstraints, PaymentContext, UnauthenticatedReceiveTlvs};
4039
use crate::chain;
4140
use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock};
@@ -67,13 +66,10 @@ use crate::ln::outbound_payment;
6766
use crate::ln::outbound_payment::{OutboundPayments, PendingOutboundPayment, RetryableInvoiceRequest, SendAlongPathArgs, StaleExpiration};
6867
use crate::offers::invoice::Bolt12Invoice;
6968
use crate::offers::invoice::UnsignedBolt12Invoice;
70-
use crate::offers::invoice_request::InvoiceRequest;
7169
use crate::offers::nonce::Nonce;
72-
use crate::offers::parse::Bolt12SemanticError;
7370
use crate::offers::signer;
7471
use crate::onion_message::async_payments::{AsyncPaymentsMessage, HeldHtlcAvailable, ReleaseHeldHtlc, AsyncPaymentsMessageHandler};
75-
use crate::onion_message::messenger::{DefaultMessageRouter, Destination, MessageRouter, MessageSendInstructions, Responder, ResponseInstruction};
76-
use crate::onion_message::offers::OffersMessage;
72+
use crate::onion_message::messenger::{MessageRouter, MessageSendInstructions, Responder, ResponseInstruction};
7773
use crate::sign::{EntropySource, NodeSigner, Recipient, SignerProvider};
7874
use crate::sign::ecdsa::EcdsaChannelSigner;
7975
use crate::util::config::{UserConfig, ChannelConfig, ChannelConfigUpdate};
@@ -84,14 +80,20 @@ use crate::util::ser::{BigSize, FixedLengthReader, Readable, ReadableArgs, Maybe
8480
use crate::util::ser::TransactionU16LenLimited;
8581
use crate::util::logger::{Level, Logger, WithContext};
8682
use crate::util::errors::APIError;
87-
#[cfg(async_payments)]
88-
use crate::offers::static_invoice::StaticInvoice;
8983

9084
#[cfg(feature = "dnssec")]
9185
use crate::onion_message::dns_resolution::{DNSResolverMessage, OMNameResolver};
9286

87+
#[cfg(async_payments)]
88+
use {
89+
crate::blinded_path::message::{BlindedMessagePath, MessageContext},
90+
crate::offers::static_invoice::StaticInvoice,
91+
crate::onion_message::messenger::Destination,
92+
};
93+
9394
#[cfg(not(c_bindings))]
9495
use {
96+
crate::onion_message::messenger::DefaultMessageRouter,
9597
crate::routing::router::DefaultRouter,
9698
crate::routing::gossip::NetworkGraph,
9799
crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters},
@@ -2169,8 +2171,6 @@ where
21692171
//
21702172
// Lock order tree:
21712173
//
2172-
// `pending_offers_messages`
2173-
//
21742174
// `pending_async_payments_messages`
21752175
//
21762176
// `total_consistency_lock`
@@ -2418,10 +2418,6 @@ where
24182418
event_persist_notifier: Notifier,
24192419
needs_persist_flag: AtomicBool,
24202420

2421-
#[cfg(not(any(test, feature = "_test_utils")))]
2422-
pending_offers_messages: Mutex<Vec<(OffersMessage, MessageSendInstructions)>>,
2423-
#[cfg(any(test, feature = "_test_utils"))]
2424-
pub(crate) pending_offers_messages: Mutex<Vec<(OffersMessage, MessageSendInstructions)>>,
24252421
pending_async_payments_messages: Mutex<Vec<(AsyncPaymentsMessage, MessageSendInstructions)>>,
24262422

24272423
/// Tracks the message events that are to be broadcasted when we are connected to some peer.
@@ -3345,7 +3341,6 @@ where
33453341
needs_persist_flag: AtomicBool::new(false),
33463342
funding_batch_states: Mutex::new(BTreeMap::new()),
33473343

3348-
pending_offers_messages: Mutex::new(Vec::new()),
33493344
pending_async_payments_messages: Mutex::new(Vec::new()),
33503345
pending_broadcast_messages: Mutex::new(Vec::new()),
33513346

@@ -9474,10 +9469,6 @@ where
94749469
MR::Target: MessageRouter,
94759470
L::Target: Logger,
94769471
{
9477-
fn get_pending_offers_messages(&self) -> MutexGuard<'_, Vec<(OffersMessage, MessageSendInstructions)>> {
9478-
self.pending_offers_messages.lock().expect("Mutex is locked by other thread.")
9479-
}
9480-
94819472
#[cfg(feature = "dnssec")]
94829473
fn get_pending_dns_onion_messages(&self) -> MutexGuard<'_, Vec<(DNSResolverMessage, MessageSendInstructions)>> {
94839474
self.pending_dns_onion_messages.lock().expect("Mutex is locked by other thread.")
@@ -9534,10 +9525,6 @@ where
95349525
self.pending_outbound_payments.release_invoice_requests_awaiting_invoice()
95359526
}
95369527

9537-
fn enqueue_invoice_request(&self, invoice_request: InvoiceRequest, reply_paths: Vec<BlindedMessagePath>) -> Result<(), Bolt12SemanticError> {
9538-
self.enqueue_invoice_request(invoice_request, reply_paths)
9539-
}
9540-
95419528
fn get_current_blocktime(&self) -> Duration {
95429529
Duration::from_secs(self.highest_seen_timestamp.load(Ordering::Acquire) as u64)
95439530
}
@@ -9584,13 +9571,6 @@ where
95849571
}
95859572
}
95869573

9587-
/// Defines the maximum number of [`OffersMessage`] including different reply paths to be sent
9588-
/// along different paths.
9589-
/// Sending multiple requests increases the chances of successful delivery in case some
9590-
/// paths are unavailable. However, only one invoice for a given [`PaymentId`] will be paid,
9591-
/// even if multiple invoices are received.
9592-
pub const OFFERS_MESSAGE_REQUEST_LIMIT: usize = 10;
9593-
95949574
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>
95959575
where
95969576
M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
@@ -9603,41 +9583,6 @@ where
96039583
MR::Target: MessageRouter,
96049584
L::Target: Logger,
96059585
{
9606-
fn enqueue_invoice_request(
9607-
&self,
9608-
invoice_request: InvoiceRequest,
9609-
reply_paths: Vec<BlindedMessagePath>,
9610-
) -> Result<(), Bolt12SemanticError> {
9611-
let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
9612-
if !invoice_request.paths().is_empty() {
9613-
reply_paths
9614-
.iter()
9615-
.flat_map(|reply_path| invoice_request.paths().iter().map(move |path| (path, reply_path)))
9616-
.take(OFFERS_MESSAGE_REQUEST_LIMIT)
9617-
.for_each(|(path, reply_path)| {
9618-
let instructions = MessageSendInstructions::WithSpecifiedReplyPath {
9619-
destination: Destination::BlindedPath(path.clone()),
9620-
reply_path: reply_path.clone(),
9621-
};
9622-
let message = OffersMessage::InvoiceRequest(invoice_request.clone());
9623-
pending_offers_messages.push((message, instructions));
9624-
});
9625-
} else if let Some(node_id) = invoice_request.issuer_signing_pubkey() {
9626-
for reply_path in reply_paths {
9627-
let instructions = MessageSendInstructions::WithSpecifiedReplyPath {
9628-
destination: Destination::Node(node_id),
9629-
reply_path,
9630-
};
9631-
let message = OffersMessage::InvoiceRequest(invoice_request.clone());
9632-
pending_offers_messages.push((message, instructions));
9633-
}
9634-
} else {
9635-
debug_assert!(false);
9636-
return Err(Bolt12SemanticError::MissingIssuerSigningPubkey);
9637-
}
9638-
Ok(())
9639-
}
9640-
96419586
#[cfg(async_payments)]
96429587
pub(super) fn duration_since_epoch(&self) -> Duration {
96439588
#[cfg(not(feature = "std"))]
@@ -13158,7 +13103,6 @@ where
1315813103

1315913104
funding_batch_states: Mutex::new(BTreeMap::new()),
1316013105

13161-
pending_offers_messages: Mutex::new(Vec::new()),
1316213106
pending_async_payments_messages: Mutex::new(Vec::new()),
1316313107

1316413108
pending_broadcast_messages: Mutex::new(Vec::new()),

lightning/src/ln/offers_tests.rs

+7-7
Original file line numberDiff line numberDiff line change
@@ -1327,7 +1327,7 @@ fn fails_authentication_when_handling_invoice_request() {
13271327
expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
13281328

13291329
connect_peers(david, alice);
1330-
match &mut david.node.pending_offers_messages.lock().unwrap().first_mut().unwrap().1 {
1330+
match &mut david.offers_handler.pending_offers_messages.lock().unwrap().first_mut().unwrap().1 {
13311331
MessageSendInstructions::WithSpecifiedReplyPath { destination, .. } =>
13321332
*destination = Destination::Node(alice_id),
13331333
_ => panic!(),
@@ -1352,7 +1352,7 @@ fn fails_authentication_when_handling_invoice_request() {
13521352
.unwrap();
13531353
expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
13541354

1355-
match &mut david.node.pending_offers_messages.lock().unwrap().first_mut().unwrap().1 {
1355+
match &mut david.offers_handler.pending_offers_messages.lock().unwrap().first_mut().unwrap().1 {
13561356
MessageSendInstructions::WithSpecifiedReplyPath { destination, .. } =>
13571357
*destination = Destination::BlindedPath(invalid_path),
13581358
_ => panic!(),
@@ -1432,7 +1432,7 @@ fn fails_authentication_when_handling_invoice_for_offer() {
14321432

14331433
// Don't send the invoice request, but grab its reply path to use with a different request.
14341434
let invalid_reply_path = {
1435-
let mut pending_offers_messages = david.node.pending_offers_messages.lock().unwrap();
1435+
let mut pending_offers_messages = david.offers_handler.pending_offers_messages.lock().unwrap();
14361436
let pending_invoice_request = pending_offers_messages.pop().unwrap();
14371437
pending_offers_messages.clear();
14381438
match pending_invoice_request.1 {
@@ -1449,7 +1449,7 @@ fn fails_authentication_when_handling_invoice_for_offer() {
14491449
// Swap out the reply path to force authentication to fail when handling the invoice since it
14501450
// will be sent over the wrong blinded path.
14511451
{
1452-
let mut pending_offers_messages = david.node.pending_offers_messages.lock().unwrap();
1452+
let mut pending_offers_messages = david.offers_handler.pending_offers_messages.lock().unwrap();
14531453
let mut pending_invoice_request = pending_offers_messages.first_mut().unwrap();
14541454
match &mut pending_invoice_request.1 {
14551455
MessageSendInstructions::WithSpecifiedReplyPath { reply_path, .. } =>
@@ -1536,7 +1536,7 @@ fn fails_authentication_when_handling_invoice_for_refund() {
15361536
let expected_invoice = alice.offers_handler.request_refund_payment(&refund).unwrap();
15371537

15381538
connect_peers(david, alice);
1539-
match &mut alice.node.pending_offers_messages.lock().unwrap().first_mut().unwrap().1 {
1539+
match &mut alice.offers_handler.pending_offers_messages.lock().unwrap().first_mut().unwrap().1 {
15401540
MessageSendInstructions::WithSpecifiedReplyPath { destination, .. } =>
15411541
*destination = Destination::Node(david_id),
15421542
_ => panic!(),
@@ -1567,7 +1567,7 @@ fn fails_authentication_when_handling_invoice_for_refund() {
15671567

15681568
let expected_invoice = alice.offers_handler.request_refund_payment(&refund).unwrap();
15691569

1570-
match &mut alice.node.pending_offers_messages.lock().unwrap().first_mut().unwrap().1 {
1570+
match &mut alice.offers_handler.pending_offers_messages.lock().unwrap().first_mut().unwrap().1 {
15711571
MessageSendInstructions::WithSpecifiedReplyPath { destination, .. } =>
15721572
*destination = Destination::BlindedPath(invalid_path),
15731573
_ => panic!(),
@@ -2158,7 +2158,7 @@ fn fails_paying_invoice_with_unknown_required_features() {
21582158
destination: Destination::BlindedPath(reply_path),
21592159
};
21602160
let message = OffersMessage::Invoice(invoice);
2161-
alice.node.pending_offers_messages.lock().unwrap().push((message, instructions));
2161+
alice.offers_handler.pending_offers_messages.lock().unwrap().push((message, instructions));
21622162

21632163
let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
21642164
charlie.onion_messenger.handle_onion_message(alice_id, &onion_message);

lightning/src/offers/flow.rs

+60-22
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,7 @@ use crate::blinded_path::payment::{
2626
BlindedPaymentPath, Bolt12OfferContext, Bolt12RefundContext, PaymentContext,
2727
};
2828
use crate::events::PaymentFailureReason;
29-
use crate::ln::channelmanager::{
30-
Bolt12PaymentError, PaymentId, Verification, OFFERS_MESSAGE_REQUEST_LIMIT,
31-
};
29+
use crate::ln::channelmanager::{Bolt12PaymentError, PaymentId, Verification};
3230
use crate::ln::inbound_payment;
3331
use crate::ln::outbound_payment::{Retry, RetryableInvoiceRequest, StaleExpiration};
3432
use crate::offers::invoice::{
@@ -86,11 +84,6 @@ use {
8684
///
8785
/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
8886
pub trait OffersMessageCommons {
89-
/// Get pending offers messages
90-
fn get_pending_offers_messages(
91-
&self,
92-
) -> MutexGuard<'_, Vec<(OffersMessage, MessageSendInstructions)>>;
93-
9487
#[cfg(feature = "dnssec")]
9588
/// Get pending DNS onion messages
9689
fn get_pending_dns_onion_messages(
@@ -177,11 +170,6 @@ pub trait OffersMessageCommons {
177170
&self,
178171
) -> Vec<(PaymentId, RetryableInvoiceRequest)>;
179172

180-
/// Enqueue invoice request
181-
fn enqueue_invoice_request(
182-
&self, invoice_request: InvoiceRequest, reply_paths: Vec<BlindedMessagePath>,
183-
) -> Result<(), Bolt12SemanticError>;
184-
185173
/// Get the current time determined by highest seen timestamp
186174
fn get_current_blocktime(&self) -> Duration;
187175

@@ -582,6 +570,11 @@ where
582570

583571
message_router: MR,
584572

573+
#[cfg(not(any(test, feature = "_test_utils")))]
574+
pending_offers_messages: Mutex<Vec<(OffersMessage, MessageSendInstructions)>>,
575+
#[cfg(any(test, feature = "_test_utils"))]
576+
pub(crate) pending_offers_messages: Mutex<Vec<(OffersMessage, MessageSendInstructions)>>,
577+
585578
#[cfg(feature = "_test_utils")]
586579
/// In testing, it is useful be able to forge a name -> offer mapping so that we can pay an
587580
/// offer generated in the test.
@@ -614,9 +607,13 @@ where
614607
inbound_payment_key: expanded_inbound_key,
615608
our_network_pubkey,
616609
secp_ctx,
610+
entropy_source,
611+
617612
commons,
613+
618614
message_router,
619-
entropy_source,
615+
616+
pending_offers_messages: Mutex::new(Vec::new()),
620617
#[cfg(feature = "_test_utils")]
621618
testing_dnssec_proof_offer_resolution_override: Mutex::new(new_hash_map()),
622619
logger,
@@ -666,6 +663,13 @@ where
666663
/// [`Refund`]: crate::offers::refund
667664
pub const MAX_SHORT_LIVED_RELATIVE_EXPIRY: Duration = Duration::from_secs(60 * 60 * 24);
668665

666+
/// Defines the maximum number of [`OffersMessage`] including different reply paths to be sent
667+
/// along different paths.
668+
/// Sending multiple requests increases the chances of successful delivery in case some
669+
/// paths are unavailable. However, only one invoice for a given [`PaymentId`] will be paid,
670+
/// even if multiple invoices are received.
671+
pub const OFFERS_MESSAGE_REQUEST_LIMIT: usize = 10;
672+
669673
impl<ES: Deref, OMC: Deref, MR: Deref, L: Deref> OffersMessageFlow<ES, OMC, MR, L>
670674
where
671675
ES::Target: EntropySource,
@@ -744,6 +748,42 @@ where
744748
)
745749
.and_then(|paths| (!paths.is_empty()).then(|| paths).ok_or(()))
746750
}
751+
752+
fn enqueue_invoice_request(
753+
&self, invoice_request: InvoiceRequest, reply_paths: Vec<BlindedMessagePath>,
754+
) -> Result<(), Bolt12SemanticError> {
755+
let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
756+
if !invoice_request.paths().is_empty() {
757+
reply_paths
758+
.iter()
759+
.flat_map(|reply_path| {
760+
invoice_request.paths().iter().map(move |path| (path, reply_path))
761+
})
762+
.take(OFFERS_MESSAGE_REQUEST_LIMIT)
763+
.for_each(|(path, reply_path)| {
764+
let instructions = MessageSendInstructions::WithSpecifiedReplyPath {
765+
destination: Destination::BlindedPath(path.clone()),
766+
reply_path: reply_path.clone(),
767+
};
768+
let message = OffersMessage::InvoiceRequest(invoice_request.clone());
769+
pending_offers_messages.push((message, instructions));
770+
});
771+
} else if let Some(node_id) = invoice_request.issuer_signing_pubkey() {
772+
for reply_path in reply_paths {
773+
let instructions = MessageSendInstructions::WithSpecifiedReplyPath {
774+
destination: Destination::Node(node_id),
775+
reply_path,
776+
};
777+
let message = OffersMessage::InvoiceRequest(invoice_request.clone());
778+
pending_offers_messages.push((message, instructions));
779+
}
780+
} else {
781+
debug_assert!(false);
782+
return Err(Bolt12SemanticError::MissingIssuerSigningPubkey);
783+
}
784+
785+
Ok(())
786+
}
747787
}
748788

749789
impl<ES: Deref, OMC: Deref, MR: Deref, L: Deref> OffersMessageFlow<ES, OMC, MR, L>
@@ -798,7 +838,7 @@ where
798838

799839
create_pending_payment(&invoice_request, nonce)?;
800840

801-
self.commons.enqueue_invoice_request(invoice_request, reply_paths)
841+
self.enqueue_invoice_request(invoice_request, reply_paths)
802842
}
803843
}
804844

@@ -1066,7 +1106,7 @@ where
10661106
});
10671107
match self.create_blinded_paths(context) {
10681108
Ok(reply_paths) => {
1069-
match self.commons.enqueue_invoice_request(invoice_request, reply_paths) {
1109+
match self.enqueue_invoice_request(invoice_request, reply_paths) {
10701110
Ok(_) => {},
10711111
Err(_) => {
10721112
log_warn!(
@@ -1090,7 +1130,7 @@ where
10901130
}
10911131

10921132
fn release_pending_messages(&self) -> Vec<(OffersMessage, MessageSendInstructions)> {
1093-
core::mem::take(&mut self.commons.get_pending_offers_messages())
1133+
core::mem::take(&mut self.pending_offers_messages.lock().unwrap())
10941134
}
10951135
}
10961136

@@ -1330,10 +1370,8 @@ where
13301370
let hmac = signer::hmac_for_held_htlc_available_context(nonce, expanded_key);
13311371
let context =
13321372
MessageContext::AsyncPayments(AsyncPaymentsContext::InboundPayment { nonce, hmac });
1333-
let async_receive_message_paths = self
1334-
.commons
1335-
.create_blinded_paths(context)
1336-
.map_err(|()| Bolt12SemanticError::MissingPaths)?;
1373+
let async_receive_message_paths =
1374+
self.create_blinded_paths(context).map_err(|()| Bolt12SemanticError::MissingPaths)?;
13371375

13381376
StaticInvoiceBuilder::for_offer_using_derived_keys(
13391377
offer,
@@ -1525,7 +1563,7 @@ where
15251563
.create_blinded_paths(context)
15261564
.map_err(|_| Bolt12SemanticError::MissingPaths)?;
15271565

1528-
let mut pending_offers_messages = self.commons.get_pending_offers_messages();
1566+
let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
15291567
if refund.paths().is_empty() {
15301568
for reply_path in reply_paths {
15311569
let instructions = MessageSendInstructions::WithSpecifiedReplyPath {

0 commit comments

Comments
 (0)