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