1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! LDK sends, receives, and forwards onion messages via this [`OnionMessenger`], which lives here,
11 //! as well as various types, traits, and utilities that it uses.
13 use bitcoin::hashes::{Hash, HashEngine};
14 use bitcoin::hashes::hmac::{Hmac, HmacEngine};
15 use bitcoin::hashes::sha256::Hash as Sha256;
16 use bitcoin::secp256k1::{self, PublicKey, Scalar, Secp256k1, SecretKey};
18 use crate::blinded_path::{BlindedPath, IntroductionNode, NextMessageHop, NodeIdLookUp};
19 use crate::blinded_path::message::{advance_path_by_one, ForwardTlvs, ReceiveTlvs};
20 use crate::blinded_path::utils;
21 use crate::events::{Event, EventHandler, EventsProvider};
22 use crate::sign::{EntropySource, NodeSigner, Recipient};
23 use crate::ln::features::{InitFeatures, NodeFeatures};
24 use crate::ln::msgs::{self, OnionMessage, OnionMessageHandler, SocketAddress};
25 use crate::ln::onion_utils;
26 use crate::routing::gossip::{NetworkGraph, NodeId, ReadOnlyNetworkGraph};
27 use super::packet::OnionMessageContents;
28 use super::packet::ParsedOnionMessageContents;
29 use super::offers::OffersMessageHandler;
30 use super::packet::{BIG_PACKET_HOP_DATA_LEN, ForwardControlTlvs, Packet, Payload, ReceiveControlTlvs, SMALL_PACKET_HOP_DATA_LEN};
31 use crate::util::logger::{Logger, WithContext};
32 use crate::util::ser::Writeable;
37 use crate::sync::Mutex;
38 use crate::prelude::*;
40 #[cfg(not(c_bindings))]
42 crate::sign::KeysManager,
43 crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager},
44 crate::ln::peer_handler::IgnoringMessageHandler,
48 pub(super) const MAX_TIMER_TICKS: usize = 2;
50 /// A trivial trait which describes any [`OnionMessenger`].
52 /// This is not exported to bindings users as general cover traits aren't useful in other
54 pub trait AOnionMessenger {
55 /// A type implementing [`EntropySource`]
56 type EntropySource: EntropySource + ?Sized;
57 /// A type that may be dereferenced to [`Self::EntropySource`]
58 type ES: Deref<Target = Self::EntropySource>;
59 /// A type implementing [`NodeSigner`]
60 type NodeSigner: NodeSigner + ?Sized;
61 /// A type that may be dereferenced to [`Self::NodeSigner`]
62 type NS: Deref<Target = Self::NodeSigner>;
63 /// A type implementing [`Logger`]
64 type Logger: Logger + ?Sized;
65 /// A type that may be dereferenced to [`Self::Logger`]
66 type L: Deref<Target = Self::Logger>;
67 /// A type implementing [`NodeIdLookUp`]
68 type NodeIdLookUp: NodeIdLookUp + ?Sized;
69 /// A type that may be dereferenced to [`Self::NodeIdLookUp`]
70 type NL: Deref<Target = Self::NodeIdLookUp>;
71 /// A type implementing [`MessageRouter`]
72 type MessageRouter: MessageRouter + ?Sized;
73 /// A type that may be dereferenced to [`Self::MessageRouter`]
74 type MR: Deref<Target = Self::MessageRouter>;
75 /// A type implementing [`OffersMessageHandler`]
76 type OffersMessageHandler: OffersMessageHandler + ?Sized;
77 /// A type that may be dereferenced to [`Self::OffersMessageHandler`]
78 type OMH: Deref<Target = Self::OffersMessageHandler>;
79 /// A type implementing [`CustomOnionMessageHandler`]
80 type CustomOnionMessageHandler: CustomOnionMessageHandler + ?Sized;
81 /// A type that may be dereferenced to [`Self::CustomOnionMessageHandler`]
82 type CMH: Deref<Target = Self::CustomOnionMessageHandler>;
83 /// Returns a reference to the actual [`OnionMessenger`] object.
84 fn get_om(&self) -> &OnionMessenger<Self::ES, Self::NS, Self::L, Self::NL, Self::MR, Self::OMH, Self::CMH>;
87 impl<ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, CMH: Deref> AOnionMessenger
88 for OnionMessenger<ES, NS, L, NL, MR, OMH, CMH> where
89 ES::Target: EntropySource,
90 NS::Target: NodeSigner,
92 NL::Target: NodeIdLookUp,
93 MR::Target: MessageRouter,
94 OMH::Target: OffersMessageHandler,
95 CMH::Target: CustomOnionMessageHandler,
97 type EntropySource = ES::Target;
99 type NodeSigner = NS::Target;
101 type Logger = L::Target;
103 type NodeIdLookUp = NL::Target;
105 type MessageRouter = MR::Target;
107 type OffersMessageHandler = OMH::Target;
109 type CustomOnionMessageHandler = CMH::Target;
111 fn get_om(&self) -> &OnionMessenger<ES, NS, L, NL, MR, OMH, CMH> { self }
114 /// A sender, receiver and forwarder of [`OnionMessage`]s.
116 /// # Handling Messages
118 /// `OnionMessenger` implements [`OnionMessageHandler`], making it responsible for either forwarding
119 /// messages to peers or delegating to the appropriate handler for the message type. Currently, the
120 /// available handlers are:
121 /// * [`OffersMessageHandler`], for responding to [`InvoiceRequest`]s and paying [`Bolt12Invoice`]s
122 /// * [`CustomOnionMessageHandler`], for handling user-defined message types
124 /// # Sending Messages
126 /// [`OnionMessage`]s are sent initially using [`OnionMessenger::send_onion_message`]. When handling
127 /// a message, the matched handler may return a response message which `OnionMessenger` will send
133 /// # extern crate bitcoin;
134 /// # use bitcoin::hashes::_export::_core::time::Duration;
135 /// # use bitcoin::hashes::hex::FromHex;
136 /// # use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey, self};
137 /// # use lightning::blinded_path::{BlindedPath, EmptyNodeIdLookUp};
138 /// # use lightning::sign::{EntropySource, KeysManager};
139 /// # use lightning::ln::peer_handler::IgnoringMessageHandler;
140 /// # use lightning::onion_message::messenger::{Destination, MessageRouter, OnionMessagePath, OnionMessenger};
141 /// # use lightning::onion_message::packet::OnionMessageContents;
142 /// # use lightning::util::logger::{Logger, Record};
143 /// # use lightning::util::ser::{Writeable, Writer};
144 /// # use lightning::io;
145 /// # use std::sync::Arc;
146 /// # struct FakeLogger;
147 /// # impl Logger for FakeLogger {
148 /// # fn log(&self, record: Record) { println!("{:?}" , record); }
150 /// # struct FakeMessageRouter {}
151 /// # impl MessageRouter for FakeMessageRouter {
152 /// # fn find_path(&self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination) -> Result<OnionMessagePath, ()> {
153 /// # let secp_ctx = Secp256k1::new();
154 /// # let node_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
155 /// # let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
156 /// # let hop_node_id2 = hop_node_id1;
157 /// # Ok(OnionMessagePath {
158 /// # intermediate_nodes: vec![hop_node_id1, hop_node_id2],
160 /// # first_node_addresses: None,
163 /// # fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
164 /// # &self, _recipient: PublicKey, _peers: Vec<PublicKey>, _secp_ctx: &Secp256k1<T>
165 /// # ) -> Result<Vec<BlindedPath>, ()> {
169 /// # let seed = [42u8; 32];
170 /// # let time = Duration::from_secs(123456);
171 /// # let keys_manager = KeysManager::new(&seed, time.as_secs(), time.subsec_nanos());
172 /// # let logger = Arc::new(FakeLogger {});
173 /// # let node_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
174 /// # let secp_ctx = Secp256k1::new();
175 /// # let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
176 /// # let (hop_node_id3, hop_node_id4) = (hop_node_id1, hop_node_id1);
177 /// # let destination_node_id = hop_node_id1;
178 /// # let node_id_lookup = EmptyNodeIdLookUp {};
179 /// # let message_router = Arc::new(FakeMessageRouter {});
180 /// # let custom_message_handler = IgnoringMessageHandler {};
181 /// # let offers_message_handler = IgnoringMessageHandler {};
182 /// // Create the onion messenger. This must use the same `keys_manager` as is passed to your
183 /// // ChannelManager.
184 /// let onion_messenger = OnionMessenger::new(
185 /// &keys_manager, &keys_manager, logger, &node_id_lookup, message_router,
186 /// &offers_message_handler, &custom_message_handler
189 /// # #[derive(Debug)]
190 /// # struct YourCustomMessage {}
191 /// impl Writeable for YourCustomMessage {
192 /// fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
194 /// // Write your custom onion message to `w`
197 /// impl OnionMessageContents for YourCustomMessage {
198 /// fn tlv_type(&self) -> u64 {
199 /// # let your_custom_message_type = 42;
200 /// your_custom_message_type
202 /// fn msg_type(&self) -> &'static str { "YourCustomMessageType" }
204 /// // Send a custom onion message to a node id.
205 /// let destination = Destination::Node(destination_node_id);
206 /// let reply_path = None;
207 /// # let message = YourCustomMessage {};
208 /// onion_messenger.send_onion_message(message, destination, reply_path);
210 /// // Create a blinded path to yourself, for someone to send an onion message to.
211 /// # let your_node_id = hop_node_id1;
212 /// let hops = [hop_node_id3, hop_node_id4, your_node_id];
213 /// let blinded_path = BlindedPath::new_for_message(&hops, &keys_manager, &secp_ctx).unwrap();
215 /// // Send a custom onion message to a blinded path.
216 /// let destination = Destination::BlindedPath(blinded_path);
217 /// let reply_path = None;
218 /// # let message = YourCustomMessage {};
219 /// onion_messenger.send_onion_message(message, destination, reply_path);
222 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
223 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
224 pub struct OnionMessenger<ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, CMH: Deref>
226 ES::Target: EntropySource,
227 NS::Target: NodeSigner,
229 NL::Target: NodeIdLookUp,
230 MR::Target: MessageRouter,
231 OMH::Target: OffersMessageHandler,
232 CMH::Target: CustomOnionMessageHandler,
237 message_recipients: Mutex<HashMap<PublicKey, OnionMessageRecipient>>,
238 secp_ctx: Secp256k1<secp256k1::All>,
243 intercept_messages_for_offline_peers: bool,
244 pending_events: Mutex<Vec<Event>>,
247 /// [`OnionMessage`]s buffered to be sent.
248 enum OnionMessageRecipient {
249 /// Messages for a node connected as a peer.
250 ConnectedPeer(VecDeque<OnionMessage>),
252 /// Messages for a node that is not yet connected, which are dropped after [`MAX_TIMER_TICKS`]
253 /// and tracked here.
254 PendingConnection(VecDeque<OnionMessage>, Option<Vec<SocketAddress>>, usize),
257 impl OnionMessageRecipient {
258 fn pending_connection(addresses: Vec<SocketAddress>) -> Self {
259 Self::PendingConnection(VecDeque::new(), Some(addresses), 0)
262 fn pending_messages(&self) -> &VecDeque<OnionMessage> {
264 OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
265 OnionMessageRecipient::PendingConnection(pending_messages, _, _) => pending_messages,
269 fn enqueue_message(&mut self, message: OnionMessage) {
270 let pending_messages = match self {
271 OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
272 OnionMessageRecipient::PendingConnection(pending_messages, _, _) => pending_messages,
275 pending_messages.push_back(message);
278 fn dequeue_message(&mut self) -> Option<OnionMessage> {
279 let pending_messages = match self {
280 OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
281 OnionMessageRecipient::PendingConnection(pending_messages, _, _) => {
282 debug_assert!(false);
287 pending_messages.pop_front()
291 fn release_pending_messages(&mut self) -> VecDeque<OnionMessage> {
292 let pending_messages = match self {
293 OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
294 OnionMessageRecipient::PendingConnection(pending_messages, _, _) => pending_messages,
297 core::mem::take(pending_messages)
300 fn mark_connected(&mut self) {
301 if let OnionMessageRecipient::PendingConnection(pending_messages, _, _) = self {
302 let mut new_pending_messages = VecDeque::new();
303 core::mem::swap(pending_messages, &mut new_pending_messages);
304 *self = OnionMessageRecipient::ConnectedPeer(new_pending_messages);
308 fn is_connected(&self) -> bool {
310 OnionMessageRecipient::ConnectedPeer(..) => true,
311 OnionMessageRecipient::PendingConnection(..) => false,
317 /// The `Responder` struct creates an appropriate [`ResponseInstruction`]
318 /// for responding to a message.
319 pub struct Responder {
320 /// The path along which a response can be sent.
321 reply_path: BlindedPath,
322 path_id: Option<[u8; 32]>
326 /// Creates a new [`Responder`] instance with the provided reply path.
327 fn new(reply_path: BlindedPath, path_id: Option<[u8; 32]>) -> Self {
334 /// Creates the appropriate [`ResponseInstruction`] for a given response.
335 pub fn respond<T: OnionMessageContents>(self, response: T) -> ResponseInstruction<T> {
336 ResponseInstruction::WithoutReplyPath(OnionMessageResponse {
338 reply_path: self.reply_path,
339 path_id: self.path_id,
344 /// This struct contains the information needed to reply to a received message.
345 pub struct OnionMessageResponse<T: OnionMessageContents> {
347 reply_path: BlindedPath,
348 path_id: Option<[u8; 32]>,
351 /// `ResponseInstruction` represents instructions for responding to received messages.
352 pub enum ResponseInstruction<T: OnionMessageContents> {
353 /// Indicates that a response should be sent without including a reply path
354 /// for the recipient to respond back.
355 WithoutReplyPath(OnionMessageResponse<T>),
356 /// Indicates that there's no response to send back.
360 /// An [`OnionMessage`] for [`OnionMessenger`] to send.
362 /// These are obtained when released from [`OnionMessenger`]'s handlers after which they are
363 /// enqueued for sending.
364 #[cfg(not(c_bindings))]
365 pub struct PendingOnionMessage<T: OnionMessageContents> {
366 /// The message contents to send in an [`OnionMessage`].
369 /// The destination of the message.
370 pub destination: Destination,
372 /// A reply path to include in the [`OnionMessage`] for a response.
373 pub reply_path: Option<BlindedPath>,
377 /// An [`OnionMessage`] for [`OnionMessenger`] to send.
379 /// These are obtained when released from [`OnionMessenger`]'s handlers after which they are
380 /// enqueued for sending.
381 pub type PendingOnionMessage<T> = (T, Destination, Option<BlindedPath>);
383 pub(crate) fn new_pending_onion_message<T: OnionMessageContents>(
384 contents: T, destination: Destination, reply_path: Option<BlindedPath>
385 ) -> PendingOnionMessage<T> {
386 #[cfg(not(c_bindings))]
387 return PendingOnionMessage { contents, destination, reply_path };
389 return (contents, destination, reply_path);
392 /// A trait defining behavior for routing an [`OnionMessage`].
393 pub trait MessageRouter {
394 /// Returns a route for sending an [`OnionMessage`] to the given [`Destination`].
396 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
397 ) -> Result<OnionMessagePath, ()>;
399 /// Creates [`BlindedPath`]s to the `recipient` node. The nodes in `peers` are assumed to be
400 /// direct peers with the `recipient`.
401 fn create_blinded_paths<
402 T: secp256k1::Signing + secp256k1::Verification
404 &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
405 ) -> Result<Vec<BlindedPath>, ()>;
408 /// A [`MessageRouter`] that can only route to a directly connected [`Destination`].
409 pub struct DefaultMessageRouter<G: Deref<Target=NetworkGraph<L>>, L: Deref, ES: Deref>
412 ES::Target: EntropySource,
418 impl<G: Deref<Target=NetworkGraph<L>>, L: Deref, ES: Deref> DefaultMessageRouter<G, L, ES>
421 ES::Target: EntropySource,
423 /// Creates a [`DefaultMessageRouter`] using the given [`NetworkGraph`].
424 pub fn new(network_graph: G, entropy_source: ES) -> Self {
425 Self { network_graph, entropy_source }
429 impl<G: Deref<Target=NetworkGraph<L>>, L: Deref, ES: Deref> MessageRouter for DefaultMessageRouter<G, L, ES>
432 ES::Target: EntropySource,
435 &self, sender: PublicKey, peers: Vec<PublicKey>, mut destination: Destination
436 ) -> Result<OnionMessagePath, ()> {
437 let network_graph = self.network_graph.deref().read_only();
438 destination.resolve(&network_graph);
440 let first_node = match destination.first_node() {
441 Some(first_node) => first_node,
442 None => return Err(()),
445 if peers.contains(&first_node) || sender == first_node {
446 Ok(OnionMessagePath {
447 intermediate_nodes: vec![], destination, first_node_addresses: None
450 let node_announcement = network_graph
451 .node(&NodeId::from_pubkey(&first_node))
452 .and_then(|node_info| node_info.announcement_info.as_ref())
453 .and_then(|announcement_info| announcement_info.announcement_message.as_ref())
454 .map(|node_announcement| &node_announcement.contents);
456 match node_announcement {
457 Some(node_announcement) if node_announcement.features.supports_onion_messages() => {
458 let first_node_addresses = Some(node_announcement.addresses.clone());
459 Ok(OnionMessagePath {
460 intermediate_nodes: vec![], destination, first_node_addresses
468 fn create_blinded_paths<
469 T: secp256k1::Signing + secp256k1::Verification
471 &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
472 ) -> Result<Vec<BlindedPath>, ()> {
473 // Limit the number of blinded paths that are computed.
474 const MAX_PATHS: usize = 3;
476 // Ensure peers have at least three channels so that it is more difficult to infer the
477 // recipient's node_id.
478 const MIN_PEER_CHANNELS: usize = 3;
480 let network_graph = self.network_graph.deref().read_only();
481 let is_recipient_announced =
482 network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient));
484 let mut peer_info = peers.iter()
485 // Limit to peers with announced channels
488 .node(&NodeId::from_pubkey(pubkey))
489 .filter(|info| info.channels.len() >= MIN_PEER_CHANNELS)
490 .map(|info| (*pubkey, info.is_tor_only(), info.channels.len()))
492 // Exclude Tor-only nodes when the recipient is announced.
493 .filter(|(_, is_tor_only, _)| !(*is_tor_only && is_recipient_announced))
494 .collect::<Vec<_>>();
496 // Prefer using non-Tor nodes with the most channels as the introduction node.
497 peer_info.sort_unstable_by(|(_, a_tor_only, a_channels), (_, b_tor_only, b_channels)| {
498 a_tor_only.cmp(b_tor_only).then(a_channels.cmp(b_channels).reverse())
501 let paths = peer_info.into_iter()
502 .map(|(pubkey, _, _)| vec![pubkey, recipient])
503 .map(|node_pks| BlindedPath::new_for_message(&node_pks, &*self.entropy_source, secp_ctx))
505 .collect::<Result<Vec<_>, _>>();
508 Ok(paths) if !paths.is_empty() => Ok(paths),
510 if is_recipient_announced {
511 BlindedPath::one_hop_for_message(recipient, &*self.entropy_source, secp_ctx)
512 .map(|path| vec![path])
521 /// A path for sending an [`OnionMessage`].
523 pub struct OnionMessagePath {
524 /// Nodes on the path between the sender and the destination.
525 pub intermediate_nodes: Vec<PublicKey>,
527 /// The recipient of the message.
528 pub destination: Destination,
530 /// Addresses that may be used to connect to [`OnionMessagePath::first_node`].
532 /// Only needs to be set if a connection to the node is required. [`OnionMessenger`] may use
533 /// this to initiate such a connection.
534 pub first_node_addresses: Option<Vec<SocketAddress>>,
537 impl OnionMessagePath {
538 /// Returns the first node in the path.
539 pub fn first_node(&self) -> Option<PublicKey> {
540 self.intermediate_nodes
543 .or_else(|| self.destination.first_node())
547 /// The destination of an onion message.
548 #[derive(Clone, Hash, Debug, PartialEq, Eq)]
549 pub enum Destination {
550 /// We're sending this onion message to a node.
552 /// We're sending this onion message to a blinded path.
553 BlindedPath(BlindedPath),
557 /// Attempts to resolve the [`IntroductionNode::DirectedShortChannelId`] of a
558 /// [`Destination::BlindedPath`] to a [`IntroductionNode::NodeId`], if applicable, using the
559 /// provided [`ReadOnlyNetworkGraph`].
560 pub fn resolve(&mut self, network_graph: &ReadOnlyNetworkGraph) {
561 if let Destination::BlindedPath(path) = self {
562 if let IntroductionNode::DirectedShortChannelId(..) = path.introduction_node {
563 if let Some(pubkey) = path
564 .public_introduction_node_id(network_graph)
565 .and_then(|node_id| node_id.as_pubkey().ok())
567 path.introduction_node = IntroductionNode::NodeId(pubkey);
573 pub(super) fn num_hops(&self) -> usize {
575 Destination::Node(_) => 1,
576 Destination::BlindedPath(BlindedPath { blinded_hops, .. }) => blinded_hops.len(),
580 fn first_node(&self) -> Option<PublicKey> {
582 Destination::Node(node_id) => Some(*node_id),
583 Destination::BlindedPath(BlindedPath { introduction_node, .. }) => {
584 match introduction_node {
585 IntroductionNode::NodeId(pubkey) => Some(*pubkey),
586 IntroductionNode::DirectedShortChannelId(..) => None,
593 /// Result of successfully [sending an onion message].
595 /// [sending an onion message]: OnionMessenger::send_onion_message
596 #[derive(Clone, Hash, Debug, PartialEq, Eq)]
597 pub enum SendSuccess {
598 /// The message was buffered and will be sent once it is processed by
599 /// [`OnionMessageHandler::next_onion_message_for_peer`].
601 /// The message was buffered and will be sent once the node is connected as a peer and it is
602 /// processed by [`OnionMessageHandler::next_onion_message_for_peer`].
603 BufferedAwaitingConnection(PublicKey),
606 /// Errors that may occur when [sending an onion message].
608 /// [sending an onion message]: OnionMessenger::send_onion_message
609 #[derive(Clone, Hash, Debug, PartialEq, Eq)]
611 /// Errored computing onion message packet keys.
612 Secp256k1(secp256k1::Error),
613 /// Because implementations such as Eclair will drop onion messages where the message packet
614 /// exceeds 32834 bytes, we refuse to send messages where the packet exceeds this size.
616 /// The provided [`Destination`] was an invalid [`BlindedPath`] due to not having any blinded
619 /// The first hop is not a peer and doesn't have a known [`SocketAddress`].
620 InvalidFirstHop(PublicKey),
621 /// A path from the sender to the destination could not be found by the [`MessageRouter`].
623 /// Onion message contents must have a TLV type >= 64.
625 /// Our next-hop peer's buffer was full or our total outbound buffer was full.
627 /// Failed to retrieve our node id from the provided [`NodeSigner`].
629 /// [`NodeSigner`]: crate::sign::NodeSigner
631 /// The provided [`Destination`] has a blinded path with an unresolved introduction node. An
632 /// attempt to resolve it in the [`MessageRouter`] when finding an [`OnionMessagePath`] likely
634 UnresolvedIntroductionNode,
635 /// We attempted to send to a blinded path where we are the introduction node, and failed to
636 /// advance the blinded path to make the second hop the new introduction node. Either
637 /// [`NodeSigner::ecdh`] failed, we failed to tweak the current blinding point to get the
638 /// new blinding point, or we were attempting to send to ourselves.
639 BlindedPathAdvanceFailed,
642 /// Handler for custom onion messages. If you are using [`SimpleArcOnionMessenger`],
643 /// [`SimpleRefOnionMessenger`], or prefer to ignore inbound custom onion messages,
644 /// [`IgnoringMessageHandler`] must be provided to [`OnionMessenger::new`]. Otherwise, a custom
645 /// implementation of this trait must be provided, with [`CustomMessage`] specifying the supported
648 /// See [`OnionMessenger`] for example usage.
650 /// [`IgnoringMessageHandler`]: crate::ln::peer_handler::IgnoringMessageHandler
651 /// [`CustomMessage`]: Self::CustomMessage
652 pub trait CustomOnionMessageHandler {
653 /// The message known to the handler. To support multiple message types, you may want to make this
654 /// an enum with a variant for each supported message.
655 type CustomMessage: OnionMessageContents;
657 /// Called with the custom message that was received, returning a response to send, if any.
659 /// The returned [`Self::CustomMessage`], if any, is enqueued to be sent by [`OnionMessenger`].
660 fn handle_custom_message(&self, message: Self::CustomMessage, responder: Option<Responder>) -> ResponseInstruction<Self::CustomMessage>;
662 /// Read a custom message of type `message_type` from `buffer`, returning `Ok(None)` if the
663 /// message type is unknown.
664 fn read_custom_message<R: io::Read>(&self, message_type: u64, buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError>;
666 /// Releases any [`Self::CustomMessage`]s that need to be sent.
668 /// Typically, this is used for messages initiating a message flow rather than in response to
669 /// another message. The latter should use the return value of [`Self::handle_custom_message`].
670 #[cfg(not(c_bindings))]
671 fn release_pending_custom_messages(&self) -> Vec<PendingOnionMessage<Self::CustomMessage>>;
673 /// Releases any [`Self::CustomMessage`]s that need to be sent.
675 /// Typically, this is used for messages initiating a message flow rather than in response to
676 /// another message. The latter should use the return value of [`Self::handle_custom_message`].
678 fn release_pending_custom_messages(&self) -> Vec<(Self::CustomMessage, Destination, Option<BlindedPath>)>;
681 /// A processed incoming onion message, containing either a Forward (another onion message)
682 /// or a Receive payload with decrypted contents.
683 #[derive(Clone, Debug)]
684 pub enum PeeledOnion<T: OnionMessageContents> {
685 /// Forwarded onion, with the next node id and a new onion
686 Forward(NextMessageHop, OnionMessage),
687 /// Received onion message, with decrypted contents, path_id, and reply path
688 Receive(ParsedOnionMessageContents<T>, Option<[u8; 32]>, Option<BlindedPath>)
692 /// Creates an [`OnionMessage`] with the given `contents` for sending to the destination of
693 /// `path`, first calling [`Destination::resolve`] on `path.destination` with the given
694 /// [`ReadOnlyNetworkGraph`].
696 /// Returns the node id of the peer to send the message to, the message itself, and any addresses
697 /// needed to connect to the first node.
698 pub fn create_onion_message_resolving_destination<
699 ES: Deref, NS: Deref, NL: Deref, T: OnionMessageContents
701 entropy_source: &ES, node_signer: &NS, node_id_lookup: &NL,
702 network_graph: &ReadOnlyNetworkGraph, secp_ctx: &Secp256k1<secp256k1::All>,
703 mut path: OnionMessagePath, contents: T, reply_path: Option<BlindedPath>,
704 ) -> Result<(PublicKey, OnionMessage, Option<Vec<SocketAddress>>), SendError>
706 ES::Target: EntropySource,
707 NS::Target: NodeSigner,
708 NL::Target: NodeIdLookUp,
710 path.destination.resolve(network_graph);
711 create_onion_message(
712 entropy_source, node_signer, node_id_lookup, secp_ctx, path, contents, reply_path,
716 /// Creates an [`OnionMessage`] with the given `contents` for sending to the destination of
719 /// Returns the node id of the peer to send the message to, the message itself, and any addresses
720 /// needed to connect to the first node.
722 /// Returns [`SendError::UnresolvedIntroductionNode`] if:
723 /// - `destination` contains a blinded path with an [`IntroductionNode::DirectedShortChannelId`],
724 /// - unless it can be resolved by [`NodeIdLookUp::next_node_id`].
725 /// Use [`create_onion_message_resolving_destination`] instead to resolve the introduction node
726 /// first with a [`ReadOnlyNetworkGraph`].
727 pub fn create_onion_message<ES: Deref, NS: Deref, NL: Deref, T: OnionMessageContents>(
728 entropy_source: &ES, node_signer: &NS, node_id_lookup: &NL,
729 secp_ctx: &Secp256k1<secp256k1::All>, path: OnionMessagePath, contents: T,
730 reply_path: Option<BlindedPath>,
731 ) -> Result<(PublicKey, OnionMessage, Option<Vec<SocketAddress>>), SendError>
733 ES::Target: EntropySource,
734 NS::Target: NodeSigner,
735 NL::Target: NodeIdLookUp,
737 let OnionMessagePath { intermediate_nodes, mut destination, first_node_addresses } = path;
738 if let Destination::BlindedPath(BlindedPath { ref blinded_hops, .. }) = destination {
739 if blinded_hops.is_empty() {
740 return Err(SendError::TooFewBlindedHops);
744 if contents.tlv_type() < 64 { return Err(SendError::InvalidMessage) }
746 // If we are sending straight to a blinded path and we are the introduction node, we need to
747 // advance the blinded path by 1 hop so the second hop is the new introduction node.
748 if intermediate_nodes.len() == 0 {
749 if let Destination::BlindedPath(ref mut blinded_path) = destination {
750 let our_node_id = node_signer.get_node_id(Recipient::Node)
751 .map_err(|()| SendError::GetNodeIdFailed)?;
752 let introduction_node_id = match blinded_path.introduction_node {
753 IntroductionNode::NodeId(pubkey) => pubkey,
754 IntroductionNode::DirectedShortChannelId(direction, scid) => {
755 match node_id_lookup.next_node_id(scid) {
756 Some(next_node_id) => *direction.select_pubkey(&our_node_id, &next_node_id),
757 None => return Err(SendError::UnresolvedIntroductionNode),
761 if introduction_node_id == our_node_id {
762 advance_path_by_one(blinded_path, node_signer, node_id_lookup, &secp_ctx)
763 .map_err(|()| SendError::BlindedPathAdvanceFailed)?;
768 let blinding_secret_bytes = entropy_source.get_secure_random_bytes();
769 let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
770 let (first_node_id, blinding_point) = if let Some(first_node_id) = intermediate_nodes.first() {
771 (*first_node_id, PublicKey::from_secret_key(&secp_ctx, &blinding_secret))
774 Destination::Node(pk) => (*pk, PublicKey::from_secret_key(&secp_ctx, &blinding_secret)),
775 Destination::BlindedPath(BlindedPath { introduction_node, blinding_point, .. }) => {
776 match introduction_node {
777 IntroductionNode::NodeId(pubkey) => (*pubkey, *blinding_point),
778 IntroductionNode::DirectedShortChannelId(..) => {
779 return Err(SendError::UnresolvedIntroductionNode);
785 let (packet_payloads, packet_keys) = packet_payloads_and_keys(
786 &secp_ctx, &intermediate_nodes, destination, contents, reply_path, &blinding_secret
789 let prng_seed = entropy_source.get_secure_random_bytes();
790 let onion_routing_packet = construct_onion_message_packet(
791 packet_payloads, packet_keys, prng_seed).map_err(|()| SendError::TooBigPacket)?;
793 let message = OnionMessage { blinding_point, onion_routing_packet };
794 Ok((first_node_id, message, first_node_addresses))
797 /// Decode one layer of an incoming [`OnionMessage`].
799 /// Returns either the next layer of the onion for forwarding or the decrypted content for the
801 pub fn peel_onion_message<NS: Deref, L: Deref, CMH: Deref>(
802 msg: &OnionMessage, secp_ctx: &Secp256k1<secp256k1::All>, node_signer: NS, logger: L,
804 ) -> Result<PeeledOnion<<<CMH>::Target as CustomOnionMessageHandler>::CustomMessage>, ()>
806 NS::Target: NodeSigner,
808 CMH::Target: CustomOnionMessageHandler,
810 let control_tlvs_ss = match node_signer.ecdh(Recipient::Node, &msg.blinding_point, None) {
813 log_error!(logger, "Failed to retrieve node secret: {:?}", e);
817 let onion_decode_ss = {
818 let blinding_factor = {
819 let mut hmac = HmacEngine::<Sha256>::new(b"blinded_node_id");
820 hmac.input(control_tlvs_ss.as_ref());
821 Hmac::from_engine(hmac).to_byte_array()
823 match node_signer.ecdh(Recipient::Node, &msg.onion_routing_packet.public_key,
824 Some(&Scalar::from_be_bytes(blinding_factor).unwrap()))
826 Ok(ss) => ss.secret_bytes(),
828 log_trace!(logger, "Failed to compute onion packet shared secret");
833 match onion_utils::decode_next_untagged_hop(
834 onion_decode_ss, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac,
835 (control_tlvs_ss, custom_handler.deref(), logger.deref())
837 Ok((Payload::Receive::<ParsedOnionMessageContents<<<CMH as Deref>::Target as CustomOnionMessageHandler>::CustomMessage>> {
838 message, control_tlvs: ReceiveControlTlvs::Unblinded(ReceiveTlvs { path_id }), reply_path,
840 Ok(PeeledOnion::Receive(message, path_id, reply_path))
842 Ok((Payload::Forward(ForwardControlTlvs::Unblinded(ForwardTlvs {
843 next_hop, next_blinding_override
844 })), Some((next_hop_hmac, new_packet_bytes)))) => {
845 // TODO: we need to check whether `next_hop` is our node, in which case this is a dummy
846 // blinded hop and this onion message is destined for us. In this situation, we should keep
847 // unwrapping the onion layers to get to the final payload. Since we don't have the option
848 // of creating blinded paths with dummy hops currently, we should be ok to not handle this
850 let new_pubkey = match onion_utils::next_hop_pubkey(&secp_ctx, msg.onion_routing_packet.public_key, &onion_decode_ss) {
853 log_trace!(logger, "Failed to compute next hop packet pubkey: {}", e);
857 let outgoing_packet = Packet {
859 public_key: new_pubkey,
860 hop_data: new_packet_bytes,
863 let onion_message = OnionMessage {
864 blinding_point: match next_blinding_override {
865 Some(blinding_point) => blinding_point,
867 match onion_utils::next_hop_pubkey(
868 &secp_ctx, msg.blinding_point, control_tlvs_ss.as_ref()
872 log_trace!(logger, "Failed to compute next blinding point: {}", e);
878 onion_routing_packet: outgoing_packet,
881 Ok(PeeledOnion::Forward(next_hop, onion_message))
884 log_trace!(logger, "Errored decoding onion message packet: {:?}", e);
888 log_trace!(logger, "Received bogus onion message packet, either the sender encoded a final hop as a forwarding hop or vice versa");
894 impl<ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, CMH: Deref>
895 OnionMessenger<ES, NS, L, NL, MR, OMH, CMH>
897 ES::Target: EntropySource,
898 NS::Target: NodeSigner,
900 NL::Target: NodeIdLookUp,
901 MR::Target: MessageRouter,
902 OMH::Target: OffersMessageHandler,
903 CMH::Target: CustomOnionMessageHandler,
905 /// Constructs a new `OnionMessenger` to send, forward, and delegate received onion messages to
906 /// their respective handlers.
908 entropy_source: ES, node_signer: NS, logger: L, node_id_lookup: NL, message_router: MR,
909 offers_handler: OMH, custom_handler: CMH
912 entropy_source, node_signer, logger, node_id_lookup, message_router,
913 offers_handler, custom_handler, false
917 /// Similar to [`Self::new`], but rather than dropping onion messages that are
918 /// intended to be forwarded to offline peers, we will intercept them for
919 /// later forwarding.
921 /// Interception flow:
922 /// 1. If an onion message for an offline peer is received, `OnionMessenger` will
923 /// generate an [`Event::OnionMessageIntercepted`]. Event handlers can
924 /// then choose to persist this onion message for later forwarding, or drop
926 /// 2. When the offline peer later comes back online, `OnionMessenger` will
927 /// generate an [`Event::OnionMessagePeerConnected`]. Event handlers will
928 /// then fetch all previously intercepted onion messages for this peer.
929 /// 3. Once the stored onion messages are fetched, they can finally be
930 /// forwarded to the now-online peer via [`Self::forward_onion_message`].
934 /// LDK will not rate limit how many [`Event::OnionMessageIntercepted`]s
935 /// are generated, so it is the caller's responsibility to limit how many
936 /// onion messages are persisted and only persist onion messages for relevant
938 pub fn new_with_offline_peer_interception(
939 entropy_source: ES, node_signer: NS, logger: L, node_id_lookup: NL,
940 message_router: MR, offers_handler: OMH, custom_handler: CMH
943 entropy_source, node_signer, logger, node_id_lookup, message_router,
944 offers_handler, custom_handler, true
949 entropy_source: ES, node_signer: NS, logger: L, node_id_lookup: NL,
950 message_router: MR, offers_handler: OMH, custom_handler: CMH,
951 intercept_messages_for_offline_peers: bool
953 let mut secp_ctx = Secp256k1::new();
954 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
958 message_recipients: Mutex::new(new_hash_map()),
965 intercept_messages_for_offline_peers,
966 pending_events: Mutex::new(Vec::new()),
971 pub(crate) fn set_offers_handler(&mut self, offers_handler: OMH) {
972 self.offers_handler = offers_handler;
975 /// Sends an [`OnionMessage`] with the given `contents` to `destination`.
977 /// See [`OnionMessenger`] for example usage.
978 pub fn send_onion_message<T: OnionMessageContents>(
979 &self, contents: T, destination: Destination, reply_path: Option<BlindedPath>
980 ) -> Result<SendSuccess, SendError> {
981 self.find_path_and_enqueue_onion_message(
982 contents, destination, reply_path, format_args!("")
986 fn find_path_and_enqueue_onion_message<T: OnionMessageContents>(
987 &self, contents: T, destination: Destination, reply_path: Option<BlindedPath>,
988 log_suffix: fmt::Arguments
989 ) -> Result<SendSuccess, SendError> {
990 let mut logger = WithContext::from(&self.logger, None, None, None);
991 let result = self.find_path(destination).and_then(|path| {
992 let first_hop = path.intermediate_nodes.get(0).map(|p| *p);
993 logger = WithContext::from(&self.logger, first_hop, None, None);
994 self.enqueue_onion_message(path, contents, reply_path, log_suffix)
997 match result.as_ref() {
998 Err(SendError::GetNodeIdFailed) => {
999 log_warn!(logger, "Unable to retrieve node id {}", log_suffix);
1001 Err(SendError::PathNotFound) => {
1002 log_trace!(logger, "Failed to find path {}", log_suffix);
1005 log_trace!(logger, "Failed sending onion message {}: {:?}", log_suffix, e);
1007 Ok(SendSuccess::Buffered) => {
1008 log_trace!(logger, "Buffered onion message {}", log_suffix);
1010 Ok(SendSuccess::BufferedAwaitingConnection(node_id)) => {
1013 "Buffered onion message waiting on peer connection {}: {}",
1022 fn find_path(&self, destination: Destination) -> Result<OnionMessagePath, SendError> {
1023 let sender = self.node_signer
1024 .get_node_id(Recipient::Node)
1025 .map_err(|_| SendError::GetNodeIdFailed)?;
1027 let peers = self.message_recipients.lock().unwrap()
1029 .filter(|(_, recipient)| matches!(recipient, OnionMessageRecipient::ConnectedPeer(_)))
1030 .map(|(node_id, _)| *node_id)
1034 .find_path(sender, peers, destination)
1035 .map_err(|_| SendError::PathNotFound)
1038 fn enqueue_onion_message<T: OnionMessageContents>(
1039 &self, path: OnionMessagePath, contents: T, reply_path: Option<BlindedPath>,
1040 log_suffix: fmt::Arguments
1041 ) -> Result<SendSuccess, SendError> {
1042 log_trace!(self.logger, "Constructing onion message {}: {:?}", log_suffix, contents);
1044 let (first_node_id, onion_message, addresses) = create_onion_message(
1045 &self.entropy_source, &self.node_signer, &self.node_id_lookup, &self.secp_ctx, path,
1046 contents, reply_path,
1049 let mut message_recipients = self.message_recipients.lock().unwrap();
1050 if outbound_buffer_full(&first_node_id, &message_recipients) {
1051 return Err(SendError::BufferFull);
1054 match message_recipients.entry(first_node_id) {
1055 hash_map::Entry::Vacant(e) => match addresses {
1056 None => Err(SendError::InvalidFirstHop(first_node_id)),
1057 Some(addresses) => {
1058 e.insert(OnionMessageRecipient::pending_connection(addresses))
1059 .enqueue_message(onion_message);
1060 Ok(SendSuccess::BufferedAwaitingConnection(first_node_id))
1063 hash_map::Entry::Occupied(mut e) => {
1064 e.get_mut().enqueue_message(onion_message);
1065 if e.get().is_connected() {
1066 Ok(SendSuccess::Buffered)
1068 Ok(SendSuccess::BufferedAwaitingConnection(first_node_id))
1074 /// Forwards an [`OnionMessage`] to `peer_node_id`. Useful if we initialized
1075 /// the [`OnionMessenger`] with [`Self::new_with_offline_peer_interception`]
1076 /// and want to forward a previously intercepted onion message to a peer that
1077 /// has just come online.
1078 pub fn forward_onion_message(
1079 &self, message: OnionMessage, peer_node_id: &PublicKey
1080 ) -> Result<(), SendError> {
1081 let mut message_recipients = self.message_recipients.lock().unwrap();
1082 if outbound_buffer_full(&peer_node_id, &message_recipients) {
1083 return Err(SendError::BufferFull);
1086 match message_recipients.entry(*peer_node_id) {
1087 hash_map::Entry::Occupied(mut e) if e.get().is_connected() => {
1088 e.get_mut().enqueue_message(message);
1091 _ => Err(SendError::InvalidFirstHop(*peer_node_id))
1095 #[cfg(any(test, feature = "_test_utils"))]
1096 pub fn send_onion_message_using_path<T: OnionMessageContents>(
1097 &self, path: OnionMessagePath, contents: T, reply_path: Option<BlindedPath>
1098 ) -> Result<SendSuccess, SendError> {
1099 self.enqueue_onion_message(path, contents, reply_path, format_args!(""))
1102 pub(crate) fn peel_onion_message(
1103 &self, msg: &OnionMessage
1104 ) -> Result<PeeledOnion<<<CMH>::Target as CustomOnionMessageHandler>::CustomMessage>, ()> {
1106 msg, &self.secp_ctx, &*self.node_signer, &*self.logger, &*self.custom_handler
1110 fn handle_onion_message_response<T: OnionMessageContents>(
1111 &self, response: ResponseInstruction<T>
1113 if let ResponseInstruction::WithoutReplyPath(response) = response {
1114 let message_type = response.message.msg_type();
1115 let _ = self.find_path_and_enqueue_onion_message(
1116 response.message, Destination::BlindedPath(response.reply_path), None,
1118 "when responding with {} to an onion message with path_id {:02x?}",
1127 pub(super) fn release_pending_msgs(&self) -> HashMap<PublicKey, VecDeque<OnionMessage>> {
1128 let mut message_recipients = self.message_recipients.lock().unwrap();
1129 let mut msgs = new_hash_map();
1130 // We don't want to disconnect the peers by removing them entirely from the original map, so we
1131 // release the pending message buffers individually.
1132 for (node_id, recipient) in &mut *message_recipients {
1133 msgs.insert(*node_id, recipient.release_pending_messages());
1138 fn enqueue_event(&self, event: Event) {
1139 const MAX_EVENTS_BUFFER_SIZE: usize = (1 << 10) * 256;
1140 let mut pending_events = self.pending_events.lock().unwrap();
1141 let total_buffered_bytes: usize = pending_events
1143 .map(|ev| ev.serialized_length())
1145 if total_buffered_bytes >= MAX_EVENTS_BUFFER_SIZE {
1146 log_trace!(self.logger, "Dropping event {:?}: buffer full", event);
1149 pending_events.push(event);
1153 fn outbound_buffer_full(peer_node_id: &PublicKey, buffer: &HashMap<PublicKey, OnionMessageRecipient>) -> bool {
1154 const MAX_TOTAL_BUFFER_SIZE: usize = (1 << 20) * 128;
1155 const MAX_PER_PEER_BUFFER_SIZE: usize = (1 << 10) * 256;
1156 let mut total_buffered_bytes = 0;
1157 let mut peer_buffered_bytes = 0;
1158 for (pk, peer_buf) in buffer {
1159 for om in peer_buf.pending_messages() {
1160 let om_len = om.serialized_length();
1161 if pk == peer_node_id {
1162 peer_buffered_bytes += om_len;
1164 total_buffered_bytes += om_len;
1166 if total_buffered_bytes >= MAX_TOTAL_BUFFER_SIZE ||
1167 peer_buffered_bytes >= MAX_PER_PEER_BUFFER_SIZE
1176 impl<ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, CMH: Deref> EventsProvider
1177 for OnionMessenger<ES, NS, L, NL, MR, OMH, CMH>
1179 ES::Target: EntropySource,
1180 NS::Target: NodeSigner,
1182 NL::Target: NodeIdLookUp,
1183 MR::Target: MessageRouter,
1184 OMH::Target: OffersMessageHandler,
1185 CMH::Target: CustomOnionMessageHandler,
1187 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
1188 for (node_id, recipient) in self.message_recipients.lock().unwrap().iter_mut() {
1189 if let OnionMessageRecipient::PendingConnection(_, addresses, _) = recipient {
1190 if let Some(addresses) = addresses.take() {
1191 handler.handle_event(Event::ConnectionNeeded { node_id: *node_id, addresses });
1195 let mut events = Vec::new();
1196 core::mem::swap(&mut *self.pending_events.lock().unwrap(), &mut events);
1198 handler.handle_event(ev);
1203 impl<ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, CMH: Deref> OnionMessageHandler
1204 for OnionMessenger<ES, NS, L, NL, MR, OMH, CMH>
1206 ES::Target: EntropySource,
1207 NS::Target: NodeSigner,
1209 NL::Target: NodeIdLookUp,
1210 MR::Target: MessageRouter,
1211 OMH::Target: OffersMessageHandler,
1212 CMH::Target: CustomOnionMessageHandler,
1214 fn handle_onion_message(&self, peer_node_id: &PublicKey, msg: &OnionMessage) {
1215 let logger = WithContext::from(&self.logger, Some(*peer_node_id), None, None);
1216 match self.peel_onion_message(msg) {
1217 Ok(PeeledOnion::Receive(message, path_id, reply_path)) => {
1220 "Received an onion message with path_id {:02x?} and {} reply_path: {:?}",
1221 path_id, if reply_path.is_some() { "a" } else { "no" }, message);
1224 ParsedOnionMessageContents::Offers(msg) => {
1225 let responder = reply_path.map(
1226 |reply_path| Responder::new(reply_path, path_id)
1228 let response_instructions = self.offers_handler.handle_message(msg, responder);
1229 self.handle_onion_message_response(response_instructions);
1231 ParsedOnionMessageContents::Custom(msg) => {
1232 let responder = reply_path.map(
1233 |reply_path| Responder::new(reply_path, path_id)
1235 let response_instructions = self.custom_handler.handle_custom_message(msg, responder);
1236 self.handle_onion_message_response(response_instructions);
1240 Ok(PeeledOnion::Forward(next_hop, onion_message)) => {
1241 let next_node_id = match next_hop {
1242 NextMessageHop::NodeId(pubkey) => pubkey,
1243 NextMessageHop::ShortChannelId(scid) => match self.node_id_lookup.next_node_id(scid) {
1244 Some(pubkey) => pubkey,
1246 log_trace!(self.logger, "Dropping forwarded onion messager: unable to resolve next hop using SCID {}", scid);
1252 let mut message_recipients = self.message_recipients.lock().unwrap();
1253 if outbound_buffer_full(&next_node_id, &message_recipients) {
1256 "Dropping forwarded onion message to peer {}: outbound buffer full",
1263 .entry(next_node_id)
1264 .or_insert_with(|| OnionMessageRecipient::ConnectedPeer(VecDeque::new()));
1266 match message_recipients.entry(next_node_id) {
1267 hash_map::Entry::Occupied(mut e) if matches!(
1268 e.get(), OnionMessageRecipient::ConnectedPeer(..)
1270 e.get_mut().enqueue_message(onion_message);
1271 log_trace!(logger, "Forwarding an onion message to peer {}", next_node_id);
1273 _ if self.intercept_messages_for_offline_peers => {
1275 Event::OnionMessageIntercepted {
1276 peer_node_id: next_node_id, message: onion_message
1283 "Dropping forwarded onion message to disconnected peer {}",
1290 log_error!(logger, "Failed to process onion message {:?}", e);
1295 fn peer_connected(&self, their_node_id: &PublicKey, init: &msgs::Init, _inbound: bool) -> Result<(), ()> {
1296 if init.features.supports_onion_messages() {
1297 self.message_recipients.lock().unwrap()
1298 .entry(*their_node_id)
1299 .or_insert_with(|| OnionMessageRecipient::ConnectedPeer(VecDeque::new()))
1301 if self.intercept_messages_for_offline_peers {
1303 Event::OnionMessagePeerConnected { peer_node_id: *their_node_id }
1307 self.message_recipients.lock().unwrap().remove(their_node_id);
1313 fn peer_disconnected(&self, their_node_id: &PublicKey) {
1314 match self.message_recipients.lock().unwrap().remove(their_node_id) {
1315 Some(OnionMessageRecipient::ConnectedPeer(..)) => {},
1316 Some(_) => debug_assert!(false),
1321 fn timer_tick_occurred(&self) {
1322 let mut message_recipients = self.message_recipients.lock().unwrap();
1324 // Drop any pending recipients since the last call to avoid retaining buffered messages for
1326 message_recipients.retain(|_, recipient| match recipient {
1327 OnionMessageRecipient::PendingConnection(_, None, ticks) => *ticks < MAX_TIMER_TICKS,
1328 OnionMessageRecipient::PendingConnection(_, Some(_), _) => true,
1332 // Increment a timer tick for pending recipients so that their buffered messages are dropped
1333 // at MAX_TIMER_TICKS.
1334 for recipient in message_recipients.values_mut() {
1335 if let OnionMessageRecipient::PendingConnection(_, None, ticks) = recipient {
1341 fn provided_node_features(&self) -> NodeFeatures {
1342 let mut features = NodeFeatures::empty();
1343 features.set_onion_messages_optional();
1347 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
1348 let mut features = InitFeatures::empty();
1349 features.set_onion_messages_optional();
1353 // Before returning any messages to send for the peer, this method will see if any messages were
1354 // enqueued in the handler by users, find a path to the corresponding blinded path's introduction
1355 // node, and then enqueue the message for sending to the first peer in the full path.
1356 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<OnionMessage> {
1357 // Enqueue any initiating `OffersMessage`s to send.
1358 for message in self.offers_handler.release_pending_messages() {
1359 #[cfg(not(c_bindings))]
1360 let PendingOnionMessage { contents, destination, reply_path } = message;
1362 let (contents, destination, reply_path) = message;
1363 let _ = self.find_path_and_enqueue_onion_message(
1364 contents, destination, reply_path, format_args!("when sending OffersMessage")
1368 // Enqueue any initiating `CustomMessage`s to send.
1369 for message in self.custom_handler.release_pending_custom_messages() {
1370 #[cfg(not(c_bindings))]
1371 let PendingOnionMessage { contents, destination, reply_path } = message;
1373 let (contents, destination, reply_path) = message;
1374 let _ = self.find_path_and_enqueue_onion_message(
1375 contents, destination, reply_path, format_args!("when sending CustomMessage")
1379 self.message_recipients.lock().unwrap()
1380 .get_mut(&peer_node_id)
1381 .and_then(|buffer| buffer.dequeue_message())
1385 // TODO: parameterize the below Simple* types with OnionMessenger and handle the messages it
1387 /// Useful for simplifying the parameters of [`SimpleArcChannelManager`] and
1388 /// [`SimpleArcPeerManager`]. See their docs for more details.
1390 /// This is not exported to bindings users as type aliases aren't supported in most languages.
1392 /// [`SimpleArcChannelManager`]: crate::ln::channelmanager::SimpleArcChannelManager
1393 /// [`SimpleArcPeerManager`]: crate::ln::peer_handler::SimpleArcPeerManager
1394 #[cfg(not(c_bindings))]
1395 pub type SimpleArcOnionMessenger<M, T, F, L> = OnionMessenger<
1399 Arc<SimpleArcChannelManager<M, T, F, L>>,
1400 Arc<DefaultMessageRouter<Arc<NetworkGraph<Arc<L>>>, Arc<L>, Arc<KeysManager>>>,
1401 Arc<SimpleArcChannelManager<M, T, F, L>>,
1402 IgnoringMessageHandler
1405 /// Useful for simplifying the parameters of [`SimpleRefChannelManager`] and
1406 /// [`SimpleRefPeerManager`]. See their docs for more details.
1408 /// This is not exported to bindings users as type aliases aren't supported in most languages.
1410 /// [`SimpleRefChannelManager`]: crate::ln::channelmanager::SimpleRefChannelManager
1411 /// [`SimpleRefPeerManager`]: crate::ln::peer_handler::SimpleRefPeerManager
1412 #[cfg(not(c_bindings))]
1413 pub type SimpleRefOnionMessenger<
1414 'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, M, T, F, L
1419 &'i SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L>,
1420 &'j DefaultMessageRouter<&'g NetworkGraph<&'b L>, &'b L, &'a KeysManager>,
1421 &'i SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L>,
1422 IgnoringMessageHandler
1425 /// Construct onion packet payloads and keys for sending an onion message along the given
1426 /// `unblinded_path` to the given `destination`.
1427 fn packet_payloads_and_keys<T: OnionMessageContents, S: secp256k1::Signing + secp256k1::Verification>(
1428 secp_ctx: &Secp256k1<S>, unblinded_path: &[PublicKey], destination: Destination, message: T,
1429 mut reply_path: Option<BlindedPath>, session_priv: &SecretKey
1430 ) -> Result<(Vec<(Payload<T>, [u8; 32])>, Vec<onion_utils::OnionKeys>), SendError> {
1431 let num_hops = unblinded_path.len() + destination.num_hops();
1432 let mut payloads = Vec::with_capacity(num_hops);
1433 let mut onion_packet_keys = Vec::with_capacity(num_hops);
1435 let (mut intro_node_id_blinding_pt, num_blinded_hops) = match &destination {
1436 Destination::Node(_) => (None, 0),
1437 Destination::BlindedPath(BlindedPath { introduction_node, blinding_point, blinded_hops }) => {
1438 let introduction_node_id = match introduction_node {
1439 IntroductionNode::NodeId(pubkey) => pubkey,
1440 IntroductionNode::DirectedShortChannelId(..) => {
1441 return Err(SendError::UnresolvedIntroductionNode);
1444 (Some((*introduction_node_id, *blinding_point)), blinded_hops.len())
1447 let num_unblinded_hops = num_hops - num_blinded_hops;
1449 let mut unblinded_path_idx = 0;
1450 let mut blinded_path_idx = 0;
1451 let mut prev_control_tlvs_ss = None;
1452 let mut final_control_tlvs = None;
1453 utils::construct_keys_callback(secp_ctx, unblinded_path.iter(), Some(destination), session_priv,
1454 |_, onion_packet_ss, ephemeral_pubkey, control_tlvs_ss, unblinded_pk_opt, enc_payload_opt| {
1455 if num_unblinded_hops != 0 && unblinded_path_idx < num_unblinded_hops {
1456 if let Some(ss) = prev_control_tlvs_ss.take() {
1457 payloads.push((Payload::Forward(ForwardControlTlvs::Unblinded(
1459 next_hop: NextMessageHop::NodeId(unblinded_pk_opt.unwrap()),
1460 next_blinding_override: None,
1464 prev_control_tlvs_ss = Some(control_tlvs_ss);
1465 unblinded_path_idx += 1;
1466 } else if let Some((intro_node_id, blinding_pt)) = intro_node_id_blinding_pt.take() {
1467 if let Some(control_tlvs_ss) = prev_control_tlvs_ss.take() {
1468 payloads.push((Payload::Forward(ForwardControlTlvs::Unblinded(ForwardTlvs {
1469 next_hop: NextMessageHop::NodeId(intro_node_id),
1470 next_blinding_override: Some(blinding_pt),
1471 })), control_tlvs_ss));
1474 if blinded_path_idx < num_blinded_hops.saturating_sub(1) && enc_payload_opt.is_some() {
1475 payloads.push((Payload::Forward(ForwardControlTlvs::Blinded(enc_payload_opt.unwrap())),
1477 blinded_path_idx += 1;
1478 } else if let Some(encrypted_payload) = enc_payload_opt {
1479 final_control_tlvs = Some(ReceiveControlTlvs::Blinded(encrypted_payload));
1480 prev_control_tlvs_ss = Some(control_tlvs_ss);
1483 let (rho, mu) = onion_utils::gen_rho_mu_from_shared_secret(onion_packet_ss.as_ref());
1484 onion_packet_keys.push(onion_utils::OnionKeys {
1486 shared_secret: onion_packet_ss,
1488 blinding_factor: [0; 32],
1494 ).map_err(|e| SendError::Secp256k1(e))?;
1496 if let Some(control_tlvs) = final_control_tlvs {
1497 payloads.push((Payload::Receive {
1499 reply_path: reply_path.take(),
1501 }, prev_control_tlvs_ss.unwrap()));
1503 payloads.push((Payload::Receive {
1504 control_tlvs: ReceiveControlTlvs::Unblinded(ReceiveTlvs { path_id: None, }),
1505 reply_path: reply_path.take(),
1507 }, prev_control_tlvs_ss.unwrap()));
1510 Ok((payloads, onion_packet_keys))
1513 /// Errors if the serialized payload size exceeds onion_message::BIG_PACKET_HOP_DATA_LEN
1514 fn construct_onion_message_packet<T: OnionMessageContents>(payloads: Vec<(Payload<T>, [u8; 32])>, onion_keys: Vec<onion_utils::OnionKeys>, prng_seed: [u8; 32]) -> Result<Packet, ()> {
1516 // "`len` allows larger messages to be sent than the standard 1300 bytes allowed for an HTLC
1517 // onion, but this should be used sparingly as it is reduces anonymity set, hence the
1518 // recommendation that it either look like an HTLC onion, or if larger, be a fixed size."
1519 let payloads_ser_len = onion_utils::payloads_serialized_length(&payloads);
1520 let hop_data_len = if payloads_ser_len <= SMALL_PACKET_HOP_DATA_LEN {
1521 SMALL_PACKET_HOP_DATA_LEN
1522 } else if payloads_ser_len <= BIG_PACKET_HOP_DATA_LEN {
1523 BIG_PACKET_HOP_DATA_LEN
1524 } else { return Err(()) };
1526 onion_utils::construct_onion_message_packet::<_, _>(
1527 payloads, onion_keys, prng_seed, hop_data_len)