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