Skip to content

Commit 2556bba

Browse files
committed
Enqueue onion messages in handlers
When constructing onion messages to send initially (opposed to replying to one from a handler), the user must construct an OnionMessagePath first before calling OnionMessener::send_onion_message. Additionally, having a reference to OnionMessener isn't always desirable. For instance, in an upcoming commit, ChannelManager will implement OffersMessageHandler, which OnionMessenger needs a reference to. If ChannelManager had a reference to OnionMessenger, too, there would be a dependency cycle. Instead, modify OffersMessageHandler and CustomOnionMessageHandler's interfaces to include a method for releasing pending onion messages. That way, ChannelManager may, for instance, construct and enqueue an InvoiceRequest for sending without needing a reference to OnionMessenger. Additionally, OnionMessenger has responsibility for path finding just as it does when replying to messages from a handler. It performs this when extracting messages from the handlers before returning the next message to send to a peer.
1 parent 9b379f3 commit 2556bba

File tree

6 files changed

+77
-7
lines changed

6 files changed

+77
-7
lines changed

fuzz/src/onion_message.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use lightning::offers::invoice_request::UnsignedInvoiceRequest;
1414
use lightning::util::test_channel_signer::TestChannelSigner;
1515
use lightning::util::logger::Logger;
1616
use lightning::util::ser::{Readable, Writeable, Writer};
17-
use lightning::onion_message::{CustomOnionMessageHandler, Destination, MessageRouter, OffersMessage, OffersMessageHandler, OnionMessageContents, OnionMessagePath, OnionMessenger};
17+
use lightning::onion_message::{CustomOnionMessageHandler, Destination, MessageRouter, OffersMessage, OffersMessageHandler, OnionMessageContents, OnionMessagePath, OnionMessenger, PendingOnionMessage};
1818

1919
use crate::utils::test_logger;
2020

@@ -108,6 +108,9 @@ impl CustomOnionMessageHandler for TestCustomMessageHandler {
108108
buffer.read_to_end(&mut buf)?;
109109
return Ok(Some(TestCustomMessage {}))
110110
}
111+
fn release_pending_custom_messages(&self) -> Vec<PendingOnionMessage<Self::CustomMessage>> {
112+
vec![]
113+
}
111114
}
112115

113116
pub struct VecWriter(pub Vec<u8>);

lightning/src/ln/peer_handler.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ use crate::util::ser::{VecWriter, Writeable, Writer};
2929
use crate::ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
3030
use crate::ln::wire;
3131
use crate::ln::wire::{Encode, Type};
32-
use crate::onion_message::{CustomOnionMessageHandler, OffersMessage, OffersMessageHandler, OnionMessageContents, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
32+
use crate::onion_message::{CustomOnionMessageHandler, OffersMessage, OffersMessageHandler, OnionMessageContents, PendingOnionMessage, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
3333
use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, NodeAlias};
3434
use crate::util::atomic_counter::AtomicCounter;
3535
use crate::util::logger::Logger;
@@ -129,6 +129,9 @@ impl CustomOnionMessageHandler for IgnoringMessageHandler {
129129
fn read_custom_message<R: io::Read>(&self, _msg_type: u64, _buffer: &mut R) -> Result<Option<Infallible>, msgs::DecodeError> where Self: Sized {
130130
Ok(None)
131131
}
132+
fn release_pending_custom_messages(&self) -> Vec<PendingOnionMessage<Infallible>> {
133+
vec![]
134+
}
132135
}
133136

134137
impl OnionMessageContents for Infallible {

lightning/src/onion_message/functional_tests.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use crate::ln::msgs::{self, DecodeError, OnionMessageHandler};
1515
use crate::sign::{NodeSigner, Recipient};
1616
use crate::util::ser::{FixedLengthReader, LengthReadable, Writeable, Writer};
1717
use crate::util::test_utils;
18-
use super::{CustomOnionMessageHandler, Destination, MessageRouter, OffersMessage, OffersMessageHandler, OnionMessageContents, OnionMessagePath, OnionMessenger, SendError};
18+
use super::{CustomOnionMessageHandler, Destination, MessageRouter, OffersMessage, OffersMessageHandler, OnionMessageContents, OnionMessagePath, OnionMessenger, PendingOnionMessage, SendError};
1919

2020
use bitcoin::network::constants::Network;
2121
use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
@@ -148,6 +148,9 @@ impl CustomOnionMessageHandler for TestCustomMessageHandler {
148148
_ => Ok(None),
149149
}
150150
}
151+
fn release_pending_custom_messages(&self) -> Vec<PendingOnionMessage<Self::CustomMessage>> {
152+
vec![]
153+
}
151154
}
152155

