Skip to content

Commit 763fd54

Browse files
committed
Move AsyncPaymentsMessageHandler to flow.rs
1 parent 314c513 commit 763fd54

File tree

6 files changed

+183
-129
lines changed

6 files changed

+183
-129
lines changed

lightning-background-processor/src/lib.rs

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1083,6 +1083,7 @@ mod tests {
10831083
IgnoringMessageHandler, MessageHandler, PeerManager, SocketDescriptor,
10841084
};
10851085
use lightning::ln::types::ChannelId;
1086+
use lightning::offers::flow;
10861087
use lightning::onion_message::messenger::{DefaultMessageRouter, OnionMessenger};
10871088
use lightning::routing::gossip::{NetworkGraph, P2PGossipSync};
10881089
use lightning::routing::router::{CandidateRouteHop, DefaultRouter, Path, RouteHop};
@@ -1178,6 +1179,19 @@ mod tests {
11781179
>,
11791180
>;
11801181

1182+
type OffersMessageFlow = flow::OffersMessageFlow<
1183+
Arc<KeysManager>,
1184+
Arc<ChannelManager>,
1185+
Arc<
1186+
DefaultMessageRouter<
1187+
Arc<NetworkGraph<Arc<test_utils::TestLogger>>>,
1188+
Arc<test_utils::TestLogger>,
1189+
Arc<KeysManager>,
1190+
>,
1191+
>,
1192+
Arc<test_utils::TestLogger>,
1193+
>;
1194+
11811195
type OM = OnionMessenger<
11821196
Arc<KeysManager>,
11831197
Arc<KeysManager>,
@@ -1191,7 +1205,7 @@ mod tests {
11911205
>,
11921206
>,
11931207
IgnoringMessageHandler,
1194-
Arc<ChannelManager>,
1208+
Arc<OffersMessageFlow>,
11951209
IgnoringMessageHandler,
11961210
IgnoringMessageHandler,
11971211
>;
@@ -1587,14 +1601,23 @@ mod tests {
15871601
params,
15881602
genesis_block.header.time,
15891603
));
1604+
let offers_message_flow = Arc::new(OffersMessageFlow::new(
1605+
manager.inbound_payment_key,
1606+
manager.get_our_node_id(),
1607+
keys_manager.clone(),
1608+
manager.clone(),
1609+
msg_router.clone(),
1610+
logger.clone(),
1611+
));
1612+
15901613
let messenger = Arc::new(OnionMessenger::new(
15911614
keys_manager.clone(),
15921615
keys_manager.clone(),
15931616
logger.clone(),
15941617
manager.clone(),
15951618
msg_router.clone(),
15961619
IgnoringMessageHandler {},
1597-
manager.clone(),
1620+
offers_message_flow,
15981621
IgnoringMessageHandler {},
15991622
IgnoringMessageHandler {},
16001623
));

lightning/src/ln/async_payments_tests.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -332,7 +332,7 @@ fn ignore_unexpected_static_invoice() {
332332
nodes[0]
333333
.onion_messenger
334334
.handle_onion_message(nodes[1].node.get_our_node_id(), &unexpected_static_invoice_om);
335-
let async_pmts_msgs = AsyncPaymentsMessageHandler::release_pending_messages(nodes[0].node);
335+
let async_pmts_msgs = nodes[0].offers_handler.release_pending_messages();
336336
assert!(async_pmts_msgs.is_empty());
337337
assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
338338

@@ -356,7 +356,7 @@ fn ignore_unexpected_static_invoice() {
356356
nodes[0]
357357
.onion_messenger
358358
.handle_onion_message(nodes[1].node.get_our_node_id(), &static_invoice_om);
359-
let async_pmts_msgs = AsyncPaymentsMessageHandler::release_pending_messages(nodes[0].node);
359+
let async_pmts_msgs = nodes[0].offers_handler.release_pending_messages();
360360
assert!(!async_pmts_msgs.is_empty());
361361
assert!(async_pmts_msgs
362362
.into_iter()
@@ -381,7 +381,7 @@ fn ignore_unexpected_static_invoice() {
381381
nodes[0]
382382
.onion_messenger
383383
.handle_onion_message(nodes[1].node.get_our_node_id(), &dup_static_invoice_om);
384-
let async_pmts_msgs = AsyncPaymentsMessageHandler::release_pending_messages(nodes[0].node);
384+
let async_pmts_msgs = nodes[0].offers_handler.release_pending_messages();
385385
assert!(async_pmts_msgs.is_empty());
386386
}
387387

lightning/src/ln/channelmanager.rs

Lines changed: 19 additions & 108 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ use bitcoin::secp256k1::Secp256k1;
3333
use bitcoin::{secp256k1, Sequence};
3434

3535
use crate::events::FundingInfo;
36-
use crate::blinded_path::message::{AsyncPaymentsContext, MessageContext, OffersContext};
36+
use crate::blinded_path::message::{MessageContext, OffersContext};
3737
use crate::blinded_path::NodeIdLookUp;
3838
use crate::blinded_path::message::{BlindedMessagePath, MessageForwardNode};
3939
use crate::blinded_path::payment::{AsyncBolt12OfferContext, BlindedPaymentPath, Bolt12OfferContext, Bolt12RefundContext, PaymentConstraints, PaymentContext, UnauthenticatedReceiveTlvs};
@@ -74,9 +74,8 @@ use crate::offers::offer::{Offer, OfferBuilder};
7474
use crate::offers::parse::Bolt12SemanticError;
7575
use crate::offers::refund::{Refund, RefundBuilder};
7676
use crate::offers::signer;
77-
use crate::onion_message::async_payments::{AsyncPaymentsMessage, HeldHtlcAvailable, ReleaseHeldHtlc, AsyncPaymentsMessageHandler};
7877
use crate::onion_message::dns_resolution::HumanReadableName;
79-
use crate::onion_message::messenger::{Destination, MessageRouter, Responder, ResponseInstruction, MessageSendInstructions};
78+
use crate::onion_message::messenger::{Destination, MessageRouter, MessageSendInstructions};
8079
use crate::onion_message::offers::OffersMessage;
8180
use crate::sign::{EntropySource, NodeSigner, Recipient, SignerProvider};
8281
use crate::sign::ecdsa::EcdsaChannelSigner;
@@ -88,6 +87,7 @@ use crate::util::ser::{BigSize, FixedLengthReader, Readable, ReadableArgs, Maybe
8887
use crate::util::logger::{Level, Logger, WithContext};
8988
use crate::util::errors::APIError;
9089
#[cfg(async_payments)] use {
90+
crate::blinded_path::message::AsyncPaymentsContext,
9191
crate::offers::offer::Amount,
9292
crate::offers::static_invoice::{DEFAULT_RELATIVE_EXPIRY as STATIC_INVOICE_DEFAULT_RELATIVE_EXPIRY, StaticInvoice, StaticInvoiceBuilder},
9393
};
@@ -2553,7 +2553,10 @@ where
25532553

25542554
our_network_pubkey: PublicKey,
25552555

2556-
pub(super) inbound_payment_key: inbound_payment::ExpandedKey,
2556+
/// The [`ExpandedKey`] for use in encrypting and decrypting inbound payment data.
2557+
///
2558+
/// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
2559+
pub inbound_payment_key: inbound_payment::ExpandedKey,
25572560

25582561
/// LDK puts the [fake scids] that it generates into namespaces, to identify the type of an
25592562
/// incoming payment. To make it harder for a third-party to identify the type of a payment,
@@ -2646,7 +2649,6 @@ where
26462649
pending_offers_messages: Mutex<Vec<(OffersMessage, MessageSendInstructions)>>,
26472650
#[cfg(any(test, feature = "_test_utils"))]
26482651
pub(crate) pending_offers_messages: Mutex<Vec<(OffersMessage, MessageSendInstructions)>>,
2649-
pending_async_payments_messages: Mutex<Vec<(AsyncPaymentsMessage, MessageSendInstructions)>>,
26502652

26512653
/// Tracks the message events that are to be broadcasted when we are connected to some peer.
26522654
pending_broadcast_messages: Mutex<Vec<MessageSendEvent>>,
@@ -3579,7 +3581,6 @@ where
35793581
funding_batch_states: Mutex::new(BTreeMap::new()),
35803582

35813583
pending_offers_messages: Mutex::new(Vec::new()),
3582-
pending_async_payments_messages: Mutex::new(Vec::new()),
35833584
pending_broadcast_messages: Mutex::new(Vec::new()),
35843585

35853586
last_days_feerates: Mutex::new(VecDeque::new()),
@@ -4783,45 +4784,6 @@ where
47834784
res
47844785
}
47854786

4786-
#[cfg(async_payments)]
4787-
fn initiate_async_payment(
4788-
&self, invoice: &StaticInvoice, payment_id: PaymentId
4789-
) -> Result<(), Bolt12PaymentError> {
4790-
4791-
self.handle_static_invoice_received(invoice, payment_id)?;
4792-
4793-
let nonce = Nonce::from_entropy_source(&*self.entropy_source);
4794-
let hmac = payment_id.hmac_for_async_payment(nonce, &self.inbound_payment_key);
4795-
let reply_paths = match self.create_blinded_paths(
4796-
MessageContext::AsyncPayments(
4797-
AsyncPaymentsContext::OutboundPayment { payment_id, nonce, hmac }
4798-
)
4799-
) {
4800-
Ok(paths) => paths,
4801-
Err(()) => {
4802-
self.abandon_payment_with_reason(payment_id, PaymentFailureReason::BlindedPathCreationFailed);
4803-
return Err(Bolt12PaymentError::BlindedPathCreationFailed);
4804-
}
4805-
};
4806-
4807-
let mut pending_async_payments_messages = self.pending_async_payments_messages.lock().unwrap();
4808-
const HTLC_AVAILABLE_LIMIT: usize = 10;
4809-
reply_paths
4810-
.iter()
4811-
.flat_map(|reply_path| invoice.message_paths().iter().map(move |invoice_path| (invoice_path, reply_path)))
4812-
.take(HTLC_AVAILABLE_LIMIT)
4813-
.for_each(|(invoice_path, reply_path)| {
4814-
let instructions = MessageSendInstructions::WithSpecifiedReplyPath {
4815-
destination: Destination::BlindedPath(invoice_path.clone()),
4816-
reply_path: reply_path.clone(),
4817-
};
4818-
let message = AsyncPaymentsMessage::HeldHtlcAvailable(HeldHtlcAvailable {});
4819-
pending_async_payments_messages.push((message, instructions));
4820-
});
4821-
4822-
Ok(())
4823-
}
4824-
48254787
#[cfg(async_payments)]
48264788
fn send_payment_for_static_invoice(
48274789
&self, payment_id: PaymentId
@@ -9999,6 +9961,18 @@ where
99999961
self.pending_outbound_payments.received_offer(payment_id, retryable_invoice_request)
100009962
}
100019963

9964+
#[cfg(async_payments)]
9965+
fn handle_static_invoice_received(
9966+
&self, invoice: &StaticInvoice, payment_id: PaymentId
9967+
) -> Result<(), Bolt12PaymentError> {
9968+
self.handle_static_invoice_received(invoice, payment_id)
9969+
}
9970+
9971+
#[cfg(async_payments)]
9972+
fn send_payment_for_static_invoice(&self, payment_id: PaymentId) -> Result<(), Bolt12PaymentError> {
9973+
self.send_payment_for_static_invoice(payment_id)
9974+
}
9975+
100029976
// ----Temporary Functions----
100039977
// Set of functions temporarily moved to OffersMessageCommons for easier
100049978
// transition of code from ChannelManager to OffersMessageFlow
@@ -10018,13 +9992,6 @@ where
100189992
) -> Result<(), Bolt12SemanticError> {
100199993
self.pay_for_offer_intern(offer, quantity, amount_msats, payer_note, payment_id, human_readable_name, create_pending_payment)
100209994
}
10021-
10022-
#[cfg(async_payments)]
10023-
fn initiate_async_payment(
10024-
&self, invoice: &StaticInvoice, payment_id: PaymentId
10025-
) -> Result<(), Bolt12PaymentError> {
10026-
self.initiate_async_payment(invoice, payment_id)
10027-
}
100289995
}
100299996

100309997
/// Defines the maximum number of [`OffersMessage`] including different reply paths to be sent
@@ -12016,61 +11983,6 @@ where
1201611983
}
1201711984
}
1201811985

