Implement non-strict forwarding
[rust-lightning] / lightning / src / blinded_path / mod.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 //! Creating blinded paths and related utilities live here.
11
12 pub mod payment;
13 pub mod message;
14 pub(crate) mod utils;
15
16 use bitcoin::secp256k1::{self, PublicKey, Secp256k1, SecretKey};
17 use core::ops::Deref;
18
19 use crate::ln::msgs::DecodeError;
20 use crate::offers::invoice::BlindedPayInfo;
21 use crate::routing::gossip::{NodeId, ReadOnlyNetworkGraph};
22 use crate::sign::EntropySource;
23 use crate::util::ser::{Readable, Writeable, Writer};
24 use crate::util::scid_utils;
25
26 use crate::io;
27 use crate::prelude::*;
28
29 /// The next hop to forward an onion message along its path.
30 ///
31 /// Note that payment blinded paths always specify their next hop using an explicit node id.
32 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
33 pub enum NextMessageHop {
34         /// The node id of the next hop.
35         NodeId(PublicKey),
36         /// The short channel id leading to the next hop.
37         ShortChannelId(u64),
38 }
39
40 /// Onion messages and payments can be sent and received to blinded paths, which serve to hide the
41 /// identity of the recipient.
42 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
43 pub struct BlindedPath {
44         /// To send to a blinded path, the sender first finds a route to the unblinded
45         /// `introduction_node`, which can unblind its [`encrypted_payload`] to find out the onion
46         /// message or payment's next hop and forward it along.
47         ///
48         /// [`encrypted_payload`]: BlindedHop::encrypted_payload
49         pub introduction_node: IntroductionNode,
50         /// Used by the introduction node to decrypt its [`encrypted_payload`] to forward the onion
51         /// message or payment.
52         ///
53         /// [`encrypted_payload`]: BlindedHop::encrypted_payload
54         pub blinding_point: PublicKey,
55         /// The hops composing the blinded path.
56         pub blinded_hops: Vec<BlindedHop>,
57 }
58
59 /// The unblinded node in a [`BlindedPath`].
60 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
61 pub enum IntroductionNode {
62         /// The node id of the introduction node.
63         NodeId(PublicKey),
64         /// The short channel id of the channel leading to the introduction node. The [`Direction`]
65         /// identifies which side of the channel is the introduction node.
66         DirectedShortChannelId(Direction, u64),
67 }
68
69 /// The side of a channel that is the [`IntroductionNode`] in a [`BlindedPath`]. [BOLT 7] defines
70 /// which nodes is which in the [`ChannelAnnouncement`] message.
71 ///
72 /// [BOLT 7]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_announcement-message
73 /// [`ChannelAnnouncement`]: crate::ln::msgs::ChannelAnnouncement
74 #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
75 pub enum Direction {
76         /// The lesser node id when compared lexicographically in ascending order.
77         NodeOne,
78         /// The greater node id when compared lexicographically in ascending order.
79         NodeTwo,
80 }
81
82 /// An interface for looking up the node id of a channel counterparty for the purpose of forwarding
83 /// an [`OnionMessage`].
84 ///
85 /// [`OnionMessage`]: crate::ln::msgs::OnionMessage
86 pub trait NodeIdLookUp {
87         /// Returns the node id of the forwarding node's channel counterparty with `short_channel_id`.
88         ///
89         /// Here, the forwarding node is referring to the node of the [`OnionMessenger`] parameterized
90         /// by the [`NodeIdLookUp`] and the counterparty to one of that node's peers.
91         ///
92         /// [`OnionMessenger`]: crate::onion_message::messenger::OnionMessenger
93         fn next_node_id(&self, short_channel_id: u64) -> Option<PublicKey>;
94 }
95
96 /// A [`NodeIdLookUp`] that always returns `None`.
97 pub struct EmptyNodeIdLookUp {}
98
99 impl NodeIdLookUp for EmptyNodeIdLookUp {
100         fn next_node_id(&self, _short_channel_id: u64) -> Option<PublicKey> {
101                 None
102         }
103 }
104
105 impl Deref for EmptyNodeIdLookUp {
106         type Target = EmptyNodeIdLookUp;
107         fn deref(&self) -> &Self { self }
108 }
109
110 /// An encrypted payload and node id corresponding to a hop in a payment or onion message path, to
111 /// be encoded in the sender's onion packet. These hops cannot be identified by outside observers
112 /// and thus can be used to hide the identity of the recipient.
113 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
114 pub struct BlindedHop {
115         /// The blinded node id of this hop in a [`BlindedPath`].
116         pub blinded_node_id: PublicKey,
117         /// The encrypted payload intended for this hop in a [`BlindedPath`].
118         // The node sending to this blinded path will later encode this payload into the onion packet for
119         // this hop.
120         pub encrypted_payload: Vec<u8>,
121 }
122
123 impl BlindedPath {
124         /// Create a one-hop blinded path for a message.
125         pub fn one_hop_for_message<ES: Deref, T: secp256k1::Signing + secp256k1::Verification>(
126                 recipient_node_id: PublicKey, entropy_source: ES, secp_ctx: &Secp256k1<T>
127         ) -> Result<Self, ()> where ES::Target: EntropySource {
128                 Self::new_for_message(&[], recipient_node_id, entropy_source, secp_ctx)
129         }
130
131         /// Create a blinded path for an onion message, to be forwarded along `node_pks`. The last node
132         /// pubkey in `node_pks` will be the destination node.
133         ///
134         /// Errors if no hops are provided or if `node_pk`(s) are invalid.
135         //  TODO: make all payloads the same size with padding + add dummy hops
136         pub fn new_for_message<ES: Deref, T: secp256k1::Signing + secp256k1::Verification>(
137                 intermediate_nodes: &[message::ForwardNode], recipient_node_id: PublicKey,
138                 entropy_source: ES, secp_ctx: &Secp256k1<T>
139         ) -> Result<Self, ()> where ES::Target: EntropySource {
140                 let introduction_node = IntroductionNode::NodeId(
141                         intermediate_nodes.first().map_or(recipient_node_id, |n| n.node_id)
142                 );
143                 let blinding_secret_bytes = entropy_source.get_secure_random_bytes();
144                 let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
145
146                 Ok(BlindedPath {
147                         introduction_node,
148                         blinding_point: PublicKey::from_secret_key(secp_ctx, &blinding_secret),
149                         blinded_hops: message::blinded_hops(
150                                 secp_ctx, intermediate_nodes, recipient_node_id, &blinding_secret,
151                         ).map_err(|_| ())?,
152                 })
153         }
154
155         /// Create a one-hop blinded path for a payment.
156         pub fn one_hop_for_payment<ES: Deref, T: secp256k1::Signing + secp256k1::Verification>(
157                 payee_node_id: PublicKey, payee_tlvs: payment::ReceiveTlvs, min_final_cltv_expiry_delta: u16,
158                 entropy_source: ES, secp_ctx: &Secp256k1<T>
159         ) -> Result<(BlindedPayInfo, Self), ()> where ES::Target: EntropySource {
160                 // This value is not considered in pathfinding for 1-hop blinded paths, because it's intended to
161                 // be in relation to a specific channel.
162                 let htlc_maximum_msat = u64::max_value();
163                 Self::new_for_payment(
164                         &[], payee_node_id, payee_tlvs, htlc_maximum_msat, min_final_cltv_expiry_delta,
165                         entropy_source, secp_ctx
166                 )
167         }
168
169         /// Create a blinded path for a payment, to be forwarded along `intermediate_nodes`.
170         ///
171         /// Errors if:
172         /// * a provided node id is invalid
173         /// * [`BlindedPayInfo`] calculation results in an integer overflow
174         /// * any unknown features are required in the provided [`ForwardTlvs`]
175         ///
176         /// [`ForwardTlvs`]: crate::blinded_path::payment::ForwardTlvs
177         //  TODO: make all payloads the same size with padding + add dummy hops
178         pub fn new_for_payment<ES: Deref, T: secp256k1::Signing + secp256k1::Verification>(
179                 intermediate_nodes: &[payment::ForwardNode], payee_node_id: PublicKey,
180                 payee_tlvs: payment::ReceiveTlvs, htlc_maximum_msat: u64, min_final_cltv_expiry_delta: u16,
181                 entropy_source: ES, secp_ctx: &Secp256k1<T>
182         ) -> Result<(BlindedPayInfo, Self), ()> where ES::Target: EntropySource {
183                 let introduction_node = IntroductionNode::NodeId(
184                         intermediate_nodes.first().map_or(payee_node_id, |n| n.node_id)
185                 );
186                 let blinding_secret_bytes = entropy_source.get_secure_random_bytes();
187                 let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
188
189                 let blinded_payinfo = payment::compute_payinfo(
190                         intermediate_nodes, &payee_tlvs, htlc_maximum_msat, min_final_cltv_expiry_delta
191                 )?;
192                 Ok((blinded_payinfo, BlindedPath {
193                         introduction_node,
194                         blinding_point: PublicKey::from_secret_key(secp_ctx, &blinding_secret),
195                         blinded_hops: payment::blinded_hops(
196                                 secp_ctx, intermediate_nodes, payee_node_id, payee_tlvs, &blinding_secret
197                         ).map_err(|_| ())?,
198                 }))
199         }
200
201         /// Returns the introduction [`NodeId`] of the blinded path, if it is publicly reachable (i.e.,
202         /// it is found in the network graph).
203         pub fn public_introduction_node_id<'a>(
204                 &self, network_graph: &'a ReadOnlyNetworkGraph
205         ) -> Option<&'a NodeId> {
206                 match &self.introduction_node {
207                         IntroductionNode::NodeId(pubkey) => {
208                                 let node_id = NodeId::from_pubkey(pubkey);
209                                 network_graph.nodes().get_key_value(&node_id).map(|(key, _)| key)
210                         },
211                         IntroductionNode::DirectedShortChannelId(direction, scid) => {
212                                 network_graph
213                                         .channel(*scid)
214                                         .map(|c| match direction {
215                                                 Direction::NodeOne => &c.node_one,
216                                                 Direction::NodeTwo => &c.node_two,
217                                         })
218                         },
219                 }
220         }
221
222         /// Attempts to a use a compact representation for the [`IntroductionNode`] by using a directed
223         /// short channel id from a channel in `network_graph` leading to the introduction node.
224         ///
225         /// While this may result in a smaller encoding, there is a trade off in that the path may
226         /// become invalid if the channel is closed or hasn't been propagated via gossip. Therefore,
227         /// calling this may not be suitable for long-lived blinded paths.
228         pub fn use_compact_introduction_node(&mut self, network_graph: &ReadOnlyNetworkGraph) {
229                 if let IntroductionNode::NodeId(pubkey) = &self.introduction_node {
230                         let node_id = NodeId::from_pubkey(pubkey);
231                         if let Some(node_info) = network_graph.node(&node_id) {
232                                 if let Some((scid, channel_info)) = node_info
233                                         .channels
234                                         .iter()
235                                         .filter_map(|scid| network_graph.channel(*scid).map(|info| (*scid, info)))
236                                         .min_by_key(|(scid, _)| scid_utils::block_from_scid(*scid))
237                                 {
238                                         let direction = if node_id == channel_info.node_one {
239                                                 Direction::NodeOne
240                                         } else {
241                                                 debug_assert_eq!(node_id, channel_info.node_two);
242                                                 Direction::NodeTwo
243                                         };
244                                         self.introduction_node =
245                                                 IntroductionNode::DirectedShortChannelId(direction, scid);
246                                 }
247                         }
248                 }
249         }
250 }
251
252 impl Writeable for BlindedPath {
253         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
254                 match &self.introduction_node {
255                         IntroductionNode::NodeId(pubkey) => pubkey.write(w)?,
256                         IntroductionNode::DirectedShortChannelId(direction, scid) => {
257                                 match direction {
258                                         Direction::NodeOne => 0u8.write(w)?,
259                                         Direction::NodeTwo => 1u8.write(w)?,
260                                 }
261                                 scid.write(w)?;
262                         },
263                 }
264
265                 self.blinding_point.write(w)?;
266                 (self.blinded_hops.len() as u8).write(w)?;
267                 for hop in &self.blinded_hops {
268                         hop.write(w)?;
269                 }
270                 Ok(())
271         }
272 }
273
274 impl Readable for BlindedPath {
275         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
276                 let mut first_byte: u8 = Readable::read(r)?;
277                 let introduction_node = match first_byte {
278                         0 => IntroductionNode::DirectedShortChannelId(Direction::NodeOne, Readable::read(r)?),
279                         1 => IntroductionNode::DirectedShortChannelId(Direction::NodeTwo, Readable::read(r)?),
280                         2|3 => {
281                                 use io::Read;
282                                 let mut pubkey_read = core::slice::from_mut(&mut first_byte).chain(r.by_ref());
283                                 IntroductionNode::NodeId(Readable::read(&mut pubkey_read)?)
284                         },
285                         _ => return Err(DecodeError::InvalidValue),
286                 };
287                 let blinding_point = Readable::read(r)?;
288                 let num_hops: u8 = Readable::read(r)?;
289                 if num_hops == 0 { return Err(DecodeError::InvalidValue) }
290                 let mut blinded_hops: Vec<BlindedHop> = Vec::with_capacity(num_hops.into());
291                 for _ in 0..num_hops {
292                         blinded_hops.push(Readable::read(r)?);
293                 }
294                 Ok(BlindedPath {
295                         introduction_node,
296                         blinding_point,
297                         blinded_hops,
298                 })
299         }
300 }
301
302 impl_writeable!(BlindedHop, {
303         blinded_node_id,
304         encrypted_payload
305 });
306
307 impl Direction {
308         /// Returns the [`NodeId`] from the inputs corresponding to the direction.
309         pub fn select_node_id<'a>(&self, node_a: &'a NodeId, node_b: &'a NodeId) -> &'a NodeId {
310                 match self {
311                         Direction::NodeOne => core::cmp::min(node_a, node_b),
312                         Direction::NodeTwo => core::cmp::max(node_a, node_b),
313                 }
314         }
315
316         /// Returns the [`PublicKey`] from the inputs corresponding to the direction.
317         pub fn select_pubkey<'a>(&self, node_a: &'a PublicKey, node_b: &'a PublicKey) -> &'a PublicKey {
318                 let (node_one, node_two) = if NodeId::from_pubkey(node_a) < NodeId::from_pubkey(node_b) {
319                         (node_a, node_b)
320                 } else {
321                         (node_b, node_a)
322                 };
323                 match self {
324                         Direction::NodeOne => node_one,
325                         Direction::NodeTwo => node_two,
326                 }
327         }
328 }