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, ForwardNode, 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::blinded_path::message::ForwardNode;
139 /// # use lightning::sign::{EntropySource, KeysManager};
140 /// # use lightning::ln::peer_handler::IgnoringMessageHandler;
141 /// # use lightning::onion_message::messenger::{Destination, MessageRouter, OnionMessagePath, OnionMessenger};
142 /// # use lightning::onion_message::packet::OnionMessageContents;
143 /// # use lightning::util::logger::{Logger, Record};
144 /// # use lightning::util::ser::{Writeable, Writer};
145 /// # use lightning::io;
146 /// # use std::sync::Arc;
147 /// # struct FakeLogger;
148 /// # impl Logger for FakeLogger {
149 /// # fn log(&self, record: Record) { println!("{:?}" , record); }
151 /// # struct FakeMessageRouter {}
152 /// # impl MessageRouter for FakeMessageRouter {
153 /// # fn find_path(&self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination) -> Result<OnionMessagePath, ()> {
154 /// # let secp_ctx = Secp256k1::new();
155 /// # let node_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
156 /// # let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
157 /// # let hop_node_id2 = hop_node_id1;
158 /// # Ok(OnionMessagePath {
159 /// # intermediate_nodes: vec![hop_node_id1, hop_node_id2],
161 /// # first_node_addresses: None,
164 /// # fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
165 /// # &self, _recipient: PublicKey, _peers: Vec<PublicKey>, _secp_ctx: &Secp256k1<T>
166 /// # ) -> Result<Vec<BlindedPath>, ()> {
170 /// # let seed = [42u8; 32];
171 /// # let time = Duration::from_secs(123456);
172 /// # let keys_manager = KeysManager::new(&seed, time.as_secs(), time.subsec_nanos());
173 /// # let logger = Arc::new(FakeLogger {});
174 /// # let node_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
175 /// # let secp_ctx = Secp256k1::new();
176 /// # let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
177 /// # let (hop_node_id3, hop_node_id4) = (hop_node_id1, hop_node_id1);
178 /// # let destination_node_id = hop_node_id1;
179 /// # let node_id_lookup = EmptyNodeIdLookUp {};
180 /// # let message_router = Arc::new(FakeMessageRouter {});
181 /// # let custom_message_handler = IgnoringMessageHandler {};
182 /// # let offers_message_handler = IgnoringMessageHandler {};
183 /// // Create the onion messenger. This must use the same `keys_manager` as is passed to your
184 /// // ChannelManager.
185 /// let onion_messenger = OnionMessenger::new(
186 /// &keys_manager, &keys_manager, logger, &node_id_lookup, message_router,
187 /// &offers_message_handler, &custom_message_handler
190 /// # #[derive(Debug)]
191 /// # struct YourCustomMessage {}
192 /// impl Writeable for YourCustomMessage {
193 /// fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
195 /// // Write your custom onion message to `w`
198 /// impl OnionMessageContents for YourCustomMessage {
199 /// fn tlv_type(&self) -> u64 {
200 /// # let your_custom_message_type = 42;
201 /// your_custom_message_type
203 /// fn msg_type(&self) -> &'static str { "YourCustomMessageType" }
205 /// // Send a custom onion message to a node id.
206 /// let destination = Destination::Node(destination_node_id);
207 /// let reply_path = None;
208 /// # let message = YourCustomMessage {};
209 /// onion_messenger.send_onion_message(message, destination, reply_path);
211 /// // Create a blinded path to yourself, for someone to send an onion message to.
212 /// # let your_node_id = hop_node_id1;
214 /// ForwardNode { node_id: hop_node_id3, short_channel_id: None },
215 /// ForwardNode { node_id: hop_node_id4, short_channel_id: None },
217 /// let blinded_path = BlindedPath::new_for_message(&hops, your_node_id, &keys_manager, &secp_ctx).unwrap();
219 /// // Send a custom onion message to a blinded path.
220 /// let destination = Destination::BlindedPath(blinded_path);
221 /// let reply_path = None;
222 /// # let message = YourCustomMessage {};
223 /// onion_messenger.send_onion_message(message, destination, reply_path);
226 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
227 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
228 pub struct OnionMessenger<ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, CMH: Deref>
230 ES::Target: EntropySource,
231 NS::Target: NodeSigner,
233 NL::Target: NodeIdLookUp,
234 MR::Target: MessageRouter,
235 OMH::Target: OffersMessageHandler,
236 CMH::Target: CustomOnionMessageHandler,
241 message_recipients: Mutex<HashMap<PublicKey, OnionMessageRecipient>>,
242 secp_ctx: Secp256k1<secp256k1::All>,
247 intercept_messages_for_offline_peers: bool,
248 pending_events: Mutex<PendingEvents>,
251 struct PendingEvents {
252 intercepted_msgs: Vec<Event>,
253 peer_connecteds: Vec<Event>,
256 /// [`OnionMessage`]s buffered to be sent.
257 enum OnionMessageRecipient {
258 /// Messages for a node connected as a peer.
259 ConnectedPeer(VecDeque<OnionMessage>),
261 /// Messages for a node that is not yet connected, which are dropped after [`MAX_TIMER_TICKS`]
262 /// and tracked here.
263 PendingConnection(VecDeque<OnionMessage>, Option<Vec<SocketAddress>>, usize),
266 impl OnionMessageRecipient {
267 fn pending_connection(addresses: Vec<SocketAddress>) -> Self {
268 Self::PendingConnection(VecDeque::new(), Some(addresses), 0)
271 fn pending_messages(&self) -> &VecDeque<OnionMessage> {
273 OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
274 OnionMessageRecipient::PendingConnection(pending_messages, _, _) => pending_messages,
278 fn enqueue_message(&mut self, message: OnionMessage) {
279 let pending_messages = match self {
280 OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
281 OnionMessageRecipient::PendingConnection(pending_messages, _, _) => pending_messages,
284 pending_messages.push_back(message);
287 fn dequeue_message(&mut self) -> Option<OnionMessage> {
288 let pending_messages = match self {
289 OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
290 OnionMessageRecipient::PendingConnection(pending_messages, _, _) => {
291 debug_assert!(false);
296 pending_messages.pop_front()
300 fn release_pending_messages(&mut self) -> VecDeque<OnionMessage> {
301 let pending_messages = match self {
302 OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
303 OnionMessageRecipient::PendingConnection(pending_messages, _, _) => pending_messages,
306 core::mem::take(pending_messages)
309 fn mark_connected(&mut self) {
310 if let OnionMessageRecipient::PendingConnection(pending_messages, _, _) = self {
311 let mut new_pending_messages = VecDeque::new();
312 core::mem::swap(pending_messages, &mut new_pending_messages);
313 *self = OnionMessageRecipient::ConnectedPeer(new_pending_messages);
317 fn is_connected(&self) -> bool {
319 OnionMessageRecipient::ConnectedPeer(..) => true,
320 OnionMessageRecipient::PendingConnection(..) => false,
326 /// The `Responder` struct creates an appropriate [`ResponseInstruction`]
327 /// for responding to a message.
328 pub struct Responder {
329 /// The path along which a response can be sent.
330 reply_path: BlindedPath,
331 path_id: Option<[u8; 32]>
335 /// Creates a new [`Responder`] instance with the provided reply path.
336 pub(super) fn new(reply_path: BlindedPath, path_id: Option<[u8; 32]>) -> Self {
343 /// Creates a [`ResponseInstruction::WithoutReplyPath`] for a given response.
345 /// Use when the recipient doesn't need to send back a reply to us.
346 pub fn respond<T: OnionMessageContents>(self, response: T) -> ResponseInstruction<T> {
347 ResponseInstruction::WithoutReplyPath(OnionMessageResponse {
349 reply_path: self.reply_path,
350 path_id: self.path_id,
354 /// Creates a [`ResponseInstruction::WithReplyPath`] for a given response.
356 /// Use when the recipient needs to send back a reply to us.
357 pub fn respond_with_reply_path<T: OnionMessageContents>(self, response: T) -> ResponseInstruction<T> {
358 ResponseInstruction::WithReplyPath(OnionMessageResponse {
360 reply_path: self.reply_path,
361 path_id: self.path_id,
366 /// This struct contains the information needed to reply to a received message.
367 pub struct OnionMessageResponse<T: OnionMessageContents> {
369 reply_path: BlindedPath,
370 path_id: Option<[u8; 32]>,
373 /// `ResponseInstruction` represents instructions for responding to received messages.
374 pub enum ResponseInstruction<T: OnionMessageContents> {
375 /// Indicates that a response should be sent including a reply path for
376 /// the recipient to respond back.
377 WithReplyPath(OnionMessageResponse<T>),
378 /// Indicates that a response should be sent without including a reply path
379 /// for the recipient to respond back.
380 WithoutReplyPath(OnionMessageResponse<T>),
381 /// Indicates that there's no response to send back.
385 /// An [`OnionMessage`] for [`OnionMessenger`] to send.
387 /// These are obtained when released from [`OnionMessenger`]'s handlers after which they are
388 /// enqueued for sending.
389 #[cfg(not(c_bindings))]
390 pub struct PendingOnionMessage<T: OnionMessageContents> {
391 /// The message contents to send in an [`OnionMessage`].
394 /// The destination of the message.
395 pub destination: Destination,
397 /// A reply path to include in the [`OnionMessage`] for a response.
398 pub reply_path: Option<BlindedPath>,
402 /// An [`OnionMessage`] for [`OnionMessenger`] to send.
404 /// These are obtained when released from [`OnionMessenger`]'s handlers after which they are
405 /// enqueued for sending.
406 pub type PendingOnionMessage<T> = (T, Destination, Option<BlindedPath>);
408 pub(crate) fn new_pending_onion_message<T: OnionMessageContents>(
409 contents: T, destination: Destination, reply_path: Option<BlindedPath>
410 ) -> PendingOnionMessage<T> {
411 #[cfg(not(c_bindings))]
412 return PendingOnionMessage { contents, destination, reply_path };
414 return (contents, destination, reply_path);
417 /// A trait defining behavior for routing an [`OnionMessage`].
418 pub trait MessageRouter {
419 /// Returns a route for sending an [`OnionMessage`] to the given [`Destination`].
421 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
422 ) -> Result<OnionMessagePath, ()>;
424 /// Creates [`BlindedPath`]s to the `recipient` node. The nodes in `peers` are assumed to be
425 /// direct peers with the `recipient`.
426 fn create_blinded_paths<
427 T: secp256k1::Signing + secp256k1::Verification
429 &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
430 ) -> Result<Vec<BlindedPath>, ()>;
432 /// Creates compact [`BlindedPath`]s to the `recipient` node. The nodes in `peers` are assumed
433 /// to be direct peers with the `recipient`.
435 /// Compact blinded paths use short channel ids instead of pubkeys for a smaller serialization,
436 /// which is beneficial when a QR code is used to transport the data. The SCID is passed using a
437 /// [`ForwardNode`] but may be `None` for graceful degradation.
439 /// Implementations using additional intermediate nodes are responsible for using a
440 /// [`ForwardNode`] with `Some` short channel id, if possible. Similarly, implementations should
441 /// call [`BlindedPath::use_compact_introduction_node`].
443 /// The provided implementation simply delegates to [`MessageRouter::create_blinded_paths`],
444 /// ignoring the short channel ids.
445 fn create_compact_blinded_paths<
446 T: secp256k1::Signing + secp256k1::Verification
448 &self, recipient: PublicKey, peers: Vec<ForwardNode>, secp_ctx: &Secp256k1<T>,
449 ) -> Result<Vec<BlindedPath>, ()> {
452 .map(|ForwardNode { node_id, short_channel_id: _ }| node_id)
454 self.create_blinded_paths(recipient, peers, secp_ctx)
458 /// A [`MessageRouter`] that can only route to a directly connected [`Destination`].
462 /// Creating [`BlindedPath`]s may affect privacy since, if a suitable path cannot be found, it will
463 /// create a one-hop path using the recipient as the introduction node if it is a announced node.
464 /// Otherwise, there is no way to find a path to the introduction node in order to send a message,
465 /// and thus an `Err` is returned.
466 pub struct DefaultMessageRouter<G: Deref<Target=NetworkGraph<L>>, L: Deref, ES: Deref>
469 ES::Target: EntropySource,
475 impl<G: Deref<Target=NetworkGraph<L>>, L: Deref, ES: Deref> DefaultMessageRouter<G, L, ES>
478 ES::Target: EntropySource,
480 /// Creates a [`DefaultMessageRouter`] using the given [`NetworkGraph`].
481 pub fn new(network_graph: G, entropy_source: ES) -> Self {
482 Self { network_graph, entropy_source }
485 fn create_blinded_paths_from_iter<
486 I: Iterator<Item = ForwardNode>,
487 T: secp256k1::Signing + secp256k1::Verification
489 &self, recipient: PublicKey, peers: I, secp_ctx: &Secp256k1<T>, compact_paths: bool
490 ) -> Result<Vec<BlindedPath>, ()> {
491 // Limit the number of blinded paths that are computed.
492 const MAX_PATHS: usize = 3;
494 // Ensure peers have at least three channels so that it is more difficult to infer the
495 // recipient's node_id.
496 const MIN_PEER_CHANNELS: usize = 3;
498 let network_graph = self.network_graph.deref().read_only();
499 let is_recipient_announced =
500 network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient));
502 let mut peer_info = peers
503 // Limit to peers with announced channels
506 .node(&NodeId::from_pubkey(&peer.node_id))
507 .filter(|info| info.channels.len() >= MIN_PEER_CHANNELS)
508 .map(|info| (peer, info.is_tor_only(), info.channels.len()))
510 // Exclude Tor-only nodes when the recipient is announced.
511 .filter(|(_, is_tor_only, _)| !(*is_tor_only && is_recipient_announced))
512 .collect::<Vec<_>>();
514 // Prefer using non-Tor nodes with the most channels as the introduction node.
515 peer_info.sort_unstable_by(|(_, a_tor_only, a_channels), (_, b_tor_only, b_channels)| {
516 a_tor_only.cmp(b_tor_only).then(a_channels.cmp(b_channels).reverse())
519 let paths = peer_info.into_iter()
520 .map(|(peer, _, _)| {
521 BlindedPath::new_for_message(&[peer], recipient, &*self.entropy_source, secp_ctx)
524 .collect::<Result<Vec<_>, _>>();
526 let mut paths = match paths {
527 Ok(paths) if !paths.is_empty() => Ok(paths),
529 if is_recipient_announced {
530 BlindedPath::one_hop_for_message(recipient, &*self.entropy_source, secp_ctx)
531 .map(|path| vec![path])
539 for path in &mut paths {
540 path.use_compact_introduction_node(&network_graph);
548 impl<G: Deref<Target=NetworkGraph<L>>, L: Deref, ES: Deref> MessageRouter for DefaultMessageRouter<G, L, ES>
551 ES::Target: EntropySource,
554 &self, sender: PublicKey, peers: Vec<PublicKey>, mut destination: Destination
555 ) -> Result<OnionMessagePath, ()> {
556 let network_graph = self.network_graph.deref().read_only();
557 destination.resolve(&network_graph);
559 let first_node = match destination.first_node() {
560 Some(first_node) => first_node,
561 None => return Err(()),
564 if peers.contains(&first_node) || sender == first_node {
565 Ok(OnionMessagePath {
566 intermediate_nodes: vec![], destination, first_node_addresses: None
569 let node_details = network_graph
570 .node(&NodeId::from_pubkey(&first_node))
571 .and_then(|node_info| node_info.announcement_info.as_ref())
572 .map(|announcement_info| (announcement_info.features(), announcement_info.addresses()));
575 Some((features, addresses)) if features.supports_onion_messages() && addresses.len() > 0 => {
576 let first_node_addresses = Some(addresses.clone());
577 Ok(OnionMessagePath {
578 intermediate_nodes: vec![], destination, first_node_addresses
586 fn create_blinded_paths<
587 T: secp256k1::Signing + secp256k1::Verification
589 &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
590 ) -> Result<Vec<BlindedPath>, ()> {
593 .map(|node_id| ForwardNode { node_id, short_channel_id: None });
594 self.create_blinded_paths_from_iter(recipient, peers, secp_ctx, false)
597 fn create_compact_blinded_paths<
598 T: secp256k1::Signing + secp256k1::Verification
600 &self, recipient: PublicKey, peers: Vec<ForwardNode>, secp_ctx: &Secp256k1<T>,
601 ) -> Result<Vec<BlindedPath>, ()> {
602 self.create_blinded_paths_from_iter(recipient, peers.into_iter(), secp_ctx, true)
606 /// A path for sending an [`OnionMessage`].
608 pub struct OnionMessagePath {
609 /// Nodes on the path between the sender and the destination.
610 pub intermediate_nodes: Vec<PublicKey>,
612 /// The recipient of the message.
613 pub destination: Destination,
615 /// Addresses that may be used to connect to [`OnionMessagePath::first_node`].
617 /// Only needs to be set if a connection to the node is required. [`OnionMessenger`] may use
618 /// this to initiate such a connection.
619 pub first_node_addresses: Option<Vec<SocketAddress>>,
622 impl OnionMessagePath {
623 /// Returns the first node in the path.
624 pub fn first_node(&self) -> Option<PublicKey> {
625 self.intermediate_nodes
628 .or_else(|| self.destination.first_node())
632 /// The destination of an onion message.
633 #[derive(Clone, Hash, Debug, PartialEq, Eq)]
634 pub enum Destination {
635 /// We're sending this onion message to a node.
637 /// We're sending this onion message to a blinded path.
638 BlindedPath(BlindedPath),
642 /// Attempts to resolve the [`IntroductionNode::DirectedShortChannelId`] of a
643 /// [`Destination::BlindedPath`] to a [`IntroductionNode::NodeId`], if applicable, using the
644 /// provided [`ReadOnlyNetworkGraph`].
645 pub fn resolve(&mut self, network_graph: &ReadOnlyNetworkGraph) {
646 if let Destination::BlindedPath(path) = self {
647 if let IntroductionNode::DirectedShortChannelId(..) = path.introduction_node {
648 if let Some(pubkey) = path
649 .public_introduction_node_id(network_graph)
650 .and_then(|node_id| node_id.as_pubkey().ok())
652 path.introduction_node = IntroductionNode::NodeId(pubkey);
658 pub(super) fn num_hops(&self) -> usize {
660 Destination::Node(_) => 1,
661 Destination::BlindedPath(BlindedPath { blinded_hops, .. }) => blinded_hops.len(),
665 fn first_node(&self) -> Option<PublicKey> {
667 Destination::Node(node_id) => Some(*node_id),
668 Destination::BlindedPath(BlindedPath { introduction_node, .. }) => {
669 match introduction_node {
670 IntroductionNode::NodeId(pubkey) => Some(*pubkey),
671 IntroductionNode::DirectedShortChannelId(..) => None,
678 /// Result of successfully [sending an onion message].
680 /// [sending an onion message]: OnionMessenger::send_onion_message
681 #[derive(Clone, Hash, Debug, PartialEq, Eq)]
682 pub enum SendSuccess {
683 /// The message was buffered and will be sent once it is processed by
684 /// [`OnionMessageHandler::next_onion_message_for_peer`].
686 /// The message was buffered and will be sent once the node is connected as a peer and it is
687 /// processed by [`OnionMessageHandler::next_onion_message_for_peer`].
688 BufferedAwaitingConnection(PublicKey),
691 /// Errors that may occur when [sending an onion message].
693 /// [sending an onion message]: OnionMessenger::send_onion_message
694 #[derive(Clone, Hash, Debug, PartialEq, Eq)]
696 /// Errored computing onion message packet keys.
697 Secp256k1(secp256k1::Error),
698 /// Because implementations such as Eclair will drop onion messages where the message packet
699 /// exceeds 32834 bytes, we refuse to send messages where the packet exceeds this size.
701 /// The provided [`Destination`] was an invalid [`BlindedPath`] due to not having any blinded
704 /// The first hop is not a peer and doesn't have a known [`SocketAddress`].
705 InvalidFirstHop(PublicKey),
706 /// Indicates that a path could not be found by the [`MessageRouter`].
708 /// This occurs when either:
709 /// - No path from the sender to the destination was found to send the onion message
710 /// - No reply path to the sender could be created when responding to an onion message
712 /// Onion message contents must have a TLV type >= 64.
714 /// Our next-hop peer's buffer was full or our total outbound buffer was full.
716 /// Failed to retrieve our node id from the provided [`NodeSigner`].
718 /// [`NodeSigner`]: crate::sign::NodeSigner
720 /// The provided [`Destination`] has a blinded path with an unresolved introduction node. An
721 /// attempt to resolve it in the [`MessageRouter`] when finding an [`OnionMessagePath`] likely
723 UnresolvedIntroductionNode,
724 /// We attempted to send to a blinded path where we are the introduction node, and failed to
725 /// advance the blinded path to make the second hop the new introduction node. Either
726 /// [`NodeSigner::ecdh`] failed, we failed to tweak the current blinding point to get the
727 /// new blinding point, or we were attempting to send to ourselves.
728 BlindedPathAdvanceFailed,
731 /// Handler for custom onion messages. If you are using [`SimpleArcOnionMessenger`],
732 /// [`SimpleRefOnionMessenger`], or prefer to ignore inbound custom onion messages,
733 /// [`IgnoringMessageHandler`] must be provided to [`OnionMessenger::new`]. Otherwise, a custom
734 /// implementation of this trait must be provided, with [`CustomMessage`] specifying the supported
737 /// See [`OnionMessenger`] for example usage.
739 /// [`IgnoringMessageHandler`]: crate::ln::peer_handler::IgnoringMessageHandler
740 /// [`CustomMessage`]: Self::CustomMessage
741 pub trait CustomOnionMessageHandler {
742 /// The message known to the handler. To support multiple message types, you may want to make this
743 /// an enum with a variant for each supported message.
744 type CustomMessage: OnionMessageContents;
746 /// Called with the custom message that was received, returning a response to send, if any.
748 /// The returned [`Self::CustomMessage`], if any, is enqueued to be sent by [`OnionMessenger`].
749 fn handle_custom_message(&self, message: Self::CustomMessage, responder: Option<Responder>) -> ResponseInstruction<Self::CustomMessage>;
751 /// Read a custom message of type `message_type` from `buffer`, returning `Ok(None)` if the
752 /// message type is unknown.
753 fn read_custom_message<R: io::Read>(&self, message_type: u64, buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError>;
755 /// Releases any [`Self::CustomMessage`]s that need to be sent.
757 /// Typically, this is used for messages initiating a message flow rather than in response to
758 /// another message. The latter should use the return value of [`Self::handle_custom_message`].
759 #[cfg(not(c_bindings))]
760 fn release_pending_custom_messages(&self) -> Vec<PendingOnionMessage<Self::CustomMessage>>;
762 /// Releases any [`Self::CustomMessage`]s that need to be sent.
764 /// Typically, this is used for messages initiating a message flow rather than in response to
765 /// another message. The latter should use the return value of [`Self::handle_custom_message`].
767 fn release_pending_custom_messages(&self) -> Vec<(Self::CustomMessage, Destination, Option<BlindedPath>)>;
770 /// A processed incoming onion message, containing either a Forward (another onion message)
771 /// or a Receive payload with decrypted contents.
772 #[derive(Clone, Debug)]
773 pub enum PeeledOnion<T: OnionMessageContents> {
774 /// Forwarded onion, with the next node id and a new onion
775 Forward(NextMessageHop, OnionMessage),
776 /// Received onion message, with decrypted contents, path_id, and reply path
777 Receive(ParsedOnionMessageContents<T>, Option<[u8; 32]>, Option<BlindedPath>)
781 /// Creates an [`OnionMessage`] with the given `contents` for sending to the destination of
782 /// `path`, first calling [`Destination::resolve`] on `path.destination` with the given
783 /// [`ReadOnlyNetworkGraph`].
785 /// Returns the node id of the peer to send the message to, the message itself, and any addresses
786 /// needed to connect to the first node.
787 pub fn create_onion_message_resolving_destination<
788 ES: Deref, NS: Deref, NL: Deref, T: OnionMessageContents
790 entropy_source: &ES, node_signer: &NS, node_id_lookup: &NL,
791 network_graph: &ReadOnlyNetworkGraph, secp_ctx: &Secp256k1<secp256k1::All>,
792 mut path: OnionMessagePath, contents: T, reply_path: Option<BlindedPath>,
793 ) -> Result<(PublicKey, OnionMessage, Option<Vec<SocketAddress>>), SendError>
795 ES::Target: EntropySource,
796 NS::Target: NodeSigner,
797 NL::Target: NodeIdLookUp,
799 path.destination.resolve(network_graph);
800 create_onion_message(
801 entropy_source, node_signer, node_id_lookup, secp_ctx, path, contents, reply_path,
805 /// Creates an [`OnionMessage`] with the given `contents` for sending to the destination of
808 /// Returns the node id of the peer to send the message to, the message itself, and any addresses
809 /// needed to connect to the first node.
811 /// Returns [`SendError::UnresolvedIntroductionNode`] if:
812 /// - `destination` contains a blinded path with an [`IntroductionNode::DirectedShortChannelId`],
813 /// - unless it can be resolved by [`NodeIdLookUp::next_node_id`].
814 /// Use [`create_onion_message_resolving_destination`] instead to resolve the introduction node
815 /// first with a [`ReadOnlyNetworkGraph`].
816 pub fn create_onion_message<ES: Deref, NS: Deref, NL: Deref, T: OnionMessageContents>(
817 entropy_source: &ES, node_signer: &NS, node_id_lookup: &NL,
818 secp_ctx: &Secp256k1<secp256k1::All>, path: OnionMessagePath, contents: T,
819 reply_path: Option<BlindedPath>,
820 ) -> Result<(PublicKey, OnionMessage, Option<Vec<SocketAddress>>), SendError>
822 ES::Target: EntropySource,
823 NS::Target: NodeSigner,
824 NL::Target: NodeIdLookUp,
826 let OnionMessagePath { intermediate_nodes, mut destination, first_node_addresses } = path;
827 if let Destination::BlindedPath(BlindedPath { ref blinded_hops, .. }) = destination {
828 if blinded_hops.is_empty() {
829 return Err(SendError::TooFewBlindedHops);
833 if contents.tlv_type() < 64 { return Err(SendError::InvalidMessage) }
835 // If we are sending straight to a blinded path and we are the introduction node, we need to
836 // advance the blinded path by 1 hop so the second hop is the new introduction node.
837 if intermediate_nodes.len() == 0 {
838 if let Destination::BlindedPath(ref mut blinded_path) = destination {
839 let our_node_id = node_signer.get_node_id(Recipient::Node)
840 .map_err(|()| SendError::GetNodeIdFailed)?;
841 let introduction_node_id = match blinded_path.introduction_node {
842 IntroductionNode::NodeId(pubkey) => pubkey,
843 IntroductionNode::DirectedShortChannelId(direction, scid) => {
844 match node_id_lookup.next_node_id(scid) {
845 Some(next_node_id) => *direction.select_pubkey(&our_node_id, &next_node_id),
846 None => return Err(SendError::UnresolvedIntroductionNode),
850 if introduction_node_id == our_node_id {
851 advance_path_by_one(blinded_path, node_signer, node_id_lookup, &secp_ctx)
852 .map_err(|()| SendError::BlindedPathAdvanceFailed)?;
857 let blinding_secret_bytes = entropy_source.get_secure_random_bytes();
858 let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
859 let (first_node_id, blinding_point) = if let Some(first_node_id) = intermediate_nodes.first() {
860 (*first_node_id, PublicKey::from_secret_key(&secp_ctx, &blinding_secret))
863 Destination::Node(pk) => (*pk, PublicKey::from_secret_key(&secp_ctx, &blinding_secret)),
864 Destination::BlindedPath(BlindedPath { introduction_node, blinding_point, .. }) => {
865 match introduction_node {
866 IntroductionNode::NodeId(pubkey) => (*pubkey, *blinding_point),
867 IntroductionNode::DirectedShortChannelId(..) => {
868 return Err(SendError::UnresolvedIntroductionNode);
874 let (packet_payloads, packet_keys) = packet_payloads_and_keys(
875 &secp_ctx, &intermediate_nodes, destination, contents, reply_path, &blinding_secret
878 let prng_seed = entropy_source.get_secure_random_bytes();
879 let onion_routing_packet = construct_onion_message_packet(
880 packet_payloads, packet_keys, prng_seed).map_err(|()| SendError::TooBigPacket)?;
882 let message = OnionMessage { blinding_point, onion_routing_packet };
883 Ok((first_node_id, message, first_node_addresses))
886 /// Decode one layer of an incoming [`OnionMessage`].
888 /// Returns either the next layer of the onion for forwarding or the decrypted content for the
890 pub fn peel_onion_message<NS: Deref, L: Deref, CMH: Deref>(
891 msg: &OnionMessage, secp_ctx: &Secp256k1<secp256k1::All>, node_signer: NS, logger: L,
893 ) -> Result<PeeledOnion<<<CMH>::Target as CustomOnionMessageHandler>::CustomMessage>, ()>
895 NS::Target: NodeSigner,
897 CMH::Target: CustomOnionMessageHandler,
899 let control_tlvs_ss = match node_signer.ecdh(Recipient::Node, &msg.blinding_point, None) {
902 log_error!(logger, "Failed to retrieve node secret: {:?}", e);
906 let onion_decode_ss = {
907 let blinding_factor = {
908 let mut hmac = HmacEngine::<Sha256>::new(b"blinded_node_id");
909 hmac.input(control_tlvs_ss.as_ref());
910 Hmac::from_engine(hmac).to_byte_array()
912 match node_signer.ecdh(Recipient::Node, &msg.onion_routing_packet.public_key,
913 Some(&Scalar::from_be_bytes(blinding_factor).unwrap()))
915 Ok(ss) => ss.secret_bytes(),
917 log_trace!(logger, "Failed to compute onion packet shared secret");
922 match onion_utils::decode_next_untagged_hop(
923 onion_decode_ss, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac,
924 (control_tlvs_ss, custom_handler.deref(), logger.deref())
926 Ok((Payload::Receive::<ParsedOnionMessageContents<<<CMH as Deref>::Target as CustomOnionMessageHandler>::CustomMessage>> {
927 message, control_tlvs: ReceiveControlTlvs::Unblinded(ReceiveTlvs { path_id }), reply_path,
929 Ok(PeeledOnion::Receive(message, path_id, reply_path))
931 Ok((Payload::Forward(ForwardControlTlvs::Unblinded(ForwardTlvs {
932 next_hop, next_blinding_override
933 })), Some((next_hop_hmac, new_packet_bytes)))) => {
934 // TODO: we need to check whether `next_hop` is our node, in which case this is a dummy
935 // blinded hop and this onion message is destined for us. In this situation, we should keep
936 // unwrapping the onion layers to get to the final payload. Since we don't have the option
937 // of creating blinded paths with dummy hops currently, we should be ok to not handle this
939 let new_pubkey = match onion_utils::next_hop_pubkey(&secp_ctx, msg.onion_routing_packet.public_key, &onion_decode_ss) {
942 log_trace!(logger, "Failed to compute next hop packet pubkey: {}", e);
946 let outgoing_packet = Packet {
948 public_key: new_pubkey,
949 hop_data: new_packet_bytes,
952 let onion_message = OnionMessage {
953 blinding_point: match next_blinding_override {
954 Some(blinding_point) => blinding_point,
956 match onion_utils::next_hop_pubkey(
957 &secp_ctx, msg.blinding_point, control_tlvs_ss.as_ref()
961 log_trace!(logger, "Failed to compute next blinding point: {}", e);
967 onion_routing_packet: outgoing_packet,
970 Ok(PeeledOnion::Forward(next_hop, onion_message))
973 log_trace!(logger, "Errored decoding onion message packet: {:?}", e);
977 log_trace!(logger, "Received bogus onion message packet, either the sender encoded a final hop as a forwarding hop or vice versa");
983 impl<ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, CMH: Deref>
984 OnionMessenger<ES, NS, L, NL, MR, OMH, CMH>
986 ES::Target: EntropySource,
987 NS::Target: NodeSigner,
989 NL::Target: NodeIdLookUp,
990 MR::Target: MessageRouter,
991 OMH::Target: OffersMessageHandler,
992 CMH::Target: CustomOnionMessageHandler,
994 /// Constructs a new `OnionMessenger` to send, forward, and delegate received onion messages to
995 /// their respective handlers.
997 entropy_source: ES, node_signer: NS, logger: L, node_id_lookup: NL, message_router: MR,
998 offers_handler: OMH, custom_handler: CMH
1001 entropy_source, node_signer, logger, node_id_lookup, message_router,
1002 offers_handler, custom_handler, false
1006 /// Similar to [`Self::new`], but rather than dropping onion messages that are
1007 /// intended to be forwarded to offline peers, we will intercept them for
1008 /// later forwarding.
1010 /// Interception flow:
1011 /// 1. If an onion message for an offline peer is received, `OnionMessenger` will
1012 /// generate an [`Event::OnionMessageIntercepted`]. Event handlers can
1013 /// then choose to persist this onion message for later forwarding, or drop
1015 /// 2. When the offline peer later comes back online, `OnionMessenger` will
1016 /// generate an [`Event::OnionMessagePeerConnected`]. Event handlers will
1017 /// then fetch all previously intercepted onion messages for this peer.
1018 /// 3. Once the stored onion messages are fetched, they can finally be
1019 /// forwarded to the now-online peer via [`Self::forward_onion_message`].
1023 /// LDK will not rate limit how many [`Event::OnionMessageIntercepted`]s
1024 /// are generated, so it is the caller's responsibility to limit how many
1025 /// onion messages are persisted and only persist onion messages for relevant
1027 pub fn new_with_offline_peer_interception(
1028 entropy_source: ES, node_signer: NS, logger: L, node_id_lookup: NL,
1029 message_router: MR, offers_handler: OMH, custom_handler: CMH
1032 entropy_source, node_signer, logger, node_id_lookup, message_router,
1033 offers_handler, custom_handler, true
1038 entropy_source: ES, node_signer: NS, logger: L, node_id_lookup: NL,
1039 message_router: MR, offers_handler: OMH, custom_handler: CMH,
1040 intercept_messages_for_offline_peers: bool
1042 let mut secp_ctx = Secp256k1::new();
1043 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
1047 message_recipients: Mutex::new(new_hash_map()),
1054 intercept_messages_for_offline_peers,
1055 pending_events: Mutex::new(PendingEvents {
1056 intercepted_msgs: Vec::new(),
1057 peer_connecteds: Vec::new(),
1063 pub(crate) fn set_offers_handler(&mut self, offers_handler: OMH) {
1064 self.offers_handler = offers_handler;
1067 /// Sends an [`OnionMessage`] with the given `contents` to `destination`.
1069 /// See [`OnionMessenger`] for example usage.
1070 pub fn send_onion_message<T: OnionMessageContents>(
1071 &self, contents: T, destination: Destination, reply_path: Option<BlindedPath>
1072 ) -> Result<SendSuccess, SendError> {
1073 self.find_path_and_enqueue_onion_message(
1074 contents, destination, reply_path, format_args!("")
1078 fn find_path_and_enqueue_onion_message<T: OnionMessageContents>(
1079 &self, contents: T, destination: Destination, reply_path: Option<BlindedPath>,
1080 log_suffix: fmt::Arguments
1081 ) -> Result<SendSuccess, SendError> {
1082 let mut logger = WithContext::from(&self.logger, None, None, None);
1083 let result = self.find_path(destination).and_then(|path| {
1084 let first_hop = path.intermediate_nodes.get(0).map(|p| *p);
1085 logger = WithContext::from(&self.logger, first_hop, None, None);
1086 self.enqueue_onion_message(path, contents, reply_path, log_suffix)
1089 match result.as_ref() {
1090 Err(SendError::GetNodeIdFailed) => {
1091 log_warn!(logger, "Unable to retrieve node id {}", log_suffix);
1093 Err(SendError::PathNotFound) => {
1094 log_trace!(logger, "Failed to find path {}", log_suffix);
1097 log_trace!(logger, "Failed sending onion message {}: {:?}", log_suffix, e);
1099 Ok(SendSuccess::Buffered) => {
1100 log_trace!(logger, "Buffered onion message {}", log_suffix);
1102 Ok(SendSuccess::BufferedAwaitingConnection(node_id)) => {
1105 "Buffered onion message waiting on peer connection {}: {}",
1114 fn find_path(&self, destination: Destination) -> Result<OnionMessagePath, SendError> {
1115 let sender = self.node_signer
1116 .get_node_id(Recipient::Node)
1117 .map_err(|_| SendError::GetNodeIdFailed)?;
1119 let peers = self.message_recipients.lock().unwrap()
1121 .filter(|(_, recipient)| matches!(recipient, OnionMessageRecipient::ConnectedPeer(_)))
1122 .map(|(node_id, _)| *node_id)
1126 .find_path(sender, peers, destination)
1127 .map_err(|_| SendError::PathNotFound)
1130 fn create_blinded_path(&self) -> Result<BlindedPath, SendError> {
1131 let recipient = self.node_signer
1132 .get_node_id(Recipient::Node)
1133 .map_err(|_| SendError::GetNodeIdFailed)?;
1134 let secp_ctx = &self.secp_ctx;
1136 let peers = self.message_recipients.lock().unwrap()
1138 .filter(|(_, peer)| matches!(peer, OnionMessageRecipient::ConnectedPeer(_)))
1139 .map(|(node_id, _ )| *node_id)
1140 .collect::<Vec<_>>();
1143 .create_blinded_paths(recipient, peers, secp_ctx)
1144 .and_then(|paths| paths.into_iter().next().ok_or(()))
1145 .map_err(|_| SendError::PathNotFound)
1148 fn enqueue_onion_message<T: OnionMessageContents>(
1149 &self, path: OnionMessagePath, contents: T, reply_path: Option<BlindedPath>,
1150 log_suffix: fmt::Arguments
1151 ) -> Result<SendSuccess, SendError> {
1152 log_trace!(self.logger, "Constructing onion message {}: {:?}", log_suffix, contents);
1154 let (first_node_id, onion_message, addresses) = create_onion_message(
1155 &self.entropy_source, &self.node_signer, &self.node_id_lookup, &self.secp_ctx, path,
1156 contents, reply_path,
1159 let mut message_recipients = self.message_recipients.lock().unwrap();
1160 if outbound_buffer_full(&first_node_id, &message_recipients) {
1161 return Err(SendError::BufferFull);
1164 match message_recipients.entry(first_node_id) {
1165 hash_map::Entry::Vacant(e) => match addresses {
1166 None => Err(SendError::InvalidFirstHop(first_node_id)),
1167 Some(addresses) => {
1168 e.insert(OnionMessageRecipient::pending_connection(addresses))
1169 .enqueue_message(onion_message);
1170 Ok(SendSuccess::BufferedAwaitingConnection(first_node_id))
1173 hash_map::Entry::Occupied(mut e) => {
1174 e.get_mut().enqueue_message(onion_message);
1175 if e.get().is_connected() {
1176 Ok(SendSuccess::Buffered)
1178 Ok(SendSuccess::BufferedAwaitingConnection(first_node_id))
1184 /// Forwards an [`OnionMessage`] to `peer_node_id`. Useful if we initialized
1185 /// the [`OnionMessenger`] with [`Self::new_with_offline_peer_interception`]
1186 /// and want to forward a previously intercepted onion message to a peer that
1187 /// has just come online.
1188 pub fn forward_onion_message(
1189 &self, message: OnionMessage, peer_node_id: &PublicKey
1190 ) -> Result<(), SendError> {
1191 let mut message_recipients = self.message_recipients.lock().unwrap();
1192 if outbound_buffer_full(&peer_node_id, &message_recipients) {
1193 return Err(SendError::BufferFull);
1196 match message_recipients.entry(*peer_node_id) {
1197 hash_map::Entry::Occupied(mut e) if e.get().is_connected() => {
1198 e.get_mut().enqueue_message(message);
1201 _ => Err(SendError::InvalidFirstHop(*peer_node_id))
1205 #[cfg(any(test, feature = "_test_utils"))]
1206 pub fn send_onion_message_using_path<T: OnionMessageContents>(
1207 &self, path: OnionMessagePath, contents: T, reply_path: Option<BlindedPath>
1208 ) -> Result<SendSuccess, SendError> {
1209 self.enqueue_onion_message(path, contents, reply_path, format_args!(""))
1212 pub(crate) fn peel_onion_message(
1213 &self, msg: &OnionMessage
1214 ) -> Result<PeeledOnion<<<CMH>::Target as CustomOnionMessageHandler>::CustomMessage>, ()> {
1216 msg, &self.secp_ctx, &*self.node_signer, &*self.logger, &*self.custom_handler
1220 /// Handles the response to an [`OnionMessage`] based on its [`ResponseInstruction`],
1221 /// enqueueing any response for sending.
1223 /// This function is useful for asynchronous handling of [`OnionMessage`]s.
1224 /// Handlers have the option to return [`ResponseInstruction::NoResponse`], indicating that
1225 /// no immediate response should be sent. Then, they can transfer the associated [`Responder`]
1226 /// to another task responsible for generating the response asynchronously. Subsequently, when
1227 /// the response is prepared and ready for sending, that task can invoke this method to enqueue
1228 /// the response for delivery.
1229 pub fn handle_onion_message_response<T: OnionMessageContents>(
1230 &self, response: ResponseInstruction<T>
1231 ) -> Result<Option<SendSuccess>, SendError> {
1232 let (response, create_reply_path) = match response {
1233 ResponseInstruction::WithReplyPath(response) => (response, true),
1234 ResponseInstruction::WithoutReplyPath(response) => (response, false),
1235 ResponseInstruction::NoResponse => return Ok(None),
1238 let message_type = response.message.msg_type();
1239 let reply_path = if create_reply_path {
1240 match self.create_blinded_path() {
1241 Ok(reply_path) => Some(reply_path),
1245 "Failed to create reply path when responding with {} to an onion message \
1246 with path_id {:02x?}: {:?}",
1247 message_type, response.path_id, err
1254 self.find_path_and_enqueue_onion_message(
1255 response.message, Destination::BlindedPath(response.reply_path), reply_path,
1257 "when responding with {} to an onion message with path_id {:02x?}",
1261 ).map(|result| Some(result))
1265 pub(super) fn release_pending_msgs(&self) -> HashMap<PublicKey, VecDeque<OnionMessage>> {
1266 let mut message_recipients = self.message_recipients.lock().unwrap();
1267 let mut msgs = new_hash_map();
1268 // We don't want to disconnect the peers by removing them entirely from the original map, so we
1269 // release the pending message buffers individually.
1270 for (node_id, recipient) in &mut *message_recipients {
1271 msgs.insert(*node_id, recipient.release_pending_messages());
1276 fn enqueue_intercepted_event(&self, event: Event) {
1277 const MAX_EVENTS_BUFFER_SIZE: usize = (1 << 10) * 256;
1278 let mut pending_events = self.pending_events.lock().unwrap();
1279 let total_buffered_bytes: usize =
1280 pending_events.intercepted_msgs.iter().map(|ev| ev.serialized_length()).sum();
1281 if total_buffered_bytes >= MAX_EVENTS_BUFFER_SIZE {
1282 log_trace!(self.logger, "Dropping event {:?}: buffer full", event);
1285 pending_events.intercepted_msgs.push(event);
1288 /// Processes any events asynchronously using the given handler.
1290 /// Note that the event handler is called in the order each event was generated, however
1291 /// futures are polled in parallel for some events to allow for parallelism where events do not
1292 /// have an ordering requirement.
1294 /// See the trait-level documentation of [`EventsProvider`] for requirements.
1295 pub async fn process_pending_events_async<Future: core::future::Future<Output = ()> + core::marker::Unpin, H: Fn(Event) -> Future>(
1298 let mut intercepted_msgs = Vec::new();
1299 let mut peer_connecteds = Vec::new();
1301 let mut pending_events = self.pending_events.lock().unwrap();
1302 core::mem::swap(&mut pending_events.intercepted_msgs, &mut intercepted_msgs);
1303 core::mem::swap(&mut pending_events.peer_connecteds, &mut peer_connecteds);
1306 let mut futures = Vec::with_capacity(intercepted_msgs.len());
1307 for (node_id, recipient) in self.message_recipients.lock().unwrap().iter_mut() {
1308 if let OnionMessageRecipient::PendingConnection(_, addresses, _) = recipient {
1309 if let Some(addresses) = addresses.take() {
1310 futures.push(Some(handler(Event::ConnectionNeeded { node_id: *node_id, addresses })));
1315 for ev in intercepted_msgs {
1316 if let Event::OnionMessageIntercepted { .. } = ev {} else { debug_assert!(false); }
1317 futures.push(Some(handler(ev)));
1319 // Let the `OnionMessageIntercepted` events finish before moving on to peer_connecteds
1320 crate::util::async_poll::MultiFuturePoller(futures).await;
1322 if peer_connecteds.len() <= 1 {
1323 for event in peer_connecteds { handler(event).await; }
1325 let mut futures = Vec::new();
1326 for event in peer_connecteds {
1327 futures.push(Some(handler(event)));
1329 crate::util::async_poll::MultiFuturePoller(futures).await;
1334 fn outbound_buffer_full(peer_node_id: &PublicKey, buffer: &HashMap<PublicKey, OnionMessageRecipient>) -> bool {
1335 const MAX_TOTAL_BUFFER_SIZE: usize = (1 << 20) * 128;
1336 const MAX_PER_PEER_BUFFER_SIZE: usize = (1 << 10) * 256;
1337 let mut total_buffered_bytes = 0;
1338 let mut peer_buffered_bytes = 0;
1339 for (pk, peer_buf) in buffer {
1340 for om in peer_buf.pending_messages() {
1341 let om_len = om.serialized_length();
1342 if pk == peer_node_id {
1343 peer_buffered_bytes += om_len;
1345 total_buffered_bytes += om_len;
1347 if total_buffered_bytes >= MAX_TOTAL_BUFFER_SIZE ||
1348 peer_buffered_bytes >= MAX_PER_PEER_BUFFER_SIZE
1357 impl<ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, CMH: Deref> EventsProvider
1358 for OnionMessenger<ES, NS, L, NL, MR, OMH, CMH>
1360 ES::Target: EntropySource,
1361 NS::Target: NodeSigner,
1363 NL::Target: NodeIdLookUp,
1364 MR::Target: MessageRouter,
1365 OMH::Target: OffersMessageHandler,
1366 CMH::Target: CustomOnionMessageHandler,
1368 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
1369 for (node_id, recipient) in self.message_recipients.lock().unwrap().iter_mut() {
1370 if let OnionMessageRecipient::PendingConnection(_, addresses, _) = recipient {
1371 if let Some(addresses) = addresses.take() {
1372 handler.handle_event(Event::ConnectionNeeded { node_id: *node_id, addresses });
1376 let mut events = Vec::new();
1378 let mut pending_events = self.pending_events.lock().unwrap();
1379 #[cfg(debug_assertions)] {
1380 for ev in pending_events.intercepted_msgs.iter() {
1381 if let Event::OnionMessageIntercepted { .. } = ev {} else { panic!(); }
1383 for ev in pending_events.peer_connecteds.iter() {
1384 if let Event::OnionMessagePeerConnected { .. } = ev {} else { panic!(); }
1387 core::mem::swap(&mut pending_events.intercepted_msgs, &mut events);
1388 events.append(&mut pending_events.peer_connecteds);
1389 pending_events.peer_connecteds.shrink_to(10); // Limit total heap usage
1392 handler.handle_event(ev);
1397 impl<ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, CMH: Deref> OnionMessageHandler
1398 for OnionMessenger<ES, NS, L, NL, MR, OMH, CMH>
1400 ES::Target: EntropySource,
1401 NS::Target: NodeSigner,
1403 NL::Target: NodeIdLookUp,
1404 MR::Target: MessageRouter,
1405 OMH::Target: OffersMessageHandler,
1406 CMH::Target: CustomOnionMessageHandler,
1408 fn handle_onion_message(&self, peer_node_id: &PublicKey, msg: &OnionMessage) {
1409 let logger = WithContext::from(&self.logger, Some(*peer_node_id), None, None);
1410 match self.peel_onion_message(msg) {
1411 Ok(PeeledOnion::Receive(message, path_id, reply_path)) => {
1414 "Received an onion message with path_id {:02x?} and {} reply_path: {:?}",
1415 path_id, if reply_path.is_some() { "a" } else { "no" }, message);
1418 ParsedOnionMessageContents::Offers(msg) => {
1419 let responder = reply_path.map(
1420 |reply_path| Responder::new(reply_path, path_id)
1422 let response_instructions = self.offers_handler.handle_message(msg, responder);
1423 let _ = self.handle_onion_message_response(response_instructions);
1425 ParsedOnionMessageContents::Custom(msg) => {
1426 let responder = reply_path.map(
1427 |reply_path| Responder::new(reply_path, path_id)
1429 let response_instructions = self.custom_handler.handle_custom_message(msg, responder);
1430 let _ = self.handle_onion_message_response(response_instructions);
1434 Ok(PeeledOnion::Forward(next_hop, onion_message)) => {
1435 let next_node_id = match next_hop {
1436 NextMessageHop::NodeId(pubkey) => pubkey,
1437 NextMessageHop::ShortChannelId(scid) => match self.node_id_lookup.next_node_id(scid) {
1438 Some(pubkey) => pubkey,
1440 log_trace!(self.logger, "Dropping forwarded onion messager: unable to resolve next hop using SCID {}", scid);
1446 let mut message_recipients = self.message_recipients.lock().unwrap();
1447 if outbound_buffer_full(&next_node_id, &message_recipients) {
1450 "Dropping forwarded onion message to peer {}: outbound buffer full",
1457 .entry(next_node_id)
1458 .or_insert_with(|| OnionMessageRecipient::ConnectedPeer(VecDeque::new()));
1460 match message_recipients.entry(next_node_id) {
1461 hash_map::Entry::Occupied(mut e) if matches!(
1462 e.get(), OnionMessageRecipient::ConnectedPeer(..)
1464 e.get_mut().enqueue_message(onion_message);
1465 log_trace!(logger, "Forwarding an onion message to peer {}", next_node_id);
1467 _ if self.intercept_messages_for_offline_peers => {
1468 self.enqueue_intercepted_event(
1469 Event::OnionMessageIntercepted {
1470 peer_node_id: next_node_id, message: onion_message
1477 "Dropping forwarded onion message to disconnected peer {}",
1484 log_error!(logger, "Failed to process onion message {:?}", e);
1489 fn peer_connected(&self, their_node_id: &PublicKey, init: &msgs::Init, _inbound: bool) -> Result<(), ()> {
1490 if init.features.supports_onion_messages() {
1491 self.message_recipients.lock().unwrap()
1492 .entry(*their_node_id)
1493 .or_insert_with(|| OnionMessageRecipient::ConnectedPeer(VecDeque::new()))
1495 if self.intercept_messages_for_offline_peers {
1496 self.pending_events.lock().unwrap().peer_connecteds.push(
1497 Event::OnionMessagePeerConnected { peer_node_id: *their_node_id }
1501 self.message_recipients.lock().unwrap().remove(their_node_id);
1507 fn peer_disconnected(&self, their_node_id: &PublicKey) {
1508 match self.message_recipients.lock().unwrap().remove(their_node_id) {
1509 Some(OnionMessageRecipient::ConnectedPeer(..)) => {},
1510 Some(_) => debug_assert!(false),
1515 fn timer_tick_occurred(&self) {
1516 let mut message_recipients = self.message_recipients.lock().unwrap();
1518 // Drop any pending recipients since the last call to avoid retaining buffered messages for
1520 message_recipients.retain(|_, recipient| match recipient {
1521 OnionMessageRecipient::PendingConnection(_, None, ticks) => *ticks < MAX_TIMER_TICKS,
1522 OnionMessageRecipient::PendingConnection(_, Some(_), _) => true,
1526 // Increment a timer tick for pending recipients so that their buffered messages are dropped
1527 // at MAX_TIMER_TICKS.
1528 for recipient in message_recipients.values_mut() {
1529 if let OnionMessageRecipient::PendingConnection(_, None, ticks) = recipient {
1535 fn provided_node_features(&self) -> NodeFeatures {
1536 let mut features = NodeFeatures::empty();
1537 features.set_onion_messages_optional();
1541 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
1542 let mut features = InitFeatures::empty();
1543 features.set_onion_messages_optional();
1547 // Before returning any messages to send for the peer, this method will see if any messages were
1548 // enqueued in the handler by users, find a path to the corresponding blinded path's introduction
1549 // node, and then enqueue the message for sending to the first peer in the full path.
1550 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<OnionMessage> {
1551 // Enqueue any initiating `OffersMessage`s to send.
1552 for message in self.offers_handler.release_pending_messages() {
1553 #[cfg(not(c_bindings))]
1554 let PendingOnionMessage { contents, destination, reply_path } = message;
1556 let (contents, destination, reply_path) = message;
1557 let _ = self.find_path_and_enqueue_onion_message(
1558 contents, destination, reply_path, format_args!("when sending OffersMessage")
1562 // Enqueue any initiating `CustomMessage`s to send.
1563 for message in self.custom_handler.release_pending_custom_messages() {
1564 #[cfg(not(c_bindings))]
1565 let PendingOnionMessage { contents, destination, reply_path } = message;
1567 let (contents, destination, reply_path) = message;
1568 let _ = self.find_path_and_enqueue_onion_message(
1569 contents, destination, reply_path, format_args!("when sending CustomMessage")
1573 self.message_recipients.lock().unwrap()
1574 .get_mut(&peer_node_id)
1575 .and_then(|buffer| buffer.dequeue_message())
1579 // TODO: parameterize the below Simple* types with OnionMessenger and handle the messages it
1581 /// Useful for simplifying the parameters of [`SimpleArcChannelManager`] and
1582 /// [`SimpleArcPeerManager`]. See their docs for more details.
1584 /// This is not exported to bindings users as type aliases aren't supported in most languages.
1586 /// [`SimpleArcChannelManager`]: crate::ln::channelmanager::SimpleArcChannelManager
1587 /// [`SimpleArcPeerManager`]: crate::ln::peer_handler::SimpleArcPeerManager
1588 #[cfg(not(c_bindings))]
1589 pub type SimpleArcOnionMessenger<M, T, F, L> = OnionMessenger<
1593 Arc<SimpleArcChannelManager<M, T, F, L>>,
1594 Arc<DefaultMessageRouter<Arc<NetworkGraph<Arc<L>>>, Arc<L>, Arc<KeysManager>>>,
1595 Arc<SimpleArcChannelManager<M, T, F, L>>,
1596 IgnoringMessageHandler
1599 /// Useful for simplifying the parameters of [`SimpleRefChannelManager`] and
1600 /// [`SimpleRefPeerManager`]. See their docs for more details.
1602 /// This is not exported to bindings users as type aliases aren't supported in most languages.
1604 /// [`SimpleRefChannelManager`]: crate::ln::channelmanager::SimpleRefChannelManager
1605 /// [`SimpleRefPeerManager`]: crate::ln::peer_handler::SimpleRefPeerManager
1606 #[cfg(not(c_bindings))]
1607 pub type SimpleRefOnionMessenger<
1608 'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, M, T, F, L
1613 &'i SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L>,
1614 &'j DefaultMessageRouter<&'g NetworkGraph<&'b L>, &'b L, &'a KeysManager>,
1615 &'i SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L>,
1616 IgnoringMessageHandler
1619 /// Construct onion packet payloads and keys for sending an onion message along the given
1620 /// `unblinded_path` to the given `destination`.
1621 fn packet_payloads_and_keys<T: OnionMessageContents, S: secp256k1::Signing + secp256k1::Verification>(
1622 secp_ctx: &Secp256k1<S>, unblinded_path: &[PublicKey], destination: Destination, message: T,
1623 mut reply_path: Option<BlindedPath>, session_priv: &SecretKey
1624 ) -> Result<(Vec<(Payload<T>, [u8; 32])>, Vec<onion_utils::OnionKeys>), SendError> {
1625 let num_hops = unblinded_path.len() + destination.num_hops();
1626 let mut payloads = Vec::with_capacity(num_hops);
1627 let mut onion_packet_keys = Vec::with_capacity(num_hops);
1629 let (mut intro_node_id_blinding_pt, num_blinded_hops) = match &destination {
1630 Destination::Node(_) => (None, 0),
1631 Destination::BlindedPath(BlindedPath { introduction_node, blinding_point, blinded_hops }) => {
1632 let introduction_node_id = match introduction_node {
1633 IntroductionNode::NodeId(pubkey) => pubkey,
1634 IntroductionNode::DirectedShortChannelId(..) => {
1635 return Err(SendError::UnresolvedIntroductionNode);
1638 (Some((*introduction_node_id, *blinding_point)), blinded_hops.len())
1641 let num_unblinded_hops = num_hops - num_blinded_hops;
1643 let mut unblinded_path_idx = 0;
1644 let mut blinded_path_idx = 0;
1645 let mut prev_control_tlvs_ss = None;
1646 let mut final_control_tlvs = None;
1647 utils::construct_keys_callback(secp_ctx, unblinded_path.iter(), Some(destination), session_priv,
1648 |_, onion_packet_ss, ephemeral_pubkey, control_tlvs_ss, unblinded_pk_opt, enc_payload_opt| {
1649 if num_unblinded_hops != 0 && unblinded_path_idx < num_unblinded_hops {
1650 if let Some(ss) = prev_control_tlvs_ss.take() {
1651 payloads.push((Payload::Forward(ForwardControlTlvs::Unblinded(
1653 next_hop: NextMessageHop::NodeId(unblinded_pk_opt.unwrap()),
1654 next_blinding_override: None,
1658 prev_control_tlvs_ss = Some(control_tlvs_ss);
1659 unblinded_path_idx += 1;
1660 } else if let Some((intro_node_id, blinding_pt)) = intro_node_id_blinding_pt.take() {
1661 if let Some(control_tlvs_ss) = prev_control_tlvs_ss.take() {
1662 payloads.push((Payload::Forward(ForwardControlTlvs::Unblinded(ForwardTlvs {
1663 next_hop: NextMessageHop::NodeId(intro_node_id),
1664 next_blinding_override: Some(blinding_pt),
1665 })), control_tlvs_ss));
1668 if blinded_path_idx < num_blinded_hops.saturating_sub(1) && enc_payload_opt.is_some() {
1669 payloads.push((Payload::Forward(ForwardControlTlvs::Blinded(enc_payload_opt.unwrap())),
1671 blinded_path_idx += 1;
1672 } else if let Some(encrypted_payload) = enc_payload_opt {
1673 final_control_tlvs = Some(ReceiveControlTlvs::Blinded(encrypted_payload));
1674 prev_control_tlvs_ss = Some(control_tlvs_ss);
1677 let (rho, mu) = onion_utils::gen_rho_mu_from_shared_secret(onion_packet_ss.as_ref());
1678 onion_packet_keys.push(onion_utils::OnionKeys {
1680 shared_secret: onion_packet_ss,
1682 blinding_factor: [0; 32],
1688 ).map_err(|e| SendError::Secp256k1(e))?;
1690 if let Some(control_tlvs) = final_control_tlvs {
1691 payloads.push((Payload::Receive {
1693 reply_path: reply_path.take(),
1695 }, prev_control_tlvs_ss.unwrap()));
1697 payloads.push((Payload::Receive {
1698 control_tlvs: ReceiveControlTlvs::Unblinded(ReceiveTlvs { path_id: None, }),
1699 reply_path: reply_path.take(),
1701 }, prev_control_tlvs_ss.unwrap()));
1704 Ok((payloads, onion_packet_keys))
1707 /// Errors if the serialized payload size exceeds onion_message::BIG_PACKET_HOP_DATA_LEN
1708 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, ()> {
1710 // "`len` allows larger messages to be sent than the standard 1300 bytes allowed for an HTLC
1711 // onion, but this should be used sparingly as it is reduces anonymity set, hence the
1712 // recommendation that it either look like an HTLC onion, or if larger, be a fixed size."
1713 let payloads_ser_len = onion_utils::payloads_serialized_length(&payloads);
1714 let hop_data_len = if payloads_ser_len <= SMALL_PACKET_HOP_DATA_LEN {
1715 SMALL_PACKET_HOP_DATA_LEN
1716 } else if payloads_ser_len <= BIG_PACKET_HOP_DATA_LEN {
1717 BIG_PACKET_HOP_DATA_LEN
1718 } else { return Err(()) };
1720 onion_utils::construct_onion_message_packet::<_, _>(
1721 payloads, onion_keys, prng_seed, hop_data_len)