Skip to content

Commit ecd853e

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 840efd5 commit ecd853e

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
@@ -153,6 +153,22 @@ where
153153
custom_handler: CMH,
154154
}
155155

156+
/// An [`OnionMessage`] for [`OnionMessenger`] to send.
157+
///
158+
/// These are obtained when released from [`OnionMessenger`]'s handlers after which they are
159+
/// enqueued for sending.
160+
pub struct PendingOnionMessage<T: OnionMessageContents> {
161+
/// The message contents to send in an [`OnionMessage`].
162+
pub contents: T,
163+
164+
/// The destination of the message.
165+
pub destination: Destination,
166+
167+
/// A reply path to include in the [`OnionMessage`] for a response.
168+
pub reply_path: Option<BlindedPath>,
169+
170+
}
171+
156172
/// A trait defining behavior for routing an [`OnionMessage`].
157173
pub trait MessageRouter {
158174
/// Returns a route for sending an [`OnionMessage`] to the given [`Destination`].
@@ -246,11 +262,19 @@ pub trait CustomOnionMessageHandler {
246262
type CustomMessage: OnionMessageContents;
247263

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

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

256280
/// A processed incoming onion message, containing either a Forward (another onion message)
@@ -475,7 +499,7 @@ where
475499
match reply_path {
476500
Some(reply_path) => {
477501
self.find_path_and_enqueue_onion_message(
478-
response, Destination::BlindedPath(reply_path), log_suffix
502+
response, Destination::BlindedPath(reply_path), None, log_suffix
479503
);
480504
},
481505
None => {
@@ -486,7 +510,8 @@ where
486510
}
487511

488512
fn find_path_and_enqueue_onion_message<T: OnionMessageContents>(
489-
&self, contents: T, destination: Destination, log_suffix: fmt::Arguments
513+
&self, contents: T, destination: Destination, reply_path: Option<BlindedPath>,
514+
log_suffix: fmt::Arguments
490515
) {
491516
let sender = match self.node_signer.get_node_id(Recipient::Node) {
492517
Ok(node_id) => node_id,
@@ -507,7 +532,7 @@ where
507532

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

510-
if let Err(e) = self.send_onion_message(path, contents, None) {
535+
if let Err(e) = self.send_onion_message(path, contents, reply_path) {
511536
log_trace!(self.logger, "Failed sending onion message {}: {:?}", log_suffix, e);
512537
return;
513538
}
@@ -644,7 +669,26 @@ where
644669
features
645670
}
646671

672+
// Before returning any messages to send for the peer, this method will see if any messages were
673+
// enqueued in the handler by users, find a path to the corresponding blinded path's introduction
674+
// node, and then enqueue the message for sending to the first peer in the full path.
647675
fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<OnionMessage> {
676+
// Enqueue any initiating `OffersMessage`s to send.
677+
for message in self.offers_handler.release_pending_messages() {
678+
let PendingOnionMessage { contents, destination, reply_path } = message;
679+
self.find_path_and_enqueue_onion_message(
680+
contents, destination, reply_path, format_args!("when sending OffersMessage")
681+
);
682+
}
683+
684+
// Enqueue any initiating `CustomMessage`s to send.
685+
for message in self.custom_handler.release_pending_custom_messages() {
686+
let PendingOnionMessage { contents, destination, reply_path } = message;
687+
self.find_path_and_enqueue_onion_message(
688+
contents, destination, reply_path, format_args!("when sending CustomMessage")
689+
);
690+
}
691+
648692
let mut pending_msgs = self.pending_messages.lock().unwrap();
649693
if let Some(msgs) = pending_msgs.get_mut(&peer_node_id) {
650694
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, PeeledOnion, SendError, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
30+
pub use self::messenger::{CustomOnionMessageHandler, DefaultMessageRouter, Destination, MessageRouter, OnionMessageContents, OnionMessagePath, OnionMessenger, PeeledOnion, PendingOnionMessage, SendError, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
3131
pub use self::offers::{OffersMessage, OffersMessageHandler};
3232
pub use self::packet::{Packet, ParsedOnionMessageContents};
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)