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