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::async_payments::{AsyncPaymentsMessage, AsyncPaymentsMessageHandler};
28 use super::packet::OnionMessageContents;
29 use super::packet::ParsedOnionMessageContents;
30 use super::offers::OffersMessageHandler;
31 use super::packet::{BIG_PACKET_HOP_DATA_LEN, ForwardControlTlvs, Packet, Payload, ReceiveControlTlvs, SMALL_PACKET_HOP_DATA_LEN};
32 use crate::util::logger::{Logger, WithContext};
33 use crate::util::ser::Writeable;
38 use crate::sync::Mutex;
39 use crate::prelude::*;
41 #[cfg(not(c_bindings))]
43 crate::sign::KeysManager,
44 crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager},
45 crate::ln::peer_handler::IgnoringMessageHandler,
49 pub(super) const MAX_TIMER_TICKS: usize = 2;
51 /// A trivial trait which describes any [`OnionMessenger`].
53 /// This is not exported to bindings users as general cover traits aren't useful in other
55 pub trait AOnionMessenger {
56 /// A type implementing [`EntropySource`]
57 type EntropySource: EntropySource + ?Sized;
58 /// A type that may be dereferenced to [`Self::EntropySource`]
59 type ES: Deref<Target = Self::EntropySource>;
60 /// A type implementing [`NodeSigner`]
61 type NodeSigner: NodeSigner + ?Sized;
62 /// A type that may be dereferenced to [`Self::NodeSigner`]
63 type NS: Deref<Target = Self::NodeSigner>;
64 /// A type implementing [`Logger`]
65 type Logger: Logger + ?Sized;
66 /// A type that may be dereferenced to [`Self::Logger`]
67 type L: Deref<Target = Self::Logger>;
68 /// A type implementing [`NodeIdLookUp`]
69 type NodeIdLookUp: NodeIdLookUp + ?Sized;
70 /// A type that may be dereferenced to [`Self::NodeIdLookUp`]
71 type NL: Deref<Target = Self::NodeIdLookUp>;
72 /// A type implementing [`MessageRouter`]
73 type MessageRouter: MessageRouter + ?Sized;
74 /// A type that may be dereferenced to [`Self::MessageRouter`]
75 type MR: Deref<Target = Self::MessageRouter>;
76 /// A type implementing [`OffersMessageHandler`]
77 type OffersMessageHandler: OffersMessageHandler + ?Sized;
78 /// A type that may be dereferenced to [`Self::OffersMessageHandler`]
79 type OMH: Deref<Target = Self::OffersMessageHandler>;
80 /// A type implementing [`AsyncPaymentsMessageHandler`]
81 type AsyncPaymentsMessageHandler: AsyncPaymentsMessageHandler + ?Sized;
82 /// A type that may be dereferenced to [`Self::AsyncPaymentsMessageHandler`]
83 type APH: Deref<Target = Self::AsyncPaymentsMessageHandler>;
84 /// A type implementing [`CustomOnionMessageHandler`]
85 type CustomOnionMessageHandler: CustomOnionMessageHandler + ?Sized;
86 /// A type that may be dereferenced to [`Self::CustomOnionMessageHandler`]
87 type CMH: Deref<Target = Self::CustomOnionMessageHandler>;
88 /// Returns a reference to the actual [`OnionMessenger`] object.
89 fn get_om(&self) -> &OnionMessenger<Self::ES, Self::NS, Self::L, Self::NL, Self::MR, Self::OMH, Self::APH, Self::CMH>;
92 impl<ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, APH: Deref, CMH: Deref> AOnionMessenger
93 for OnionMessenger<ES, NS, L, NL, MR, OMH, APH, CMH> where
94 ES::Target: EntropySource,
95 NS::Target: NodeSigner,
97 NL::Target: NodeIdLookUp,
98 MR::Target: MessageRouter,
99 OMH::Target: OffersMessageHandler,
100 APH:: Target: AsyncPaymentsMessageHandler,
101 CMH::Target: CustomOnionMessageHandler,
103 type EntropySource = ES::Target;
105 type NodeSigner = NS::Target;
107 type Logger = L::Target;
109 type NodeIdLookUp = NL::Target;
111 type MessageRouter = MR::Target;
113 type OffersMessageHandler = OMH::Target;
115 type AsyncPaymentsMessageHandler = APH::Target;
117 type CustomOnionMessageHandler = CMH::Target;
119 fn get_om(&self) -> &OnionMessenger<ES, NS, L, NL, MR, OMH, APH, CMH> { self }
122 /// A sender, receiver and forwarder of [`OnionMessage`]s.
124 /// # Handling Messages
126 /// `OnionMessenger` implements [`OnionMessageHandler`], making it responsible for either forwarding
127 /// messages to peers or delegating to the appropriate handler for the message type. Currently, the
128 /// available handlers are:
129 /// * [`OffersMessageHandler`], for responding to [`InvoiceRequest`]s and paying [`Bolt12Invoice`]s
130 /// * [`CustomOnionMessageHandler`], for handling user-defined message types
132 /// # Sending Messages
134 /// [`OnionMessage`]s are sent initially using [`OnionMessenger::send_onion_message`]. When handling
135 /// a message, the matched handler may return a response message which `OnionMessenger` will send
141 /// # extern crate bitcoin;
142 /// # use bitcoin::hashes::_export::_core::time::Duration;
143 /// # use bitcoin::hashes::hex::FromHex;
144 /// # use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey, self};
145 /// # use lightning::blinded_path::{BlindedPath, EmptyNodeIdLookUp};
146 /// # use lightning::blinded_path::message::ForwardNode;
147 /// # use lightning::sign::{EntropySource, KeysManager};
148 /// # use lightning::ln::peer_handler::IgnoringMessageHandler;
149 /// # use lightning::onion_message::messenger::{Destination, MessageRouter, OnionMessagePath, OnionMessenger};
150 /// # use lightning::onion_message::packet::OnionMessageContents;
151 /// # use lightning::util::logger::{Logger, Record};
152 /// # use lightning::util::ser::{Writeable, Writer};
153 /// # use lightning::io;
154 /// # use std::sync::Arc;
155 /// # struct FakeLogger;
156 /// # impl Logger for FakeLogger {
157 /// # fn log(&self, record: Record) { println!("{:?}" , record); }
159 /// # struct FakeMessageRouter {}
160 /// # impl MessageRouter for FakeMessageRouter {
161 /// # fn find_path(&self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination) -> Result<OnionMessagePath, ()> {
162 /// # let secp_ctx = Secp256k1::new();
163 /// # let node_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
164 /// # let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
165 /// # let hop_node_id2 = hop_node_id1;
166 /// # Ok(OnionMessagePath {
167 /// # intermediate_nodes: vec![hop_node_id1, hop_node_id2],
169 /// # first_node_addresses: None,
172 /// # fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
173 /// # &self, _recipient: PublicKey, _peers: Vec<PublicKey>, _secp_ctx: &Secp256k1<T>
174 /// # ) -> Result<Vec<BlindedPath>, ()> {
178 /// # let seed = [42u8; 32];
179 /// # let time = Duration::from_secs(123456);
180 /// # let keys_manager = KeysManager::new(&seed, time.as_secs(), time.subsec_nanos());
181 /// # let logger = Arc::new(FakeLogger {});
182 /// # let node_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
183 /// # let secp_ctx = Secp256k1::new();
184 /// # let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
185 /// # let (hop_node_id3, hop_node_id4) = (hop_node_id1, hop_node_id1);
186 /// # let destination_node_id = hop_node_id1;
187 /// # let node_id_lookup = EmptyNodeIdLookUp {};
188 /// # let message_router = Arc::new(FakeMessageRouter {});
189 /// # let custom_message_handler = IgnoringMessageHandler {};
190 /// # let offers_message_handler = IgnoringMessageHandler {};
191 /// # let async_payments_message_handler = IgnoringMessageHandler {};
192 /// // Create the onion messenger. This must use the same `keys_manager` as is passed to your
193 /// // ChannelManager.
194 /// let onion_messenger = OnionMessenger::new(
195 /// &keys_manager, &keys_manager, logger, &node_id_lookup, message_router,
196 /// &offers_message_handler, &async_payments_message_handler, &custom_message_handler
199 /// # #[derive(Debug)]
200 /// # struct YourCustomMessage {}
201 /// impl Writeable for YourCustomMessage {
202 /// fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
204 /// // Write your custom onion message to `w`
207 /// impl OnionMessageContents for YourCustomMessage {
208 /// fn tlv_type(&self) -> u64 {
209 /// # let your_custom_message_type = 42;
210 /// your_custom_message_type
212 /// fn msg_type(&self) -> &'static str { "YourCustomMessageType" }
214 /// // Send a custom onion message to a node id.
215 /// let destination = Destination::Node(destination_node_id);
216 /// let reply_path = None;
217 /// # let message = YourCustomMessage {};
218 /// onion_messenger.send_onion_message(message, destination, reply_path);
220 /// // Create a blinded path to yourself, for someone to send an onion message to.
221 /// # let your_node_id = hop_node_id1;
223 /// ForwardNode { node_id: hop_node_id3, short_channel_id: None },
224 /// ForwardNode { node_id: hop_node_id4, short_channel_id: None },
226 /// let blinded_path = BlindedPath::new_for_message(&hops, your_node_id, &keys_manager, &secp_ctx).unwrap();
228 /// // Send a custom onion message to a blinded path.
229 /// let destination = Destination::BlindedPath(blinded_path);
230 /// let reply_path = None;
231 /// # let message = YourCustomMessage {};
232 /// onion_messenger.send_onion_message(message, destination, reply_path);
235 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
236 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
237 pub struct OnionMessenger<
238 ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, APH: Deref, CMH: Deref
240 ES::Target: EntropySource,
241 NS::Target: NodeSigner,
243 NL::Target: NodeIdLookUp,
244 MR::Target: MessageRouter,
245 OMH::Target: OffersMessageHandler,
246 APH::Target: AsyncPaymentsMessageHandler,
247 CMH::Target: CustomOnionMessageHandler,
252 message_recipients: Mutex<HashMap<PublicKey, OnionMessageRecipient>>,
253 secp_ctx: Secp256k1<secp256k1::All>,
257 async_payments_handler: APH,
259 intercept_messages_for_offline_peers: bool,
260 pending_events: Mutex<PendingEvents>,
263 struct PendingEvents {
264 intercepted_msgs: Vec<Event>,
265 peer_connecteds: Vec<Event>,
268 /// [`OnionMessage`]s buffered to be sent.
269 enum OnionMessageRecipient {
270 /// Messages for a node connected as a peer.
271 ConnectedPeer(VecDeque<OnionMessage>),
273 /// Messages for a node that is not yet connected, which are dropped after [`MAX_TIMER_TICKS`]
274 /// and tracked here.
275 PendingConnection(VecDeque<OnionMessage>, Option<Vec<SocketAddress>>, usize),
278 impl OnionMessageRecipient {
279 fn pending_connection(addresses: Vec<SocketAddress>) -> Self {
280 Self::PendingConnection(VecDeque::new(), Some(addresses), 0)
283 fn pending_messages(&self) -> &VecDeque<OnionMessage> {
285 OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
286 OnionMessageRecipient::PendingConnection(pending_messages, _, _) => pending_messages,
290 fn enqueue_message(&mut self, message: OnionMessage) {
291 let pending_messages = match self {
292 OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
293 OnionMessageRecipient::PendingConnection(pending_messages, _, _) => pending_messages,
296 pending_messages.push_back(message);
299 fn dequeue_message(&mut self) -> Option<OnionMessage> {
300 let pending_messages = match self {
301 OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
302 OnionMessageRecipient::PendingConnection(pending_messages, _, _) => {
303 debug_assert!(false);
308 pending_messages.pop_front()
312 fn release_pending_messages(&mut self) -> VecDeque<OnionMessage> {
313 let pending_messages = match self {
314 OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
315 OnionMessageRecipient::PendingConnection(pending_messages, _, _) => pending_messages,
318 core::mem::take(pending_messages)
321 fn mark_connected(&mut self) {
322 if let OnionMessageRecipient::PendingConnection(pending_messages, _, _) = self {
323 let mut new_pending_messages = VecDeque::new();
324 core::mem::swap(pending_messages, &mut new_pending_messages);
325 *self = OnionMessageRecipient::ConnectedPeer(new_pending_messages);
329 fn is_connected(&self) -> bool {
331 OnionMessageRecipient::ConnectedPeer(..) => true,
332 OnionMessageRecipient::PendingConnection(..) => false,
338 /// The `Responder` struct creates an appropriate [`ResponseInstruction`]
339 /// for responding to a message.
340 #[derive(Clone, Debug, Eq, PartialEq)]
341 pub struct Responder {
342 /// The path along which a response can be sent.
343 reply_path: BlindedPath,
344 path_id: Option<[u8; 32]>
347 impl_writeable_tlv_based!(Responder, {
348 (0, reply_path, required),
349 (2, path_id, option),
353 /// Creates a new [`Responder`] instance with the provided reply path.
354 pub(super) fn new(reply_path: BlindedPath, path_id: Option<[u8; 32]>) -> Self {
361 /// Creates a [`ResponseInstruction::WithoutReplyPath`] for a given response.
363 /// Use when the recipient doesn't need to send back a reply to us.
364 pub fn respond<T: OnionMessageContents>(self, response: T) -> ResponseInstruction<T> {
365 ResponseInstruction::WithoutReplyPath(OnionMessageResponse {
367 reply_path: self.reply_path,
368 path_id: self.path_id,
372 /// Creates a [`ResponseInstruction::WithReplyPath`] for a given response.
374 /// Use when the recipient needs to send back a reply to us.
375 pub fn respond_with_reply_path<T: OnionMessageContents>(self, response: T) -> ResponseInstruction<T> {
376 ResponseInstruction::WithReplyPath(OnionMessageResponse {
378 reply_path: self.reply_path,
379 path_id: self.path_id,
384 /// This struct contains the information needed to reply to a received message.
385 pub struct OnionMessageResponse<T: OnionMessageContents> {
387 reply_path: BlindedPath,
388 path_id: Option<[u8; 32]>,
391 /// `ResponseInstruction` represents instructions for responding to received messages.
392 pub enum ResponseInstruction<T: OnionMessageContents> {
393 /// Indicates that a response should be sent including a reply path for
394 /// the recipient to respond back.
395 WithReplyPath(OnionMessageResponse<T>),
396 /// Indicates that a response should be sent without including a reply path
397 /// for the recipient to respond back.
398 WithoutReplyPath(OnionMessageResponse<T>),
399 /// Indicates that there's no response to send back.
403 /// An [`OnionMessage`] for [`OnionMessenger`] to send.
405 /// These are obtained when released from [`OnionMessenger`]'s handlers after which they are
406 /// enqueued for sending.
407 #[cfg(not(c_bindings))]
408 pub struct PendingOnionMessage<T: OnionMessageContents> {
409 /// The message contents to send in an [`OnionMessage`].
412 /// The destination of the message.
413 pub destination: Destination,
415 /// A reply path to include in the [`OnionMessage`] for a response.
416 pub reply_path: Option<BlindedPath>,
420 /// An [`OnionMessage`] for [`OnionMessenger`] to send.
422 /// These are obtained when released from [`OnionMessenger`]'s handlers after which they are
423 /// enqueued for sending.
424 pub type PendingOnionMessage<T> = (T, Destination, Option<BlindedPath>);
426 pub(crate) fn new_pending_onion_message<T: OnionMessageContents>(
427 contents: T, destination: Destination, reply_path: Option<BlindedPath>
428 ) -> PendingOnionMessage<T> {
429 #[cfg(not(c_bindings))]
430 return PendingOnionMessage { contents, destination, reply_path };
432 return (contents, destination, reply_path);
435 /// A trait defining behavior for routing an [`OnionMessage`].
436 pub trait MessageRouter {
437 /// Returns a route for sending an [`OnionMessage`] to the given [`Destination`].
439 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
440 ) -> Result<OnionMessagePath, ()>;
442 /// Creates [`BlindedPath`]s to the `recipient` node. The nodes in `peers` are assumed to be
443 /// direct peers with the `recipient`.
444 fn create_blinded_paths<
445 T: secp256k1::Signing + secp256k1::Verification
447 &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
448 ) -> Result<Vec<BlindedPath>, ()>;
450 /// Creates compact [`BlindedPath`]s to the `recipient` node. The nodes in `peers` are assumed
451 /// to be direct peers with the `recipient`.
453 /// Compact blinded paths use short channel ids instead of pubkeys for a smaller serialization,
454 /// which is beneficial when a QR code is used to transport the data. The SCID is passed using a
455 /// [`ForwardNode`] but may be `None` for graceful degradation.
457 /// Implementations using additional intermediate nodes are responsible for using a
458 /// [`ForwardNode`] with `Some` short channel id, if possible. Similarly, implementations should
459 /// call [`BlindedPath::use_compact_introduction_node`].
461 /// The provided implementation simply delegates to [`MessageRouter::create_blinded_paths`],
462 /// ignoring the short channel ids.
463 fn create_compact_blinded_paths<
464 T: secp256k1::Signing + secp256k1::Verification
466 &self, recipient: PublicKey, peers: Vec<ForwardNode>, secp_ctx: &Secp256k1<T>,
467 ) -> Result<Vec<BlindedPath>, ()> {
470 .map(|ForwardNode { node_id, short_channel_id: _ }| node_id)
472 self.create_blinded_paths(recipient, peers, secp_ctx)
476 /// A [`MessageRouter`] that can only route to a directly connected [`Destination`].
480 /// Creating [`BlindedPath`]s may affect privacy since, if a suitable path cannot be found, it will
481 /// create a one-hop path using the recipient as the introduction node if it is a announced node.
482 /// Otherwise, there is no way to find a path to the introduction node in order to send a message,
483 /// and thus an `Err` is returned.
484 pub struct DefaultMessageRouter<G: Deref<Target=NetworkGraph<L>>, L: Deref, ES: Deref>
487 ES::Target: EntropySource,
493 impl<G: Deref<Target=NetworkGraph<L>>, L: Deref, ES: Deref> DefaultMessageRouter<G, L, ES>
496 ES::Target: EntropySource,
498 /// Creates a [`DefaultMessageRouter`] using the given [`NetworkGraph`].
499 pub fn new(network_graph: G, entropy_source: ES) -> Self {
500 Self { network_graph, entropy_source }
503 fn create_blinded_paths_from_iter<
504 I: Iterator<Item = ForwardNode>,
505 T: secp256k1::Signing + secp256k1::Verification
507 &self, recipient: PublicKey, peers: I, secp_ctx: &Secp256k1<T>, compact_paths: bool
508 ) -> Result<Vec<BlindedPath>, ()> {
509 // Limit the number of blinded paths that are computed.
510 const MAX_PATHS: usize = 3;
512 // Ensure peers have at least three channels so that it is more difficult to infer the
513 // recipient's node_id.
514 const MIN_PEER_CHANNELS: usize = 3;
516 let network_graph = self.network_graph.deref().read_only();
517 let is_recipient_announced =
518 network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient));
520 let mut peer_info = peers
521 // Limit to peers with announced channels
524 .node(&NodeId::from_pubkey(&peer.node_id))
525 .filter(|info| info.channels.len() >= MIN_PEER_CHANNELS)
526 .map(|info| (peer, info.is_tor_only(), info.channels.len()))
528 // Exclude Tor-only nodes when the recipient is announced.
529 .filter(|(_, is_tor_only, _)| !(*is_tor_only && is_recipient_announced))
530 .collect::<Vec<_>>();
532 // Prefer using non-Tor nodes with the most channels as the introduction node.
533 peer_info.sort_unstable_by(|(_, a_tor_only, a_channels), (_, b_tor_only, b_channels)| {
534 a_tor_only.cmp(b_tor_only).then(a_channels.cmp(b_channels).reverse())
537 let paths = peer_info.into_iter()
538 .map(|(peer, _, _)| {
539 BlindedPath::new_for_message(&[peer], recipient, &*self.entropy_source, secp_ctx)
542 .collect::<Result<Vec<_>, _>>();
544 let mut paths = match paths {
545 Ok(paths) if !paths.is_empty() => Ok(paths),
547 if is_recipient_announced {
548 BlindedPath::one_hop_for_message(recipient, &*self.entropy_source, secp_ctx)
549 .map(|path| vec![path])
557 for path in &mut paths {
558 path.use_compact_introduction_node(&network_graph);
566 impl<G: Deref<Target=NetworkGraph<L>>, L: Deref, ES: Deref> MessageRouter for DefaultMessageRouter<G, L, ES>
569 ES::Target: EntropySource,
572 &self, sender: PublicKey, peers: Vec<PublicKey>, mut destination: Destination
573 ) -> Result<OnionMessagePath, ()> {
574 let network_graph = self.network_graph.deref().read_only();
575 destination.resolve(&network_graph);
577 let first_node = match destination.first_node() {
578 Some(first_node) => first_node,
579 None => return Err(()),
582 if peers.contains(&first_node) || sender == first_node {
583 Ok(OnionMessagePath {
584 intermediate_nodes: vec![], destination, first_node_addresses: None
587 let node_details = network_graph
588 .node(&NodeId::from_pubkey(&first_node))
589 .and_then(|node_info| node_info.announcement_info.as_ref())
590 .map(|announcement_info| (announcement_info.features(), announcement_info.addresses()));
593 Some((features, addresses)) if features.supports_onion_messages() && addresses.len() > 0 => {
594 let first_node_addresses = Some(addresses.clone());
595 Ok(OnionMessagePath {
596 intermediate_nodes: vec![], destination, first_node_addresses
604 fn create_blinded_paths<
605 T: secp256k1::Signing + secp256k1::Verification
607 &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
608 ) -> Result<Vec<BlindedPath>, ()> {
611 .map(|node_id| ForwardNode { node_id, short_channel_id: None });
612 self.create_blinded_paths_from_iter(recipient, peers, secp_ctx, false)
615 fn create_compact_blinded_paths<
616 T: secp256k1::Signing + secp256k1::Verification
618 &self, recipient: PublicKey, peers: Vec<ForwardNode>, secp_ctx: &Secp256k1<T>,
619 ) -> Result<Vec<BlindedPath>, ()> {
620 self.create_blinded_paths_from_iter(recipient, peers.into_iter(), secp_ctx, true)
624 /// A path for sending an [`OnionMessage`].
626 pub struct OnionMessagePath {
627 /// Nodes on the path between the sender and the destination.
628 pub intermediate_nodes: Vec<PublicKey>,
630 /// The recipient of the message.
631 pub destination: Destination,
633 /// Addresses that may be used to connect to [`OnionMessagePath::first_node`].
635 /// Only needs to be set if a connection to the node is required. [`OnionMessenger`] may use
636 /// this to initiate such a connection.
637 pub first_node_addresses: Option<Vec<SocketAddress>>,
640 impl OnionMessagePath {
641 /// Returns the first node in the path.
642 pub fn first_node(&self) -> Option<PublicKey> {
643 self.intermediate_nodes
646 .or_else(|| self.destination.first_node())
650 /// The destination of an onion message.
651 #[derive(Clone, Hash, Debug, PartialEq, Eq)]
652 pub enum Destination {
653 /// We're sending this onion message to a node.
655 /// We're sending this onion message to a blinded path.
656 BlindedPath(BlindedPath),
660 /// Attempts to resolve the [`IntroductionNode::DirectedShortChannelId`] of a
661 /// [`Destination::BlindedPath`] to a [`IntroductionNode::NodeId`], if applicable, using the
662 /// provided [`ReadOnlyNetworkGraph`].
663 pub fn resolve(&mut self, network_graph: &ReadOnlyNetworkGraph) {
664 if let Destination::BlindedPath(path) = self {
665 if let IntroductionNode::DirectedShortChannelId(..) = path.introduction_node {
666 if let Some(pubkey) = path
667 .public_introduction_node_id(network_graph)
668 .and_then(|node_id| node_id.as_pubkey().ok())
670 path.introduction_node = IntroductionNode::NodeId(pubkey);
676 pub(super) fn num_hops(&self) -> usize {
678 Destination::Node(_) => 1,
679 Destination::BlindedPath(BlindedPath { blinded_hops, .. }) => blinded_hops.len(),
683 fn first_node(&self) -> Option<PublicKey> {
685 Destination::Node(node_id) => Some(*node_id),
686 Destination::BlindedPath(BlindedPath { introduction_node, .. }) => {
687 match introduction_node {
688 IntroductionNode::NodeId(pubkey) => Some(*pubkey),
689 IntroductionNode::DirectedShortChannelId(..) => None,
696 /// Result of successfully [sending an onion message].
698 /// [sending an onion message]: OnionMessenger::send_onion_message
699 #[derive(Clone, Hash, Debug, PartialEq, Eq)]
700 pub enum SendSuccess {
701 /// The message was buffered and will be sent once it is processed by
702 /// [`OnionMessageHandler::next_onion_message_for_peer`].
704 /// The message was buffered and will be sent once the node is connected as a peer and it is
705 /// processed by [`OnionMessageHandler::next_onion_message_for_peer`].
706 BufferedAwaitingConnection(PublicKey),
709 /// Errors that may occur when [sending an onion message].
711 /// [sending an onion message]: OnionMessenger::send_onion_message
712 #[derive(Clone, Hash, Debug, PartialEq, Eq)]
714 /// Errored computing onion message packet keys.
715 Secp256k1(secp256k1::Error),
716 /// Because implementations such as Eclair will drop onion messages where the message packet
717 /// exceeds 32834 bytes, we refuse to send messages where the packet exceeds this size.
719 /// The provided [`Destination`] was an invalid [`BlindedPath`] due to not having any blinded
722 /// The first hop is not a peer and doesn't have a known [`SocketAddress`].
723 InvalidFirstHop(PublicKey),
724 /// Indicates that a path could not be found by the [`MessageRouter`].
726 /// This occurs when either:
727 /// - No path from the sender to the destination was found to send the onion message
728 /// - No reply path to the sender could be created when responding to an onion message
730 /// Onion message contents must have a TLV type >= 64.
732 /// Our next-hop peer's buffer was full or our total outbound buffer was full.
734 /// Failed to retrieve our node id from the provided [`NodeSigner`].
736 /// [`NodeSigner`]: crate::sign::NodeSigner
738 /// The provided [`Destination`] has a blinded path with an unresolved introduction node. An
739 /// attempt to resolve it in the [`MessageRouter`] when finding an [`OnionMessagePath`] likely
741 UnresolvedIntroductionNode,
742 /// We attempted to send to a blinded path where we are the introduction node, and failed to
743 /// advance the blinded path to make the second hop the new introduction node. Either
744 /// [`NodeSigner::ecdh`] failed, we failed to tweak the current blinding point to get the
745 /// new blinding point, or we were attempting to send to ourselves.
746 BlindedPathAdvanceFailed,
749 /// Handler for custom onion messages. If you are using [`SimpleArcOnionMessenger`],
750 /// [`SimpleRefOnionMessenger`], or prefer to ignore inbound custom onion messages,
751 /// [`IgnoringMessageHandler`] must be provided to [`OnionMessenger::new`]. Otherwise, a custom
752 /// implementation of this trait must be provided, with [`CustomMessage`] specifying the supported
755 /// See [`OnionMessenger`] for example usage.
757 /// [`IgnoringMessageHandler`]: crate::ln::peer_handler::IgnoringMessageHandler
758 /// [`CustomMessage`]: Self::CustomMessage
759 pub trait CustomOnionMessageHandler {
760 /// The message known to the handler. To support multiple message types, you may want to make this
761 /// an enum with a variant for each supported message.
762 type CustomMessage: OnionMessageContents;
764 /// Called with the custom message that was received, returning a response to send, if any.
766 /// The returned [`Self::CustomMessage`], if any, is enqueued to be sent by [`OnionMessenger`].
767 fn handle_custom_message(&self, message: Self::CustomMessage, responder: Option<Responder>) -> ResponseInstruction<Self::CustomMessage>;
769 /// Read a custom message of type `message_type` from `buffer`, returning `Ok(None)` if the
770 /// message type is unknown.
771 fn read_custom_message<R: io::Read>(&self, message_type: u64, buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError>;
773 /// Releases any [`Self::CustomMessage`]s that need to be sent.
775 /// Typically, this is used for messages initiating a message flow rather than in response to
776 /// another message. The latter should use the return value of [`Self::handle_custom_message`].
777 #[cfg(not(c_bindings))]
778 fn release_pending_custom_messages(&self) -> Vec<PendingOnionMessage<Self::CustomMessage>>;
780 /// Releases any [`Self::CustomMessage`]s that need to be sent.
782 /// Typically, this is used for messages initiating a message flow rather than in response to
783 /// another message. The latter should use the return value of [`Self::handle_custom_message`].
785 fn release_pending_custom_messages(&self) -> Vec<(Self::CustomMessage, Destination, Option<BlindedPath>)>;
788 /// A processed incoming onion message, containing either a Forward (another onion message)
789 /// or a Receive payload with decrypted contents.
790 #[derive(Clone, Debug)]
791 pub enum PeeledOnion<T: OnionMessageContents> {
792 /// Forwarded onion, with the next node id and a new onion
793 Forward(NextMessageHop, OnionMessage),
794 /// Received onion message, with decrypted contents, path_id, and reply path
795 Receive(ParsedOnionMessageContents<T>, Option<[u8; 32]>, Option<BlindedPath>)
799 /// Creates an [`OnionMessage`] with the given `contents` for sending to the destination of
800 /// `path`, first calling [`Destination::resolve`] on `path.destination` with the given
801 /// [`ReadOnlyNetworkGraph`].
803 /// Returns the node id of the peer to send the message to, the message itself, and any addresses
804 /// needed to connect to the first node.
805 pub fn create_onion_message_resolving_destination<
806 ES: Deref, NS: Deref, NL: Deref, T: OnionMessageContents
808 entropy_source: &ES, node_signer: &NS, node_id_lookup: &NL,
809 network_graph: &ReadOnlyNetworkGraph, secp_ctx: &Secp256k1<secp256k1::All>,
810 mut path: OnionMessagePath, contents: T, reply_path: Option<BlindedPath>,
811 ) -> Result<(PublicKey, OnionMessage, Option<Vec<SocketAddress>>), SendError>
813 ES::Target: EntropySource,
814 NS::Target: NodeSigner,
815 NL::Target: NodeIdLookUp,
817 path.destination.resolve(network_graph);
818 create_onion_message(
819 entropy_source, node_signer, node_id_lookup, secp_ctx, path, contents, reply_path,
823 /// Creates an [`OnionMessage`] with the given `contents` for sending to the destination of
826 /// Returns the node id of the peer to send the message to, the message itself, and any addresses
827 /// needed to connect to the first node.
829 /// Returns [`SendError::UnresolvedIntroductionNode`] if:
830 /// - `destination` contains a blinded path with an [`IntroductionNode::DirectedShortChannelId`],
831 /// - unless it can be resolved by [`NodeIdLookUp::next_node_id`].
832 /// Use [`create_onion_message_resolving_destination`] instead to resolve the introduction node
833 /// first with a [`ReadOnlyNetworkGraph`].
834 pub fn create_onion_message<ES: Deref, NS: Deref, NL: Deref, T: OnionMessageContents>(
835 entropy_source: &ES, node_signer: &NS, node_id_lookup: &NL,
836 secp_ctx: &Secp256k1<secp256k1::All>, path: OnionMessagePath, contents: T,
837 reply_path: Option<BlindedPath>,
838 ) -> Result<(PublicKey, OnionMessage, Option<Vec<SocketAddress>>), SendError>
840 ES::Target: EntropySource,
841 NS::Target: NodeSigner,
842 NL::Target: NodeIdLookUp,
844 let OnionMessagePath { intermediate_nodes, mut destination, first_node_addresses } = path;
845 if let Destination::BlindedPath(BlindedPath { ref blinded_hops, .. }) = destination {
846 if blinded_hops.is_empty() {
847 return Err(SendError::TooFewBlindedHops);
851 if contents.tlv_type() < 64 { return Err(SendError::InvalidMessage) }
853 // If we are sending straight to a blinded path and we are the introduction node, we need to
854 // advance the blinded path by 1 hop so the second hop is the new introduction node.
855 if intermediate_nodes.len() == 0 {
856 if let Destination::BlindedPath(ref mut blinded_path) = destination {
857 let our_node_id = node_signer.get_node_id(Recipient::Node)
858 .map_err(|()| SendError::GetNodeIdFailed)?;
859 let introduction_node_id = match blinded_path.introduction_node {
860 IntroductionNode::NodeId(pubkey) => pubkey,
861 IntroductionNode::DirectedShortChannelId(direction, scid) => {
862 match node_id_lookup.next_node_id(scid) {
863 Some(next_node_id) => *direction.select_pubkey(&our_node_id, &next_node_id),
864 None => return Err(SendError::UnresolvedIntroductionNode),
868 if introduction_node_id == our_node_id {
869 advance_path_by_one(blinded_path, node_signer, node_id_lookup, &secp_ctx)
870 .map_err(|()| SendError::BlindedPathAdvanceFailed)?;
875 let blinding_secret_bytes = entropy_source.get_secure_random_bytes();
876 let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
877 let (first_node_id, blinding_point) = if let Some(first_node_id) = intermediate_nodes.first() {
878 (*first_node_id, PublicKey::from_secret_key(&secp_ctx, &blinding_secret))
881 Destination::Node(pk) => (*pk, PublicKey::from_secret_key(&secp_ctx, &blinding_secret)),
882 Destination::BlindedPath(BlindedPath { introduction_node, blinding_point, .. }) => {
883 match introduction_node {
884 IntroductionNode::NodeId(pubkey) => (*pubkey, *blinding_point),
885 IntroductionNode::DirectedShortChannelId(..) => {
886 return Err(SendError::UnresolvedIntroductionNode);
892 let (packet_payloads, packet_keys) = packet_payloads_and_keys(
893 &secp_ctx, &intermediate_nodes, destination, contents, reply_path, &blinding_secret
896 let prng_seed = entropy_source.get_secure_random_bytes();
897 let onion_routing_packet = construct_onion_message_packet(
898 packet_payloads, packet_keys, prng_seed).map_err(|()| SendError::TooBigPacket)?;
900 let message = OnionMessage { blinding_point, onion_routing_packet };
901 Ok((first_node_id, message, first_node_addresses))
904 /// Decode one layer of an incoming [`OnionMessage`].
906 /// Returns either the next layer of the onion for forwarding or the decrypted content for the
908 pub fn peel_onion_message<NS: Deref, L: Deref, CMH: Deref>(
909 msg: &OnionMessage, secp_ctx: &Secp256k1<secp256k1::All>, node_signer: NS, logger: L,
911 ) -> Result<PeeledOnion<<<CMH>::Target as CustomOnionMessageHandler>::CustomMessage>, ()>
913 NS::Target: NodeSigner,
915 CMH::Target: CustomOnionMessageHandler,
917 let control_tlvs_ss = match node_signer.ecdh(Recipient::Node, &msg.blinding_point, None) {
920 log_error!(logger, "Failed to retrieve node secret: {:?}", e);
924 let onion_decode_ss = {
925 let blinding_factor = {
926 let mut hmac = HmacEngine::<Sha256>::new(b"blinded_node_id");
927 hmac.input(control_tlvs_ss.as_ref());
928 Hmac::from_engine(hmac).to_byte_array()
930 match node_signer.ecdh(Recipient::Node, &msg.onion_routing_packet.public_key,
931 Some(&Scalar::from_be_bytes(blinding_factor).unwrap()))
933 Ok(ss) => ss.secret_bytes(),
935 log_trace!(logger, "Failed to compute onion packet shared secret");
940 match onion_utils::decode_next_untagged_hop(
941 onion_decode_ss, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac,
942 (control_tlvs_ss, custom_handler.deref(), logger.deref())
944 Ok((Payload::Receive::<ParsedOnionMessageContents<<<CMH as Deref>::Target as CustomOnionMessageHandler>::CustomMessage>> {
945 message, control_tlvs: ReceiveControlTlvs::Unblinded(ReceiveTlvs { path_id }), reply_path,
947 Ok(PeeledOnion::Receive(message, path_id, reply_path))
949 Ok((Payload::Forward(ForwardControlTlvs::Unblinded(ForwardTlvs {
950 next_hop, next_blinding_override
951 })), Some((next_hop_hmac, new_packet_bytes)))) => {
952 // TODO: we need to check whether `next_hop` is our node, in which case this is a dummy
953 // blinded hop and this onion message is destined for us. In this situation, we should keep
954 // unwrapping the onion layers to get to the final payload. Since we don't have the option
955 // of creating blinded paths with dummy hops currently, we should be ok to not handle this
957 let new_pubkey = match onion_utils::next_hop_pubkey(&secp_ctx, msg.onion_routing_packet.public_key, &onion_decode_ss) {
960 log_trace!(logger, "Failed to compute next hop packet pubkey: {}", e);
964 let outgoing_packet = Packet {
966 public_key: new_pubkey,
967 hop_data: new_packet_bytes,
970 let onion_message = OnionMessage {
971 blinding_point: match next_blinding_override {
972 Some(blinding_point) => blinding_point,
974 match onion_utils::next_hop_pubkey(
975 &secp_ctx, msg.blinding_point, control_tlvs_ss.as_ref()
979 log_trace!(logger, "Failed to compute next blinding point: {}", e);
985 onion_routing_packet: outgoing_packet,
988 Ok(PeeledOnion::Forward(next_hop, onion_message))
991 log_trace!(logger, "Errored decoding onion message packet: {:?}", e);
995 log_trace!(logger, "Received bogus onion message packet, either the sender encoded a final hop as a forwarding hop or vice versa");
1001 impl<ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, APH: Deref, CMH: Deref>
1002 OnionMessenger<ES, NS, L, NL, MR, OMH, APH, CMH>
1004 ES::Target: EntropySource,
1005 NS::Target: NodeSigner,
1007 NL::Target: NodeIdLookUp,
1008 MR::Target: MessageRouter,
1009 OMH::Target: OffersMessageHandler,
1010 APH::Target: AsyncPaymentsMessageHandler,
1011 CMH::Target: CustomOnionMessageHandler,
1013 /// Constructs a new `OnionMessenger` to send, forward, and delegate received onion messages to
1014 /// their respective handlers.
1016 entropy_source: ES, node_signer: NS, logger: L, node_id_lookup: NL, message_router: MR,
1017 offers_handler: OMH, async_payments_handler: APH, custom_handler: CMH
1020 entropy_source, node_signer, logger, node_id_lookup, message_router,
1021 offers_handler, async_payments_handler, custom_handler, false
1025 /// Similar to [`Self::new`], but rather than dropping onion messages that are
1026 /// intended to be forwarded to offline peers, we will intercept them for
1027 /// later forwarding.
1029 /// Interception flow:
1030 /// 1. If an onion message for an offline peer is received, `OnionMessenger` will
1031 /// generate an [`Event::OnionMessageIntercepted`]. Event handlers can
1032 /// then choose to persist this onion message for later forwarding, or drop
1034 /// 2. When the offline peer later comes back online, `OnionMessenger` will
1035 /// generate an [`Event::OnionMessagePeerConnected`]. Event handlers will
1036 /// then fetch all previously intercepted onion messages for this peer.
1037 /// 3. Once the stored onion messages are fetched, they can finally be
1038 /// forwarded to the now-online peer via [`Self::forward_onion_message`].
1042 /// LDK will not rate limit how many [`Event::OnionMessageIntercepted`]s
1043 /// are generated, so it is the caller's responsibility to limit how many
1044 /// onion messages are persisted and only persist onion messages for relevant
1046 pub fn new_with_offline_peer_interception(
1047 entropy_source: ES, node_signer: NS, logger: L, node_id_lookup: NL,
1048 message_router: MR, offers_handler: OMH, async_payments_handler: APH, custom_handler: CMH
1051 entropy_source, node_signer, logger, node_id_lookup, message_router,
1052 offers_handler, async_payments_handler, custom_handler, true
1057 entropy_source: ES, node_signer: NS, logger: L, node_id_lookup: NL,
1058 message_router: MR, offers_handler: OMH, async_payments_handler: APH, custom_handler: CMH,
1059 intercept_messages_for_offline_peers: bool
1061 let mut secp_ctx = Secp256k1::new();
1062 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
1066 message_recipients: Mutex::new(new_hash_map()),
1072 async_payments_handler,
1074 intercept_messages_for_offline_peers,
1075 pending_events: Mutex::new(PendingEvents {
1076 intercepted_msgs: Vec::new(),
1077 peer_connecteds: Vec::new(),
1083 pub(crate) fn set_offers_handler(&mut self, offers_handler: OMH) {
1084 self.offers_handler = offers_handler;
1087 /// Sends an [`OnionMessage`] with the given `contents` to `destination`.
1089 /// See [`OnionMessenger`] for example usage.
1090 pub fn send_onion_message<T: OnionMessageContents>(
1091 &self, contents: T, destination: Destination, reply_path: Option<BlindedPath>
1092 ) -> Result<SendSuccess, SendError> {
1093 self.find_path_and_enqueue_onion_message(
1094 contents, destination, reply_path, format_args!("")
1098 fn find_path_and_enqueue_onion_message<T: OnionMessageContents>(
1099 &self, contents: T, destination: Destination, reply_path: Option<BlindedPath>,
1100 log_suffix: fmt::Arguments
1101 ) -> Result<SendSuccess, SendError> {
1102 let mut logger = WithContext::from(&self.logger, None, None, None);
1103 let result = self.find_path(destination).and_then(|path| {
1104 let first_hop = path.intermediate_nodes.get(0).map(|p| *p);
1105 logger = WithContext::from(&self.logger, first_hop, None, None);
1106 self.enqueue_onion_message(path, contents, reply_path, log_suffix)
1109 match result.as_ref() {
1110 Err(SendError::GetNodeIdFailed) => {
1111 log_warn!(logger, "Unable to retrieve node id {}", log_suffix);
1113 Err(SendError::PathNotFound) => {
1114 log_trace!(logger, "Failed to find path {}", log_suffix);
1117 log_trace!(logger, "Failed sending onion message {}: {:?}", log_suffix, e);
1119 Ok(SendSuccess::Buffered) => {
1120 log_trace!(logger, "Buffered onion message {}", log_suffix);
1122 Ok(SendSuccess::BufferedAwaitingConnection(node_id)) => {
1125 "Buffered onion message waiting on peer connection {}: {}",
1134 fn find_path(&self, destination: Destination) -> Result<OnionMessagePath, SendError> {
1135 let sender = self.node_signer
1136 .get_node_id(Recipient::Node)
1137 .map_err(|_| SendError::GetNodeIdFailed)?;
1139 let peers = self.message_recipients.lock().unwrap()
1141 .filter(|(_, recipient)| matches!(recipient, OnionMessageRecipient::ConnectedPeer(_)))
1142 .map(|(node_id, _)| *node_id)
1146 .find_path(sender, peers, destination)
1147 .map_err(|_| SendError::PathNotFound)
1150 fn create_blinded_path(&self) -> Result<BlindedPath, SendError> {
1151 let recipient = self.node_signer
1152 .get_node_id(Recipient::Node)
1153 .map_err(|_| SendError::GetNodeIdFailed)?;
1154 let secp_ctx = &self.secp_ctx;
1156 let peers = self.message_recipients.lock().unwrap()
1158 .filter(|(_, peer)| matches!(peer, OnionMessageRecipient::ConnectedPeer(_)))
1159 .map(|(node_id, _ )| *node_id)
1160 .collect::<Vec<_>>();
1163 .create_blinded_paths(recipient, peers, secp_ctx)
1164 .and_then(|paths| paths.into_iter().next().ok_or(()))
1165 .map_err(|_| SendError::PathNotFound)
1168 fn enqueue_onion_message<T: OnionMessageContents>(
1169 &self, path: OnionMessagePath, contents: T, reply_path: Option<BlindedPath>,
1170 log_suffix: fmt::Arguments
1171 ) -> Result<SendSuccess, SendError> {
1172 log_trace!(self.logger, "Constructing onion message {}: {:?}", log_suffix, contents);
1174 let (first_node_id, onion_message, addresses) = create_onion_message(
1175 &self.entropy_source, &self.node_signer, &self.node_id_lookup, &self.secp_ctx, path,
1176 contents, reply_path,
1179 let mut message_recipients = self.message_recipients.lock().unwrap();
1180 if outbound_buffer_full(&first_node_id, &message_recipients) {
1181 return Err(SendError::BufferFull);
1184 match message_recipients.entry(first_node_id) {
1185 hash_map::Entry::Vacant(e) => match addresses {
1186 None => Err(SendError::InvalidFirstHop(first_node_id)),
1187 Some(addresses) => {
1188 e.insert(OnionMessageRecipient::pending_connection(addresses))
1189 .enqueue_message(onion_message);
1190 Ok(SendSuccess::BufferedAwaitingConnection(first_node_id))
1193 hash_map::Entry::Occupied(mut e) => {
1194 e.get_mut().enqueue_message(onion_message);
1195 if e.get().is_connected() {
1196 Ok(SendSuccess::Buffered)
1198 Ok(SendSuccess::BufferedAwaitingConnection(first_node_id))
1204 /// Forwards an [`OnionMessage`] to `peer_node_id`. Useful if we initialized
1205 /// the [`OnionMessenger`] with [`Self::new_with_offline_peer_interception`]
1206 /// and want to forward a previously intercepted onion message to a peer that
1207 /// has just come online.
1208 pub fn forward_onion_message(
1209 &self, message: OnionMessage, peer_node_id: &PublicKey
1210 ) -> Result<(), SendError> {
1211 let mut message_recipients = self.message_recipients.lock().unwrap();
1212 if outbound_buffer_full(&peer_node_id, &message_recipients) {
1213 return Err(SendError::BufferFull);
1216 match message_recipients.entry(*peer_node_id) {
1217 hash_map::Entry::Occupied(mut e) if e.get().is_connected() => {
1218 e.get_mut().enqueue_message(message);
1221 _ => Err(SendError::InvalidFirstHop(*peer_node_id))
1225 #[cfg(any(test, feature = "_test_utils"))]
1226 pub fn send_onion_message_using_path<T: OnionMessageContents>(
1227 &self, path: OnionMessagePath, contents: T, reply_path: Option<BlindedPath>
1228 ) -> Result<SendSuccess, SendError> {
1229 self.enqueue_onion_message(path, contents, reply_path, format_args!(""))
1232 pub(crate) fn peel_onion_message(
1233 &self, msg: &OnionMessage
1234 ) -> Result<PeeledOnion<<<CMH>::Target as CustomOnionMessageHandler>::CustomMessage>, ()> {
1236 msg, &self.secp_ctx, &*self.node_signer, &*self.logger, &*self.custom_handler
1240 /// Handles the response to an [`OnionMessage`] based on its [`ResponseInstruction`],
1241 /// enqueueing any response for sending.
1243 /// This function is useful for asynchronous handling of [`OnionMessage`]s.
1244 /// Handlers have the option to return [`ResponseInstruction::NoResponse`], indicating that
1245 /// no immediate response should be sent. Then, they can transfer the associated [`Responder`]
1246 /// to another task responsible for generating the response asynchronously. Subsequently, when
1247 /// the response is prepared and ready for sending, that task can invoke this method to enqueue
1248 /// the response for delivery.
1249 pub fn handle_onion_message_response<T: OnionMessageContents>(
1250 &self, response: ResponseInstruction<T>
1251 ) -> Result<Option<SendSuccess>, SendError> {
1252 let (response, create_reply_path) = match response {
1253 ResponseInstruction::WithReplyPath(response) => (response, true),
1254 ResponseInstruction::WithoutReplyPath(response) => (response, false),
1255 ResponseInstruction::NoResponse => return Ok(None),
1258 let message_type = response.message.msg_type();
1259 let reply_path = if create_reply_path {
1260 match self.create_blinded_path() {
1261 Ok(reply_path) => Some(reply_path),
1265 "Failed to create reply path when responding with {} to an onion message \
1266 with path_id {:02x?}: {:?}",
1267 message_type, response.path_id, err
1274 self.find_path_and_enqueue_onion_message(
1275 response.message, Destination::BlindedPath(response.reply_path), reply_path,
1277 "when responding with {} to an onion message with path_id {:02x?}",
1281 ).map(|result| Some(result))
1285 pub(super) fn release_pending_msgs(&self) -> HashMap<PublicKey, VecDeque<OnionMessage>> {
1286 let mut message_recipients = self.message_recipients.lock().unwrap();
1287 let mut msgs = new_hash_map();
1288 // We don't want to disconnect the peers by removing them entirely from the original map, so we
1289 // release the pending message buffers individually.
1290 for (node_id, recipient) in &mut *message_recipients {
1291 msgs.insert(*node_id, recipient.release_pending_messages());
1296 fn enqueue_intercepted_event(&self, event: Event) {
1297 const MAX_EVENTS_BUFFER_SIZE: usize = (1 << 10) * 256;
1298 let mut pending_events = self.pending_events.lock().unwrap();
1299 let total_buffered_bytes: usize =
1300 pending_events.intercepted_msgs.iter().map(|ev| ev.serialized_length()).sum();
1301 if total_buffered_bytes >= MAX_EVENTS_BUFFER_SIZE {
1302 log_trace!(self.logger, "Dropping event {:?}: buffer full", event);
1305 pending_events.intercepted_msgs.push(event);
1308 /// Processes any events asynchronously using the given handler.
1310 /// Note that the event handler is called in the order each event was generated, however
1311 /// futures are polled in parallel for some events to allow for parallelism where events do not
1312 /// have an ordering requirement.
1314 /// See the trait-level documentation of [`EventsProvider`] for requirements.
1315 pub async fn process_pending_events_async<Future: core::future::Future<Output = ()> + core::marker::Unpin, H: Fn(Event) -> Future>(
1318 let mut intercepted_msgs = Vec::new();
1319 let mut peer_connecteds = Vec::new();
1321 let mut pending_events = self.pending_events.lock().unwrap();
1322 core::mem::swap(&mut pending_events.intercepted_msgs, &mut intercepted_msgs);
1323 core::mem::swap(&mut pending_events.peer_connecteds, &mut peer_connecteds);
1326 let mut futures = Vec::with_capacity(intercepted_msgs.len());
1327 for (node_id, recipient) in self.message_recipients.lock().unwrap().iter_mut() {
1328 if let OnionMessageRecipient::PendingConnection(_, addresses, _) = recipient {
1329 if let Some(addresses) = addresses.take() {
1330 futures.push(Some(handler(Event::ConnectionNeeded { node_id: *node_id, addresses })));
1335 for ev in intercepted_msgs {
1336 if let Event::OnionMessageIntercepted { .. } = ev {} else { debug_assert!(false); }
1337 futures.push(Some(handler(ev)));
1339 // Let the `OnionMessageIntercepted` events finish before moving on to peer_connecteds
1340 crate::util::async_poll::MultiFuturePoller(futures).await;
1342 if peer_connecteds.len() <= 1 {
1343 for event in peer_connecteds { handler(event).await; }
1345 let mut futures = Vec::new();
1346 for event in peer_connecteds {
1347 futures.push(Some(handler(event)));
1349 crate::util::async_poll::MultiFuturePoller(futures).await;
1354 fn outbound_buffer_full(peer_node_id: &PublicKey, buffer: &HashMap<PublicKey, OnionMessageRecipient>) -> bool {
1355 const MAX_TOTAL_BUFFER_SIZE: usize = (1 << 20) * 128;
1356 const MAX_PER_PEER_BUFFER_SIZE: usize = (1 << 10) * 256;
1357 let mut total_buffered_bytes = 0;
1358 let mut peer_buffered_bytes = 0;
1359 for (pk, peer_buf) in buffer {
1360 for om in peer_buf.pending_messages() {
1361 let om_len = om.serialized_length();
1362 if pk == peer_node_id {
1363 peer_buffered_bytes += om_len;
1365 total_buffered_bytes += om_len;
1367 if total_buffered_bytes >= MAX_TOTAL_BUFFER_SIZE ||
1368 peer_buffered_bytes >= MAX_PER_PEER_BUFFER_SIZE
1377 impl<ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, APH: Deref, CMH: Deref> EventsProvider
1378 for OnionMessenger<ES, NS, L, NL, MR, OMH, APH, CMH>
1380 ES::Target: EntropySource,
1381 NS::Target: NodeSigner,
1383 NL::Target: NodeIdLookUp,
1384 MR::Target: MessageRouter,
1385 OMH::Target: OffersMessageHandler,
1386 APH::Target: AsyncPaymentsMessageHandler,
1387 CMH::Target: CustomOnionMessageHandler,
1389 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
1390 for (node_id, recipient) in self.message_recipients.lock().unwrap().iter_mut() {
1391 if let OnionMessageRecipient::PendingConnection(_, addresses, _) = recipient {
1392 if let Some(addresses) = addresses.take() {
1393 handler.handle_event(Event::ConnectionNeeded { node_id: *node_id, addresses });
1397 let mut events = Vec::new();
1399 let mut pending_events = self.pending_events.lock().unwrap();
1400 #[cfg(debug_assertions)] {
1401 for ev in pending_events.intercepted_msgs.iter() {
1402 if let Event::OnionMessageIntercepted { .. } = ev {} else { panic!(); }
1404 for ev in pending_events.peer_connecteds.iter() {
1405 if let Event::OnionMessagePeerConnected { .. } = ev {} else { panic!(); }
1408 core::mem::swap(&mut pending_events.intercepted_msgs, &mut events);
1409 events.append(&mut pending_events.peer_connecteds);
1410 pending_events.peer_connecteds.shrink_to(10); // Limit total heap usage
1413 handler.handle_event(ev);
1418 impl<ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, APH: Deref, CMH: Deref> OnionMessageHandler
1419 for OnionMessenger<ES, NS, L, NL, MR, OMH, APH, CMH>
1421 ES::Target: EntropySource,
1422 NS::Target: NodeSigner,
1424 NL::Target: NodeIdLookUp,
1425 MR::Target: MessageRouter,
1426 OMH::Target: OffersMessageHandler,
1427 APH::Target: AsyncPaymentsMessageHandler,
1428 CMH::Target: CustomOnionMessageHandler,
1430 fn handle_onion_message(&self, peer_node_id: &PublicKey, msg: &OnionMessage) {
1431 let logger = WithContext::from(&self.logger, Some(*peer_node_id), None, None);
1432 match self.peel_onion_message(msg) {
1433 Ok(PeeledOnion::Receive(message, path_id, reply_path)) => {
1436 "Received an onion message with path_id {:02x?} and {} reply_path: {:?}",
1437 path_id, if reply_path.is_some() { "a" } else { "no" }, message);
1439 let responder = reply_path.map(
1440 |reply_path| Responder::new(reply_path, path_id)
1443 ParsedOnionMessageContents::Offers(msg) => {
1444 let response_instructions = self.offers_handler.handle_message(msg, responder);
1445 let _ = self.handle_onion_message_response(response_instructions);
1447 ParsedOnionMessageContents::AsyncPayments(AsyncPaymentsMessage::HeldHtlcAvailable(msg)) => {
1448 let response_instructions = self.async_payments_handler.held_htlc_available(
1451 let _ = self.handle_onion_message_response(response_instructions);
1453 ParsedOnionMessageContents::AsyncPayments(AsyncPaymentsMessage::ReleaseHeldHtlc(msg)) => {
1454 self.async_payments_handler.release_held_htlc(msg);
1456 ParsedOnionMessageContents::Custom(msg) => {
1457 let response_instructions = self.custom_handler.handle_custom_message(msg, responder);
1458 let _ = self.handle_onion_message_response(response_instructions);
1462 Ok(PeeledOnion::Forward(next_hop, onion_message)) => {
1463 let next_node_id = match next_hop {
1464 NextMessageHop::NodeId(pubkey) => pubkey,
1465 NextMessageHop::ShortChannelId(scid) => match self.node_id_lookup.next_node_id(scid) {
1466 Some(pubkey) => pubkey,
1468 log_trace!(self.logger, "Dropping forwarded onion messager: unable to resolve next hop using SCID {}", scid);
1474 let mut message_recipients = self.message_recipients.lock().unwrap();
1475 if outbound_buffer_full(&next_node_id, &message_recipients) {
1478 "Dropping forwarded onion message to peer {}: outbound buffer full",
1485 .entry(next_node_id)
1486 .or_insert_with(|| OnionMessageRecipient::ConnectedPeer(VecDeque::new()));
1488 match message_recipients.entry(next_node_id) {
1489 hash_map::Entry::Occupied(mut e) if matches!(
1490 e.get(), OnionMessageRecipient::ConnectedPeer(..)
1492 e.get_mut().enqueue_message(onion_message);
1493 log_trace!(logger, "Forwarding an onion message to peer {}", next_node_id);
1495 _ if self.intercept_messages_for_offline_peers => {
1496 self.enqueue_intercepted_event(
1497 Event::OnionMessageIntercepted {
1498 peer_node_id: next_node_id, message: onion_message
1505 "Dropping forwarded onion message to disconnected peer {}",
1512 log_error!(logger, "Failed to process onion message {:?}", e);
1517 fn peer_connected(&self, their_node_id: &PublicKey, init: &msgs::Init, _inbound: bool) -> Result<(), ()> {
1518 if init.features.supports_onion_messages() {
1519 self.message_recipients.lock().unwrap()
1520 .entry(*their_node_id)
1521 .or_insert_with(|| OnionMessageRecipient::ConnectedPeer(VecDeque::new()))
1523 if self.intercept_messages_for_offline_peers {
1524 self.pending_events.lock().unwrap().peer_connecteds.push(
1525 Event::OnionMessagePeerConnected { peer_node_id: *their_node_id }
1529 self.message_recipients.lock().unwrap().remove(their_node_id);
1535 fn peer_disconnected(&self, their_node_id: &PublicKey) {
1536 match self.message_recipients.lock().unwrap().remove(their_node_id) {
1537 Some(OnionMessageRecipient::ConnectedPeer(..)) => {},
1538 Some(_) => debug_assert!(false),
1543 fn timer_tick_occurred(&self) {
1544 let mut message_recipients = self.message_recipients.lock().unwrap();
1546 // Drop any pending recipients since the last call to avoid retaining buffered messages for
1548 message_recipients.retain(|_, recipient| match recipient {
1549 OnionMessageRecipient::PendingConnection(_, None, ticks) => *ticks < MAX_TIMER_TICKS,
1550 OnionMessageRecipient::PendingConnection(_, Some(_), _) => true,
1554 // Increment a timer tick for pending recipients so that their buffered messages are dropped
1555 // at MAX_TIMER_TICKS.
1556 for recipient in message_recipients.values_mut() {
1557 if let OnionMessageRecipient::PendingConnection(_, None, ticks) = recipient {
1563 fn provided_node_features(&self) -> NodeFeatures {
1564 let mut features = NodeFeatures::empty();
1565 features.set_onion_messages_optional();
1569 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
1570 let mut features = InitFeatures::empty();
1571 features.set_onion_messages_optional();
1575 // Before returning any messages to send for the peer, this method will see if any messages were
1576 // enqueued in the handler by users, find a path to the corresponding blinded path's introduction
1577 // node, and then enqueue the message for sending to the first peer in the full path.
1578 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<OnionMessage> {
1579 // Enqueue any initiating `OffersMessage`s to send.
1580 for message in self.offers_handler.release_pending_messages() {
1581 #[cfg(not(c_bindings))]
1582 let PendingOnionMessage { contents, destination, reply_path } = message;
1584 let (contents, destination, reply_path) = message;
1585 let _ = self.find_path_and_enqueue_onion_message(
1586 contents, destination, reply_path, format_args!("when sending OffersMessage")
1590 // Enqueue any initiating `CustomMessage`s to send.
1591 for message in self.custom_handler.release_pending_custom_messages() {
1592 #[cfg(not(c_bindings))]
1593 let PendingOnionMessage { contents, destination, reply_path } = message;
1595 let (contents, destination, reply_path) = message;
1596 let _ = self.find_path_and_enqueue_onion_message(
1597 contents, destination, reply_path, format_args!("when sending CustomMessage")
1601 self.message_recipients.lock().unwrap()
1602 .get_mut(&peer_node_id)
1603 .and_then(|buffer| buffer.dequeue_message())
1607 // TODO: parameterize the below Simple* types with OnionMessenger and handle the messages it
1609 /// Useful for simplifying the parameters of [`SimpleArcChannelManager`] and
1610 /// [`SimpleArcPeerManager`]. See their docs for more details.
1612 /// This is not exported to bindings users as type aliases aren't supported in most languages.
1614 /// [`SimpleArcChannelManager`]: crate::ln::channelmanager::SimpleArcChannelManager
1615 /// [`SimpleArcPeerManager`]: crate::ln::peer_handler::SimpleArcPeerManager
1616 #[cfg(not(c_bindings))]
1617 pub type SimpleArcOnionMessenger<M, T, F, L> = OnionMessenger<
1621 Arc<SimpleArcChannelManager<M, T, F, L>>,
1622 Arc<DefaultMessageRouter<Arc<NetworkGraph<Arc<L>>>, Arc<L>, Arc<KeysManager>>>,
1623 Arc<SimpleArcChannelManager<M, T, F, L>>,
1624 IgnoringMessageHandler,
1625 IgnoringMessageHandler
1628 /// Useful for simplifying the parameters of [`SimpleRefChannelManager`] and
1629 /// [`SimpleRefPeerManager`]. See their docs for more details.
1631 /// This is not exported to bindings users as type aliases aren't supported in most languages.
1633 /// [`SimpleRefChannelManager`]: crate::ln::channelmanager::SimpleRefChannelManager
1634 /// [`SimpleRefPeerManager`]: crate::ln::peer_handler::SimpleRefPeerManager
1635 #[cfg(not(c_bindings))]
1636 pub type SimpleRefOnionMessenger<
1637 'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, M, T, F, L
1642 &'i SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L>,
1643 &'j DefaultMessageRouter<&'g NetworkGraph<&'b L>, &'b L, &'a KeysManager>,
1644 &'i SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L>,
1645 IgnoringMessageHandler,
1646 IgnoringMessageHandler
1649 /// Construct onion packet payloads and keys for sending an onion message along the given
1650 /// `unblinded_path` to the given `destination`.
1651 fn packet_payloads_and_keys<T: OnionMessageContents, S: secp256k1::Signing + secp256k1::Verification>(
1652 secp_ctx: &Secp256k1<S>, unblinded_path: &[PublicKey], destination: Destination, message: T,
1653 mut reply_path: Option<BlindedPath>, session_priv: &SecretKey
1654 ) -> Result<(Vec<(Payload<T>, [u8; 32])>, Vec<onion_utils::OnionKeys>), SendError> {
1655 let num_hops = unblinded_path.len() + destination.num_hops();
1656 let mut payloads = Vec::with_capacity(num_hops);
1657 let mut onion_packet_keys = Vec::with_capacity(num_hops);
1659 let (mut intro_node_id_blinding_pt, num_blinded_hops) = match &destination {
1660 Destination::Node(_) => (None, 0),
1661 Destination::BlindedPath(BlindedPath { introduction_node, blinding_point, blinded_hops }) => {
1662 let introduction_node_id = match introduction_node {
1663 IntroductionNode::NodeId(pubkey) => pubkey,
1664 IntroductionNode::DirectedShortChannelId(..) => {
1665 return Err(SendError::UnresolvedIntroductionNode);
1668 (Some((*introduction_node_id, *blinding_point)), blinded_hops.len())
1671 let num_unblinded_hops = num_hops - num_blinded_hops;
1673 let mut unblinded_path_idx = 0;
1674 let mut blinded_path_idx = 0;
1675 let mut prev_control_tlvs_ss = None;
1676 let mut final_control_tlvs = None;
1677 utils::construct_keys_callback(secp_ctx, unblinded_path.iter(), Some(destination), session_priv,
1678 |_, onion_packet_ss, ephemeral_pubkey, control_tlvs_ss, unblinded_pk_opt, enc_payload_opt| {
1679 if num_unblinded_hops != 0 && unblinded_path_idx < num_unblinded_hops {
1680 if let Some(ss) = prev_control_tlvs_ss.take() {
1681 payloads.push((Payload::Forward(ForwardControlTlvs::Unblinded(
1683 next_hop: NextMessageHop::NodeId(unblinded_pk_opt.unwrap()),
1684 next_blinding_override: None,
1688 prev_control_tlvs_ss = Some(control_tlvs_ss);
1689 unblinded_path_idx += 1;
1690 } else if let Some((intro_node_id, blinding_pt)) = intro_node_id_blinding_pt.take() {
1691 if let Some(control_tlvs_ss) = prev_control_tlvs_ss.take() {
1692 payloads.push((Payload::Forward(ForwardControlTlvs::Unblinded(ForwardTlvs {
1693 next_hop: NextMessageHop::NodeId(intro_node_id),
1694 next_blinding_override: Some(blinding_pt),
1695 })), control_tlvs_ss));
1698 if blinded_path_idx < num_blinded_hops.saturating_sub(1) && enc_payload_opt.is_some() {
1699 payloads.push((Payload::Forward(ForwardControlTlvs::Blinded(enc_payload_opt.unwrap())),
1701 blinded_path_idx += 1;
1702 } else if let Some(encrypted_payload) = enc_payload_opt {
1703 final_control_tlvs = Some(ReceiveControlTlvs::Blinded(encrypted_payload));
1704 prev_control_tlvs_ss = Some(control_tlvs_ss);
1707 let (rho, mu) = onion_utils::gen_rho_mu_from_shared_secret(onion_packet_ss.as_ref());
1708 onion_packet_keys.push(onion_utils::OnionKeys {
1710 shared_secret: onion_packet_ss,
1712 blinding_factor: [0; 32],
1718 ).map_err(|e| SendError::Secp256k1(e))?;
1720 if let Some(control_tlvs) = final_control_tlvs {
1721 payloads.push((Payload::Receive {
1723 reply_path: reply_path.take(),
1725 }, prev_control_tlvs_ss.unwrap()));
1727 payloads.push((Payload::Receive {
1728 control_tlvs: ReceiveControlTlvs::Unblinded(ReceiveTlvs { path_id: None, }),
1729 reply_path: reply_path.take(),
1731 }, prev_control_tlvs_ss.unwrap()));
1734 Ok((payloads, onion_packet_keys))
1737 /// Errors if the serialized payload size exceeds onion_message::BIG_PACKET_HOP_DATA_LEN
1738 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, ()> {
1740 // "`len` allows larger messages to be sent than the standard 1300 bytes allowed for an HTLC
1741 // onion, but this should be used sparingly as it is reduces anonymity set, hence the
1742 // recommendation that it either look like an HTLC onion, or if larger, be a fixed size."
1743 let payloads_ser_len = onion_utils::payloads_serialized_length(&payloads);
1744 let hop_data_len = if payloads_ser_len <= SMALL_PACKET_HOP_DATA_LEN {
1745 SMALL_PACKET_HOP_DATA_LEN
1746 } else if payloads_ser_len <= BIG_PACKET_HOP_DATA_LEN {
1747 BIG_PACKET_HOP_DATA_LEN
1748 } else { return Err(()) };
1750 onion_utils::construct_onion_message_packet::<_, _>(
1751 payloads, onion_keys, prng_seed, hop_data_len)