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