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