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