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