153156
fn create_nodes(num_messengers: u8) -> Vec<MessengerNode> {

lightning/src/onion_message/messenger.rs

Lines changed: 53 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,28 @@ where
154154
custom_handler: CMH,
155155
}
156156

157+
/// An [`OnionMessage`] for [`OnionMessenger`] to send.
158+
///
159+
/// These are obtained when released from [`OnionMessenger`]'s handlers after which they are
160+
/// enqueued for sending.
161+
///
162+
/// [`OnionMessage`]: crate::ln::msgs::OnionMessage
163+
pub struct PendingOnionMessage<T> {
164+
/// The message contents to send in an [`OnionMessage`].
165+
///
166+
/// [`OnionMessage`]: crate::ln::msgs::OnionMessage
167+
pub contents: T,
168+
169+
/// The destination of the message.
170+
pub destination: Destination,
171+
172+
/// A reply path to include in the [`OnionMessage`] for a response.
173+
///
174+
/// [`OnionMessage`]: crate::ln::msgs::OnionMessage
175+
pub reply_path: Option<BlindedPath>,
176+
177+
}
178+
157179
/// A trait defining behavior for routing an [`OnionMessage`].
158180
///
159181
/// [`OnionMessage`]: msgs::OnionMessage
@@ -251,11 +273,19 @@ pub trait CustomOnionMessageHandler {
251273
type CustomMessage: OnionMessageContents;
252274

253275
/// Called with the custom message that was received, returning a response to send, if any.
276+
///
277+
/// The returned [`Self::CustomMessage`], if any, is enqueued to be sent by [`OnionMessenger`].
254278
fn handle_custom_message(&self, msg: Self::CustomMessage) -> Option<Self::CustomMessage>;
255279

256280
/// Read a custom message of type `message_type` from `buffer`, returning `Ok(None)` if the
257281
/// message type is unknown.
258282
fn read_custom_message<R: io::Read>(&self, message_type: u64, buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError>;
283+
284+
/// Releases any [`Self::CustomMessage`]s that need to be sent.
285+
///
286+
/// Typically, this is used for messages initiating a message flow rather than in response to
287+
/// another message. The latter should use the return value of [`Self::handle_custom_message`].
288+
fn release_pending_custom_messages(&self) -> Vec<PendingOnionMessage<Self::CustomMessage>>;
259289
}
260290

261291
impl<ES: Deref, NS: Deref, L: Deref, MR: Deref, OMH: Deref, CMH: Deref>
@@ -353,7 +383,7 @@ where
353383
match reply_path {
354384
Some(reply_path) => {
355385
self.find_path_and_enqueue_onion_message(
356-
response, Destination::BlindedPath(reply_path), log_suffix
386+
response, Destination::BlindedPath(reply_path), None, log_suffix
357387
);
358388
},
359389
None => {
@@ -364,7 +394,8 @@ where
364394
}
365395

366396
fn find_path_and_enqueue_onion_message<T: OnionMessageContents>(
367-
&self, contents: T, destination: Destination, log_suffix: fmt::Arguments
397+
&self, contents: T, destination: Destination, reply_path: Option<BlindedPath>,
398+
log_suffix: fmt::Arguments
368399
) {
369400
let sender = match self.node_signer.get_node_id(Recipient::Node) {
370401
Ok(node_id) => node_id,
@@ -385,7 +416,7 @@ where
385416

386417
log_trace!(self.logger, "Sending onion message {}", log_suffix);
387418

388-
if let Err(e) = self.send_onion_message(path, contents, None) {
419+
if let Err(e) = self.send_onion_message(path, contents, reply_path) {
389420
log_trace!(self.logger, "Failed sending onion message {}: {:?}", log_suffix, e);
390421
return;
391422
}
@@ -589,7 +620,26 @@ where
589620
features
590621
}
591622

623+
// Before returning any messages to send for the peer, this method will see if any messages were
624+
// enqueued in the handler by users, find a path to the corresponding blinded path's introduction
625+
// node, and then enqueue the message for sending to the first peer in the full path.
592626
fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<msgs::OnionMessage> {
627+
// Enqueue any initiating `OffersMessage`s to send.
628+
for message in self.offers_handler.release_pending_messages() {
629+
let PendingOnionMessage { contents, destination, reply_path } = message;
630+
self.find_path_and_enqueue_onion_message(
631+
contents, destination, reply_path, format_args!("when sending OffersMessage")
632+
);
633+
}
634+
635+
// Enqueue any initiating `CustomMessage`s to send.
636+
for message in self.custom_handler.release_pending_custom_messages() {
637+
let PendingOnionMessage { contents, destination, reply_path } = message;
638+
self.find_path_and_enqueue_onion_message(
639+
contents, destination, reply_path, format_args!("when sending CustomMessage")
640+
);
641+
}
642+
593643
let mut pending_msgs = self.pending_messages.lock().unwrap();
594644
if let Some(msgs) = pending_msgs.get_mut(&peer_node_id) {
595645
return msgs.pop_front()

lightning/src/onion_message/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,6 @@ mod packet;
2727
mod functional_tests;
2828

2929
// Re-export structs so they can be imported with just the `onion_message::` module prefix.
30-
pub use self::messenger::{CustomOnionMessageHandler, DefaultMessageRouter, Destination, MessageRouter, OnionMessageContents, OnionMessagePath, OnionMessenger, SendError, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
30+
pub use self::messenger::{CustomOnionMessageHandler, DefaultMessageRouter, Destination, MessageRouter, OnionMessageContents, OnionMessagePath, OnionMessenger, PendingOnionMessage, SendError, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
3131
pub use self::offers::{OffersMessage, OffersMessageHandler};
3232
pub(crate) use self::packet::{ControlTlvs, Packet};

lightning/src/onion_message/offers.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ use crate::offers::invoice_request::InvoiceRequest;
1717
use crate::offers::invoice::Bolt12Invoice;
1818
use crate::offers::parse::Bolt12ParseError;
1919
use crate::onion_message::OnionMessageContents;
20+
use crate::onion_message::messenger::PendingOnionMessage;
2021
use crate::util::logger::Logger;
2122
use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer};
2223

@@ -33,7 +34,17 @@ const INVOICE_ERROR_TLV_TYPE: u64 = 68;
3334
pub trait OffersMessageHandler {
3435
/// Handles the given message by either responding with an [`Bolt12Invoice`], sending a payment,
3536
/// or replying with an error.
37+
///
38+
/// The returned [`OffersMessage`], if any, is enqueued to be sent by [`OnionMessenger`].
39+
///
40+
/// [`OnionMessenger`]: crate::onion_message::messenger::OnionMessenger
3641
fn handle_message(&self, message: OffersMessage) -> Option<OffersMessage>;
42+
43+
/// Releases any [`OffersMessage`]s that need to be sent.
44+
///
45+
/// Typically, this is used for messages initiating a payment flow rather than in response to
46+
/// another message. The latter should use the return value of [`Self::handle_message`].
47+
fn release_pending_messages(&self) -> Vec<PendingOnionMessage<OffersMessage>> { vec![] }
3748
}
3849

3950
/// Possible BOLT 12 Offers messages sent and received via an [`OnionMessage`].

0 commit comments

Comments
 (0)