Introduce ResponseInstruction::WithReplyPath variant.
[rust-lightning] / lightning / src / onion_message / messenger.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
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
8 // licenses.
9
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.
12
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};
17
18 use crate::blinded_path::{BlindedPath, IntroductionNode, NextMessageHop, NodeIdLookUp};
19 use crate::blinded_path::message::{advance_path_by_one, ForwardNode, ForwardTlvs, ReceiveTlvs};
20 use crate::blinded_path::utils;
21 use crate::events::{Event, EventHandler, EventsProvider};
22 use crate::sign::{EntropySource, NodeSigner, Recipient};
23 use crate::ln::features::{InitFeatures, NodeFeatures};
24 use crate::ln::msgs::{self, OnionMessage, OnionMessageHandler, SocketAddress};
25 use crate::ln::onion_utils;
26 use crate::routing::gossip::{NetworkGraph, NodeId, ReadOnlyNetworkGraph};
27 use super::packet::OnionMessageContents;
28 use super::packet::ParsedOnionMessageContents;
29 use super::offers::OffersMessageHandler;
30 use super::packet::{BIG_PACKET_HOP_DATA_LEN, ForwardControlTlvs, Packet, Payload, ReceiveControlTlvs, SMALL_PACKET_HOP_DATA_LEN};
31 use crate::util::logger::{Logger, WithContext};
32 use crate::util::ser::Writeable;
33
34 use core::fmt;
35 use core::ops::Deref;
36 use crate::io;
37 use crate::sync::Mutex;
38 use crate::prelude::*;
39
40 #[cfg(not(c_bindings))]
41 use {
42         crate::sign::KeysManager,
43         crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager},
44         crate::ln::peer_handler::IgnoringMessageHandler,
45         crate::sync::Arc,
46 };
47
48 pub(super) const MAX_TIMER_TICKS: usize = 2;
49
50 /// A sender, receiver and forwarder of [`OnionMessage`]s.
51 ///
52 /// # Handling Messages
53 ///
54 /// `OnionMessenger` implements [`OnionMessageHandler`], making it responsible for either forwarding
55 /// messages to peers or delegating to the appropriate handler for the message type. Currently, the
56 /// available handlers are:
57 /// * [`OffersMessageHandler`], for responding to [`InvoiceRequest`]s and paying [`Bolt12Invoice`]s
58 /// * [`CustomOnionMessageHandler`], for handling user-defined message types
59 ///
60 /// # Sending Messages
61 ///
62 /// [`OnionMessage`]s are sent initially using [`OnionMessenger::send_onion_message`]. When handling
63 /// a message, the matched handler may return a response message which `OnionMessenger` will send
64 /// on its behalf.
65 ///
66 /// # Example
67 ///
68 /// ```
69 /// # extern crate bitcoin;
70 /// # use bitcoin::hashes::_export::_core::time::Duration;
71 /// # use bitcoin::hashes::hex::FromHex;
72 /// # use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey, self};
73 /// # use lightning::blinded_path::{BlindedPath, EmptyNodeIdLookUp};
74 /// # use lightning::blinded_path::message::ForwardNode;
75 /// # use lightning::sign::{EntropySource, KeysManager};
76 /// # use lightning::ln::peer_handler::IgnoringMessageHandler;
77 /// # use lightning::onion_message::messenger::{Destination, MessageRouter, OnionMessagePath, OnionMessenger};
78 /// # use lightning::onion_message::packet::OnionMessageContents;
79 /// # use lightning::util::logger::{Logger, Record};
80 /// # use lightning::util::ser::{Writeable, Writer};
81 /// # use lightning::io;
82 /// # use std::sync::Arc;
83 /// # struct FakeLogger;
84 /// # impl Logger for FakeLogger {
85 /// #     fn log(&self, record: Record) { println!("{:?}" , record); }
86 /// # }
87 /// # struct FakeMessageRouter {}
88 /// # impl MessageRouter for FakeMessageRouter {
89 /// #     fn find_path(&self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination) -> Result<OnionMessagePath, ()> {
90 /// #         let secp_ctx = Secp256k1::new();
91 /// #         let node_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
92 /// #         let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
93 /// #         let hop_node_id2 = hop_node_id1;
94 /// #         Ok(OnionMessagePath {
95 /// #             intermediate_nodes: vec![hop_node_id1, hop_node_id2],
96 /// #             destination,
97 /// #             first_node_addresses: None,
98 /// #         })
99 /// #     }
100 /// #     fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
101 /// #         &self, _recipient: PublicKey, _peers: Vec<ForwardNode>, _secp_ctx: &Secp256k1<T>
102 /// #     ) -> Result<Vec<BlindedPath>, ()> {
103 /// #         unreachable!()
104 /// #     }
105 /// # }
106 /// # let seed = [42u8; 32];
107 /// # let time = Duration::from_secs(123456);
108 /// # let keys_manager = KeysManager::new(&seed, time.as_secs(), time.subsec_nanos());
109 /// # let logger = Arc::new(FakeLogger {});
110 /// # let node_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
111 /// # let secp_ctx = Secp256k1::new();
112 /// # let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
113 /// # let (hop_node_id3, hop_node_id4) = (hop_node_id1, hop_node_id1);
114 /// # let destination_node_id = hop_node_id1;
115 /// # let node_id_lookup = EmptyNodeIdLookUp {};
116 /// # let message_router = Arc::new(FakeMessageRouter {});
117 /// # let custom_message_handler = IgnoringMessageHandler {};
118 /// # let offers_message_handler = IgnoringMessageHandler {};
119 /// // Create the onion messenger. This must use the same `keys_manager` as is passed to your
120 /// // ChannelManager.
121 /// let onion_messenger = OnionMessenger::new(
122 ///     &keys_manager, &keys_manager, logger, &node_id_lookup, message_router,
123 ///     &offers_message_handler, &custom_message_handler
124 /// );
125
126 /// # #[derive(Debug)]
127 /// # struct YourCustomMessage {}
128 /// impl Writeable for YourCustomMessage {
129 ///     fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
130 ///             # Ok(())
131 ///             // Write your custom onion message to `w`
132 ///     }
133 /// }
134 /// impl OnionMessageContents for YourCustomMessage {
135 ///     fn tlv_type(&self) -> u64 {
136 ///             # let your_custom_message_type = 42;
137 ///             your_custom_message_type
138 ///     }
139 ///     fn msg_type(&self) -> &'static str { "YourCustomMessageType" }
140 /// }
141 /// // Send a custom onion message to a node id.
142 /// let destination = Destination::Node(destination_node_id);
143 /// let reply_path = None;
144 /// # let message = YourCustomMessage {};
145 /// onion_messenger.send_onion_message(message, destination, reply_path);
146 ///
147 /// // Create a blinded path to yourself, for someone to send an onion message to.
148 /// # let your_node_id = hop_node_id1;
149 /// let hops = [
150 ///     ForwardNode { node_id: hop_node_id3, short_channel_id: None },
151 ///     ForwardNode { node_id: hop_node_id4, short_channel_id: None },
152 /// ];
153 /// let blinded_path = BlindedPath::new_for_message(&hops, your_node_id, &keys_manager, &secp_ctx).unwrap();
154 ///
155 /// // Send a custom onion message to a blinded path.
156 /// let destination = Destination::BlindedPath(blinded_path);
157 /// let reply_path = None;
158 /// # let message = YourCustomMessage {};
159 /// onion_messenger.send_onion_message(message, destination, reply_path);
160 /// ```
161 ///
162 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
163 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
164 pub struct OnionMessenger<ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, CMH: Deref>
165 where
166         ES::Target: EntropySource,
167         NS::Target: NodeSigner,
168         L::Target: Logger,
169         NL::Target: NodeIdLookUp,
170         MR::Target: MessageRouter,
171         OMH::Target: OffersMessageHandler,
172         CMH::Target: CustomOnionMessageHandler,
173 {
174         entropy_source: ES,
175         node_signer: NS,
176         logger: L,
177         message_recipients: Mutex<HashMap<PublicKey, OnionMessageRecipient>>,
178         secp_ctx: Secp256k1<secp256k1::All>,
179         node_id_lookup: NL,
180         message_router: MR,
181         offers_handler: OMH,
182         custom_handler: CMH,
183         intercept_messages_for_offline_peers: bool,
184         pending_events: Mutex<Vec<Event>>,
185 }
186
187 /// [`OnionMessage`]s buffered to be sent.
188 enum OnionMessageRecipient {
189         /// Messages for a node connected as a peer.
190         ConnectedPeer(VecDeque<OnionMessage>),
191
192         /// Messages for a node that is not yet connected, which are dropped after [`MAX_TIMER_TICKS`]
193         /// and tracked here.
194         PendingConnection(VecDeque<OnionMessage>, Option<Vec<SocketAddress>>, usize),
195 }
196
197 impl OnionMessageRecipient {
198         fn pending_connection(addresses: Vec<SocketAddress>) -> Self {
199                 Self::PendingConnection(VecDeque::new(), Some(addresses), 0)
200         }
201
202         fn pending_messages(&self) -> &VecDeque<OnionMessage> {
203                 match self {
204                         OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
205                         OnionMessageRecipient::PendingConnection(pending_messages, _, _) => pending_messages,
206                 }
207         }
208
209         fn enqueue_message(&mut self, message: OnionMessage) {
210                 let pending_messages = match self {
211                         OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
212                         OnionMessageRecipient::PendingConnection(pending_messages, _, _) => pending_messages,
213                 };
214
215                 pending_messages.push_back(message);
216         }
217
218         fn dequeue_message(&mut self) -> Option<OnionMessage> {
219                 let pending_messages = match self {
220                         OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
221                         OnionMessageRecipient::PendingConnection(pending_messages, _, _) => {
222                                 debug_assert!(false);
223                                 pending_messages
224                         },
225                 };
226
227                 pending_messages.pop_front()
228         }
229
230         #[cfg(test)]
231         fn release_pending_messages(&mut self) -> VecDeque<OnionMessage> {
232                 let pending_messages = match self {
233                         OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
234                         OnionMessageRecipient::PendingConnection(pending_messages, _, _) => pending_messages,
235                 };
236
237                 core::mem::take(pending_messages)
238         }
239
240         fn mark_connected(&mut self) {
241                 if let OnionMessageRecipient::PendingConnection(pending_messages, _, _) = self {
242                         let mut new_pending_messages = VecDeque::new();
243                         core::mem::swap(pending_messages, &mut new_pending_messages);
244                         *self = OnionMessageRecipient::ConnectedPeer(new_pending_messages);
245                 }
246         }
247
248         fn is_connected(&self) -> bool {
249                 match self {
250                         OnionMessageRecipient::ConnectedPeer(..) => true,
251                         OnionMessageRecipient::PendingConnection(..) => false,
252                 }
253         }
254 }
255
256
257 /// The `Responder` struct creates an appropriate [`ResponseInstruction`]
258 /// for responding to a message.
259 pub struct Responder {
260         /// The path along which a response can be sent.
261         reply_path: BlindedPath,
262         path_id: Option<[u8; 32]>
263 }
264
265 impl Responder {
266         /// Creates a new [`Responder`] instance with the provided reply path.
267         pub(super) fn new(reply_path: BlindedPath, path_id: Option<[u8; 32]>) -> Self {
268                 Responder {
269                         reply_path,
270                         path_id,
271                 }
272         }
273
274         /// Creates a [`ResponseInstruction::WithoutReplyPath`] for a given response.
275         ///
276         /// Use when the recipient doesn't need to send back a reply to us.
277         pub fn respond<T: OnionMessageContents>(self, response: T) -> ResponseInstruction<T> {
278                 ResponseInstruction::WithoutReplyPath(OnionMessageResponse {
279                         message: response,
280                         reply_path: self.reply_path,
281                         path_id: self.path_id,
282                 })
283         }
284
285         /// Creates a [`ResponseInstruction::WithReplyPath`] for a given response.
286         ///
287         /// Use when the recipient needs to send back a reply to us.
288         pub fn respond_with_reply_path<T: OnionMessageContents>(self, response: T) -> ResponseInstruction<T> {
289                 ResponseInstruction::WithReplyPath(OnionMessageResponse {
290                         message: response,
291                         reply_path: self.reply_path,
292                         path_id: self.path_id,
293                 })
294         }
295 }
296
297 /// This struct contains the information needed to reply to a received message.
298 pub struct OnionMessageResponse<T: OnionMessageContents> {
299         message: T,
300         reply_path: BlindedPath,
301         path_id: Option<[u8; 32]>,
302 }
303
304 /// `ResponseInstruction` represents instructions for responding to received messages.
305 pub enum ResponseInstruction<T: OnionMessageContents> {
306         /// Indicates that a response should be sent including a reply path for
307         /// the recipient to respond back.
308         WithReplyPath(OnionMessageResponse<T>),
309         /// Indicates that a response should be sent without including a reply path
310         /// for the recipient to respond back.
311         WithoutReplyPath(OnionMessageResponse<T>),
312         /// Indicates that there's no response to send back.
313         NoResponse,
314 }
315
316 /// An [`OnionMessage`] for [`OnionMessenger`] to send.
317 ///
318 /// These are obtained when released from [`OnionMessenger`]'s handlers after which they are
319 /// enqueued for sending.
320 #[cfg(not(c_bindings))]
321 pub struct PendingOnionMessage<T: OnionMessageContents> {
322         /// The message contents to send in an [`OnionMessage`].
323         pub contents: T,
324
325         /// The destination of the message.
326         pub destination: Destination,
327
328         /// A reply path to include in the [`OnionMessage`] for a response.
329         pub reply_path: Option<BlindedPath>,
330 }
331
332 #[cfg(c_bindings)]
333 /// An [`OnionMessage`] for [`OnionMessenger`] to send.
334 ///
335 /// These are obtained when released from [`OnionMessenger`]'s handlers after which they are
336 /// enqueued for sending.
337 pub type PendingOnionMessage<T> = (T, Destination, Option<BlindedPath>);
338
339 pub(crate) fn new_pending_onion_message<T: OnionMessageContents>(
340         contents: T, destination: Destination, reply_path: Option<BlindedPath>
341 ) -> PendingOnionMessage<T> {
342         #[cfg(not(c_bindings))]
343         return PendingOnionMessage { contents, destination, reply_path };
344         #[cfg(c_bindings)]
345         return (contents, destination, reply_path);
346 }
347
348 /// A trait defining behavior for routing an [`OnionMessage`].
349 pub trait MessageRouter {
350         /// Returns a route for sending an [`OnionMessage`] to the given [`Destination`].
351         fn find_path(
352                 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
353         ) -> Result<OnionMessagePath, ()>;
354
355         /// Creates [`BlindedPath`]s to the `recipient` node. The nodes in `peers` are assumed to be
356         /// direct peers with the `recipient`.
357         fn create_blinded_paths<
358                 T: secp256k1::Signing + secp256k1::Verification
359         >(
360                 &self, recipient: PublicKey, peers: Vec<ForwardNode>, secp_ctx: &Secp256k1<T>,
361         ) -> Result<Vec<BlindedPath>, ()>;
362 }
363
364 /// A [`MessageRouter`] that can only route to a directly connected [`Destination`].
365 pub struct DefaultMessageRouter<G: Deref<Target=NetworkGraph<L>>, L: Deref, ES: Deref>
366 where
367         L::Target: Logger,
368         ES::Target: EntropySource,
369 {
370         network_graph: G,
371         entropy_source: ES,
372 }
373
374 impl<G: Deref<Target=NetworkGraph<L>>, L: Deref, ES: Deref> DefaultMessageRouter<G, L, ES>
375 where
376         L::Target: Logger,
377         ES::Target: EntropySource,
378 {
379         /// Creates a [`DefaultMessageRouter`] using the given [`NetworkGraph`].
380         pub fn new(network_graph: G, entropy_source: ES) -> Self {
381                 Self { network_graph, entropy_source }
382         }
383 }
384
385 impl<G: Deref<Target=NetworkGraph<L>>, L: Deref, ES: Deref> MessageRouter for DefaultMessageRouter<G, L, ES>
386 where
387         L::Target: Logger,
388         ES::Target: EntropySource,
389 {
390         fn find_path(
391                 &self, sender: PublicKey, peers: Vec<PublicKey>, mut destination: Destination
392         ) -> Result<OnionMessagePath, ()> {
393                 let network_graph = self.network_graph.deref().read_only();
394                 destination.resolve(&network_graph);
395
396                 let first_node = match destination.first_node() {
397                         Some(first_node) => first_node,
398                         None => return Err(()),
399                 };
400
401                 if peers.contains(&first_node) || sender == first_node {
402                         Ok(OnionMessagePath {
403                                 intermediate_nodes: vec![], destination, first_node_addresses: None
404                         })
405                 } else {
406                         let node_announcement = network_graph
407                                 .node(&NodeId::from_pubkey(&first_node))
408                                 .and_then(|node_info| node_info.announcement_info.as_ref())
409                                 .and_then(|announcement_info| announcement_info.announcement_message.as_ref())
410                                 .map(|node_announcement| &node_announcement.contents);
411
412                         match node_announcement {
413                                 Some(node_announcement) if node_announcement.features.supports_onion_messages() => {
414                                         let first_node_addresses = Some(node_announcement.addresses.clone());
415                                         Ok(OnionMessagePath {
416                                                 intermediate_nodes: vec![], destination, first_node_addresses
417                                         })
418                                 },
419                                 _ => Err(()),
420                         }
421                 }
422         }
423
424         fn create_blinded_paths<
425                 T: secp256k1::Signing + secp256k1::Verification
426         >(
427                 &self, recipient: PublicKey, peers: Vec<ForwardNode>, secp_ctx: &Secp256k1<T>,
428         ) -> Result<Vec<BlindedPath>, ()> {
429                 // Limit the number of blinded paths that are computed.
430                 const MAX_PATHS: usize = 3;
431
432                 // Ensure peers have at least three channels so that it is more difficult to infer the
433                 // recipient's node_id.
434                 const MIN_PEER_CHANNELS: usize = 3;
435
436                 let network_graph = self.network_graph.deref().read_only();
437                 let is_recipient_announced =
438                         network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient));
439
440                 let mut peer_info = peers.into_iter()
441                         // Limit to peers with announced channels
442                         .filter_map(|peer|
443                                 network_graph
444                                         .node(&NodeId::from_pubkey(&peer.node_id))
445                                         .filter(|info| info.channels.len() >= MIN_PEER_CHANNELS)
446                                         .map(|info| (peer, info.is_tor_only(), info.channels.len()))
447                         )
448                         // Exclude Tor-only nodes when the recipient is announced.
449                         .filter(|(_, is_tor_only, _)| !(*is_tor_only && is_recipient_announced))
450                         .collect::<Vec<_>>();
451
452                 // Prefer using non-Tor nodes with the most channels as the introduction node.
453                 peer_info.sort_unstable_by(|(_, a_tor_only, a_channels), (_, b_tor_only, b_channels)| {
454                         a_tor_only.cmp(b_tor_only).then(a_channels.cmp(b_channels).reverse())
455                 });
456
457                 let paths = peer_info.into_iter()
458                         .map(|(peer, _, _)| {
459                                 BlindedPath::new_for_message(&[peer], recipient, &*self.entropy_source, secp_ctx)
460                         })
461                         .take(MAX_PATHS)
462                         .collect::<Result<Vec<_>, _>>();
463
464                 let mut paths = match paths {
465                         Ok(paths) if !paths.is_empty() => Ok(paths),
466                         _ => {
467                                 if is_recipient_announced {
468                                         BlindedPath::one_hop_for_message(recipient, &*self.entropy_source, secp_ctx)
469                                                 .map(|path| vec![path])
470                                 } else {
471                                         Err(())
472                                 }
473                         },
474                 }?;
475                 for path in &mut paths {
476                         path.use_compact_introduction_node(&network_graph);
477                 }
478
479                 Ok(paths)
480         }
481 }
482
483 /// A path for sending an [`OnionMessage`].
484 #[derive(Clone)]
485 pub struct OnionMessagePath {
486         /// Nodes on the path between the sender and the destination.
487         pub intermediate_nodes: Vec<PublicKey>,
488
489         /// The recipient of the message.
490         pub destination: Destination,
491
492         /// Addresses that may be used to connect to [`OnionMessagePath::first_node`].
493         ///
494         /// Only needs to be set if a connection to the node is required. [`OnionMessenger`] may use
495         /// this to initiate such a connection.
496         pub first_node_addresses: Option<Vec<SocketAddress>>,
497 }
498
499 impl OnionMessagePath {
500         /// Returns the first node in the path.
501         pub fn first_node(&self) -> Option<PublicKey> {
502                 self.intermediate_nodes
503                         .first()
504                         .copied()
505                         .or_else(|| self.destination.first_node())
506         }
507 }
508
509 /// The destination of an onion message.
510 #[derive(Clone, Hash, Debug, PartialEq, Eq)]
511 pub enum Destination {
512         /// We're sending this onion message to a node.
513         Node(PublicKey),
514         /// We're sending this onion message to a blinded path.
515         BlindedPath(BlindedPath),
516 }
517
518 impl Destination {
519         /// Attempts to resolve the [`IntroductionNode::DirectedShortChannelId`] of a
520         /// [`Destination::BlindedPath`] to a [`IntroductionNode::NodeId`], if applicable, using the
521         /// provided [`ReadOnlyNetworkGraph`].
522         pub fn resolve(&mut self, network_graph: &ReadOnlyNetworkGraph) {
523                 if let Destination::BlindedPath(path) = self {
524                         if let IntroductionNode::DirectedShortChannelId(..) = path.introduction_node {
525                                 if let Some(pubkey) = path
526                                         .public_introduction_node_id(network_graph)
527                                         .and_then(|node_id| node_id.as_pubkey().ok())
528                                 {
529                                         path.introduction_node = IntroductionNode::NodeId(pubkey);
530                                 }
531                         }
532                 }
533         }
534
535         pub(super) fn num_hops(&self) -> usize {
536                 match self {
537                         Destination::Node(_) => 1,
538                         Destination::BlindedPath(BlindedPath { blinded_hops, .. }) => blinded_hops.len(),
539                 }
540         }
541
542         fn first_node(&self) -> Option<PublicKey> {
543                 match self {
544                         Destination::Node(node_id) => Some(*node_id),
545                         Destination::BlindedPath(BlindedPath { introduction_node, .. }) => {
546                                 match introduction_node {
547                                         IntroductionNode::NodeId(pubkey) => Some(*pubkey),
548                                         IntroductionNode::DirectedShortChannelId(..) => None,
549                                 }
550                         },
551                 }
552         }
553 }
554
555 /// Result of successfully [sending an onion message].
556 ///
557 /// [sending an onion message]: OnionMessenger::send_onion_message
558 #[derive(Clone, Hash, Debug, PartialEq, Eq)]
559 pub enum SendSuccess {
560         /// The message was buffered and will be sent once it is processed by
561         /// [`OnionMessageHandler::next_onion_message_for_peer`].
562         Buffered,
563         /// The message was buffered and will be sent once the node is connected as a peer and it is
564         /// processed by [`OnionMessageHandler::next_onion_message_for_peer`].
565         BufferedAwaitingConnection(PublicKey),
566 }
567
568 /// Errors that may occur when [sending an onion message].
569 ///
570 /// [sending an onion message]: OnionMessenger::send_onion_message
571 #[derive(Clone, Hash, Debug, PartialEq, Eq)]
572 pub enum SendError {
573         /// Errored computing onion message packet keys.
574         Secp256k1(secp256k1::Error),
575         /// Because implementations such as Eclair will drop onion messages where the message packet
576         /// exceeds 32834 bytes, we refuse to send messages where the packet exceeds this size.
577         TooBigPacket,
578         /// The provided [`Destination`] was an invalid [`BlindedPath`] due to not having any blinded
579         /// hops.
580         TooFewBlindedHops,
581         /// The first hop is not a peer and doesn't have a known [`SocketAddress`].
582         InvalidFirstHop(PublicKey),
583         /// Indicates that a path could not be found by the [`MessageRouter`].
584         ///
585         /// This occurs when either:
586         /// - No path from the sender to the destination was found to send the onion message
587         /// - No reply path to the sender could be created when responding to an onion message
588         PathNotFound,
589         /// Onion message contents must have a TLV type >= 64.
590         InvalidMessage,
591         /// Our next-hop peer's buffer was full or our total outbound buffer was full.
592         BufferFull,
593         /// Failed to retrieve our node id from the provided [`NodeSigner`].
594         ///
595         /// [`NodeSigner`]: crate::sign::NodeSigner
596         GetNodeIdFailed,
597         /// The provided [`Destination`] has a blinded path with an unresolved introduction node. An
598         /// attempt to resolve it in the [`MessageRouter`] when finding an [`OnionMessagePath`] likely
599         /// failed.
600         UnresolvedIntroductionNode,
601         /// We attempted to send to a blinded path where we are the introduction node, and failed to
602         /// advance the blinded path to make the second hop the new introduction node. Either
603         /// [`NodeSigner::ecdh`] failed, we failed to tweak the current blinding point to get the
604         /// new blinding point, or we were attempting to send to ourselves.
605         BlindedPathAdvanceFailed,
606 }
607
608 /// Handler for custom onion messages. If you are using [`SimpleArcOnionMessenger`],
609 /// [`SimpleRefOnionMessenger`], or prefer to ignore inbound custom onion messages,
610 /// [`IgnoringMessageHandler`] must be provided to [`OnionMessenger::new`]. Otherwise, a custom
611 /// implementation of this trait must be provided, with [`CustomMessage`] specifying the supported
612 /// message types.
613 ///
614 /// See [`OnionMessenger`] for example usage.
615 ///
616 /// [`IgnoringMessageHandler`]: crate::ln::peer_handler::IgnoringMessageHandler
617 /// [`CustomMessage`]: Self::CustomMessage
618 pub trait CustomOnionMessageHandler {
619         /// The message known to the handler. To support multiple message types, you may want to make this
620         /// an enum with a variant for each supported message.
621         type CustomMessage: OnionMessageContents;
622
623         /// Called with the custom message that was received, returning a response to send, if any.
624         ///
625         /// The returned [`Self::CustomMessage`], if any, is enqueued to be sent by [`OnionMessenger`].
626         fn handle_custom_message(&self, message: Self::CustomMessage, responder: Option<Responder>) -> ResponseInstruction<Self::CustomMessage>;
627
628         /// Read a custom message of type `message_type` from `buffer`, returning `Ok(None)` if the
629         /// message type is unknown.
630         fn read_custom_message<R: io::Read>(&self, message_type: u64, buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError>;
631
632         /// Releases any [`Self::CustomMessage`]s that need to be sent.
633         ///
634         /// Typically, this is used for messages initiating a message flow rather than in response to
635         /// another message. The latter should use the return value of [`Self::handle_custom_message`].
636         #[cfg(not(c_bindings))]
637         fn release_pending_custom_messages(&self) -> Vec<PendingOnionMessage<Self::CustomMessage>>;
638
639         /// Releases any [`Self::CustomMessage`]s that need to be sent.
640         ///
641         /// Typically, this is used for messages initiating a message flow rather than in response to
642         /// another message. The latter should use the return value of [`Self::handle_custom_message`].
643         #[cfg(c_bindings)]
644         fn release_pending_custom_messages(&self) -> Vec<(Self::CustomMessage, Destination, Option<BlindedPath>)>;
645 }
646
647 /// A processed incoming onion message, containing either a Forward (another onion message)
648 /// or a Receive payload with decrypted contents.
649 #[derive(Clone, Debug)]
650 pub enum PeeledOnion<T: OnionMessageContents> {
651         /// Forwarded onion, with the next node id and a new onion
652         Forward(NextMessageHop, OnionMessage),
653         /// Received onion message, with decrypted contents, path_id, and reply path
654         Receive(ParsedOnionMessageContents<T>, Option<[u8; 32]>, Option<BlindedPath>)
655 }
656
657
658 /// Creates an [`OnionMessage`] with the given `contents` for sending to the destination of
659 /// `path`, first calling [`Destination::resolve`] on `path.destination` with the given
660 /// [`ReadOnlyNetworkGraph`].
661 ///
662 /// Returns the node id of the peer to send the message to, the message itself, and any addresses
663 /// needed to connect to the first node.
664 pub fn create_onion_message_resolving_destination<
665         ES: Deref, NS: Deref, NL: Deref, T: OnionMessageContents
666 >(
667         entropy_source: &ES, node_signer: &NS, node_id_lookup: &NL,
668         network_graph: &ReadOnlyNetworkGraph, secp_ctx: &Secp256k1<secp256k1::All>,
669         mut path: OnionMessagePath, contents: T, reply_path: Option<BlindedPath>,
670 ) -> Result<(PublicKey, OnionMessage, Option<Vec<SocketAddress>>), SendError>
671 where
672         ES::Target: EntropySource,
673         NS::Target: NodeSigner,
674         NL::Target: NodeIdLookUp,
675 {
676         path.destination.resolve(network_graph);
677         create_onion_message(
678                 entropy_source, node_signer, node_id_lookup, secp_ctx, path, contents, reply_path,
679         )
680 }
681
682 /// Creates an [`OnionMessage`] with the given `contents` for sending to the destination of
683 /// `path`.
684 ///
685 /// Returns the node id of the peer to send the message to, the message itself, and any addresses
686 /// needed to connect to the first node.
687 ///
688 /// Returns [`SendError::UnresolvedIntroductionNode`] if:
689 /// - `destination` contains a blinded path with an [`IntroductionNode::DirectedShortChannelId`],
690 /// - unless it can be resolved by [`NodeIdLookUp::next_node_id`].
691 /// Use [`create_onion_message_resolving_destination`] instead to resolve the introduction node
692 /// first with a [`ReadOnlyNetworkGraph`].
693 pub fn create_onion_message<ES: Deref, NS: Deref, NL: Deref, T: OnionMessageContents>(
694         entropy_source: &ES, node_signer: &NS, node_id_lookup: &NL,
695         secp_ctx: &Secp256k1<secp256k1::All>, path: OnionMessagePath, contents: T,
696         reply_path: Option<BlindedPath>,
697 ) -> Result<(PublicKey, OnionMessage, Option<Vec<SocketAddress>>), SendError>
698 where
699         ES::Target: EntropySource,
700         NS::Target: NodeSigner,
701         NL::Target: NodeIdLookUp,
702 {
703         let OnionMessagePath { intermediate_nodes, mut destination, first_node_addresses } = path;
704         if let Destination::BlindedPath(BlindedPath { ref blinded_hops, .. }) = destination {
705                 if blinded_hops.is_empty() {
706                         return Err(SendError::TooFewBlindedHops);
707                 }
708         }
709
710         if contents.tlv_type() < 64 { return Err(SendError::InvalidMessage) }
711
712         // If we are sending straight to a blinded path and we are the introduction node, we need to
713         // advance the blinded path by 1 hop so the second hop is the new introduction node.
714         if intermediate_nodes.len() == 0 {
715                 if let Destination::BlindedPath(ref mut blinded_path) = destination {
716                         let our_node_id = node_signer.get_node_id(Recipient::Node)
717                                 .map_err(|()| SendError::GetNodeIdFailed)?;
718                         let introduction_node_id = match blinded_path.introduction_node {
719                                 IntroductionNode::NodeId(pubkey) => pubkey,
720                                 IntroductionNode::DirectedShortChannelId(direction, scid) => {
721                                         match node_id_lookup.next_node_id(scid) {
722                                                 Some(next_node_id) => *direction.select_pubkey(&our_node_id, &next_node_id),
723                                                 None => return Err(SendError::UnresolvedIntroductionNode),
724                                         }
725                                 },
726                         };
727                         if introduction_node_id == our_node_id {
728                                 advance_path_by_one(blinded_path, node_signer, node_id_lookup, &secp_ctx)
729                                         .map_err(|()| SendError::BlindedPathAdvanceFailed)?;
730                         }
731                 }
732         }
733
734         let blinding_secret_bytes = entropy_source.get_secure_random_bytes();
735         let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
736         let (first_node_id, blinding_point) = if let Some(first_node_id) = intermediate_nodes.first() {
737                 (*first_node_id, PublicKey::from_secret_key(&secp_ctx, &blinding_secret))
738         } else {
739                 match &destination {
740                         Destination::Node(pk) => (*pk, PublicKey::from_secret_key(&secp_ctx, &blinding_secret)),
741                         Destination::BlindedPath(BlindedPath { introduction_node, blinding_point, .. }) => {
742                                 match introduction_node {
743                                         IntroductionNode::NodeId(pubkey) => (*pubkey, *blinding_point),
744                                         IntroductionNode::DirectedShortChannelId(..) => {
745                                                 return Err(SendError::UnresolvedIntroductionNode);
746                                         },
747                                 }
748                         }
749                 }
750         };
751         let (packet_payloads, packet_keys) = packet_payloads_and_keys(
752                 &secp_ctx, &intermediate_nodes, destination, contents, reply_path, &blinding_secret
753         )?;
754
755         let prng_seed = entropy_source.get_secure_random_bytes();
756         let onion_routing_packet = construct_onion_message_packet(
757                 packet_payloads, packet_keys, prng_seed).map_err(|()| SendError::TooBigPacket)?;
758
759         let message = OnionMessage { blinding_point, onion_routing_packet };
760         Ok((first_node_id, message, first_node_addresses))
761 }
762
763 /// Decode one layer of an incoming [`OnionMessage`].
764 ///
765 /// Returns either the next layer of the onion for forwarding or the decrypted content for the
766 /// receiver.
767 pub fn peel_onion_message<NS: Deref, L: Deref, CMH: Deref>(
768         msg: &OnionMessage, secp_ctx: &Secp256k1<secp256k1::All>, node_signer: NS, logger: L,
769         custom_handler: CMH,
770 ) -> Result<PeeledOnion<<<CMH>::Target as CustomOnionMessageHandler>::CustomMessage>, ()>
771 where
772         NS::Target: NodeSigner,
773         L::Target: Logger,
774         CMH::Target: CustomOnionMessageHandler,
775 {
776         let control_tlvs_ss = match node_signer.ecdh(Recipient::Node, &msg.blinding_point, None) {
777                 Ok(ss) => ss,
778                 Err(e) =>  {
779                         log_error!(logger, "Failed to retrieve node secret: {:?}", e);
780                         return Err(());
781                 }
782         };
783         let onion_decode_ss = {
784                 let blinding_factor = {
785                         let mut hmac = HmacEngine::<Sha256>::new(b"blinded_node_id");
786                         hmac.input(control_tlvs_ss.as_ref());
787                         Hmac::from_engine(hmac).to_byte_array()
788                 };
789                 match node_signer.ecdh(Recipient::Node, &msg.onion_routing_packet.public_key,
790                         Some(&Scalar::from_be_bytes(blinding_factor).unwrap()))
791                 {
792                         Ok(ss) => ss.secret_bytes(),
793                         Err(()) => {
794                                 log_trace!(logger, "Failed to compute onion packet shared secret");
795                                 return Err(());
796                         }
797                 }
798         };
799         match onion_utils::decode_next_untagged_hop(
800                 onion_decode_ss, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac,
801                 (control_tlvs_ss, custom_handler.deref(), logger.deref())
802         ) {
803                 Ok((Payload::Receive::<ParsedOnionMessageContents<<<CMH as Deref>::Target as CustomOnionMessageHandler>::CustomMessage>> {
804                         message, control_tlvs: ReceiveControlTlvs::Unblinded(ReceiveTlvs { path_id }), reply_path,
805                 }, None)) => {
806                         Ok(PeeledOnion::Receive(message, path_id, reply_path))
807                 },
808                 Ok((Payload::Forward(ForwardControlTlvs::Unblinded(ForwardTlvs {
809                         next_hop, next_blinding_override
810                 })), Some((next_hop_hmac, new_packet_bytes)))) => {
811                         // TODO: we need to check whether `next_hop` is our node, in which case this is a dummy
812                         // blinded hop and this onion message is destined for us. In this situation, we should keep
813                         // unwrapping the onion layers to get to the final payload. Since we don't have the option
814                         // of creating blinded paths with dummy hops currently, we should be ok to not handle this
815                         // for now.
816                         let new_pubkey = match onion_utils::next_hop_pubkey(&secp_ctx, msg.onion_routing_packet.public_key, &onion_decode_ss) {
817                                 Ok(pk) => pk,
818                                 Err(e) => {
819                                         log_trace!(logger, "Failed to compute next hop packet pubkey: {}", e);
820                                         return Err(())
821                                 }
822                         };
823                         let outgoing_packet = Packet {
824                                 version: 0,
825                                 public_key: new_pubkey,
826                                 hop_data: new_packet_bytes,
827                                 hmac: next_hop_hmac,
828                         };
829                         let onion_message = OnionMessage {
830                                 blinding_point: match next_blinding_override {
831                                         Some(blinding_point) => blinding_point,
832                                         None => {
833                                                 match onion_utils::next_hop_pubkey(
834                                                         &secp_ctx, msg.blinding_point, control_tlvs_ss.as_ref()
835                                                 ) {
836                                                         Ok(bp) => bp,
837                                                         Err(e) => {
838                                                                 log_trace!(logger, "Failed to compute next blinding point: {}", e);
839                                                                 return Err(())
840                                                         }
841                                                 }
842                                         }
843                                 },
844                                 onion_routing_packet: outgoing_packet,
845                         };
846
847                         Ok(PeeledOnion::Forward(next_hop, onion_message))
848                 },
849                 Err(e) => {
850                         log_trace!(logger, "Errored decoding onion message packet: {:?}", e);
851                         Err(())
852                 },
853                 _ => {
854                         log_trace!(logger, "Received bogus onion message packet, either the sender encoded a final hop as a forwarding hop or vice versa");
855                         Err(())
856                 },
857         }
858 }
859
860 impl<ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, CMH: Deref>
861 OnionMessenger<ES, NS, L, NL, MR, OMH, CMH>
862 where
863         ES::Target: EntropySource,
864         NS::Target: NodeSigner,
865         L::Target: Logger,
866         NL::Target: NodeIdLookUp,
867         MR::Target: MessageRouter,
868         OMH::Target: OffersMessageHandler,
869         CMH::Target: CustomOnionMessageHandler,
870 {
871         /// Constructs a new `OnionMessenger` to send, forward, and delegate received onion messages to
872         /// their respective handlers.
873         pub fn new(
874                 entropy_source: ES, node_signer: NS, logger: L, node_id_lookup: NL, message_router: MR,
875                 offers_handler: OMH, custom_handler: CMH
876         ) -> Self {
877                 Self::new_inner(
878                         entropy_source, node_signer, logger, node_id_lookup, message_router,
879                         offers_handler, custom_handler, false
880                 )
881         }
882
883         /// Similar to [`Self::new`], but rather than dropping onion messages that are
884         /// intended to be forwarded to offline peers, we will intercept them for
885         /// later forwarding.
886         ///
887         /// Interception flow:
888         /// 1. If an onion message for an offline peer is received, `OnionMessenger` will
889         ///    generate an [`Event::OnionMessageIntercepted`]. Event handlers can
890         ///    then choose to persist this onion message for later forwarding, or drop
891         ///    it.
892         /// 2. When the offline peer later comes back online, `OnionMessenger` will
893         ///    generate an [`Event::OnionMessagePeerConnected`]. Event handlers will
894         ///    then fetch all previously intercepted onion messages for this peer.
895         /// 3. Once the stored onion messages are fetched, they can finally be
896         ///    forwarded to the now-online peer via [`Self::forward_onion_message`].
897         ///
898         /// # Note
899         ///
900         /// LDK will not rate limit how many [`Event::OnionMessageIntercepted`]s
901         /// are generated, so it is the caller's responsibility to limit how many
902         /// onion messages are persisted and only persist onion messages for relevant
903         /// peers.
904         pub fn new_with_offline_peer_interception(
905                 entropy_source: ES, node_signer: NS, logger: L, node_id_lookup: NL,
906                 message_router: MR, offers_handler: OMH, custom_handler: CMH
907         ) -> Self {
908                 Self::new_inner(
909                         entropy_source, node_signer, logger, node_id_lookup, message_router,
910                         offers_handler, custom_handler, true
911                 )
912         }
913
914         fn new_inner(
915                 entropy_source: ES, node_signer: NS, logger: L, node_id_lookup: NL,
916                 message_router: MR, offers_handler: OMH, custom_handler: CMH,
917                 intercept_messages_for_offline_peers: bool
918         ) -> Self {
919                 let mut secp_ctx = Secp256k1::new();
920                 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
921                 OnionMessenger {
922                         entropy_source,
923                         node_signer,
924                         message_recipients: Mutex::new(new_hash_map()),
925                         secp_ctx,
926                         logger,
927                         node_id_lookup,
928                         message_router,
929                         offers_handler,
930                         custom_handler,
931                         intercept_messages_for_offline_peers,
932                         pending_events: Mutex::new(Vec::new()),
933                 }
934         }
935
936         #[cfg(test)]
937         pub(crate) fn set_offers_handler(&mut self, offers_handler: OMH) {
938                 self.offers_handler = offers_handler;
939         }
940
941         /// Sends an [`OnionMessage`] with the given `contents` to `destination`.
942         ///
943         /// See [`OnionMessenger`] for example usage.
944         pub fn send_onion_message<T: OnionMessageContents>(
945                 &self, contents: T, destination: Destination, reply_path: Option<BlindedPath>
946         ) -> Result<SendSuccess, SendError> {
947                 self.find_path_and_enqueue_onion_message(
948                         contents, destination, reply_path, format_args!("")
949                 )
950         }
951
952         fn find_path_and_enqueue_onion_message<T: OnionMessageContents>(
953                 &self, contents: T, destination: Destination, reply_path: Option<BlindedPath>,
954                 log_suffix: fmt::Arguments
955         ) -> Result<SendSuccess, SendError> {
956                 let mut logger = WithContext::from(&self.logger, None, None, None);
957                 let result = self.find_path(destination).and_then(|path| {
958                         let first_hop = path.intermediate_nodes.get(0).map(|p| *p);
959                         logger = WithContext::from(&self.logger, first_hop, None, None);
960                         self.enqueue_onion_message(path, contents, reply_path, log_suffix)
961                 });
962
963                 match result.as_ref() {
964                         Err(SendError::GetNodeIdFailed) => {
965                                 log_warn!(logger, "Unable to retrieve node id {}", log_suffix);
966                         },
967                         Err(SendError::PathNotFound) => {
968                                 log_trace!(logger, "Failed to find path {}", log_suffix);
969                         },
970                         Err(e) => {
971                                 log_trace!(logger, "Failed sending onion message {}: {:?}", log_suffix, e);
972                         },
973                         Ok(SendSuccess::Buffered) => {
974                                 log_trace!(logger, "Buffered onion message {}", log_suffix);
975                         },
976                         Ok(SendSuccess::BufferedAwaitingConnection(node_id)) => {
977                                 log_trace!(
978                                         logger,
979                                         "Buffered onion message waiting on peer connection {}: {}",
980                                         log_suffix, node_id
981                                 );
982                         },
983                 }
984
985                 result
986         }
987
988         fn find_path(&self, destination: Destination) -> Result<OnionMessagePath, SendError> {
989                 let sender = self.node_signer
990                         .get_node_id(Recipient::Node)
991                         .map_err(|_| SendError::GetNodeIdFailed)?;
992
993                 let peers = self.message_recipients.lock().unwrap()
994                         .iter()
995                         .filter(|(_, recipient)| matches!(recipient, OnionMessageRecipient::ConnectedPeer(_)))
996                         .map(|(node_id, _)| *node_id)
997                         .collect();
998
999                 self.message_router
1000                         .find_path(sender, peers, destination)
1001                         .map_err(|_| SendError::PathNotFound)
1002         }
1003
1004         fn create_blinded_path(&self) -> Result<BlindedPath, SendError> {
1005                 let recipient = self.node_signer
1006                         .get_node_id(Recipient::Node)
1007                         .map_err(|_| SendError::GetNodeIdFailed)?;
1008                 let secp_ctx = &self.secp_ctx;
1009
1010                 let peers = self.message_recipients.lock().unwrap()
1011                         .iter()
1012                         .filter(|(_, peer)| matches!(peer, OnionMessageRecipient::ConnectedPeer(_)))
1013                         .map(|(node_id, _ )| ForwardNode {
1014                                 node_id: *node_id,
1015                                 short_channel_id: None,
1016                         })
1017                         .collect::<Vec<_>>();
1018
1019                 self.message_router
1020                         .create_blinded_paths(recipient, peers, secp_ctx)
1021                         .and_then(|paths| paths.into_iter().next().ok_or(()))
1022                         .map_err(|_| SendError::PathNotFound)
1023         }
1024
1025         fn enqueue_onion_message<T: OnionMessageContents>(
1026                 &self, path: OnionMessagePath, contents: T, reply_path: Option<BlindedPath>,
1027                 log_suffix: fmt::Arguments
1028         ) -> Result<SendSuccess, SendError> {
1029                 log_trace!(self.logger, "Constructing onion message {}: {:?}", log_suffix, contents);
1030
1031                 let (first_node_id, onion_message, addresses) = create_onion_message(
1032                         &self.entropy_source, &self.node_signer, &self.node_id_lookup, &self.secp_ctx, path,
1033                         contents, reply_path,
1034                 )?;
1035
1036                 let mut message_recipients = self.message_recipients.lock().unwrap();
1037                 if outbound_buffer_full(&first_node_id, &message_recipients) {
1038                         return Err(SendError::BufferFull);
1039                 }
1040
1041                 match message_recipients.entry(first_node_id) {
1042                         hash_map::Entry::Vacant(e) => match addresses {
1043                                 None => Err(SendError::InvalidFirstHop(first_node_id)),
1044                                 Some(addresses) => {
1045                                         e.insert(OnionMessageRecipient::pending_connection(addresses))
1046                                                 .enqueue_message(onion_message);
1047                                         Ok(SendSuccess::BufferedAwaitingConnection(first_node_id))
1048                                 },
1049                         },
1050                         hash_map::Entry::Occupied(mut e) => {
1051                                 e.get_mut().enqueue_message(onion_message);
1052                                 if e.get().is_connected() {
1053                                         Ok(SendSuccess::Buffered)
1054                                 } else {
1055                                         Ok(SendSuccess::BufferedAwaitingConnection(first_node_id))
1056                                 }
1057                         },
1058                 }
1059         }
1060
1061         /// Forwards an [`OnionMessage`] to `peer_node_id`. Useful if we initialized
1062         /// the [`OnionMessenger`] with [`Self::new_with_offline_peer_interception`]
1063         /// and want to forward a previously intercepted onion message to a peer that
1064         /// has just come online.
1065         pub fn forward_onion_message(
1066                 &self, message: OnionMessage, peer_node_id: &PublicKey
1067         ) -> Result<(), SendError> {
1068                 let mut message_recipients = self.message_recipients.lock().unwrap();
1069                 if outbound_buffer_full(&peer_node_id, &message_recipients) {
1070                         return Err(SendError::BufferFull);
1071                 }
1072
1073                 match message_recipients.entry(*peer_node_id) {
1074                         hash_map::Entry::Occupied(mut e) if e.get().is_connected() => {
1075                                 e.get_mut().enqueue_message(message);
1076                                 Ok(())
1077                         },
1078                         _ => Err(SendError::InvalidFirstHop(*peer_node_id))
1079                 }
1080         }
1081
1082         #[cfg(any(test, feature = "_test_utils"))]
1083         pub fn send_onion_message_using_path<T: OnionMessageContents>(
1084                 &self, path: OnionMessagePath, contents: T, reply_path: Option<BlindedPath>
1085         ) -> Result<SendSuccess, SendError> {
1086                 self.enqueue_onion_message(path, contents, reply_path, format_args!(""))
1087         }
1088
1089         pub(crate) fn peel_onion_message(
1090                 &self, msg: &OnionMessage
1091         ) -> Result<PeeledOnion<<<CMH>::Target as CustomOnionMessageHandler>::CustomMessage>, ()> {
1092                 peel_onion_message(
1093                         msg, &self.secp_ctx, &*self.node_signer, &*self.logger, &*self.custom_handler
1094                 )
1095         }
1096
1097         /// Handles the response to an [`OnionMessage`] based on its [`ResponseInstruction`],
1098         /// enqueueing any response for sending.
1099         ///
1100         /// This function is useful for asynchronous handling of [`OnionMessage`]s.
1101         /// Handlers have the option to return [`ResponseInstruction::NoResponse`], indicating that
1102         /// no immediate response should be sent. Then, they can transfer the associated [`Responder`]
1103         /// to another task responsible for generating the response asynchronously. Subsequently, when
1104         /// the response is prepared and ready for sending, that task can invoke this method to enqueue
1105         /// the response for delivery.
1106         pub fn handle_onion_message_response<T: OnionMessageContents>(
1107                 &self, response: ResponseInstruction<T>
1108         ) -> Result<Option<SendSuccess>, SendError> {
1109                 let (response, create_reply_path) = match response {
1110                         ResponseInstruction::WithReplyPath(response) => (response, true),
1111                         ResponseInstruction::WithoutReplyPath(response) => (response, false),
1112                         ResponseInstruction::NoResponse => return Ok(None),
1113                 };
1114
1115                 let message_type = response.message.msg_type();
1116                 let reply_path = if create_reply_path {
1117                         match self.create_blinded_path() {
1118                                 Ok(reply_path) => Some(reply_path),
1119                                 Err(err) => {
1120                                         log_trace!(
1121                                                 self.logger,
1122                                                 "Failed to create reply path when responding with {} to an onion message \
1123                                                 with path_id {:02x?}: {:?}",
1124                                                 message_type, response.path_id, err
1125                                         );
1126                                         return Err(err);
1127                                 }
1128                         }
1129                 } else { None };
1130
1131                 self.find_path_and_enqueue_onion_message(
1132                         response.message, Destination::BlindedPath(response.reply_path), reply_path,
1133                         format_args!(
1134                                 "when responding with {} to an onion message with path_id {:02x?}",
1135                                 message_type,
1136                                 response.path_id
1137                         )
1138                 ).map(|result| Some(result))
1139         }
1140
1141         #[cfg(test)]
1142         pub(super) fn release_pending_msgs(&self) -> HashMap<PublicKey, VecDeque<OnionMessage>> {
1143                 let mut message_recipients = self.message_recipients.lock().unwrap();
1144                 let mut msgs = new_hash_map();
1145                 // We don't want to disconnect the peers by removing them entirely from the original map, so we
1146                 // release the pending message buffers individually.
1147                 for (node_id, recipient) in &mut *message_recipients {
1148                         msgs.insert(*node_id, recipient.release_pending_messages());
1149                 }
1150                 msgs
1151         }
1152
1153         fn enqueue_event(&self, event: Event) {
1154                 const MAX_EVENTS_BUFFER_SIZE: usize = (1 << 10) * 256;
1155                 let mut pending_events = self.pending_events.lock().unwrap();
1156                 let total_buffered_bytes: usize = pending_events
1157                         .iter()
1158                         .map(|ev| ev.serialized_length())
1159                         .sum();
1160                 if total_buffered_bytes >= MAX_EVENTS_BUFFER_SIZE {
1161                         log_trace!(self.logger, "Dropping event {:?}: buffer full", event);
1162                         return
1163                 }
1164                 pending_events.push(event);
1165         }
1166 }
1167
1168 fn outbound_buffer_full(peer_node_id: &PublicKey, buffer: &HashMap<PublicKey, OnionMessageRecipient>) -> bool {
1169         const MAX_TOTAL_BUFFER_SIZE: usize = (1 << 20) * 128;
1170         const MAX_PER_PEER_BUFFER_SIZE: usize = (1 << 10) * 256;
1171         let mut total_buffered_bytes = 0;
1172         let mut peer_buffered_bytes = 0;
1173         for (pk, peer_buf) in buffer {
1174                 for om in peer_buf.pending_messages() {
1175                         let om_len = om.serialized_length();
1176                         if pk == peer_node_id {
1177                                 peer_buffered_bytes += om_len;
1178                         }
1179                         total_buffered_bytes += om_len;
1180
1181                         if total_buffered_bytes >= MAX_TOTAL_BUFFER_SIZE ||
1182                                 peer_buffered_bytes >= MAX_PER_PEER_BUFFER_SIZE
1183                         {
1184                                 return true
1185                         }
1186                 }
1187         }
1188         false
1189 }
1190
1191 impl<ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, CMH: Deref> EventsProvider
1192 for OnionMessenger<ES, NS, L, NL, MR, OMH, CMH>
1193 where
1194         ES::Target: EntropySource,
1195         NS::Target: NodeSigner,
1196         L::Target: Logger,
1197         NL::Target: NodeIdLookUp,
1198         MR::Target: MessageRouter,
1199         OMH::Target: OffersMessageHandler,
1200         CMH::Target: CustomOnionMessageHandler,
1201 {
1202         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
1203                 for (node_id, recipient) in self.message_recipients.lock().unwrap().iter_mut() {
1204                         if let OnionMessageRecipient::PendingConnection(_, addresses, _) = recipient {
1205                                 if let Some(addresses) = addresses.take() {
1206                                         handler.handle_event(Event::ConnectionNeeded { node_id: *node_id, addresses });
1207                                 }
1208                         }
1209                 }
1210                 let mut events = Vec::new();
1211                 core::mem::swap(&mut *self.pending_events.lock().unwrap(), &mut events);
1212                 for ev in events {
1213                         handler.handle_event(ev);
1214                 }
1215         }
1216 }
1217
1218 impl<ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, CMH: Deref> OnionMessageHandler
1219 for OnionMessenger<ES, NS, L, NL, MR, OMH, CMH>
1220 where
1221         ES::Target: EntropySource,
1222         NS::Target: NodeSigner,
1223         L::Target: Logger,
1224         NL::Target: NodeIdLookUp,
1225         MR::Target: MessageRouter,
1226         OMH::Target: OffersMessageHandler,
1227         CMH::Target: CustomOnionMessageHandler,
1228 {
1229         fn handle_onion_message(&self, peer_node_id: &PublicKey, msg: &OnionMessage) {
1230                 let logger = WithContext::from(&self.logger, Some(*peer_node_id), None, None);
1231                 match self.peel_onion_message(msg) {
1232                         Ok(PeeledOnion::Receive(message, path_id, reply_path)) => {
1233                                 log_trace!(
1234                                         logger,
1235                                         "Received an onion message with path_id {:02x?} and {} reply_path: {:?}",
1236                                         path_id, if reply_path.is_some() { "a" } else { "no" }, message);
1237
1238                                 match message {
1239                                         ParsedOnionMessageContents::Offers(msg) => {
1240                                                 let responder = reply_path.map(
1241                                                         |reply_path| Responder::new(reply_path, path_id)
1242                                                 );
1243                                                 let response_instructions = self.offers_handler.handle_message(msg, responder);
1244                                                 let _ = self.handle_onion_message_response(response_instructions);
1245                                         },
1246                                         ParsedOnionMessageContents::Custom(msg) => {
1247                                                 let responder = reply_path.map(
1248                                                         |reply_path| Responder::new(reply_path, path_id)
1249                                                 );
1250                                                 let response_instructions = self.custom_handler.handle_custom_message(msg, responder);
1251                                                 let _ = self.handle_onion_message_response(response_instructions);
1252                                         },
1253                                 }
1254                         },
1255                         Ok(PeeledOnion::Forward(next_hop, onion_message)) => {
1256                                 let next_node_id = match next_hop {
1257                                         NextMessageHop::NodeId(pubkey) => pubkey,
1258                                         NextMessageHop::ShortChannelId(scid) => match self.node_id_lookup.next_node_id(scid) {
1259                                                 Some(pubkey) => pubkey,
1260                                                 None => {
1261                                                         log_trace!(self.logger, "Dropping forwarded onion messager: unable to resolve next hop using SCID {}", scid);
1262                                                         return
1263                                                 },
1264                                         },
1265                                 };
1266
1267                                 let mut message_recipients = self.message_recipients.lock().unwrap();
1268                                 if outbound_buffer_full(&next_node_id, &message_recipients) {
1269                                         log_trace!(
1270                                                 logger,
1271                                                 "Dropping forwarded onion message to peer {}: outbound buffer full",
1272                                                 next_node_id);
1273                                         return
1274                                 }
1275
1276                                 #[cfg(fuzzing)]
1277                                 message_recipients
1278                                         .entry(next_node_id)
1279                                         .or_insert_with(|| OnionMessageRecipient::ConnectedPeer(VecDeque::new()));
1280
1281                                 match message_recipients.entry(next_node_id) {
1282                                         hash_map::Entry::Occupied(mut e) if matches!(
1283                                                 e.get(), OnionMessageRecipient::ConnectedPeer(..)
1284                                         ) => {
1285                                                 e.get_mut().enqueue_message(onion_message);
1286                                                 log_trace!(logger, "Forwarding an onion message to peer {}", next_node_id);
1287                                         },
1288                                         _ if self.intercept_messages_for_offline_peers => {
1289                                                 self.enqueue_event(
1290                                                         Event::OnionMessageIntercepted {
1291                                                                 peer_node_id: next_node_id, message: onion_message
1292                                                         }
1293                                                 );
1294                                         },
1295                                         _ => {
1296                                                 log_trace!(
1297                                                         logger,
1298                                                         "Dropping forwarded onion message to disconnected peer {}",
1299                                                         next_node_id);
1300                                                 return
1301                                         },
1302                                 }
1303                         },
1304                         Err(e) => {
1305                                 log_error!(logger, "Failed to process onion message {:?}", e);
1306                         }
1307                 }
1308         }
1309
1310         fn peer_connected(&self, their_node_id: &PublicKey, init: &msgs::Init, _inbound: bool) -> Result<(), ()> {
1311                 if init.features.supports_onion_messages() {
1312                         self.message_recipients.lock().unwrap()
1313                                 .entry(*their_node_id)
1314                                 .or_insert_with(|| OnionMessageRecipient::ConnectedPeer(VecDeque::new()))
1315                                 .mark_connected();
1316                         if self.intercept_messages_for_offline_peers {
1317                                 self.enqueue_event(
1318                                         Event::OnionMessagePeerConnected { peer_node_id: *their_node_id }
1319                                 );
1320                         }
1321                 } else {
1322                         self.message_recipients.lock().unwrap().remove(their_node_id);
1323                 }
1324
1325                 Ok(())
1326         }
1327
1328         fn peer_disconnected(&self, their_node_id: &PublicKey) {
1329                 match self.message_recipients.lock().unwrap().remove(their_node_id) {
1330                         Some(OnionMessageRecipient::ConnectedPeer(..)) => {},
1331                         Some(_) => debug_assert!(false),
1332                         None => {},
1333                 }
1334         }
1335
1336         fn timer_tick_occurred(&self) {
1337                 let mut message_recipients = self.message_recipients.lock().unwrap();
1338
1339                 // Drop any pending recipients since the last call to avoid retaining buffered messages for
1340                 // too long.
1341                 message_recipients.retain(|_, recipient| match recipient {
1342                         OnionMessageRecipient::PendingConnection(_, None, ticks) => *ticks < MAX_TIMER_TICKS,
1343                         OnionMessageRecipient::PendingConnection(_, Some(_), _) => true,
1344                         _ => true,
1345                 });
1346
1347                 // Increment a timer tick for pending recipients so that their buffered messages are dropped
1348                 // at MAX_TIMER_TICKS.
1349                 for recipient in message_recipients.values_mut() {
1350                         if let OnionMessageRecipient::PendingConnection(_, None, ticks) = recipient {
1351                                 *ticks += 1;
1352                         }
1353                 }
1354         }
1355
1356         fn provided_node_features(&self) -> NodeFeatures {
1357                 let mut features = NodeFeatures::empty();
1358                 features.set_onion_messages_optional();
1359                 features
1360         }
1361
1362         fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
1363                 let mut features = InitFeatures::empty();
1364                 features.set_onion_messages_optional();
1365                 features
1366         }
1367
1368         // Before returning any messages to send for the peer, this method will see if any messages were
1369         // enqueued in the handler by users, find a path to the corresponding blinded path's introduction
1370         // node, and then enqueue the message for sending to the first peer in the full path.
1371         fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<OnionMessage> {
1372                 // Enqueue any initiating `OffersMessage`s to send.
1373                 for message in self.offers_handler.release_pending_messages() {
1374                         #[cfg(not(c_bindings))]
1375                         let PendingOnionMessage { contents, destination, reply_path } = message;
1376                         #[cfg(c_bindings)]
1377                         let (contents, destination, reply_path) = message;
1378                         let _ = self.find_path_and_enqueue_onion_message(
1379                                 contents, destination, reply_path, format_args!("when sending OffersMessage")
1380                         );
1381                 }
1382
1383                 // Enqueue any initiating `CustomMessage`s to send.
1384                 for message in self.custom_handler.release_pending_custom_messages() {
1385                         #[cfg(not(c_bindings))]
1386                         let PendingOnionMessage { contents, destination, reply_path } = message;
1387                         #[cfg(c_bindings)]
1388                         let (contents, destination, reply_path) = message;
1389                         let _ = self.find_path_and_enqueue_onion_message(
1390                                 contents, destination, reply_path, format_args!("when sending CustomMessage")
1391                         );
1392                 }
1393
1394                 self.message_recipients.lock().unwrap()
1395                         .get_mut(&peer_node_id)
1396                         .and_then(|buffer| buffer.dequeue_message())
1397         }
1398 }
1399
1400 // TODO: parameterize the below Simple* types with OnionMessenger and handle the messages it
1401 // produces
1402 /// Useful for simplifying the parameters of [`SimpleArcChannelManager`] and
1403 /// [`SimpleArcPeerManager`]. See their docs for more details.
1404 ///
1405 /// This is not exported to bindings users as type aliases aren't supported in most languages.
1406 ///
1407 /// [`SimpleArcChannelManager`]: crate::ln::channelmanager::SimpleArcChannelManager
1408 /// [`SimpleArcPeerManager`]: crate::ln::peer_handler::SimpleArcPeerManager
1409 #[cfg(not(c_bindings))]
1410 pub type SimpleArcOnionMessenger<M, T, F, L> = OnionMessenger<
1411         Arc<KeysManager>,
1412         Arc<KeysManager>,
1413         Arc<L>,
1414         Arc<SimpleArcChannelManager<M, T, F, L>>,
1415         Arc<DefaultMessageRouter<Arc<NetworkGraph<Arc<L>>>, Arc<L>, Arc<KeysManager>>>,
1416         Arc<SimpleArcChannelManager<M, T, F, L>>,
1417         IgnoringMessageHandler
1418 >;
1419
1420 /// Useful for simplifying the parameters of [`SimpleRefChannelManager`] and
1421 /// [`SimpleRefPeerManager`]. See their docs for more details.
1422 ///
1423 /// This is not exported to bindings users as type aliases aren't supported in most languages.
1424 ///
1425 /// [`SimpleRefChannelManager`]: crate::ln::channelmanager::SimpleRefChannelManager
1426 /// [`SimpleRefPeerManager`]: crate::ln::peer_handler::SimpleRefPeerManager
1427 #[cfg(not(c_bindings))]
1428 pub type SimpleRefOnionMessenger<
1429         'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, M, T, F, L
1430 > = OnionMessenger<
1431         &'a KeysManager,
1432         &'a KeysManager,
1433         &'b L,
1434         &'i SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L>,
1435         &'j DefaultMessageRouter<&'g NetworkGraph<&'b L>, &'b L, &'a KeysManager>,
1436         &'i SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L>,
1437         IgnoringMessageHandler
1438 >;
1439
1440 /// Construct onion packet payloads and keys for sending an onion message along the given
1441 /// `unblinded_path` to the given `destination`.
1442 fn packet_payloads_and_keys<T: OnionMessageContents, S: secp256k1::Signing + secp256k1::Verification>(
1443         secp_ctx: &Secp256k1<S>, unblinded_path: &[PublicKey], destination: Destination, message: T,
1444         mut reply_path: Option<BlindedPath>, session_priv: &SecretKey
1445 ) -> Result<(Vec<(Payload<T>, [u8; 32])>, Vec<onion_utils::OnionKeys>), SendError> {
1446         let num_hops = unblinded_path.len() + destination.num_hops();
1447         let mut payloads = Vec::with_capacity(num_hops);
1448         let mut onion_packet_keys = Vec::with_capacity(num_hops);
1449
1450         let (mut intro_node_id_blinding_pt, num_blinded_hops) = match &destination {
1451                 Destination::Node(_) => (None, 0),
1452                 Destination::BlindedPath(BlindedPath { introduction_node, blinding_point, blinded_hops }) => {
1453                         let introduction_node_id = match introduction_node {
1454                                 IntroductionNode::NodeId(pubkey) => pubkey,
1455                                 IntroductionNode::DirectedShortChannelId(..) => {
1456                                         return Err(SendError::UnresolvedIntroductionNode);
1457                                 },
1458                         };
1459                         (Some((*introduction_node_id, *blinding_point)), blinded_hops.len())
1460                 },
1461         };
1462         let num_unblinded_hops = num_hops - num_blinded_hops;
1463
1464         let mut unblinded_path_idx = 0;
1465         let mut blinded_path_idx = 0;
1466         let mut prev_control_tlvs_ss = None;
1467         let mut final_control_tlvs = None;
1468         utils::construct_keys_callback(secp_ctx, unblinded_path.iter(), Some(destination), session_priv,
1469                 |_, onion_packet_ss, ephemeral_pubkey, control_tlvs_ss, unblinded_pk_opt, enc_payload_opt| {
1470                         if num_unblinded_hops != 0 && unblinded_path_idx < num_unblinded_hops {
1471                                 if let Some(ss) = prev_control_tlvs_ss.take() {
1472                                         payloads.push((Payload::Forward(ForwardControlTlvs::Unblinded(
1473                                                 ForwardTlvs {
1474                                                         next_hop: NextMessageHop::NodeId(unblinded_pk_opt.unwrap()),
1475                                                         next_blinding_override: None,
1476                                                 }
1477                                         )), ss));
1478                                 }
1479                                 prev_control_tlvs_ss = Some(control_tlvs_ss);
1480                                 unblinded_path_idx += 1;
1481                         } else if let Some((intro_node_id, blinding_pt)) = intro_node_id_blinding_pt.take() {
1482                                 if let Some(control_tlvs_ss) = prev_control_tlvs_ss.take() {
1483                                         payloads.push((Payload::Forward(ForwardControlTlvs::Unblinded(ForwardTlvs {
1484                                                 next_hop: NextMessageHop::NodeId(intro_node_id),
1485                                                 next_blinding_override: Some(blinding_pt),
1486                                         })), control_tlvs_ss));
1487                                 }
1488                         }
1489                         if blinded_path_idx < num_blinded_hops.saturating_sub(1) && enc_payload_opt.is_some() {
1490                                 payloads.push((Payload::Forward(ForwardControlTlvs::Blinded(enc_payload_opt.unwrap())),
1491                                         control_tlvs_ss));
1492                                 blinded_path_idx += 1;
1493                         } else if let Some(encrypted_payload) = enc_payload_opt {
1494                                 final_control_tlvs = Some(ReceiveControlTlvs::Blinded(encrypted_payload));
1495                                 prev_control_tlvs_ss = Some(control_tlvs_ss);
1496                         }
1497
1498                         let (rho, mu) = onion_utils::gen_rho_mu_from_shared_secret(onion_packet_ss.as_ref());
1499                         onion_packet_keys.push(onion_utils::OnionKeys {
1500                                 #[cfg(test)]
1501                                 shared_secret: onion_packet_ss,
1502                                 #[cfg(test)]
1503                                 blinding_factor: [0; 32],
1504                                 ephemeral_pubkey,
1505                                 rho,
1506                                 mu,
1507                         });
1508                 }
1509         ).map_err(|e| SendError::Secp256k1(e))?;
1510
1511         if let Some(control_tlvs) = final_control_tlvs {
1512                 payloads.push((Payload::Receive {
1513                         control_tlvs,
1514                         reply_path: reply_path.take(),
1515                         message,
1516                 }, prev_control_tlvs_ss.unwrap()));
1517         } else {
1518                 payloads.push((Payload::Receive {
1519                         control_tlvs: ReceiveControlTlvs::Unblinded(ReceiveTlvs { path_id: None, }),
1520                         reply_path: reply_path.take(),
1521                         message,
1522                 }, prev_control_tlvs_ss.unwrap()));
1523         }
1524
1525         Ok((payloads, onion_packet_keys))
1526 }
1527
1528 /// Errors if the serialized payload size exceeds onion_message::BIG_PACKET_HOP_DATA_LEN
1529 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, ()> {
1530         // Spec rationale:
1531         // "`len` allows larger messages to be sent than the standard 1300 bytes allowed for an HTLC
1532         // onion, but this should be used sparingly as it is reduces anonymity set, hence the
1533         // recommendation that it either look like an HTLC onion, or if larger, be a fixed size."
1534         let payloads_ser_len = onion_utils::payloads_serialized_length(&payloads);
1535         let hop_data_len = if payloads_ser_len <= SMALL_PACKET_HOP_DATA_LEN {
1536                 SMALL_PACKET_HOP_DATA_LEN
1537         } else if payloads_ser_len <= BIG_PACKET_HOP_DATA_LEN {
1538                 BIG_PACKET_HOP_DATA_LEN
1539         } else { return Err(()) };
1540
1541         onion_utils::construct_onion_message_packet::<_, _>(
1542                 payloads, onion_keys, prng_seed, hop_data_len)
1543 }