12019-
impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, MR: Deref, L: Deref>
12020-
AsyncPaymentsMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, MR, L>
12021-
where
12022-
M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
12023-
T::Target: BroadcasterInterface,
12024-
ES::Target: EntropySource,
12025-
NS::Target: NodeSigner,
12026-
SP::Target: SignerProvider,
12027-
F::Target: FeeEstimator,
12028-
R::Target: Router,
12029-
MR::Target: MessageRouter,
12030-
L::Target: Logger,
12031-
{
12032-
fn handle_held_htlc_available(
12033-
&self, _message: HeldHtlcAvailable, _context: AsyncPaymentsContext,
12034-
_responder: Option<Responder>
12035-
) -> Option<(ReleaseHeldHtlc, ResponseInstruction)> {
12036-
#[cfg(async_payments)] {
12037-
match _context {
12038-
AsyncPaymentsContext::InboundPayment { nonce, hmac, path_absolute_expiry } => {
12039-
if let Err(()) = signer::verify_held_htlc_available_context(
12040-
nonce, hmac, &self.inbound_payment_key
12041-
) { return None }
12042-
if self.duration_since_epoch() > path_absolute_expiry { return None }
12043-
},
12044-
_ => return None
12045-
}
12046-
return _responder.map(|responder| (ReleaseHeldHtlc {}, responder.respond()))
12047-
}
12048-
#[cfg(not(async_payments))]
12049-
return None
12050-
}
12051-
12052-
fn handle_release_held_htlc(&self, _message: ReleaseHeldHtlc, _context: AsyncPaymentsContext) {
12053-
#[cfg(async_payments)] {
12054-
let (payment_id, nonce, hmac) = match _context {
12055-
AsyncPaymentsContext::OutboundPayment { payment_id, hmac, nonce } => {
12056-
(payment_id, nonce, hmac)
12057-
},
12058-
_ => return
12059-
};
12060-
if payment_id.verify_for_async_payment(hmac, nonce, &self.inbound_payment_key).is_err() { return }
12061-
if let Err(e) = self.send_payment_for_static_invoice(payment_id) {
12062-
log_trace!(
12063-
self.logger, "Failed to release held HTLC with payment id {}: {:?}", payment_id, e
12064-
);
12065-
}
12066-
}
12067-
}
12068-
12069-
fn release_pending_messages(&self) -> Vec<(AsyncPaymentsMessage, MessageSendInstructions)> {
12070-
core::mem::take(&mut self.pending_async_payments_messages.lock().unwrap())
12071-
}
12072-
}
12073-
1207411986
impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, MR: Deref, L: Deref>
1207511987
NodeIdLookUp for ChannelManager<M, T, ES, NS, SP, F, R, MR, L>
1207611988
where
@@ -14025,7 +13937,6 @@ where
1402513937
funding_batch_states: Mutex::new(BTreeMap::new()),
1402613938

