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<PendingEvents>,
247 struct PendingEvents {
248 intercepted_msgs: Vec<Event>,
249 peer_connecteds: Vec<Event>,
252 /// [`OnionMessage`]s buffered to be sent.
253 enum OnionMessageRecipient {
254 /// Messages for a node connected as a peer.
255 ConnectedPeer(VecDeque<OnionMessage>),
257 /// Messages for a node that is not yet connected, which are dropped after [`MAX_TIMER_TICKS`]
258 /// and tracked here.
259 PendingConnection(VecDeque<OnionMessage>, Option<Vec<SocketAddress>>, usize),
262 impl OnionMessageRecipient {
263 fn pending_connection(addresses: Vec<SocketAddress>) -> Self {
264 Self::PendingConnection(VecDeque::new(), Some(addresses), 0)
267 fn pending_messages(&self) -> &VecDeque<OnionMessage> {
269 OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
270 OnionMessageRecipient::PendingConnection(pending_messages, _, _) => pending_messages,
274 fn enqueue_message(&mut self, message: OnionMessage) {
275 let pending_messages = match self {
276 OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
277 OnionMessageRecipient::PendingConnection(pending_messages, _, _) => pending_messages,
280 pending_messages.push_back(message);
283 fn dequeue_message(&mut self) -> Option<OnionMessage> {
284 let pending_messages = match self {
285 OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
286 OnionMessageRecipient::PendingConnection(pending_messages, _, _) => {
287 debug_assert!(false);
292 pending_messages.pop_front()
296 fn release_pending_messages(&mut self) -> VecDeque<OnionMessage> {
297 let pending_messages = match self {
298 OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
299 OnionMessageRecipient::PendingConnection(pending_messages, _, _) => pending_messages,
302 core::mem::take(pending_messages)
305 fn mark_connected(&mut self) {
306 if let OnionMessageRecipient::PendingConnection(pending_messages, _, _) = self {
307 let mut new_pending_messages = VecDeque::new();
308 core::mem::swap(pending_messages, &mut new_pending_messages);
309 *self = OnionMessageRecipient::ConnectedPeer(new_pending_messages);
313 fn is_connected(&self) -> bool {
315 OnionMessageRecipient::ConnectedPeer(..) => true,
316 OnionMessageRecipient::PendingConnection(..) => false,
322 /// The `Responder` struct creates an appropriate [`ResponseInstruction`]
323 /// for responding to a message.
324 pub struct Responder {
325 /// The path along which a response can be sent.
326 reply_path: BlindedPath,
327 path_id: Option<[u8; 32]>
331 /// Creates a new [`Responder`] instance with the provided reply path.
332 fn new(reply_path: BlindedPath, path_id: Option<[u8; 32]>) -> Self {
339 /// Creates the appropriate [`ResponseInstruction`] for a given response.
340 pub fn respond<T: OnionMessageContents>(self, response: T) -> ResponseInstruction<T> {
341 ResponseInstruction::WithoutReplyPath(OnionMessageResponse {
343 reply_path: self.reply_path,
344 path_id: self.path_id,
349 /// This struct contains the information needed to reply to a received message.
350 pub struct OnionMessageResponse<T: OnionMessageContents> {
352 reply_path: BlindedPath,
353 path_id: Option<[u8; 32]>,
356 /// `ResponseInstruction` represents instructions for responding to received messages.
357 pub enum ResponseInstruction<T: OnionMessageContents> {
358 /// Indicates that a response should be sent without including a reply path
359 /// for the recipient to respond back.
360 WithoutReplyPath(OnionMessageResponse<T>),
361 /// Indicates that there's no response to send back.
365 /// An [`OnionMessage`] for [`OnionMessenger`] to send.
367 /// These are obtained when released from [`OnionMessenger`]'s handlers after which they are
368 /// enqueued for sending.
369 #[cfg(not(c_bindings))]
370 pub struct PendingOnionMessage<T: OnionMessageContents> {
371 /// The message contents to send in an [`OnionMessage`].
374 /// The destination of the message.
375 pub destination: Destination,
377 /// A reply path to include in the [`OnionMessage`] for a response.
378 pub reply_path: Option<BlindedPath>,
382 /// An [`OnionMessage`] for [`OnionMessenger`] to send.
384 /// These are obtained when released from [`OnionMessenger`]'s handlers after which they are
385 /// enqueued for sending.
386 pub type PendingOnionMessage<T> = (T, Destination, Option<BlindedPath>);
388 pub(crate) fn new_pending_onion_message<T: OnionMessageContents>(
389 contents: T, destination: Destination, reply_path: Option<BlindedPath>
390 ) -> PendingOnionMessage<T> {
391 #[cfg(not(c_bindings))]
392 return PendingOnionMessage { contents, destination, reply_path };
394 return (contents, destination, reply_path);
397 /// A trait defining behavior for routing an [`OnionMessage`].
398 pub trait MessageRouter {
399 /// Returns a route for sending an [`OnionMessage`] to the given [`Destination`].
401 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
402 ) -> Result<OnionMessagePath, ()>;
404 /// Creates [`BlindedPath`]s to the `recipient` node. The nodes in `peers` are assumed to be
405 /// direct peers with the `recipient`.
406 fn create_blinded_paths<
407 T: secp256k1::Signing + secp256k1::Verification
409 &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
410 ) -> Result<Vec<BlindedPath>, ()>;
413 /// A [`MessageRouter`] that can only route to a directly connected [`Destination`].
414 pub struct DefaultMessageRouter<G: Deref<Target=NetworkGraph<L>>, L: Deref, ES: Deref>
417 ES::Target: EntropySource,
423 impl<G: Deref<Target=NetworkGraph<L>>, L: Deref, ES: Deref> DefaultMessageRouter<G, L, ES>
426 ES::Target: EntropySource,
428 /// Creates a [`DefaultMessageRouter`] using the given [`NetworkGraph`].
429 pub fn new(network_graph: G, entropy_source: ES) -> Self {
430 Self { network_graph, entropy_source }
434 impl<G: Deref<Target=NetworkGraph<L>>, L: Deref, ES: Deref> MessageRouter for DefaultMessageRouter<G, L, ES>
437 ES::Target: EntropySource,
440 &self, sender: PublicKey, peers: Vec<PublicKey>, mut destination: Destination
441 ) -> Result<OnionMessagePath, ()> {
442 let network_graph = self.network_graph.deref().read_only();
443 destination.resolve(&network_graph);
445 let first_node = match destination.first_node() {
446 Some(first_node) => first_node,
447 None => return Err(()),
450 if peers.contains(&first_node) || sender == first_node {
451 Ok(OnionMessagePath {
452 intermediate_nodes: vec![], destination, first_node_addresses: None
455 let node_announcement = network_graph
456 .node(&NodeId::from_pubkey(&first_node))
457 .and_then(|node_info| node_info.announcement_info.as_ref())
458 .and_then(|announcement_info| announcement_info.announcement_message.as_ref())
459 .map(|node_announcement| &node_announcement.contents);
461 match node_announcement {
462 Some(node_announcement) if node_announcement.features.supports_onion_messages() => {
463 let first_node_addresses = Some(node_announcement.addresses.clone());
464 Ok(OnionMessagePath {
465 intermediate_nodes: vec![], destination, first_node_addresses
473 fn create_blinded_paths<
474 T: secp256k1::Signing + secp256k1::Verification
476 &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
477 ) -> Result<Vec<BlindedPath>, ()> {
478 // Limit the number of blinded paths that are computed.
479 const MAX_PATHS: usize = 3;
481 // Ensure peers have at least three channels so that it is more difficult to infer the
482 // recipient's node_id.
483 const MIN_PEER_CHANNELS: usize = 3;
485 let network_graph = self.network_graph.deref().read_only();
486 let is_recipient_announced =
487 network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient));
489 let mut peer_info = peers.iter()
490 // Limit to peers with announced channels
493 .node(&NodeId::from_pubkey(pubkey))
494 .filter(|info| info.channels.len() >= MIN_PEER_CHANNELS)
495 .map(|info| (*pubkey, info.is_tor_only(), info.channels.len()))
497 // Exclude Tor-only nodes when the recipient is announced.
498 .filter(|(_, is_tor_only, _)| !(*is_tor_only && is_recipient_announced))
499 .collect::<Vec<_>>();
501 // Prefer using non-Tor nodes with the most channels as the introduction node.
502 peer_info.sort_unstable_by(|(_, a_tor_only, a_channels), (_, b_tor_only, b_channels)| {
503 a_tor_only.cmp(b_tor_only).then(a_channels.cmp(b_channels).reverse())
506 let paths = peer_info.into_iter()
507 .map(|(pubkey, _, _)| vec![pubkey, recipient])
508 .map(|node_pks| BlindedPath::new_for_message(&node_pks, &*self.entropy_source, secp_ctx))
510 .collect::<Result<Vec<_>, _>>();
513 Ok(paths) if !paths.is_empty() => Ok(paths),
515 if is_recipient_announced {
516 BlindedPath::one_hop_for_message(recipient, &*self.entropy_source, secp_ctx)
517 .map(|path| vec![path])
526 /// A path for sending an [`OnionMessage`].
528 pub struct OnionMessagePath {
529 /// Nodes on the path between the sender and the destination.
530 pub intermediate_nodes: Vec<PublicKey>,
532 /// The recipient of the message.
533 pub destination: Destination,
535 /// Addresses that may be used to connect to [`OnionMessagePath::first_node`].
537 /// Only needs to be set if a connection to the node is required. [`OnionMessenger`] may use
538 /// this to initiate such a connection.
539 pub first_node_addresses: Option<Vec<SocketAddress>>,
542 impl OnionMessagePath {
543 /// Returns the first node in the path.
544 pub fn first_node(&self) -> Option<PublicKey> {
545 self.intermediate_nodes
548 .or_else(|| self.destination.first_node())
552 /// The destination of an onion message.
553 #[derive(Clone, Hash, Debug, PartialEq, Eq)]
554 pub enum Destination {
555 /// We're sending this onion message to a node.
557 /// We're sending this onion message to a blinded path.
558 BlindedPath(BlindedPath),
562 /// Attempts to resolve the [`IntroductionNode::DirectedShortChannelId`] of a
563 /// [`Destination::BlindedPath`] to a [`IntroductionNode::NodeId`], if applicable, using the
564 /// provided [`ReadOnlyNetworkGraph`].
565 pub fn resolve(&mut self, network_graph: &ReadOnlyNetworkGraph) {
566 if let Destination::BlindedPath(path) = self {
567 if let IntroductionNode::DirectedShortChannelId(..) = path.introduction_node {
568 if let Some(pubkey) = path
569 .public_introduction_node_id(network_graph)
570 .and_then(|node_id| node_id.as_pubkey().ok())
572 path.introduction_node = IntroductionNode::NodeId(pubkey);
578 pub(super) fn num_hops(&self) -> usize {
580 Destination::Node(_) => 1,
581 Destination::BlindedPath(BlindedPath { blinded_hops, .. }) => blinded_hops.len(),
585 fn first_node(&self) -> Option<PublicKey> {
587 Destination::Node(node_id) => Some(*node_id),
588 Destination::BlindedPath(BlindedPath { introduction_node, .. }) => {
589 match introduction_node {
590 IntroductionNode::NodeId(pubkey) => Some(*pubkey),
591 IntroductionNode::DirectedShortChannelId(..) => None,
598 /// Result of successfully [sending an onion message].
600 /// [sending an onion message]: OnionMessenger::send_onion_message
601 #[derive(Clone, Hash, Debug, PartialEq, Eq)]
602 pub enum SendSuccess {
603 /// The message was buffered and will be sent once it is processed by
604 /// [`OnionMessageHandler::next_onion_message_for_peer`].
606 /// The message was buffered and will be sent once the node is connected as a peer and it is
607 /// processed by [`OnionMessageHandler::next_onion_message_for_peer`].
608 BufferedAwaitingConnection(PublicKey),
611 /// Errors that may occur when [sending an onion message].
613 /// [sending an onion message]: OnionMessenger::send_onion_message
614 #[derive(Clone, Hash, Debug, PartialEq, Eq)]
616 /// Errored computing onion message packet keys.
617 Secp256k1(secp256k1::Error),
618 /// Because implementations such as Eclair will drop onion messages where the message packet
619 /// exceeds 32834 bytes, we refuse to send messages where the packet exceeds this size.
621 /// The provided [`Destination`] was an invalid [`BlindedPath`] due to not having any blinded
624 /// The first hop is not a peer and doesn't have a known [`SocketAddress`].
625 InvalidFirstHop(PublicKey),
626 /// A path from the sender to the destination could not be found by the [`MessageRouter`].
628 /// Onion message contents must have a TLV type >= 64.
630 /// Our next-hop peer's buffer was full or our total outbound buffer was full.
632 /// Failed to retrieve our node id from the provided [`NodeSigner`].
634 /// [`NodeSigner`]: crate::sign::NodeSigner
636 /// The provided [`Destination`] has a blinded path with an unresolved introduction node. An
637 /// attempt to resolve it in the [`MessageRouter`] when finding an [`OnionMessagePath`] likely
639 UnresolvedIntroductionNode,
640 /// We attempted to send to a blinded path where we are the introduction node, and failed to
641 /// advance the blinded path to make the second hop the new introduction node. Either
642 /// [`NodeSigner::ecdh`] failed, we failed to tweak the current blinding point to get the
643 /// new blinding point, or we were attempting to send to ourselves.
644 BlindedPathAdvanceFailed,
647 /// Handler for custom onion messages. If you are using [`SimpleArcOnionMessenger`],
648 /// [`SimpleRefOnionMessenger`], or prefer to ignore inbound custom onion messages,
649 /// [`IgnoringMessageHandler`] must be provided to [`OnionMessenger::new`]. Otherwise, a custom
650 /// implementation of this trait must be provided, with [`CustomMessage`] specifying the supported
653 /// See [`OnionMessenger`] for example usage.
655 /// [`IgnoringMessageHandler`]: crate::ln::peer_handler::IgnoringMessageHandler
656 /// [`CustomMessage`]: Self::CustomMessage
657 pub trait CustomOnionMessageHandler {
658 /// The message known to the handler. To support multiple message types, you may want to make this
659 /// an enum with a variant for each supported message.
660 type CustomMessage: OnionMessageContents;
662 /// Called with the custom message that was received, returning a response to send, if any.
664 /// The returned [`Self::CustomMessage`], if any, is enqueued to be sent by [`OnionMessenger`].
665 fn handle_custom_message(&self, message: Self::CustomMessage, responder: Option<Responder>) -> ResponseInstruction<Self::CustomMessage>;
667 /// Read a custom message of type `message_type` from `buffer`, returning `Ok(None)` if the
668 /// message type is unknown.
669 fn read_custom_message<R: io::Read>(&self, message_type: u64, buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError>;
671 /// Releases any [`Self::CustomMessage`]s that need to be sent.
673 /// Typically, this is used for messages initiating a message flow rather than in response to
674 /// another message. The latter should use the return value of [`Self::handle_custom_message`].
675 #[cfg(not(c_bindings))]
676 fn release_pending_custom_messages(&self) -> Vec<PendingOnionMessage<Self::CustomMessage>>;
678 /// Releases any [`Self::CustomMessage`]s that need to be sent.
680 /// Typically, this is used for messages initiating a message flow rather than in response to
681 /// another message. The latter should use the return value of [`Self::handle_custom_message`].
683 fn release_pending_custom_messages(&self) -> Vec<(Self::CustomMessage, Destination, Option<BlindedPath>)>;
686 /// A processed incoming onion message, containing either a Forward (another onion message)
687 /// or a Receive payload with decrypted contents.
688 #[derive(Clone, Debug)]
689 pub enum PeeledOnion<T: OnionMessageContents> {
690 /// Forwarded onion, with the next node id and a new onion
691 Forward(NextMessageHop, OnionMessage),
692 /// Received onion message, with decrypted contents, path_id, and reply path
693 Receive(ParsedOnionMessageContents<T>, Option<[u8; 32]>, Option<BlindedPath>)
697 /// Creates an [`OnionMessage`] with the given `contents` for sending to the destination of
698 /// `path`, first calling [`Destination::resolve`] on `path.destination` with the given
699 /// [`ReadOnlyNetworkGraph`].
701 /// Returns the node id of the peer to send the message to, the message itself, and any addresses
702 /// needed to connect to the first node.
703 pub fn create_onion_message_resolving_destination<
704 ES: Deref, NS: Deref, NL: Deref, T: OnionMessageContents
706 entropy_source: &ES, node_signer: &NS, node_id_lookup: &NL,
707 network_graph: &ReadOnlyNetworkGraph, secp_ctx: &Secp256k1<secp256k1::All>,
708 mut path: OnionMessagePath, contents: T, reply_path: Option<BlindedPath>,
709 ) -> Result<(PublicKey, OnionMessage, Option<Vec<SocketAddress>>), SendError>
711 ES::Target: EntropySource,
712 NS::Target: NodeSigner,
713 NL::Target: NodeIdLookUp,
715 path.destination.resolve(network_graph);
716 create_onion_message(
717 entropy_source, node_signer, node_id_lookup, secp_ctx, path, contents, reply_path,
721 /// Creates an [`OnionMessage`] with the given `contents` for sending to the destination of
724 /// Returns the node id of the peer to send the message to, the message itself, and any addresses
725 /// needed to connect to the first node.
727 /// Returns [`SendError::UnresolvedIntroductionNode`] if:
728 /// - `destination` contains a blinded path with an [`IntroductionNode::DirectedShortChannelId`],
729 /// - unless it can be resolved by [`NodeIdLookUp::next_node_id`].
730 /// Use [`create_onion_message_resolving_destination`] instead to resolve the introduction node
731 /// first with a [`ReadOnlyNetworkGraph`].
732 pub fn create_onion_message<ES: Deref, NS: Deref, NL: Deref, T: OnionMessageContents>(
733 entropy_source: &ES, node_signer: &NS, node_id_lookup: &NL,
734 secp_ctx: &Secp256k1<secp256k1::All>, path: OnionMessagePath, contents: T,
735 reply_path: Option<BlindedPath>,
736 ) -> Result<(PublicKey, OnionMessage, Option<Vec<SocketAddress>>), SendError>
738 ES::Target: EntropySource,
739 NS::Target: NodeSigner,
740 NL::Target: NodeIdLookUp,
742 let OnionMessagePath { intermediate_nodes, mut destination, first_node_addresses } = path;
743 if let Destination::BlindedPath(BlindedPath { ref blinded_hops, .. }) = destination {
744 if blinded_hops.is_empty() {
745 return Err(SendError::TooFewBlindedHops);
749 if contents.tlv_type() < 64 { return Err(SendError::InvalidMessage) }
751 // If we are sending straight to a blinded path and we are the introduction node, we need to
752 // advance the blinded path by 1 hop so the second hop is the new introduction node.
753 if intermediate_nodes.len() == 0 {
754 if let Destination::BlindedPath(ref mut blinded_path) = destination {
755 let our_node_id = node_signer.get_node_id(Recipient::Node)
756 .map_err(|()| SendError::GetNodeIdFailed)?;
757 let introduction_node_id = match blinded_path.introduction_node {
758 IntroductionNode::NodeId(pubkey) => pubkey,
759 IntroductionNode::DirectedShortChannelId(direction, scid) => {
760 match node_id_lookup.next_node_id(scid) {
761 Some(next_node_id) => *direction.select_pubkey(&our_node_id, &next_node_id),
762 None => return Err(SendError::UnresolvedIntroductionNode),
766 if introduction_node_id == our_node_id {
767 advance_path_by_one(blinded_path, node_signer, node_id_lookup, &secp_ctx)
768 .map_err(|()| SendError::BlindedPathAdvanceFailed)?;
773 let blinding_secret_bytes = entropy_source.get_secure_random_bytes();
774 let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
775 let (first_node_id, blinding_point) = if let Some(first_node_id) = intermediate_nodes.first() {
776 (*first_node_id, PublicKey::from_secret_key(&secp_ctx, &blinding_secret))
779 Destination::Node(pk) => (*pk, PublicKey::from_secret_key(&secp_ctx, &blinding_secret)),
780 Destination::BlindedPath(BlindedPath { introduction_node, blinding_point, .. }) => {
781 match introduction_node {
782 IntroductionNode::NodeId(pubkey) => (*pubkey, *blinding_point),
783 IntroductionNode::DirectedShortChannelId(..) => {
784 return Err(SendError::UnresolvedIntroductionNode);
790 let (packet_payloads, packet_keys) = packet_payloads_and_keys(
791 &secp_ctx, &intermediate_nodes, destination, contents, reply_path, &blinding_secret
794 let prng_seed = entropy_source.get_secure_random_bytes();
795 let onion_routing_packet = construct_onion_message_packet(
796 packet_payloads, packet_keys, prng_seed).map_err(|()| SendError::TooBigPacket)?;
798 let message = OnionMessage { blinding_point, onion_routing_packet };
799 Ok((first_node_id, message, first_node_addresses))
802 /// Decode one layer of an incoming [`OnionMessage`].
804 /// Returns either the next layer of the onion for forwarding or the decrypted content for the
806 pub fn peel_onion_message<NS: Deref, L: Deref, CMH: Deref>(
807 msg: &OnionMessage, secp_ctx: &Secp256k1<secp256k1::All>, node_signer: NS, logger: L,
809 ) -> Result<PeeledOnion<<<CMH>::Target as CustomOnionMessageHandler>::CustomMessage>, ()>
811 NS::Target: NodeSigner,
813 CMH::Target: CustomOnionMessageHandler,
815 let control_tlvs_ss = match node_signer.ecdh(Recipient::Node, &msg.blinding_point, None) {
818 log_error!(logger, "Failed to retrieve node secret: {:?}", e);
822 let onion_decode_ss = {
823 let blinding_factor = {
824 let mut hmac = HmacEngine::<Sha256>::new(b"blinded_node_id");
825 hmac.input(control_tlvs_ss.as_ref());
826 Hmac::from_engine(hmac).to_byte_array()
828 match node_signer.ecdh(Recipient::Node, &msg.onion_routing_packet.public_key,
829 Some(&Scalar::from_be_bytes(blinding_factor).unwrap()))
831 Ok(ss) => ss.secret_bytes(),
833 log_trace!(logger, "Failed to compute onion packet shared secret");
838 match onion_utils::decode_next_untagged_hop(
839 onion_decode_ss, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac,
840 (control_tlvs_ss, custom_handler.deref(), logger.deref())
842 Ok((Payload::Receive::<ParsedOnionMessageContents<<<CMH as Deref>::Target as CustomOnionMessageHandler>::CustomMessage>> {
843 message, control_tlvs: ReceiveControlTlvs::Unblinded(ReceiveTlvs { path_id }), reply_path,
845 Ok(PeeledOnion::Receive(message, path_id, reply_path))
847 Ok((Payload::Forward(ForwardControlTlvs::Unblinded(ForwardTlvs {
848 next_hop, next_blinding_override
849 })), Some((next_hop_hmac, new_packet_bytes)))) => {
850 // TODO: we need to check whether `next_hop` is our node, in which case this is a dummy
851 // blinded hop and this onion message is destined for us. In this situation, we should keep
852 // unwrapping the onion layers to get to the final payload. Since we don't have the option
853 // of creating blinded paths with dummy hops currently, we should be ok to not handle this
855 let new_pubkey = match onion_utils::next_hop_pubkey(&secp_ctx, msg.onion_routing_packet.public_key, &onion_decode_ss) {
858 log_trace!(logger, "Failed to compute next hop packet pubkey: {}", e);
862 let outgoing_packet = Packet {
864 public_key: new_pubkey,
865 hop_data: new_packet_bytes,
868 let onion_message = OnionMessage {
869 blinding_point: match next_blinding_override {
870 Some(blinding_point) => blinding_point,
872 match onion_utils::next_hop_pubkey(
873 &secp_ctx, msg.blinding_point, control_tlvs_ss.as_ref()
877 log_trace!(logger, "Failed to compute next blinding point: {}", e);
883 onion_routing_packet: outgoing_packet,
886 Ok(PeeledOnion::Forward(next_hop, onion_message))
889 log_trace!(logger, "Errored decoding onion message packet: {:?}", e);
893 log_trace!(logger, "Received bogus onion message packet, either the sender encoded a final hop as a forwarding hop or vice versa");
899 impl<ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, CMH: Deref>
900 OnionMessenger<ES, NS, L, NL, MR, OMH, CMH>
902 ES::Target: EntropySource,
903 NS::Target: NodeSigner,
905 NL::Target: NodeIdLookUp,
906 MR::Target: MessageRouter,
907 OMH::Target: OffersMessageHandler,
908 CMH::Target: CustomOnionMessageHandler,
910 /// Constructs a new `OnionMessenger` to send, forward, and delegate received onion messages to
911 /// their respective handlers.
913 entropy_source: ES, node_signer: NS, logger: L, node_id_lookup: NL, message_router: MR,
914 offers_handler: OMH, custom_handler: CMH
917 entropy_source, node_signer, logger, node_id_lookup, message_router,
918 offers_handler, custom_handler, false
922 /// Similar to [`Self::new`], but rather than dropping onion messages that are
923 /// intended to be forwarded to offline peers, we will intercept them for
924 /// later forwarding.
926 /// Interception flow:
927 /// 1. If an onion message for an offline peer is received, `OnionMessenger` will
928 /// generate an [`Event::OnionMessageIntercepted`]. Event handlers can
929 /// then choose to persist this onion message for later forwarding, or drop
931 /// 2. When the offline peer later comes back online, `OnionMessenger` will
932 /// generate an [`Event::OnionMessagePeerConnected`]. Event handlers will
933 /// then fetch all previously intercepted onion messages for this peer.
934 /// 3. Once the stored onion messages are fetched, they can finally be
935 /// forwarded to the now-online peer via [`Self::forward_onion_message`].
939 /// LDK will not rate limit how many [`Event::OnionMessageIntercepted`]s
940 /// are generated, so it is the caller's responsibility to limit how many
941 /// onion messages are persisted and only persist onion messages for relevant
943 pub fn new_with_offline_peer_interception(
944 entropy_source: ES, node_signer: NS, logger: L, node_id_lookup: NL,
945 message_router: MR, offers_handler: OMH, custom_handler: CMH
948 entropy_source, node_signer, logger, node_id_lookup, message_router,
949 offers_handler, custom_handler, true
954 entropy_source: ES, node_signer: NS, logger: L, node_id_lookup: NL,
955 message_router: MR, offers_handler: OMH, custom_handler: CMH,
956 intercept_messages_for_offline_peers: bool
958 let mut secp_ctx = Secp256k1::new();
959 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
963 message_recipients: Mutex::new(new_hash_map()),
970 intercept_messages_for_offline_peers,
971 pending_events: Mutex::new(PendingEvents {
972 intercepted_msgs: Vec::new(),
973 peer_connecteds: Vec::new(),
979 pub(crate) fn set_offers_handler(&mut self, offers_handler: OMH) {
980 self.offers_handler = offers_handler;
983 /// Sends an [`OnionMessage`] with the given `contents` to `destination`.
985 /// See [`OnionMessenger`] for example usage.
986 pub fn send_onion_message<T: OnionMessageContents>(
987 &self, contents: T, destination: Destination, reply_path: Option<BlindedPath>
988 ) -> Result<SendSuccess, SendError> {
989 self.find_path_and_enqueue_onion_message(
990 contents, destination, reply_path, format_args!("")
994 fn find_path_and_enqueue_onion_message<T: OnionMessageContents>(
995 &self, contents: T, destination: Destination, reply_path: Option<BlindedPath>,
996 log_suffix: fmt::Arguments
997 ) -> Result<SendSuccess, SendError> {
998 let mut logger = WithContext::from(&self.logger, None, None, None);
999 let result = self.find_path(destination).and_then(|path| {
1000 let first_hop = path.intermediate_nodes.get(0).map(|p| *p);
1001 logger = WithContext::from(&self.logger, first_hop, None, None);
1002 self.enqueue_onion_message(path, contents, reply_path, log_suffix)
1005 match result.as_ref() {
1006 Err(SendError::GetNodeIdFailed) => {
1007 log_warn!(logger, "Unable to retrieve node id {}", log_suffix);
1009 Err(SendError::PathNotFound) => {
1010 log_trace!(logger, "Failed to find path {}", log_suffix);
1013 log_trace!(logger, "Failed sending onion message {}: {:?}", log_suffix, e);
1015 Ok(SendSuccess::Buffered) => {
1016 log_trace!(logger, "Buffered onion message {}", log_suffix);
1018 Ok(SendSuccess::BufferedAwaitingConnection(node_id)) => {
1021 "Buffered onion message waiting on peer connection {}: {}",
1030 fn find_path(&self, destination: Destination) -> Result<OnionMessagePath, SendError> {
1031 let sender = self.node_signer
1032 .get_node_id(Recipient::Node)
1033 .map_err(|_| SendError::GetNodeIdFailed)?;
1035 let peers = self.message_recipients.lock().unwrap()
1037 .filter(|(_, recipient)| matches!(recipient, OnionMessageRecipient::ConnectedPeer(_)))
1038 .map(|(node_id, _)| *node_id)
1042 .find_path(sender, peers, destination)
1043 .map_err(|_| SendError::PathNotFound)
1046 fn enqueue_onion_message<T: OnionMessageContents>(
1047 &self, path: OnionMessagePath, contents: T, reply_path: Option<BlindedPath>,
1048 log_suffix: fmt::Arguments
1049 ) -> Result<SendSuccess, SendError> {
1050 log_trace!(self.logger, "Constructing onion message {}: {:?}", log_suffix, contents);
1052 let (first_node_id, onion_message, addresses) = create_onion_message(
1053 &self.entropy_source, &self.node_signer, &self.node_id_lookup, &self.secp_ctx, path,
1054 contents, reply_path,
1057 let mut message_recipients = self.message_recipients.lock().unwrap();
1058 if outbound_buffer_full(&first_node_id, &message_recipients) {
1059 return Err(SendError::BufferFull);
1062 match message_recipients.entry(first_node_id) {
1063 hash_map::Entry::Vacant(e) => match addresses {
1064 None => Err(SendError::InvalidFirstHop(first_node_id)),
1065 Some(addresses) => {
1066 e.insert(OnionMessageRecipient::pending_connection(addresses))
1067 .enqueue_message(onion_message);
1068 Ok(SendSuccess::BufferedAwaitingConnection(first_node_id))
1071 hash_map::Entry::Occupied(mut e) => {
1072 e.get_mut().enqueue_message(onion_message);
1073 if e.get().is_connected() {
1074 Ok(SendSuccess::Buffered)
1076 Ok(SendSuccess::BufferedAwaitingConnection(first_node_id))
1082 /// Forwards an [`OnionMessage`] to `peer_node_id`. Useful if we initialized
1083 /// the [`OnionMessenger`] with [`Self::new_with_offline_peer_interception`]
1084 /// and want to forward a previously intercepted onion message to a peer that
1085 /// has just come online.
1086 pub fn forward_onion_message(
1087 &self, message: OnionMessage, peer_node_id: &PublicKey
1088 ) -> Result<(), SendError> {
1089 let mut message_recipients = self.message_recipients.lock().unwrap();
1090 if outbound_buffer_full(&peer_node_id, &message_recipients) {
1091 return Err(SendError::BufferFull);
1094 match message_recipients.entry(*peer_node_id) {
1095 hash_map::Entry::Occupied(mut e) if e.get().is_connected() => {
1096 e.get_mut().enqueue_message(message);
1099 _ => Err(SendError::InvalidFirstHop(*peer_node_id))
1103 #[cfg(any(test, feature = "_test_utils"))]
1104 pub fn send_onion_message_using_path<T: OnionMessageContents>(
1105 &self, path: OnionMessagePath, contents: T, reply_path: Option<BlindedPath>
1106 ) -> Result<SendSuccess, SendError> {
1107 self.enqueue_onion_message(path, contents, reply_path, format_args!(""))
1110 pub(crate) fn peel_onion_message(
1111 &self, msg: &OnionMessage
1112 ) -> Result<PeeledOnion<<<CMH>::Target as CustomOnionMessageHandler>::CustomMessage>, ()> {
1114 msg, &self.secp_ctx, &*self.node_signer, &*self.logger, &*self.custom_handler
1118 fn handle_onion_message_response<T: OnionMessageContents>(
1119 &self, response: ResponseInstruction<T>
1121 if let ResponseInstruction::WithoutReplyPath(response) = response {
1122 let message_type = response.message.msg_type();
1123 let _ = self.find_path_and_enqueue_onion_message(
1124 response.message, Destination::BlindedPath(response.reply_path), None,
1126 "when responding with {} to an onion message with path_id {:02x?}",
1135 pub(super) fn release_pending_msgs(&self) -> HashMap<PublicKey, VecDeque<OnionMessage>> {
1136 let mut message_recipients = self.message_recipients.lock().unwrap();
1137 let mut msgs = new_hash_map();
1138 // We don't want to disconnect the peers by removing them entirely from the original map, so we
1139 // release the pending message buffers individually.
1140 for (node_id, recipient) in &mut *message_recipients {
1141 msgs.insert(*node_id, recipient.release_pending_messages());
1146 fn enqueue_intercepted_event(&self, event: Event) {
1147 const MAX_EVENTS_BUFFER_SIZE: usize = (1 << 10) * 256;
1148 let mut pending_events = self.pending_events.lock().unwrap();
1149 let total_buffered_bytes: usize =
1150 pending_events.intercepted_msgs.iter().map(|ev| ev.serialized_length()).sum();
1151 if total_buffered_bytes >= MAX_EVENTS_BUFFER_SIZE {
1152 log_trace!(self.logger, "Dropping event {:?}: buffer full", event);
1155 pending_events.intercepted_msgs.push(event);
1159 fn outbound_buffer_full(peer_node_id: &PublicKey, buffer: &HashMap<PublicKey, OnionMessageRecipient>) -> bool {
1160 const MAX_TOTAL_BUFFER_SIZE: usize = (1 << 20) * 128;
1161 const MAX_PER_PEER_BUFFER_SIZE: usize = (1 << 10) * 256;
1162 let mut total_buffered_bytes = 0;
1163 let mut peer_buffered_bytes = 0;
1164 for (pk, peer_buf) in buffer {
1165 for om in peer_buf.pending_messages() {
1166 let om_len = om.serialized_length();
1167 if pk == peer_node_id {
1168 peer_buffered_bytes += om_len;
1170 total_buffered_bytes += om_len;
1172 if total_buffered_bytes >= MAX_TOTAL_BUFFER_SIZE ||
1173 peer_buffered_bytes >= MAX_PER_PEER_BUFFER_SIZE
1182 impl<ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, CMH: Deref> EventsProvider
1183 for OnionMessenger<ES, NS, L, NL, MR, OMH, CMH>
1185 ES::Target: EntropySource,
1186 NS::Target: NodeSigner,
1188 NL::Target: NodeIdLookUp,
1189 MR::Target: MessageRouter,
1190 OMH::Target: OffersMessageHandler,
1191 CMH::Target: CustomOnionMessageHandler,
1193 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
1194 for (node_id, recipient) in self.message_recipients.lock().unwrap().iter_mut() {
1195 if let OnionMessageRecipient::PendingConnection(_, addresses, _) = recipient {
1196 if let Some(addresses) = addresses.take() {
1197 handler.handle_event(Event::ConnectionNeeded { node_id: *node_id, addresses });
1201 let mut events = Vec::new();
1203 let mut pending_events = self.pending_events.lock().unwrap();
1204 #[cfg(debug_assertions)] {
1205 for ev in pending_events.intercepted_msgs.iter() {
1206 if let Event::OnionMessageIntercepted { .. } = ev {} else { panic!(); }
1208 for ev in pending_events.peer_connecteds.iter() {
1209 if let Event::OnionMessagePeerConnected { .. } = ev {} else { panic!(); }
1212 core::mem::swap(&mut pending_events.intercepted_msgs, &mut events);
1213 events.append(&mut pending_events.peer_connecteds);
1214 pending_events.peer_connecteds.shrink_to(10); // Limit total heap usage
1217 handler.handle_event(ev);
1222 impl<ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, CMH: Deref> OnionMessageHandler
1223 for OnionMessenger<ES, NS, L, NL, MR, OMH, CMH>
1225 ES::Target: EntropySource,
1226 NS::Target: NodeSigner,
1228 NL::Target: NodeIdLookUp,
1229 MR::Target: MessageRouter,
1230 OMH::Target: OffersMessageHandler,
1231 CMH::Target: CustomOnionMessageHandler,
1233 fn handle_onion_message(&self, peer_node_id: &PublicKey, msg: &OnionMessage) {
1234 let logger = WithContext::from(&self.logger, Some(*peer_node_id), None, None);
1235 match self.peel_onion_message(msg) {
1236 Ok(PeeledOnion::Receive(message, path_id, reply_path)) => {
1239 "Received an onion message with path_id {:02x?} and {} reply_path: {:?}",
1240 path_id, if reply_path.is_some() { "a" } else { "no" }, message);
1243 ParsedOnionMessageContents::Offers(msg) => {
1244 let responder = reply_path.map(
1245 |reply_path| Responder::new(reply_path, path_id)
1247 let response_instructions = self.offers_handler.handle_message(msg, responder);
1248 self.handle_onion_message_response(response_instructions);
1250 ParsedOnionMessageContents::Custom(msg) => {
1251 let responder = reply_path.map(
1252 |reply_path| Responder::new(reply_path, path_id)
1254 let response_instructions = self.custom_handler.handle_custom_message(msg, responder);
1255 self.handle_onion_message_response(response_instructions);
1259 Ok(PeeledOnion::Forward(next_hop, onion_message)) => {
1260 let next_node_id = match next_hop {
1261 NextMessageHop::NodeId(pubkey) => pubkey,
1262 NextMessageHop::ShortChannelId(scid) => match self.node_id_lookup.next_node_id(scid) {
1263 Some(pubkey) => pubkey,
1265 log_trace!(self.logger, "Dropping forwarded onion messager: unable to resolve next hop using SCID {}", scid);
1271 let mut message_recipients = self.message_recipients.lock().unwrap();
1272 if outbound_buffer_full(&next_node_id, &message_recipients) {
1275 "Dropping forwarded onion message to peer {}: outbound buffer full",
1282 .entry(next_node_id)
1283 .or_insert_with(|| OnionMessageRecipient::ConnectedPeer(VecDeque::new()));
1285 match message_recipients.entry(next_node_id) {
1286 hash_map::Entry::Occupied(mut e) if matches!(
1287 e.get(), OnionMessageRecipient::ConnectedPeer(..)
1289 e.get_mut().enqueue_message(onion_message);
1290 log_trace!(logger, "Forwarding an onion message to peer {}", next_node_id);
1292 _ if self.intercept_messages_for_offline_peers => {
1293 self.enqueue_intercepted_event(
1294 Event::OnionMessageIntercepted {
1295 peer_node_id: next_node_id, message: onion_message
1302 "Dropping forwarded onion message to disconnected peer {}",
1309 log_error!(logger, "Failed to process onion message {:?}", e);
1314 fn peer_connected(&self, their_node_id: &PublicKey, init: &msgs::Init, _inbound: bool) -> Result<(), ()> {
1315 if init.features.supports_onion_messages() {
1316 self.message_recipients.lock().unwrap()
1317 .entry(*their_node_id)
1318 .or_insert_with(|| OnionMessageRecipient::ConnectedPeer(VecDeque::new()))
1320 if self.intercept_messages_for_offline_peers {
1321 self.pending_events.lock().unwrap().peer_connecteds.push(
1322 Event::OnionMessagePeerConnected { peer_node_id: *their_node_id }
1326 self.message_recipients.lock().unwrap().remove(their_node_id);
1332 fn peer_disconnected(&self, their_node_id: &PublicKey) {
1333 match self.message_recipients.lock().unwrap().remove(their_node_id) {
1334 Some(OnionMessageRecipient::ConnectedPeer(..)) => {},
1335 Some(_) => debug_assert!(false),
1340 fn timer_tick_occurred(&self) {
1341 let mut message_recipients = self.message_recipients.lock().unwrap();
1343 // Drop any pending recipients since the last call to avoid retaining buffered messages for
1345 message_recipients.retain(|_, recipient| match recipient {
1346 OnionMessageRecipient::PendingConnection(_, None, ticks) => *ticks < MAX_TIMER_TICKS,
1347 OnionMessageRecipient::PendingConnection(_, Some(_), _) => true,
1351 // Increment a timer tick for pending recipients so that their buffered messages are dropped
1352 // at MAX_TIMER_TICKS.
1353 for recipient in message_recipients.values_mut() {
1354 if let OnionMessageRecipient::PendingConnection(_, None, ticks) = recipient {
1360 fn provided_node_features(&self) -> NodeFeatures {
1361 let mut features = NodeFeatures::empty();
1362 features.set_onion_messages_optional();
1366 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
1367 let mut features = InitFeatures::empty();
1368 features.set_onion_messages_optional();
1372 // Before returning any messages to send for the peer, this method will see if any messages were
1373 // enqueued in the handler by users, find a path to the corresponding blinded path's introduction
1374 // node, and then enqueue the message for sending to the first peer in the full path.
1375 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<OnionMessage> {
1376 // Enqueue any initiating `OffersMessage`s to send.
1377 for message in self.offers_handler.release_pending_messages() {
1378 #[cfg(not(c_bindings))]
1379 let PendingOnionMessage { contents, destination, reply_path } = message;
1381 let (contents, destination, reply_path) = message;
1382 let _ = self.find_path_and_enqueue_onion_message(
1383 contents, destination, reply_path, format_args!("when sending OffersMessage")
1387 // Enqueue any initiating `CustomMessage`s to send.
1388 for message in self.custom_handler.release_pending_custom_messages() {
1389 #[cfg(not(c_bindings))]
1390 let PendingOnionMessage { contents, destination, reply_path } = message;
1392 let (contents, destination, reply_path) = message;
1393 let _ = self.find_path_and_enqueue_onion_message(
1394 contents, destination, reply_path, format_args!("when sending CustomMessage")
1398 self.message_recipients.lock().unwrap()
1399 .get_mut(&peer_node_id)
1400 .and_then(|buffer| buffer.dequeue_message())
1404 // TODO: parameterize the below Simple* types with OnionMessenger and handle the messages it
1406 /// Useful for simplifying the parameters of [`SimpleArcChannelManager`] and
1407 /// [`SimpleArcPeerManager`]. See their docs for more details.
1409 /// This is not exported to bindings users as type aliases aren't supported in most languages.
1411 /// [`SimpleArcChannelManager`]: crate::ln::channelmanager::SimpleArcChannelManager
1412 /// [`SimpleArcPeerManager`]: crate::ln::peer_handler::SimpleArcPeerManager
1413 #[cfg(not(c_bindings))]
1414 pub type SimpleArcOnionMessenger<M, T, F, L> = OnionMessenger<
1418 Arc<SimpleArcChannelManager<M, T, F, L>>,
1419 Arc<DefaultMessageRouter<Arc<NetworkGraph<Arc<L>>>, Arc<L>, Arc<KeysManager>>>,
1420 Arc<SimpleArcChannelManager<M, T, F, L>>,
1421 IgnoringMessageHandler
1424 /// Useful for simplifying the parameters of [`SimpleRefChannelManager`] and
1425 /// [`SimpleRefPeerManager`]. See their docs for more details.
1427 /// This is not exported to bindings users as type aliases aren't supported in most languages.
1429 /// [`SimpleRefChannelManager`]: crate::ln::channelmanager::SimpleRefChannelManager
1430 /// [`SimpleRefPeerManager`]: crate::ln::peer_handler::SimpleRefPeerManager
1431 #[cfg(not(c_bindings))]
1432 pub type SimpleRefOnionMessenger<
1433 'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, M, T, F, L
1438 &'i SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L>,
1439 &'j DefaultMessageRouter<&'g NetworkGraph<&'b L>, &'b L, &'a KeysManager>,
1440 &'i SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L>,
1441 IgnoringMessageHandler
1444 /// Construct onion packet payloads and keys for sending an onion message along the given
1445 /// `unblinded_path` to the given `destination`.
1446 fn packet_payloads_and_keys<T: OnionMessageContents, S: secp256k1::Signing + secp256k1::Verification>(
1447 secp_ctx: &Secp256k1<S>, unblinded_path: &[PublicKey], destination: Destination, message: T,
1448 mut reply_path: Option<BlindedPath>, session_priv: &SecretKey
1449 ) -> Result<(Vec<(Payload<T>, [u8; 32])>, Vec<onion_utils::OnionKeys>), SendError> {
1450 let num_hops = unblinded_path.len() + destination.num_hops();
1451 let mut payloads = Vec::with_capacity(num_hops);
1452 let mut onion_packet_keys = Vec::with_capacity(num_hops);
1454 let (mut intro_node_id_blinding_pt, num_blinded_hops) = match &destination {
1455 Destination::Node(_) => (None, 0),
1456 Destination::BlindedPath(BlindedPath { introduction_node, blinding_point, blinded_hops }) => {
1457 let introduction_node_id = match introduction_node {
1458 IntroductionNode::NodeId(pubkey) => pubkey,
1459 IntroductionNode::DirectedShortChannelId(..) => {
1460 return Err(SendError::UnresolvedIntroductionNode);
1463 (Some((*introduction_node_id, *blinding_point)), blinded_hops.len())
1466 let num_unblinded_hops = num_hops - num_blinded_hops;
1468 let mut unblinded_path_idx = 0;
1469 let mut blinded_path_idx = 0;
1470 let mut prev_control_tlvs_ss = None;
1471 let mut final_control_tlvs = None;
1472 utils::construct_keys_callback(secp_ctx, unblinded_path.iter(), Some(destination), session_priv,
1473 |_, onion_packet_ss, ephemeral_pubkey, control_tlvs_ss, unblinded_pk_opt, enc_payload_opt| {
1474 if num_unblinded_hops != 0 && unblinded_path_idx < num_unblinded_hops {
1475 if let Some(ss) = prev_control_tlvs_ss.take() {
1476 payloads.push((Payload::Forward(ForwardControlTlvs::Unblinded(
1478 next_hop: NextMessageHop::NodeId(unblinded_pk_opt.unwrap()),
1479 next_blinding_override: None,
1483 prev_control_tlvs_ss = Some(control_tlvs_ss);
1484 unblinded_path_idx += 1;
1485 } else if let Some((intro_node_id, blinding_pt)) = intro_node_id_blinding_pt.take() {
1486 if let Some(control_tlvs_ss) = prev_control_tlvs_ss.take() {
1487 payloads.push((Payload::Forward(ForwardControlTlvs::Unblinded(ForwardTlvs {
1488 next_hop: NextMessageHop::NodeId(intro_node_id),
1489 next_blinding_override: Some(blinding_pt),
1490 })), control_tlvs_ss));
1493 if blinded_path_idx < num_blinded_hops.saturating_sub(1) && enc_payload_opt.is_some() {
1494 payloads.push((Payload::Forward(ForwardControlTlvs::Blinded(enc_payload_opt.unwrap())),
1496 blinded_path_idx += 1;
1497 } else if let Some(encrypted_payload) = enc_payload_opt {
1498 final_control_tlvs = Some(ReceiveControlTlvs::Blinded(encrypted_payload));
1499 prev_control_tlvs_ss = Some(control_tlvs_ss);
1502 let (rho, mu) = onion_utils::gen_rho_mu_from_shared_secret(onion_packet_ss.as_ref());
1503 onion_packet_keys.push(onion_utils::OnionKeys {
1505 shared_secret: onion_packet_ss,
1507 blinding_factor: [0; 32],
1513 ).map_err(|e| SendError::Secp256k1(e))?;
1515 if let Some(control_tlvs) = final_control_tlvs {
1516 payloads.push((Payload::Receive {
1518 reply_path: reply_path.take(),
1520 }, prev_control_tlvs_ss.unwrap()));
1522 payloads.push((Payload::Receive {
1523 control_tlvs: ReceiveControlTlvs::Unblinded(ReceiveTlvs { path_id: None, }),
1524 reply_path: reply_path.take(),
1526 }, prev_control_tlvs_ss.unwrap()));
1529 Ok((payloads, onion_packet_keys))
1532 /// Errors if the serialized payload size exceeds onion_message::BIG_PACKET_HOP_DATA_LEN
1533 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, ()> {
1535 // "`len` allows larger messages to be sent than the standard 1300 bytes allowed for an HTLC
1536 // onion, but this should be used sparingly as it is reduces anonymity set, hence the
1537 // recommendation that it either look like an HTLC onion, or if larger, be a fixed size."
1538 let payloads_ser_len = onion_utils::payloads_serialized_length(&payloads);
1539 let hop_data_len = if payloads_ser_len <= SMALL_PACKET_HOP_DATA_LEN {
1540 SMALL_PACKET_HOP_DATA_LEN
1541 } else if payloads_ser_len <= BIG_PACKET_HOP_DATA_LEN {
1542 BIG_PACKET_HOP_DATA_LEN
1543 } else { return Err(()) };
1545 onion_utils::construct_onion_message_packet::<_, _>(
1546 payloads, onion_keys, prng_seed, hop_data_len)