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