Implement receiving and forwarding onion messages
[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, Secp256k1, SecretKey};
17
18 use chain::keysinterface::{InMemorySigner, KeysInterface, KeysManager, Recipient, Sign};
19 use ln::msgs;
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::logger::Logger;
25
26 use core::ops::Deref;
27 use sync::{Arc, Mutex};
28 use prelude::*;
29
30 /// A sender, receiver and forwarder of onion messages. In upcoming releases, this object will be
31 /// used to retrieve invoices and fulfill invoice requests from [offers].
32 ///
33 /// [offers]: <https://github.com/lightning/bolts/pull/798>
34 pub struct OnionMessenger<Signer: Sign, K: Deref, L: Deref>
35         where K::Target: KeysInterface<Signer = Signer>,
36               L::Target: Logger,
37 {
38         keys_manager: K,
39         logger: L,
40         pending_messages: Mutex<HashMap<PublicKey, Vec<msgs::OnionMessage>>>,
41         secp_ctx: Secp256k1<secp256k1::All>,
42         // Coming soon:
43         // invoice_handler: InvoiceHandler,
44         // custom_handler: CustomHandler, // handles custom onion messages
45 }
46
47 /// The destination of an onion message.
48 pub enum Destination {
49         /// We're sending this onion message to a node.
50         Node(PublicKey),
51         /// We're sending this onion message to a blinded route.
52         BlindedRoute(BlindedRoute),
53 }
54
55 impl Destination {
56         pub(super) fn num_hops(&self) -> usize {
57                 match self {
58                         Destination::Node(_) => 1,
59                         Destination::BlindedRoute(BlindedRoute { blinded_hops, .. }) => blinded_hops.len(),
60                 }
61         }
62 }
63
64 impl<Signer: Sign, K: Deref, L: Deref> OnionMessenger<Signer, K, L>
65         where K::Target: KeysInterface<Signer = Signer>,
66               L::Target: Logger,
67 {
68         /// Constructs a new `OnionMessenger` to send, forward, and delegate received onion messages to
69         /// their respective handlers.
70         pub fn new(keys_manager: K, logger: L) -> Self {
71                 let mut secp_ctx = Secp256k1::new();
72                 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
73                 OnionMessenger {
74                         keys_manager,
75                         pending_messages: Mutex::new(HashMap::new()),
76                         secp_ctx,
77                         logger,
78                 }
79         }
80
81         /// Send an empty onion message to `destination`, routing it through `intermediate_nodes`.
82         pub fn send_onion_message(&self, intermediate_nodes: &[PublicKey], destination: Destination) -> Result<(), secp256k1::Error> {
83                 let blinding_secret_bytes = self.keys_manager.get_secure_random_bytes();
84                 let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
85                 let (introduction_node_id, blinding_point) = if intermediate_nodes.len() != 0 {
86                         (intermediate_nodes[0], PublicKey::from_secret_key(&self.secp_ctx, &blinding_secret))
87                 } else {
88                         match destination {
89                                 Destination::Node(pk) => (pk, PublicKey::from_secret_key(&self.secp_ctx, &blinding_secret)),
90                                 Destination::BlindedRoute(BlindedRoute { introduction_node_id, blinding_point, .. }) =>
91                                         (introduction_node_id, blinding_point),
92                         }
93                 };
94                 let (packet_payloads, packet_keys) = packet_payloads_and_keys(
95                         &self.secp_ctx, intermediate_nodes, destination, &blinding_secret)?;
96
97                 let prng_seed = self.keys_manager.get_secure_random_bytes();
98                 let onion_packet = construct_onion_message_packet(packet_payloads, packet_keys, prng_seed);
99
100                 let mut pending_per_peer_msgs = self.pending_messages.lock().unwrap();
101                 let pending_msgs = pending_per_peer_msgs.entry(introduction_node_id).or_insert(Vec::new());
102                 pending_msgs.push(
103                         msgs::OnionMessage {
104                                 blinding_point,
105                                 onion_routing_packet: onion_packet,
106                         }
107                 );
108                 Ok(())
109         }
110
111         /// Handle an incoming onion message. Currently, if a message was destined for us we will log, but
112         /// soon we'll delegate the onion message to a handler that can generate invoices or send
113         /// payments.
114         pub fn handle_onion_message(&self, _peer_node_id: &PublicKey, msg: &msgs::OnionMessage) {
115                 let control_tlvs_ss = match self.keys_manager.ecdh(Recipient::Node, &msg.blinding_point, None) {
116                         Ok(ss) => ss,
117                         Err(e) =>  {
118                                 log_error!(self.logger, "Failed to retrieve node secret: {:?}", e);
119                                 return
120                         }
121                 };
122                 let onion_decode_ss = {
123                         let blinding_factor = {
124                                 let mut hmac = HmacEngine::<Sha256>::new(b"blinded_node_id");
125                                 hmac.input(control_tlvs_ss.as_ref());
126                                 Hmac::from_engine(hmac).into_inner()
127                         };
128                         match self.keys_manager.ecdh(Recipient::Node, &msg.onion_routing_packet.public_key,
129                                 Some(&blinding_factor))
130                         {
131                                 Ok(ss) => ss.secret_bytes(),
132                                 Err(()) => {
133                                         log_trace!(self.logger, "Failed to compute onion packet shared secret");
134                                         return
135                                 }
136                         }
137                 };
138                 match onion_utils::decode_next_hop(onion_decode_ss, &msg.onion_routing_packet.hop_data[..],
139                         msg.onion_routing_packet.hmac, control_tlvs_ss)
140                 {
141                         Ok((Payload::Receive {
142                                 control_tlvs: ReceiveControlTlvs::Unblinded(ReceiveTlvs { path_id })
143                         }, None)) => {
144                                 log_info!(self.logger, "Received an onion message with path_id: {:02x?}", path_id);
145                         },
146                         Ok((Payload::Forward(ForwardControlTlvs::Unblinded(ForwardTlvs {
147                                 next_node_id, next_blinding_override
148                         })), Some((next_hop_hmac, new_packet_bytes)))) => {
149                                 // TODO: we need to check whether `next_node_id` is our node, in which case this is a dummy
150                                 // blinded hop and this onion message is destined for us. In this situation, we should keep
151                                 // unwrapping the onion layers to get to the final payload. Since we don't have the option
152                                 // of creating blinded routes with dummy hops currently, we should be ok to not handle this
153                                 // for now.
154                                 let new_pubkey = match onion_utils::next_hop_packet_pubkey(&self.secp_ctx, msg.onion_routing_packet.public_key, &onion_decode_ss) {
155                                         Ok(pk) => pk,
156                                         Err(e) => {
157                                                 log_trace!(self.logger, "Failed to compute next hop packet pubkey: {}", e);
158                                                 return
159                                         }
160                                 };
161                                 let outgoing_packet = Packet {
162                                         version: 0,
163                                         public_key: new_pubkey,
164                                         hop_data: new_packet_bytes,
165                                         hmac: next_hop_hmac,
166                                 };
167
168                                 let mut pending_per_peer_msgs = self.pending_messages.lock().unwrap();
169                                 let pending_msgs = pending_per_peer_msgs.entry(next_node_id).or_insert(Vec::new());
170                                 pending_msgs.push(
171                                         msgs::OnionMessage {
172                                                 blinding_point: match next_blinding_override {
173                                                         Some(blinding_point) => blinding_point,
174                                                         None => {
175                                                                 let blinding_factor = {
176                                                                         let mut sha = Sha256::engine();
177                                                                         sha.input(&msg.blinding_point.serialize()[..]);
178                                                                         sha.input(control_tlvs_ss.as_ref());
179                                                                         Sha256::from_engine(sha).into_inner()
180                                                                 };
181                                                                 let mut next_blinding_point = msg.blinding_point;
182                                                                 if let Err(e) = next_blinding_point.mul_assign(&self.secp_ctx, &blinding_factor[..]) {
183                                                                         log_trace!(self.logger, "Failed to compute next blinding point: {}", e);
184                                                                         return
185                                                                 }
186                                                                 next_blinding_point
187                                                         },
188                                                 },
189                                                 onion_routing_packet: outgoing_packet,
190                                         },
191                                 );
192                         },
193                         Err(e) => {
194                                 log_trace!(self.logger, "Errored decoding onion message packet: {:?}", e);
195                         },
196                         _ => {
197                                 log_trace!(self.logger, "Received bogus onion message packet, either the sender encoded a final hop as a forwarding hop or vice versa");
198                         },
199                 };
200         }
201 }
202
203 // TODO: parameterize the below Simple* types with OnionMessenger and handle the messages it
204 // produces
205 /// Useful for simplifying the parameters of [`SimpleArcChannelManager`] and
206 /// [`SimpleArcPeerManager`]. See their docs for more details.
207 ///
208 ///[`SimpleArcChannelManager`]: crate::ln::channelmanager::SimpleArcChannelManager
209 ///[`SimpleArcPeerManager`]: crate::ln::peer_handler::SimpleArcPeerManager
210 pub type SimpleArcOnionMessenger<L> = OnionMessenger<InMemorySigner, Arc<KeysManager>, Arc<L>>;
211 /// Useful for simplifying the parameters of [`SimpleRefChannelManager`] and
212 /// [`SimpleRefPeerManager`]. See their docs for more details.
213 ///
214 ///[`SimpleRefChannelManager`]: crate::ln::channelmanager::SimpleRefChannelManager
215 ///[`SimpleRefPeerManager`]: crate::ln::peer_handler::SimpleRefPeerManager
216 pub type SimpleRefOnionMessenger<'a, 'b, L> = OnionMessenger<InMemorySigner, &'a KeysManager, &'b L>;
217
218 /// Construct onion packet payloads and keys for sending an onion message along the given
219 /// `unblinded_path` to the given `destination`.
220 fn packet_payloads_and_keys<T: secp256k1::Signing + secp256k1::Verification>(
221         secp_ctx: &Secp256k1<T>, unblinded_path: &[PublicKey], destination: Destination, session_priv: &SecretKey
222 ) -> Result<(Vec<(Payload, [u8; 32])>, Vec<onion_utils::OnionKeys>), secp256k1::Error> {
223         let num_hops = unblinded_path.len() + destination.num_hops();
224         let mut payloads = Vec::with_capacity(num_hops);
225         let mut onion_packet_keys = Vec::with_capacity(num_hops);
226
227         let (mut intro_node_id_blinding_pt, num_blinded_hops) = if let Destination::BlindedRoute(BlindedRoute {
228                 introduction_node_id, blinding_point, blinded_hops }) = &destination {
229                 (Some((*introduction_node_id, *blinding_point)), blinded_hops.len()) } else { (None, 0) };
230         let num_unblinded_hops = num_hops - num_blinded_hops;
231
232         let mut unblinded_path_idx = 0;
233         let mut blinded_path_idx = 0;
234         let mut prev_control_tlvs_ss = None;
235         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| {
236                 if num_unblinded_hops != 0 && unblinded_path_idx < num_unblinded_hops {
237                         if let Some(ss) = prev_control_tlvs_ss.take() {
238                                 payloads.push((Payload::Forward(ForwardControlTlvs::Unblinded(
239                                         ForwardTlvs {
240                                                 next_node_id: unblinded_pk_opt.unwrap(),
241                                                 next_blinding_override: None,
242                                         }
243                                 )), ss));
244                         }
245                         prev_control_tlvs_ss = Some(control_tlvs_ss);
246                         unblinded_path_idx += 1;
247                 } else if let Some((intro_node_id, blinding_pt)) = intro_node_id_blinding_pt.take() {
248                         if let Some(control_tlvs_ss) = prev_control_tlvs_ss.take() {
249                                 payloads.push((Payload::Forward(ForwardControlTlvs::Unblinded(ForwardTlvs {
250                                         next_node_id: intro_node_id,
251                                         next_blinding_override: Some(blinding_pt),
252                                 })), control_tlvs_ss));
253                         }
254                         if let Some(encrypted_payload) = enc_payload_opt {
255                                 payloads.push((Payload::Forward(ForwardControlTlvs::Blinded(encrypted_payload)),
256                                         control_tlvs_ss));
257                         } else { debug_assert!(false); }
258                         blinded_path_idx += 1;
259                 } else if blinded_path_idx < num_blinded_hops - 1 && enc_payload_opt.is_some() {
260                         payloads.push((Payload::Forward(ForwardControlTlvs::Blinded(enc_payload_opt.unwrap())),
261                                 control_tlvs_ss));
262                         blinded_path_idx += 1;
263                 } else if let Some(encrypted_payload) = enc_payload_opt {
264                         payloads.push((Payload::Receive {
265                                 control_tlvs: ReceiveControlTlvs::Blinded(encrypted_payload),
266                         }, control_tlvs_ss));
267                 }
268
269                 let (rho, mu) = onion_utils::gen_rho_mu_from_shared_secret(onion_packet_ss.as_ref());
270                 onion_packet_keys.push(onion_utils::OnionKeys {
271                         #[cfg(test)]
272                         shared_secret: onion_packet_ss,
273                         #[cfg(test)]
274                         blinding_factor: [0; 32],
275                         ephemeral_pubkey,
276                         rho,
277                         mu,
278                 });
279         })?;
280
281         if let Some(control_tlvs_ss) = prev_control_tlvs_ss {
282                 payloads.push((Payload::Receive {
283                         control_tlvs: ReceiveControlTlvs::Unblinded(ReceiveTlvs { path_id: None, })
284                 }, control_tlvs_ss));
285         }
286
287         Ok((payloads, onion_packet_keys))
288 }
289
290 fn construct_onion_message_packet(payloads: Vec<(Payload, [u8; 32])>, onion_keys: Vec<onion_utils::OnionKeys>, prng_seed: [u8; 32]) -> Packet {
291         // Spec rationale:
292         // "`len` allows larger messages to be sent than the standard 1300 bytes allowed for an HTLC
293         // onion, but this should be used sparingly as it is reduces anonymity set, hence the
294         // recommendation that it either look like an HTLC onion, or if larger, be a fixed size."
295         let payloads_ser_len = onion_utils::payloads_serialized_length(&payloads);
296         let hop_data_len = if payloads_ser_len <= SMALL_PACKET_HOP_DATA_LEN {
297                 SMALL_PACKET_HOP_DATA_LEN
298         } else if payloads_ser_len <= BIG_PACKET_HOP_DATA_LEN {
299                 BIG_PACKET_HOP_DATA_LEN
300         } else { payloads_ser_len };
301
302         onion_utils::construct_onion_message_packet::<_, _>(payloads, onion_keys, prng_seed, hop_data_len)
303 }