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