Don't construct OnionMessage while holding peer lock
[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 chain::keysinterface::{InMemorySigner, KeysInterface, KeysManager, Recipient, Sign};
19 use ln::msgs::{self, OnionMessageHandler};
20 use ln::onion_utils;
21 use super::blinded_route::{BlindedRoute, ForwardTlvs, ReceiveTlvs};
22 use super::packet::{BIG_PACKET_HOP_DATA_LEN, ForwardControlTlvs, Packet, Payload, ReceiveControlTlvs, SMALL_PACKET_HOP_DATA_LEN};
23 use super::utils;
24 use util::events::OnionMessageProvider;
25 use util::logger::Logger;
26
27 use core::ops::Deref;
28 use sync::{Arc, Mutex};
29 use prelude::*;
30
31 /// A sender, receiver and forwarder of onion messages. In upcoming releases, this object will be
32 /// used to retrieve invoices and fulfill invoice requests from [offers]. Currently, only sending
33 /// and receiving empty onion messages is supported.
34 ///
35 /// # Example
36 ///
37 /// ```
38 /// # extern crate bitcoin;
39 /// # use bitcoin::hashes::_export::_core::time::Duration;
40 /// # use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
41 /// # use lightning::chain::keysinterface::{InMemorySigner, KeysManager, KeysInterface};
42 /// # use lightning::onion_message::{BlindedRoute, Destination, OnionMessenger};
43 /// # use lightning::util::logger::{Logger, Record};
44 /// # use std::sync::Arc;
45 /// # struct FakeLogger {};
46 /// # impl Logger for FakeLogger {
47 /// #     fn log(&self, record: &Record) { unimplemented!() }
48 /// # }
49 /// # let seed = [42u8; 32];
50 /// # let time = Duration::from_secs(123456);
51 /// # let keys_manager = KeysManager::new(&seed, time.as_secs(), time.subsec_nanos());
52 /// # let logger = Arc::new(FakeLogger {});
53 /// # let node_secret = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
54 /// # let secp_ctx = Secp256k1::new();
55 /// # let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
56 /// # let (hop_node_id2, hop_node_id3, hop_node_id4) = (hop_node_id1, hop_node_id1,
57 /// hop_node_id1);
58 /// # let destination_node_id = hop_node_id1;
59 /// #
60 /// // Create the onion messenger. This must use the same `keys_manager` as is passed to your
61 /// // ChannelManager.
62 /// let onion_messenger = OnionMessenger::new(&keys_manager, logger);
63 ///
64 /// // Send an empty onion message to a node id.
65 /// let intermediate_hops = [hop_node_id1, hop_node_id2];
66 /// let reply_path = None;
67 /// onion_messenger.send_onion_message(&intermediate_hops, Destination::Node(destination_node_id), reply_path);
68 ///
69 /// // Create a blinded route to yourself, for someone to send an onion message to.
70 /// # let your_node_id = hop_node_id1;
71 /// let hops = [hop_node_id3, hop_node_id4, your_node_id];
72 /// let blinded_route = BlindedRoute::new::<InMemorySigner, _, _>(&hops, &keys_manager, &secp_ctx).unwrap();
73 ///
74 /// // Send an empty onion message to a blinded route.
75 /// # let intermediate_hops = [hop_node_id1, hop_node_id2];
76 /// let reply_path = None;
77 /// onion_messenger.send_onion_message(&intermediate_hops, Destination::BlindedRoute(blinded_route), reply_path);
78 /// ```
79 ///
80 /// [offers]: <https://github.com/lightning/bolts/pull/798>
81 /// [`OnionMessenger`]: crate::onion_message::OnionMessenger
82 pub struct OnionMessenger<Signer: Sign, K: Deref, L: Deref>
83         where K::Target: KeysInterface<Signer = Signer>,
84               L::Target: Logger,
85 {
86         keys_manager: K,
87         logger: L,
88         pending_messages: Mutex<HashMap<PublicKey, VecDeque<msgs::OnionMessage>>>,
89         secp_ctx: Secp256k1<secp256k1::All>,
90         // Coming soon:
91         // invoice_handler: InvoiceHandler,
92         // custom_handler: CustomHandler, // handles custom onion messages
93 }
94
95 /// The destination of an onion message.
96 pub enum Destination {
97         /// We're sending this onion message to a node.
98         Node(PublicKey),
99         /// We're sending this onion message to a blinded route.
100         BlindedRoute(BlindedRoute),
101 }
102
103 impl Destination {
104         pub(super) fn num_hops(&self) -> usize {
105                 match self {
106                         Destination::Node(_) => 1,
107                         Destination::BlindedRoute(BlindedRoute { blinded_hops, .. }) => blinded_hops.len(),
108                 }
109         }
110 }
111
112 /// Errors that may occur when [sending an onion message].
113 ///
114 /// [sending an onion message]: OnionMessenger::send_onion_message
115 #[derive(Debug, PartialEq)]
116 pub enum SendError {
117         /// Errored computing onion message packet keys.
118         Secp256k1(secp256k1::Error),
119         /// Because implementations such as Eclair will drop onion messages where the message packet
120         /// exceeds 32834 bytes, we refuse to send messages where the packet exceeds this size.
121         TooBigPacket,
122         /// The provided [`Destination`] was an invalid [`BlindedRoute`], due to having fewer than two
123         /// blinded hops.
124         TooFewBlindedHops,
125         /// Our next-hop peer was offline or does not support onion message forwarding.
126         InvalidFirstHop,
127 }
128
129 impl<Signer: Sign, K: Deref, L: Deref> OnionMessenger<Signer, K, L>
130         where K::Target: KeysInterface<Signer = Signer>,
131               L::Target: Logger,
132 {
133         /// Constructs a new `OnionMessenger` to send, forward, and delegate received onion messages to
134         /// their respective handlers.
135         pub fn new(keys_manager: K, logger: L) -> Self {
136                 let mut secp_ctx = Secp256k1::new();
137                 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
138                 OnionMessenger {
139                         keys_manager,
140                         pending_messages: Mutex::new(HashMap::new()),
141                         secp_ctx,
142                         logger,
143                 }
144         }
145
146         /// Send an empty onion message to `destination`, routing it through `intermediate_nodes`.
147         /// See [`OnionMessenger`] for example usage.
148         pub fn send_onion_message(&self, intermediate_nodes: &[PublicKey], destination: Destination, reply_path: Option<BlindedRoute>) -> Result<(), SendError> {
149                 if let Destination::BlindedRoute(BlindedRoute { ref blinded_hops, .. }) = destination {
150                         if blinded_hops.len() < 2 {
151                                 return Err(SendError::TooFewBlindedHops);
152                         }
153                 }
154                 let blinding_secret_bytes = self.keys_manager.get_secure_random_bytes();
155                 let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
156                 let (introduction_node_id, blinding_point) = if intermediate_nodes.len() != 0 {
157                         (intermediate_nodes[0], PublicKey::from_secret_key(&self.secp_ctx, &blinding_secret))
158                 } else {
159                         match destination {
160                                 Destination::Node(pk) => (pk, PublicKey::from_secret_key(&self.secp_ctx, &blinding_secret)),
161                                 Destination::BlindedRoute(BlindedRoute { introduction_node_id, blinding_point, .. }) =>
162                                         (introduction_node_id, blinding_point),
163                         }
164                 };
165                 let (packet_payloads, packet_keys) = packet_payloads_and_keys(
166                         &self.secp_ctx, intermediate_nodes, destination, reply_path, &blinding_secret)
167                         .map_err(|e| SendError::Secp256k1(e))?;
168
169                 let prng_seed = self.keys_manager.get_secure_random_bytes();
170                 let onion_routing_packet = construct_onion_message_packet(
171                         packet_payloads, packet_keys, prng_seed).map_err(|()| SendError::TooBigPacket)?;
172
173                 let mut pending_per_peer_msgs = self.pending_messages.lock().unwrap();
174                 match pending_per_peer_msgs.entry(introduction_node_id) {
175                         hash_map::Entry::Vacant(_) => Err(SendError::InvalidFirstHop),
176                         hash_map::Entry::Occupied(mut e) => {
177                                 e.get_mut().push_back(msgs::OnionMessage { blinding_point, onion_routing_packet });
178                                 Ok(())
179                         }
180                 }
181         }
182
183         #[cfg(test)]
184         pub(super) fn release_pending_msgs(&self) -> HashMap<PublicKey, VecDeque<msgs::OnionMessage>> {
185                 let mut pending_msgs = self.pending_messages.lock().unwrap();
186                 let mut msgs = HashMap::new();
187                 // We don't want to disconnect the peers by removing them entirely from the original map, so we
188                 // swap the pending message buffers individually.
189                 for (peer_node_id, pending_messages) in &mut *pending_msgs {
190                         msgs.insert(*peer_node_id, core::mem::take(pending_messages));
191                 }
192                 msgs
193         }
194 }
195
196 impl<Signer: Sign, K: Deref, L: Deref> OnionMessageHandler for OnionMessenger<Signer, K, L>
197         where K::Target: KeysInterface<Signer = Signer>,
198               L::Target: Logger,
199 {
200         /// Handle an incoming onion message. Currently, if a message was destined for us we will log, but
201         /// soon we'll delegate the onion message to a handler that can generate invoices or send
202         /// payments.
203         fn handle_onion_message(&self, _peer_node_id: &PublicKey, msg: &msgs::OnionMessage) {
204                 let control_tlvs_ss = match self.keys_manager.ecdh(Recipient::Node, &msg.blinding_point, None) {
205                         Ok(ss) => ss,
206                         Err(e) =>  {
207                                 log_error!(self.logger, "Failed to retrieve node secret: {:?}", e);
208                                 return
209                         }
210                 };
211                 let onion_decode_ss = {
212                         let blinding_factor = {
213                                 let mut hmac = HmacEngine::<Sha256>::new(b"blinded_node_id");
214                                 hmac.input(control_tlvs_ss.as_ref());
215                                 Hmac::from_engine(hmac).into_inner()
216                         };
217                         match self.keys_manager.ecdh(Recipient::Node, &msg.onion_routing_packet.public_key,
218                                 Some(&Scalar::from_be_bytes(blinding_factor).unwrap()))
219                         {
220                                 Ok(ss) => ss.secret_bytes(),
221                                 Err(()) => {
222                                         log_trace!(self.logger, "Failed to compute onion packet shared secret");
223                                         return
224                                 }
225                         }
226                 };
227                 match onion_utils::decode_next_hop(onion_decode_ss, &msg.onion_routing_packet.hop_data[..],
228                         msg.onion_routing_packet.hmac, control_tlvs_ss)
229                 {
230                         Ok((Payload::Receive {
231                                 control_tlvs: ReceiveControlTlvs::Unblinded(ReceiveTlvs { path_id }), reply_path,
232                         }, None)) => {
233                                 log_info!(self.logger,
234                                         "Received an onion message with path_id: {:02x?} and {}reply_path",
235                                                 path_id, if reply_path.is_some() { "" } else { "no " });
236                         },
237                         Ok((Payload::Forward(ForwardControlTlvs::Unblinded(ForwardTlvs {
238                                 next_node_id, next_blinding_override
239                         })), Some((next_hop_hmac, new_packet_bytes)))) => {
240                                 // TODO: we need to check whether `next_node_id` is our node, in which case this is a dummy
241                                 // blinded hop and this onion message is destined for us. In this situation, we should keep
242                                 // unwrapping the onion layers to get to the final payload. Since we don't have the option
243                                 // of creating blinded routes with dummy hops currently, we should be ok to not handle this
244                                 // for now.
245                                 let new_pubkey = match onion_utils::next_hop_packet_pubkey(&self.secp_ctx, msg.onion_routing_packet.public_key, &onion_decode_ss) {
246                                         Ok(pk) => pk,
247                                         Err(e) => {
248                                                 log_trace!(self.logger, "Failed to compute next hop packet pubkey: {}", e);
249                                                 return
250                                         }
251                                 };
252                                 let outgoing_packet = Packet {
253                                         version: 0,
254                                         public_key: new_pubkey,
255                                         hop_data: new_packet_bytes,
256                                         hmac: next_hop_hmac,
257                                 };
258                                 let onion_message = msgs::OnionMessage {
259                                         blinding_point: match next_blinding_override {
260                                                 Some(blinding_point) => blinding_point,
261                                                 None => {
262                                                         let blinding_factor = {
263                                                                 let mut sha = Sha256::engine();
264                                                                 sha.input(&msg.blinding_point.serialize()[..]);
265                                                                 sha.input(control_tlvs_ss.as_ref());
266                                                                 Sha256::from_engine(sha).into_inner()
267                                                         };
268                                                         let next_blinding_point = msg.blinding_point;
269                                                         match next_blinding_point.mul_tweak(&self.secp_ctx, &Scalar::from_be_bytes(blinding_factor).unwrap()) {
270                                                                 Ok(bp) => bp,
271                                                                 Err(e) => {
272                                                                         log_trace!(self.logger, "Failed to compute next blinding point: {}", e);
273                                                                         return
274                                                                 }
275                                                         }
276                                                 },
277                                         },
278                                         onion_routing_packet: outgoing_packet,
279                                 };
280
281                                 let mut pending_per_peer_msgs = self.pending_messages.lock().unwrap();
282
283                                 #[cfg(fuzzing)]
284                                 pending_per_peer_msgs.entry(next_node_id).or_insert_with(VecDeque::new);
285
286                                 match pending_per_peer_msgs.entry(next_node_id) {
287                                         hash_map::Entry::Vacant(_) => {
288                                                 log_trace!(self.logger, "Dropping forwarded onion message to disconnected peer {:?}", next_node_id);
289                                                 return
290                                         },
291                                         hash_map::Entry::Occupied(mut e) => {
292                                                 e.get_mut().push_back(onion_message);
293                                                 log_trace!(self.logger, "Forwarding an onion message to peer {}", next_node_id);
294                                         }
295                                 };
296                         },
297                         Err(e) => {
298                                 log_trace!(self.logger, "Errored decoding onion message packet: {:?}", e);
299                         },
300                         _ => {
301                                 log_trace!(self.logger, "Received bogus onion message packet, either the sender encoded a final hop as a forwarding hop or vice versa");
302                         },
303                 };
304         }
305
306         fn peer_connected(&self, their_node_id: &PublicKey, init: &msgs::Init) {
307                 if init.features.supports_onion_messages() {
308                         let mut peers = self.pending_messages.lock().unwrap();
309                         peers.insert(their_node_id.clone(), VecDeque::new());
310                 }
311         }
312
313         fn peer_disconnected(&self, their_node_id: &PublicKey, _no_connection_possible: bool) {
314                 let mut pending_msgs = self.pending_messages.lock().unwrap();
315                 pending_msgs.remove(their_node_id);
316         }
317 }
318
319 impl<Signer: Sign, K: Deref, L: Deref> OnionMessageProvider for OnionMessenger<Signer, K, L>
320         where K::Target: KeysInterface<Signer = Signer>,
321               L::Target: Logger,
322 {
323         fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<msgs::OnionMessage> {
324                 let mut pending_msgs = self.pending_messages.lock().unwrap();
325                 if let Some(msgs) = pending_msgs.get_mut(&peer_node_id) {
326                         return msgs.pop_front()
327                 }
328                 None
329         }
330 }
331
332 // TODO: parameterize the below Simple* types with OnionMessenger and handle the messages it
333 // produces
334 /// Useful for simplifying the parameters of [`SimpleArcChannelManager`] and
335 /// [`SimpleArcPeerManager`]. See their docs for more details.
336 ///
337 ///[`SimpleArcChannelManager`]: crate::ln::channelmanager::SimpleArcChannelManager
338 ///[`SimpleArcPeerManager`]: crate::ln::peer_handler::SimpleArcPeerManager
339 pub type SimpleArcOnionMessenger<L> = OnionMessenger<InMemorySigner, Arc<KeysManager>, Arc<L>>;
340 /// Useful for simplifying the parameters of [`SimpleRefChannelManager`] and
341 /// [`SimpleRefPeerManager`]. See their docs for more details.
342 ///
343 ///[`SimpleRefChannelManager`]: crate::ln::channelmanager::SimpleRefChannelManager
344 ///[`SimpleRefPeerManager`]: crate::ln::peer_handler::SimpleRefPeerManager
345 pub type SimpleRefOnionMessenger<'a, 'b, L> = OnionMessenger<InMemorySigner, &'a KeysManager, &'b L>;
346
347 /// Construct onion packet payloads and keys for sending an onion message along the given
348 /// `unblinded_path` to the given `destination`.
349 fn packet_payloads_and_keys<T: secp256k1::Signing + secp256k1::Verification>(
350         secp_ctx: &Secp256k1<T>, unblinded_path: &[PublicKey], destination: Destination, mut reply_path:
351         Option<BlindedRoute>, session_priv: &SecretKey
352 ) -> Result<(Vec<(Payload, [u8; 32])>, Vec<onion_utils::OnionKeys>), secp256k1::Error> {
353         let num_hops = unblinded_path.len() + destination.num_hops();
354         let mut payloads = Vec::with_capacity(num_hops);
355         let mut onion_packet_keys = Vec::with_capacity(num_hops);
356
357         let (mut intro_node_id_blinding_pt, num_blinded_hops) = if let Destination::BlindedRoute(BlindedRoute {
358                 introduction_node_id, blinding_point, blinded_hops }) = &destination {
359                 (Some((*introduction_node_id, *blinding_point)), blinded_hops.len()) } else { (None, 0) };
360         let num_unblinded_hops = num_hops - num_blinded_hops;
361
362         let mut unblinded_path_idx = 0;
363         let mut blinded_path_idx = 0;
364         let mut prev_control_tlvs_ss = None;
365         utils::construct_keys_callback(secp_ctx, unblinded_path, Some(destination), session_priv, |_, onion_packet_ss, ephemeral_pubkey, control_tlvs_ss, unblinded_pk_opt, enc_payload_opt| {
366                 if num_unblinded_hops != 0 && unblinded_path_idx < num_unblinded_hops {
367                         if let Some(ss) = prev_control_tlvs_ss.take() {
368                                 payloads.push((Payload::Forward(ForwardControlTlvs::Unblinded(
369                                         ForwardTlvs {
370                                                 next_node_id: unblinded_pk_opt.unwrap(),
371                                                 next_blinding_override: None,
372                                         }
373                                 )), ss));
374                         }
375                         prev_control_tlvs_ss = Some(control_tlvs_ss);
376                         unblinded_path_idx += 1;
377                 } else if let Some((intro_node_id, blinding_pt)) = intro_node_id_blinding_pt.take() {
378                         if let Some(control_tlvs_ss) = prev_control_tlvs_ss.take() {
379                                 payloads.push((Payload::Forward(ForwardControlTlvs::Unblinded(ForwardTlvs {
380                                         next_node_id: intro_node_id,
381                                         next_blinding_override: Some(blinding_pt),
382                                 })), control_tlvs_ss));
383                         }
384                         if let Some(encrypted_payload) = enc_payload_opt {
385                                 payloads.push((Payload::Forward(ForwardControlTlvs::Blinded(encrypted_payload)),
386                                         control_tlvs_ss));
387                         } else { debug_assert!(false); }
388                         blinded_path_idx += 1;
389                 } else if blinded_path_idx < num_blinded_hops - 1 && enc_payload_opt.is_some() {
390                         payloads.push((Payload::Forward(ForwardControlTlvs::Blinded(enc_payload_opt.unwrap())),
391                                 control_tlvs_ss));
392                         blinded_path_idx += 1;
393                 } else if let Some(encrypted_payload) = enc_payload_opt {
394                         payloads.push((Payload::Receive {
395                                 control_tlvs: ReceiveControlTlvs::Blinded(encrypted_payload),
396                                 reply_path: reply_path.take(),
397                         }, control_tlvs_ss));
398                 }
399
400                 let (rho, mu) = onion_utils::gen_rho_mu_from_shared_secret(onion_packet_ss.as_ref());
401                 onion_packet_keys.push(onion_utils::OnionKeys {
402                         #[cfg(test)]
403                         shared_secret: onion_packet_ss,
404                         #[cfg(test)]
405                         blinding_factor: [0; 32],
406                         ephemeral_pubkey,
407                         rho,
408                         mu,
409                 });
410         })?;
411
412         if let Some(control_tlvs_ss) = prev_control_tlvs_ss {
413                 payloads.push((Payload::Receive {
414                         control_tlvs: ReceiveControlTlvs::Unblinded(ReceiveTlvs { path_id: None, }),
415                         reply_path: reply_path.take(),
416                 }, control_tlvs_ss));
417         }
418
419         Ok((payloads, onion_packet_keys))
420 }
421
422 /// Errors if the serialized payload size exceeds onion_message::BIG_PACKET_HOP_DATA_LEN
423 fn construct_onion_message_packet(payloads: Vec<(Payload, [u8; 32])>, onion_keys: Vec<onion_utils::OnionKeys>, prng_seed: [u8; 32]) -> Result<Packet, ()> {
424         // Spec rationale:
425         // "`len` allows larger messages to be sent than the standard 1300 bytes allowed for an HTLC
426         // onion, but this should be used sparingly as it is reduces anonymity set, hence the
427         // recommendation that it either look like an HTLC onion, or if larger, be a fixed size."
428         let payloads_ser_len = onion_utils::payloads_serialized_length(&payloads);
429         let hop_data_len = if payloads_ser_len <= SMALL_PACKET_HOP_DATA_LEN {
430                 SMALL_PACKET_HOP_DATA_LEN
431         } else if payloads_ser_len <= BIG_PACKET_HOP_DATA_LEN {
432                 BIG_PACKET_HOP_DATA_LEN
433         } else { return Err(()) };
434
435         Ok(onion_utils::construct_onion_message_packet::<_, _>(
436                 payloads, onion_keys, prng_seed, hop_data_len))
437 }