723e105d044cf549cfd8f392e206782b38a479af
[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 the [`OnionMessenger`]. See its docs for
11 //! more information.
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;
19 use crate::blinded_path::message::{advance_path_by_one, ForwardTlvs, ReceiveTlvs};
20 use crate::blinded_path::utils;
21 use crate::sign::{EntropySource, KeysManager, NodeSigner, Recipient};
22 use crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
23 use crate::ln::features::{InitFeatures, NodeFeatures};
24 use crate::ln::msgs::{self, OnionMessage, OnionMessageHandler};
25 use crate::ln::onion_utils;
26 use crate::ln::peer_handler::IgnoringMessageHandler;
27 pub 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;
32 use crate::util::ser::Writeable;
33
34 use core::fmt;
35 use core::ops::Deref;
36 use crate::io;
37 use crate::sync::{Arc, Mutex};
38 use crate::prelude::*;
39
40 /// A sender, receiver and forwarder of [`OnionMessage`]s.
41 ///
42 /// # Handling Messages
43 ///
44 /// `OnionMessenger` implements [`OnionMessageHandler`], making it responsible for either forwarding
45 /// messages to peers or delegating to the appropriate handler for the message type. Currently, the
46 /// available handlers are:
47 /// * [`OffersMessageHandler`], for responding to [`InvoiceRequest`]s and paying [`Bolt12Invoice`]s
48 /// * [`CustomOnionMessageHandler`], for handling user-defined message types
49 ///
50 /// # Sending Messages
51 ///
52 /// [`OnionMessage`]s are sent initially using [`OnionMessenger::send_onion_message`]. When handling
53 /// a message, the matched handler may return a response message which `OnionMessenger` will send
54 /// on its behalf.
55 ///
56 /// # Example
57 ///
58 /// ```
59 /// # extern crate bitcoin;
60 /// # use bitcoin::hashes::_export::_core::time::Duration;
61 /// # use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
62 /// # use lightning::blinded_path::BlindedPath;
63 /// # use lightning::sign::KeysManager;
64 /// # use lightning::ln::peer_handler::IgnoringMessageHandler;
65 /// # use lightning::onion_message::{OnionMessageContents, Destination, MessageRouter, OnionMessagePath, OnionMessenger};
66 /// # use lightning::util::logger::{Logger, Record};
67 /// # use lightning::util::ser::{Writeable, Writer};
68 /// # use lightning::io;
69 /// # use std::sync::Arc;
70 /// # struct FakeLogger;
71 /// # impl Logger for FakeLogger {
72 /// #     fn log(&self, record: &Record) { unimplemented!() }
73 /// # }
74 /// # struct FakeMessageRouter {}
75 /// # impl MessageRouter for FakeMessageRouter {
76 /// #     fn find_path(&self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination) -> Result<OnionMessagePath, ()> {
77 /// #         unimplemented!()
78 /// #     }
79 /// # }
80 /// # let seed = [42u8; 32];
81 /// # let time = Duration::from_secs(123456);
82 /// # let keys_manager = KeysManager::new(&seed, time.as_secs(), time.subsec_nanos());
83 /// # let logger = Arc::new(FakeLogger {});
84 /// # let node_secret = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
85 /// # let secp_ctx = Secp256k1::new();
86 /// # let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
87 /// # let (hop_node_id2, hop_node_id3, hop_node_id4) = (hop_node_id1, hop_node_id1, hop_node_id1);
88 /// # let destination_node_id = hop_node_id1;
89 /// # let message_router = Arc::new(FakeMessageRouter {});
90 /// # let custom_message_handler = IgnoringMessageHandler {};
91 /// # let offers_message_handler = IgnoringMessageHandler {};
92 /// // Create the onion messenger. This must use the same `keys_manager` as is passed to your
93 /// // ChannelManager.
94 /// let onion_messenger = OnionMessenger::new(
95 ///     &keys_manager, &keys_manager, logger, message_router, &offers_message_handler,
96 ///     &custom_message_handler
97 /// );
98 ///
99 /// # struct YourCustomMessage {}
100 /// impl Writeable for YourCustomMessage {
101 ///     fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
102 ///             # Ok(())
103 ///             // Write your custom onion message to `w`
104 ///     }
105 /// }
106 /// impl OnionMessageContents for YourCustomMessage {
107 ///     fn tlv_type(&self) -> u64 {
108 ///             # let your_custom_message_type = 42;
109 ///             your_custom_message_type
110 ///     }
111 /// }
112 /// // Send a custom onion message to a node id.
113 /// let path = OnionMessagePath {
114 ///     intermediate_nodes: vec![hop_node_id1, hop_node_id2],
115 ///     destination: Destination::Node(destination_node_id),
116 /// };
117 /// let reply_path = None;
118 /// # let message = YourCustomMessage {};
119 /// onion_messenger.send_onion_message(path, message, reply_path);
120 ///
121 /// // Create a blinded path to yourself, for someone to send an onion message to.
122 /// # let your_node_id = hop_node_id1;
123 /// let hops = [hop_node_id3, hop_node_id4, your_node_id];
124 /// let blinded_path = BlindedPath::new_for_message(&hops, &keys_manager, &secp_ctx).unwrap();
125 ///
126 /// // Send a custom onion message to a blinded path.
127 /// let path = OnionMessagePath {
128 ///     intermediate_nodes: vec![hop_node_id1, hop_node_id2],
129 ///     destination: Destination::BlindedPath(blinded_path),
130 /// };
131 /// let reply_path = None;
132 /// # let message = YourCustomMessage {};
133 /// onion_messenger.send_onion_message(path, message, reply_path);
134 /// ```
135 ///
136 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
137 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
138 pub struct OnionMessenger<ES: Deref, NS: Deref, L: Deref, MR: Deref, OMH: Deref, CMH: Deref>
139 where
140         ES::Target: EntropySource,
141         NS::Target: NodeSigner,
142         L::Target: Logger,
143         MR::Target: MessageRouter,
144         OMH::Target: OffersMessageHandler,
145         CMH:: Target: CustomOnionMessageHandler,
146 {
147         entropy_source: ES,
148         node_signer: NS,
149         logger: L,
150         pending_messages: Mutex<HashMap<PublicKey, VecDeque<OnionMessage>>>,
151         secp_ctx: Secp256k1<secp256k1::All>,
152         message_router: MR,
153         offers_handler: OMH,
154         custom_handler: CMH,
155 }
156
157 /// An [`OnionMessage`] for [`OnionMessenger`] to send.
158 ///
159 /// These are obtained when released from [`OnionMessenger`]'s handlers after which they are
160 /// enqueued for sending.
161 pub struct PendingOnionMessage<T: OnionMessageContents> {
162         /// The message contents to send in an [`OnionMessage`].
163         pub contents: T,
164
165         /// The destination of the message.
166         pub destination: Destination,
167
168         /// A reply path to include in the [`OnionMessage`] for a response.
169         pub reply_path: Option<BlindedPath>,
170 }
171
172 /// A trait defining behavior for routing an [`OnionMessage`].
173 pub trait MessageRouter {
174         /// Returns a route for sending an [`OnionMessage`] to the given [`Destination`].
175         fn find_path(
176                 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
177         ) -> Result<OnionMessagePath, ()>;
178 }
179
180 /// A [`MessageRouter`] that can only route to a directly connected [`Destination`].
181 pub struct DefaultMessageRouter;
182
183 impl MessageRouter for DefaultMessageRouter {
184         fn find_path(
185                 &self, _sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
186         ) -> Result<OnionMessagePath, ()> {
187                 if peers.contains(&destination.first_node()) {
188                         Ok(OnionMessagePath { intermediate_nodes: vec![], destination })
189                 } else {
190                         Err(())
191                 }
192         }
193 }
194
195 /// A path for sending an [`OnionMessage`].
196 #[derive(Clone)]
197 pub struct OnionMessagePath {
198         /// Nodes on the path between the sender and the destination.
199         pub intermediate_nodes: Vec<PublicKey>,
200
201         /// The recipient of the message.
202         pub destination: Destination,
203 }
204
205 /// The destination of an onion message.
206 #[derive(Clone)]
207 pub enum Destination {
208         /// We're sending this onion message to a node.
209         Node(PublicKey),
210         /// We're sending this onion message to a blinded path.
211         BlindedPath(BlindedPath),
212 }
213
214 impl Destination {
215         pub(super) fn num_hops(&self) -> usize {
216                 match self {
217                         Destination::Node(_) => 1,
218                         Destination::BlindedPath(BlindedPath { blinded_hops, .. }) => blinded_hops.len(),
219                 }
220         }
221
222         fn first_node(&self) -> PublicKey {
223                 match self {
224                         Destination::Node(node_id) => *node_id,
225                         Destination::BlindedPath(BlindedPath { introduction_node_id: node_id, .. }) => *node_id,
226                 }
227         }
228 }
229
230 /// Errors that may occur when [sending an onion message].
231 ///
232 /// [sending an onion message]: OnionMessenger::send_onion_message
233 #[derive(Debug, PartialEq, Eq)]
234 pub enum SendError {
235         /// Errored computing onion message packet keys.
236         Secp256k1(secp256k1::Error),
237         /// Because implementations such as Eclair will drop onion messages where the message packet
238         /// exceeds 32834 bytes, we refuse to send messages where the packet exceeds this size.
239         TooBigPacket,
240         /// The provided [`Destination`] was an invalid [`BlindedPath`] due to not having any blinded
241         /// hops.
242         TooFewBlindedHops,
243         /// Our next-hop peer was offline or does not support onion message forwarding.
244         InvalidFirstHop,
245         /// Onion message contents must have a TLV type >= 64.
246         InvalidMessage,
247         /// Our next-hop peer's buffer was full or our total outbound buffer was full.
248         BufferFull,
249         /// Failed to retrieve our node id from the provided [`NodeSigner`].
250         ///
251         /// [`NodeSigner`]: crate::sign::NodeSigner
252         GetNodeIdFailed,
253         /// We attempted to send to a blinded path where we are the introduction node, and failed to
254         /// advance the blinded path to make the second hop the new introduction node. Either
255         /// [`NodeSigner::ecdh`] failed, we failed to tweak the current blinding point to get the
256         /// new blinding point, or we were attempting to send to ourselves.
257         BlindedPathAdvanceFailed,
258 }
259
260 /// Handler for custom onion messages. If you are using [`SimpleArcOnionMessenger`],
261 /// [`SimpleRefOnionMessenger`], or prefer to ignore inbound custom onion messages,
262 /// [`IgnoringMessageHandler`] must be provided to [`OnionMessenger::new`]. Otherwise, a custom
263 /// implementation of this trait must be provided, with [`CustomMessage`] specifying the supported
264 /// message types.
265 ///
266 /// See [`OnionMessenger`] for example usage.
267 ///
268 /// [`IgnoringMessageHandler`]: crate::ln::peer_handler::IgnoringMessageHandler
269 /// [`CustomMessage`]: Self::CustomMessage
270 pub trait CustomOnionMessageHandler {
271         /// The message known to the handler. To support multiple message types, you may want to make this
272         /// an enum with a variant for each supported message.
273         type CustomMessage: OnionMessageContents;
274
275         /// Called with the custom message that was received, returning a response to send, if any.
276         ///
277         /// The returned [`Self::CustomMessage`], if any, is enqueued to be sent by [`OnionMessenger`].
278         fn handle_custom_message(&self, msg: Self::CustomMessage) -> Option<Self::CustomMessage>;
279
280         /// Read a custom message of type `message_type` from `buffer`, returning `Ok(None)` if the
281         /// message type is unknown.
282         fn read_custom_message<R: io::Read>(&self, message_type: u64, buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError>;
283
284         /// Releases any [`Self::CustomMessage`]s that need to be sent.
285         ///
286         /// Typically, this is used for messages initiating a message flow rather than in response to
287         /// another message. The latter should use the return value of [`Self::handle_custom_message`].
288         fn release_pending_custom_messages(&self) -> Vec<PendingOnionMessage<Self::CustomMessage>>;
289 }
290
291 /// A processed incoming onion message, containing either a Forward (another onion message)
292 /// or a Receive payload with decrypted contents.
293 pub enum PeeledOnion<T: OnionMessageContents> {
294         /// Forwarded onion, with the next node id and a new onion
295         Forward(PublicKey, OnionMessage),
296         /// Received onion message, with decrypted contents, path_id, and reply path
297         Receive(ParsedOnionMessageContents<T>, Option<[u8; 32]>, Option<BlindedPath>)
298 }
299
300 /// Creates an [`OnionMessage`] with the given `contents` for sending to the destination of
301 /// `path`.
302 ///
303 /// Returns both the node id of the peer to send the message to and the message itself.
304 pub fn create_onion_message<ES: Deref, NS: Deref, T: OnionMessageContents>(
305         entropy_source: &ES, node_signer: &NS, secp_ctx: &Secp256k1<secp256k1::All>,
306         path: OnionMessagePath, contents: T, reply_path: Option<BlindedPath>,
307 ) -> Result<(PublicKey, OnionMessage), SendError>
308 where
309         ES::Target: EntropySource,
310         NS::Target: NodeSigner,
311 {
312         let OnionMessagePath { intermediate_nodes, mut destination } = path;
313         if let Destination::BlindedPath(BlindedPath { ref blinded_hops, .. }) = destination {
314                 if blinded_hops.is_empty() {
315                         return Err(SendError::TooFewBlindedHops);
316                 }
317         }
318
319         if contents.tlv_type() < 64 { return Err(SendError::InvalidMessage) }
320
321         // If we are sending straight to a blinded path and we are the introduction node, we need to
322         // advance the blinded path by 1 hop so the second hop is the new introduction node.
323         if intermediate_nodes.len() == 0 {
324                 if let Destination::BlindedPath(ref mut blinded_path) = destination {
325                         let our_node_id = node_signer.get_node_id(Recipient::Node)
326                                 .map_err(|()| SendError::GetNodeIdFailed)?;
327                         if blinded_path.introduction_node_id == our_node_id {
328                                 advance_path_by_one(blinded_path, node_signer, &secp_ctx)
329                                         .map_err(|()| SendError::BlindedPathAdvanceFailed)?;
330                         }
331                 }
332         }
333
334         let blinding_secret_bytes = entropy_source.get_secure_random_bytes();
335         let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
336         let (first_node_id, blinding_point) = if let Some(first_node_id) = intermediate_nodes.first() {
337                 (*first_node_id, PublicKey::from_secret_key(&secp_ctx, &blinding_secret))
338         } else {
339                 match destination {
340                         Destination::Node(pk) => (pk, PublicKey::from_secret_key(&secp_ctx, &blinding_secret)),
341                         Destination::BlindedPath(BlindedPath { introduction_node_id, blinding_point, .. }) =>
342                                 (introduction_node_id, blinding_point),
343                 }
344         };
345         let (packet_payloads, packet_keys) = packet_payloads_and_keys(
346                 &secp_ctx, &intermediate_nodes, destination, contents, reply_path, &blinding_secret)
347                 .map_err(|e| SendError::Secp256k1(e))?;
348
349         let prng_seed = entropy_source.get_secure_random_bytes();
350         let onion_routing_packet = construct_onion_message_packet(
351                 packet_payloads, packet_keys, prng_seed).map_err(|()| SendError::TooBigPacket)?;
352
353         Ok((first_node_id, OnionMessage {
354                 blinding_point,
355                 onion_routing_packet
356         }))
357 }
358
359 /// Decode one layer of an incoming [`OnionMessage`].
360 ///
361 /// Returns either the next layer of the onion for forwarding or the decrypted content for the
362 /// receiver.
363 pub fn peel_onion_message<NS: Deref, L: Deref, CMH: Deref>(
364         msg: &OnionMessage, secp_ctx: &Secp256k1<secp256k1::All>, node_signer: NS, logger: L,
365         custom_handler: CMH,
366 ) -> Result<PeeledOnion<<<CMH>::Target as CustomOnionMessageHandler>::CustomMessage>, ()>
367 where
368         NS::Target: NodeSigner,
369         L::Target: Logger,
370         CMH::Target: CustomOnionMessageHandler,
371 {
372         let control_tlvs_ss = match node_signer.ecdh(Recipient::Node, &msg.blinding_point, None) {
373                 Ok(ss) => ss,
374                 Err(e) =>  {
375                         log_error!(logger, "Failed to retrieve node secret: {:?}", e);
376                         return Err(());
377                 }
378         };
379         let onion_decode_ss = {
380                 let blinding_factor = {
381                         let mut hmac = HmacEngine::<Sha256>::new(b"blinded_node_id");
382                         hmac.input(control_tlvs_ss.as_ref());
383                         Hmac::from_engine(hmac).into_inner()
384                 };
385                 match node_signer.ecdh(Recipient::Node, &msg.onion_routing_packet.public_key,
386                         Some(&Scalar::from_be_bytes(blinding_factor).unwrap()))
387                 {
388                         Ok(ss) => ss.secret_bytes(),
389                         Err(()) => {
390                                 log_trace!(logger, "Failed to compute onion packet shared secret");
391                                 return Err(());
392                         }
393                 }
394         };
395         match onion_utils::decode_next_untagged_hop(
396                 onion_decode_ss, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac,
397                 (control_tlvs_ss, custom_handler.deref(), logger.deref())
398         ) {
399                 Ok((Payload::Receive::<ParsedOnionMessageContents<<<CMH as Deref>::Target as CustomOnionMessageHandler>::CustomMessage>> {
400                         message, control_tlvs: ReceiveControlTlvs::Unblinded(ReceiveTlvs { path_id }), reply_path,
401                 }, None)) => {
402                         Ok(PeeledOnion::Receive(message, path_id, reply_path))
403                 },
404                 Ok((Payload::Forward(ForwardControlTlvs::Unblinded(ForwardTlvs {
405                         next_node_id, next_blinding_override
406                 })), Some((next_hop_hmac, new_packet_bytes)))) => {
407                         // TODO: we need to check whether `next_node_id` is our node, in which case this is a dummy
408                         // blinded hop and this onion message is destined for us. In this situation, we should keep
409                         // unwrapping the onion layers to get to the final payload. Since we don't have the option
410                         // of creating blinded paths with dummy hops currently, we should be ok to not handle this
411                         // for now.
412                         let new_pubkey = match onion_utils::next_hop_pubkey(&secp_ctx, msg.onion_routing_packet.public_key, &onion_decode_ss) {
413                                 Ok(pk) => pk,
414                                 Err(e) => {
415                                         log_trace!(logger, "Failed to compute next hop packet pubkey: {}", e);
416                                         return Err(())
417                                 }
418                         };
419                         let outgoing_packet = Packet {
420                                 version: 0,
421                                 public_key: new_pubkey,
422                                 hop_data: new_packet_bytes,
423                                 hmac: next_hop_hmac,
424                         };
425                         let onion_message = OnionMessage {
426                                 blinding_point: match next_blinding_override {
427                                         Some(blinding_point) => blinding_point,
428                                         None => {
429                                                 match onion_utils::next_hop_pubkey(
430                                                         &secp_ctx, msg.blinding_point, control_tlvs_ss.as_ref()
431                                                 ) {
432                                                         Ok(bp) => bp,
433                                                         Err(e) => {
434                                                                 log_trace!(logger, "Failed to compute next blinding point: {}", e);
435                                                                 return Err(())
436                                                         }
437                                                 }
438                                         }
439                                 },
440                                 onion_routing_packet: outgoing_packet,
441                         };
442
443                         Ok(PeeledOnion::Forward(next_node_id, onion_message))
444                 },
445                 Err(e) => {
446                         log_trace!(logger, "Errored decoding onion message packet: {:?}", e);
447                         Err(())
448                 },
449                 _ => {
450                         log_trace!(logger, "Received bogus onion message packet, either the sender encoded a final hop as a forwarding hop or vice versa");
451                         Err(())
452                 },
453         }
454 }
455
456 impl<ES: Deref, NS: Deref, L: Deref, MR: Deref, OMH: Deref, CMH: Deref>
457 OnionMessenger<ES, NS, L, MR, OMH, CMH>
458 where
459         ES::Target: EntropySource,
460         NS::Target: NodeSigner,
461         L::Target: Logger,
462         MR::Target: MessageRouter,
463         OMH::Target: OffersMessageHandler,
464         CMH::Target: CustomOnionMessageHandler,
465 {
466         /// Constructs a new `OnionMessenger` to send, forward, and delegate received onion messages to
467         /// their respective handlers.
468         pub fn new(
469                 entropy_source: ES, node_signer: NS, logger: L, message_router: MR, offers_handler: OMH,
470                 custom_handler: CMH
471         ) -> Self {
472                 let mut secp_ctx = Secp256k1::new();
473                 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
474                 OnionMessenger {
475                         entropy_source,
476                         node_signer,
477                         pending_messages: Mutex::new(HashMap::new()),
478                         secp_ctx,
479                         logger,
480                         message_router,
481                         offers_handler,
482                         custom_handler,
483                 }
484         }
485
486         /// Sends an [`OnionMessage`] with the given `contents` for sending to the destination of
487         /// `path`.
488         ///
489         /// See [`OnionMessenger`] for example usage.
490         pub fn send_onion_message<T: OnionMessageContents>(
491                 &self, path: OnionMessagePath, contents: T, reply_path: Option<BlindedPath>
492         ) -> Result<(), SendError> {
493                 let (first_node_id, onion_msg) = create_onion_message(
494                         &self.entropy_source, &self.node_signer, &self.secp_ctx, path, contents, reply_path
495                 )?;
496
497                 let mut pending_per_peer_msgs = self.pending_messages.lock().unwrap();
498                 if outbound_buffer_full(&first_node_id, &pending_per_peer_msgs) { return Err(SendError::BufferFull) }
499                 match pending_per_peer_msgs.entry(first_node_id) {
500                         hash_map::Entry::Vacant(_) => Err(SendError::InvalidFirstHop),
501                         hash_map::Entry::Occupied(mut e) => {
502                                 e.get_mut().push_back(onion_msg);
503                                 Ok(())
504                         }
505                 }
506         }
507
508         fn handle_onion_message_response<T: OnionMessageContents>(
509                 &self, response: Option<T>, reply_path: Option<BlindedPath>, log_suffix: fmt::Arguments
510         ) {
511                 if let Some(response) = response {
512                         match reply_path {
513                                 Some(reply_path) => {
514                                         self.find_path_and_enqueue_onion_message(
515                                                 response, Destination::BlindedPath(reply_path), None, log_suffix
516                                         );
517                                 },
518                                 None => {
519                                         log_trace!(self.logger, "Missing reply path {}", log_suffix);
520                                 },
521                         }
522                 }
523         }
524
525         fn find_path_and_enqueue_onion_message<T: OnionMessageContents>(
526                 &self, contents: T, destination: Destination, reply_path: Option<BlindedPath>,
527                 log_suffix: fmt::Arguments
528         ) {
529                 let sender = match self.node_signer.get_node_id(Recipient::Node) {
530                         Ok(node_id) => node_id,
531                         Err(_) => {
532                                 log_warn!(self.logger, "Unable to retrieve node id {}", log_suffix);
533                                 return;
534                         }
535                 };
536
537                 let peers = self.pending_messages.lock().unwrap().keys().copied().collect();
538                 let path = match self.message_router.find_path(sender, peers, destination) {
539                         Ok(path) => path,
540                         Err(()) => {
541                                 log_trace!(self.logger, "Failed to find path {}", log_suffix);
542                                 return;
543                         },
544                 };
545
546                 log_trace!(self.logger, "Sending onion message {}", log_suffix);
547
548                 if let Err(e) = self.send_onion_message(path, contents, reply_path) {
549                         log_trace!(self.logger, "Failed sending onion message {}: {:?}", log_suffix, e);
550                         return;
551                 }
552         }
553
554         #[cfg(test)]
555         pub(super) fn release_pending_msgs(&self) -> HashMap<PublicKey, VecDeque<OnionMessage>> {
556                 let mut pending_msgs = self.pending_messages.lock().unwrap();
557                 let mut msgs = HashMap::new();
558                 // We don't want to disconnect the peers by removing them entirely from the original map, so we
559                 // swap the pending message buffers individually.
560                 for (peer_node_id, pending_messages) in &mut *pending_msgs {
561                         msgs.insert(*peer_node_id, core::mem::take(pending_messages));
562                 }
563                 msgs
564         }
565 }
566
567 fn outbound_buffer_full(peer_node_id: &PublicKey, buffer: &HashMap<PublicKey, VecDeque<OnionMessage>>) -> bool {
568         const MAX_TOTAL_BUFFER_SIZE: usize = (1 << 20) * 128;
569         const MAX_PER_PEER_BUFFER_SIZE: usize = (1 << 10) * 256;
570         let mut total_buffered_bytes = 0;
571         let mut peer_buffered_bytes = 0;
572         for (pk, peer_buf) in buffer {
573                 for om in peer_buf {
574                         let om_len = om.serialized_length();
575                         if pk == peer_node_id {
576                                 peer_buffered_bytes += om_len;
577                         }
578                         total_buffered_bytes += om_len;
579
580                         if total_buffered_bytes >= MAX_TOTAL_BUFFER_SIZE ||
581                                 peer_buffered_bytes >= MAX_PER_PEER_BUFFER_SIZE
582                         {
583                                 return true
584                         }
585                 }
586         }
587         false
588 }
589
590 impl<ES: Deref, NS: Deref, L: Deref, MR: Deref, OMH: Deref, CMH: Deref> OnionMessageHandler
591 for OnionMessenger<ES, NS, L, MR, OMH, CMH>
592 where
593         ES::Target: EntropySource,
594         NS::Target: NodeSigner,
595         L::Target: Logger,
596         MR::Target: MessageRouter,
597         OMH::Target: OffersMessageHandler,
598         CMH::Target: CustomOnionMessageHandler,
599 {
600         fn handle_onion_message(&self, _peer_node_id: &PublicKey, msg: &OnionMessage) {
601                 match peel_onion_message(
602                         msg, &self.secp_ctx, &*self.node_signer, &*self.logger, &*self.custom_handler
603                 ) {
604                         Ok(PeeledOnion::Receive(message, path_id, reply_path)) => {
605                                 log_trace!(self.logger,
606                                         "Received an onion message with path_id {:02x?} and {} reply_path",
607                                                 path_id, if reply_path.is_some() { "a" } else { "no" });
608
609                                 match message {
610                                         ParsedOnionMessageContents::Offers(msg) => {
611                                                 let response = self.offers_handler.handle_message(msg);
612                                                 self.handle_onion_message_response(
613                                                         response, reply_path, format_args!(
614                                                                 "when responding to Offers onion message with path_id {:02x?}",
615                                                                 path_id
616                                                         )
617                                                 );
618                                         },
619                                         ParsedOnionMessageContents::Custom(msg) => {
620                                                 let response = self.custom_handler.handle_custom_message(msg);
621                                                 self.handle_onion_message_response(
622                                                         response, reply_path, format_args!(
623                                                                 "when responding to Custom onion message with path_id {:02x?}",
624                                                                 path_id
625                                                         )
626                                                 );
627                                         },
628                                 }
629                         },
630                         Ok(PeeledOnion::Forward(next_node_id, onion_message)) => {
631                                 let mut pending_per_peer_msgs = self.pending_messages.lock().unwrap();
632                                 if outbound_buffer_full(&next_node_id, &pending_per_peer_msgs) {
633                                         log_trace!(self.logger, "Dropping forwarded onion message to peer {:?}: outbound buffer full", next_node_id);
634                                         return
635                                 }
636
637                                 #[cfg(fuzzing)]
638                                 pending_per_peer_msgs.entry(next_node_id).or_insert_with(VecDeque::new);
639
640                                 match pending_per_peer_msgs.entry(next_node_id) {
641                                         hash_map::Entry::Vacant(_) => {
642                                                 log_trace!(self.logger, "Dropping forwarded onion message to disconnected peer {:?}", next_node_id);
643                                                 return
644                                         },
645                                         hash_map::Entry::Occupied(mut e) => {
646                                                 e.get_mut().push_back(onion_message);
647                                                 log_trace!(self.logger, "Forwarding an onion message to peer {}", next_node_id);
648                                         }
649                                 }
650                         },
651                         Err(e) => {
652                                 log_error!(self.logger, "Failed to process onion message {:?}", e);
653                         }
654                 }
655         }
656
657         fn peer_connected(&self, their_node_id: &PublicKey, init: &msgs::Init, _inbound: bool) -> Result<(), ()> {
658                 if init.features.supports_onion_messages() {
659                         let mut peers = self.pending_messages.lock().unwrap();
660                         peers.insert(their_node_id.clone(), VecDeque::new());
661                 }
662                 Ok(())
663         }
664
665         fn peer_disconnected(&self, their_node_id: &PublicKey) {
666                 let mut pending_msgs = self.pending_messages.lock().unwrap();
667                 pending_msgs.remove(their_node_id);
668         }
669
670         fn provided_node_features(&self) -> NodeFeatures {
671                 let mut features = NodeFeatures::empty();
672                 features.set_onion_messages_optional();
673                 features
674         }
675
676         fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
677                 let mut features = InitFeatures::empty();
678                 features.set_onion_messages_optional();
679                 features
680         }
681
682         // Before returning any messages to send for the peer, this method will see if any messages were
683         // enqueued in the handler by users, find a path to the corresponding blinded path's introduction
684         // node, and then enqueue the message for sending to the first peer in the full path.
685         fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<OnionMessage> {
686                 // Enqueue any initiating `OffersMessage`s to send.
687                 for message in self.offers_handler.release_pending_messages() {
688                         let PendingOnionMessage { contents, destination, reply_path } = message;
689                         self.find_path_and_enqueue_onion_message(
690                                 contents, destination, reply_path, format_args!("when sending OffersMessage")
691                         );
692                 }
693
694                 // Enqueue any initiating `CustomMessage`s to send.
695                 for message in self.custom_handler.release_pending_custom_messages() {
696                         let PendingOnionMessage { contents, destination, reply_path } = message;
697                         self.find_path_and_enqueue_onion_message(
698                                 contents, destination, reply_path, format_args!("when sending CustomMessage")
699                         );
700                 }
701
702                 let mut pending_msgs = self.pending_messages.lock().unwrap();
703                 if let Some(msgs) = pending_msgs.get_mut(&peer_node_id) {
704                         return msgs.pop_front()
705                 }
706                 None
707         }
708 }
709
710 // TODO: parameterize the below Simple* types with OnionMessenger and handle the messages it
711 // produces
712 /// Useful for simplifying the parameters of [`SimpleArcChannelManager`] and
713 /// [`SimpleArcPeerManager`]. See their docs for more details.
714 ///
715 /// This is not exported to bindings users as `Arc`s don't make sense in bindings.
716 ///
717 /// [`SimpleArcChannelManager`]: crate::ln::channelmanager::SimpleArcChannelManager
718 /// [`SimpleArcPeerManager`]: crate::ln::peer_handler::SimpleArcPeerManager
719 pub type SimpleArcOnionMessenger<M, T, F, L> = OnionMessenger<
720         Arc<KeysManager>,
721         Arc<KeysManager>,
722         Arc<L>,
723         Arc<DefaultMessageRouter>,
724         Arc<SimpleArcChannelManager<M, T, F, L>>,
725         IgnoringMessageHandler
726 >;
727
728 /// Useful for simplifying the parameters of [`SimpleRefChannelManager`] and
729 /// [`SimpleRefPeerManager`]. See their docs for more details.
730 ///
731 /// This is not exported to bindings users as general type aliases don't make sense in bindings.
732 ///
733 /// [`SimpleRefChannelManager`]: crate::ln::channelmanager::SimpleRefChannelManager
734 /// [`SimpleRefPeerManager`]: crate::ln::peer_handler::SimpleRefPeerManager
735 pub type SimpleRefOnionMessenger<
736         'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, M, T, F, L
737 > = OnionMessenger<
738         &'a KeysManager,
739         &'a KeysManager,
740         &'b L,
741         &'i DefaultMessageRouter,
742         &'j SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L>,
743         IgnoringMessageHandler
744 >;
745
746 /// Construct onion packet payloads and keys for sending an onion message along the given
747 /// `unblinded_path` to the given `destination`.
748 fn packet_payloads_and_keys<T: OnionMessageContents, S: secp256k1::Signing + secp256k1::Verification>(
749         secp_ctx: &Secp256k1<S>, unblinded_path: &[PublicKey], destination: Destination, message: T,
750         mut reply_path: Option<BlindedPath>, session_priv: &SecretKey
751 ) -> Result<(Vec<(Payload<T>, [u8; 32])>, Vec<onion_utils::OnionKeys>), secp256k1::Error> {
752         let num_hops = unblinded_path.len() + destination.num_hops();
753         let mut payloads = Vec::with_capacity(num_hops);
754         let mut onion_packet_keys = Vec::with_capacity(num_hops);
755
756         let (mut intro_node_id_blinding_pt, num_blinded_hops) = if let Destination::BlindedPath(BlindedPath {
757                 introduction_node_id, blinding_point, blinded_hops }) = &destination {
758                 (Some((*introduction_node_id, *blinding_point)), blinded_hops.len()) } else { (None, 0) };
759         let num_unblinded_hops = num_hops - num_blinded_hops;
760
761         let mut unblinded_path_idx = 0;
762         let mut blinded_path_idx = 0;
763         let mut prev_control_tlvs_ss = None;
764         let mut final_control_tlvs = None;
765         utils::construct_keys_callback(secp_ctx, unblinded_path.iter(), Some(destination), session_priv,
766                 |_, onion_packet_ss, ephemeral_pubkey, control_tlvs_ss, unblinded_pk_opt, enc_payload_opt| {
767                         if num_unblinded_hops != 0 && unblinded_path_idx < num_unblinded_hops {
768                                 if let Some(ss) = prev_control_tlvs_ss.take() {
769                                         payloads.push((Payload::Forward(ForwardControlTlvs::Unblinded(
770                                                 ForwardTlvs {
771                                                         next_node_id: unblinded_pk_opt.unwrap(),
772                                                         next_blinding_override: None,
773                                                 }
774                                         )), ss));
775                                 }
776                                 prev_control_tlvs_ss = Some(control_tlvs_ss);
777                                 unblinded_path_idx += 1;
778                         } else if let Some((intro_node_id, blinding_pt)) = intro_node_id_blinding_pt.take() {
779                                 if let Some(control_tlvs_ss) = prev_control_tlvs_ss.take() {
780                                         payloads.push((Payload::Forward(ForwardControlTlvs::Unblinded(ForwardTlvs {
781                                                 next_node_id: intro_node_id,
782                                                 next_blinding_override: Some(blinding_pt),
783                                         })), control_tlvs_ss));
784                                 }
785                         }
786                         if blinded_path_idx < num_blinded_hops.saturating_sub(1) && enc_payload_opt.is_some() {
787                                 payloads.push((Payload::Forward(ForwardControlTlvs::Blinded(enc_payload_opt.unwrap())),
788                                         control_tlvs_ss));
789                                 blinded_path_idx += 1;
790                         } else if let Some(encrypted_payload) = enc_payload_opt {
791                                 final_control_tlvs = Some(ReceiveControlTlvs::Blinded(encrypted_payload));
792                                 prev_control_tlvs_ss = Some(control_tlvs_ss);
793                         }
794
795                         let (rho, mu) = onion_utils::gen_rho_mu_from_shared_secret(onion_packet_ss.as_ref());
796                         onion_packet_keys.push(onion_utils::OnionKeys {
797                                 #[cfg(test)]
798                                 shared_secret: onion_packet_ss,
799                                 #[cfg(test)]
800                                 blinding_factor: [0; 32],
801                                 ephemeral_pubkey,
802                                 rho,
803                                 mu,
804                         });
805                 }
806         )?;
807
808         if let Some(control_tlvs) = final_control_tlvs {
809                 payloads.push((Payload::Receive {
810                         control_tlvs,
811                         reply_path: reply_path.take(),
812                         message,
813                 }, prev_control_tlvs_ss.unwrap()));
814         } else {
815                 payloads.push((Payload::Receive {
816                         control_tlvs: ReceiveControlTlvs::Unblinded(ReceiveTlvs { path_id: None, }),
817                         reply_path: reply_path.take(),
818                         message,
819                 }, prev_control_tlvs_ss.unwrap()));
820         }
821
822         Ok((payloads, onion_packet_keys))
823 }
824
825 /// Errors if the serialized payload size exceeds onion_message::BIG_PACKET_HOP_DATA_LEN
826 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, ()> {
827         // Spec rationale:
828         // "`len` allows larger messages to be sent than the standard 1300 bytes allowed for an HTLC
829         // onion, but this should be used sparingly as it is reduces anonymity set, hence the
830         // recommendation that it either look like an HTLC onion, or if larger, be a fixed size."
831         let payloads_ser_len = onion_utils::payloads_serialized_length(&payloads);
832         let hop_data_len = if payloads_ser_len <= SMALL_PACKET_HOP_DATA_LEN {
833                 SMALL_PACKET_HOP_DATA_LEN
834         } else if payloads_ser_len <= BIG_PACKET_HOP_DATA_LEN {
835                 BIG_PACKET_HOP_DATA_LEN
836         } else { return Err(()) };
837
838         onion_utils::construct_onion_message_packet::<_, _>(
839                 payloads, onion_keys, prng_seed, hop_data_len)
840 }