Skip to content

Commit 524ede6

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 c8df14e commit 524ede6

File tree

6 files changed

+71
-7
lines changed

6 files changed

+71
-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: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,22 @@ 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+
pub struct PendingOnionMessage<T: OnionMessageContents> {
162+
/// The message contents to send in an [`OnionMessage`].
163+
pub contents: T,
164+
165+
/// The destination of the message.
166+
pub destination: Destination,
167+
168+
/// A reply path to include in the [`OnionMessage`] for a response.
169+
pub reply_path: Option<BlindedPath>,
170+
171+
}
172+
157173
/// A trait defining behavior for routing an [`OnionMessage`].
158174
pub trait MessageRouter {
159175
/// Returns a route for sending an [`OnionMessage`] to the given [`Destination`].
@@ -247,11 +263,19 @@ pub trait CustomOnionMessageHandler {
247263
type CustomMessage: OnionMessageContents;
248264

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

252270
/// Read a custom message of type `message_type` from `buffer`, returning `Ok(None)` if the
253271
/// message type is unknown.
254272
fn read_custom_message<R: io::Read>(&self, message_type: u64, buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError>;
273+
274+
/// Releases any [`Self::CustomMessage`]s that need to be sent.
275+
///
276+
/// Typically, this is used for messages initiating a message flow rather than in response to
277+
/// another message. The latter should use the return value of [`Self::handle_custom_message`].
278+
fn release_pending_custom_messages(&self) -> Vec<PendingOnionMessage<Self::CustomMessage>>;
255279
}
256280

257281

@@ -373,7 +397,7 @@ where
373397
match reply_path {
374398
Some(reply_path) => {
375399
self.find_path_and_enqueue_onion_message(
376-
response, Destination::BlindedPath(reply_path), log_suffix
400+
response, Destination::BlindedPath(reply_path), None, log_suffix
377401
);
378402
},
379403
None => {
@@ -384,7 +408,8 @@ where
384408
}
385409

386410
fn find_path_and_enqueue_onion_message<T: OnionMessageContents>(
387-
&self, contents: T, destination: Destination, log_suffix: fmt::Arguments
411+
&self, contents: T, destination: Destination, reply_path: Option<BlindedPath>,
412+
log_suffix: fmt::Arguments
388413
) {
389414
let sender = match self.node_signer.get_node_id(Recipient::Node) {
390415
Ok(node_id) => node_id,
@@ -405,7 +430,7 @@ where
405430

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

408-
if let Err(e) = self.send_onion_message(path, contents, None) {
433+
if let Err(e) = self.send_onion_message(path, contents, reply_path) {
409434
log_trace!(self.logger, "Failed sending onion message {}: {:?}", log_suffix, e);
410435
return;
411436
}
@@ -609,7 +634,26 @@ where
609634
features
610635
}
611636

637+
// Before returning any messages to send for the peer, this method will see if any messages were
638+
// enqueued in the handler by users, find a path to the corresponding blinded path's introduction
639+
// node, and then enqueue the message for sending to the first peer in the full path.
612640
fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<OnionMessage> {
641+
// Enqueue any initiating `OffersMessage`s to send.
642+
for message in self.offers_handler.release_pending_messages() {
643+
let PendingOnionMessage { contents, destination, reply_path } = message;
644+
self.find_path_and_enqueue_onion_message(
645+
contents, destination, reply_path, format_args!("when sending OffersMessage")
646+
);
647+
}
648+
649+
// Enqueue any initiating `CustomMessage`s to send.
650+
for message in self.custom_handler.release_pending_custom_messages() {
651+
let PendingOnionMessage { contents, destination, reply_path } = message;
652+
self.find_path_and_enqueue_onion_message(
653+
contents, destination, reply_path, format_args!("when sending CustomMessage")
654+
);
655+
}
656+
613657
let mut pending_msgs = self.pending_messages.lock().unwrap();
614658
if let Some(msgs) = pending_msgs.get_mut(&peer_node_id) {
615659
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,7 +27,7 @@ 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 use self::packet::Packet;
3333
pub(crate) use self::packet::ControlTlvs;

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::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)