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