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