1402713939
pending_offers_messages: Mutex::new(Vec::new()),
14028-
pending_async_payments_messages: Mutex::new(Vec::new()),
1402913940

1403013941
pending_broadcast_messages: Mutex::new(Vec::new()),
1403113942

lightning/src/ln/functional_test_utils.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -427,7 +427,7 @@ type TestOnionMessenger<'chan_man, 'node_cfg, 'chan_mon_cfg> = OnionMessenger<
427427
&'chan_man TestChannelManager<'node_cfg, 'chan_mon_cfg>,
428428
&'node_cfg test_utils::TestMessageRouter<'chan_mon_cfg>,
429429
Arc<TestOffersMessageFlow<'chan_man, 'node_cfg, 'chan_mon_cfg>>,
430-
&'chan_man TestChannelManager<'node_cfg, 'chan_mon_cfg>,
430+
Arc<TestOffersMessageFlow<'chan_man, 'node_cfg, 'chan_mon_cfg>>,
431431
IgnoringMessageHandler,
432432
IgnoringMessageHandler,
433433
>;
@@ -440,7 +440,7 @@ type TestOnionMessenger<'chan_man, 'node_cfg, 'chan_mon_cfg> = OnionMessenger<
440440
&'chan_man TestChannelManager<'node_cfg, 'chan_mon_cfg>,
441441
&'node_cfg test_utils::TestMessageRouter<'chan_mon_cfg>,
442442
Arc<TestOffersMessageFlow<'chan_man, 'node_cfg, 'chan_mon_cfg>>,
443-
&'chan_man TestChannelManager<'node_cfg, 'chan_mon_cfg>,
443+
Arc<TestOffersMessageFlow<'chan_man, 'node_cfg, 'chan_mon_cfg>>,
444444
Arc<TestOffersMessageFlow<'chan_man, 'node_cfg, 'chan_mon_cfg>>,
445445
IgnoringMessageHandler,
446446
>;
@@ -3372,13 +3372,13 @@ pub fn create_network<'a, 'b: 'a, 'c: 'b>(node_count: usize, cfgs: &'b Vec<NodeC
33723372
#[cfg(feature = "dnssec")]
33733373
let onion_messenger = OnionMessenger::new(
33743374
dedicated_entropy, cfgs[i].keys_manager, cfgs[i].logger, &chan_mgrs[i],
3375-
&cfgs[i].message_router, offers_handler.clone(), &chan_mgrs[i], offers_handler.clone(),
3375+
&cfgs[i].message_router, offers_handler.clone(), offers_handler.clone(), offers_handler.clone(),
33763376
IgnoringMessageHandler {},
33773377
);
33783378
#[cfg(not(feature = "dnssec"))]
33793379
let onion_messenger = OnionMessenger::new(
33803380
dedicated_entropy, cfgs[i].keys_manager, cfgs[i].logger, &chan_mgrs[i],
3381-
&cfgs[i].message_router, offers_handler.clone(), &chan_mgrs[i], IgnoringMessageHandler {},
3381+
&cfgs[i].message_router, offers_handler.clone(), offers_handler.clone(), IgnoringMessageHandler {},
33823382
IgnoringMessageHandler {},
33833383
);
33843384
let gossip_sync = P2PGossipSync::new(cfgs[i].network_graph.as_ref(), None, cfgs[i].logger);

0 commit comments

Comments
 (0)