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