1 // This file is Copyright its original authors, visible in version control
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
10 //! Creating blinded paths and related utilities live here.
16 use bitcoin::secp256k1::{self, PublicKey, Secp256k1, SecretKey};
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;
27 use crate::prelude::*;
29 /// The next hop to forward an onion message along its path.
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.
36 /// The short channel id leading to the next hop.
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.
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.
53 /// [`encrypted_payload`]: BlindedHop::encrypted_payload
54 pub blinding_point: PublicKey,
55 /// The hops composing the blinded path.
56 pub blinded_hops: Vec<BlindedHop>,
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.
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),
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.
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)]
76 /// The lesser node id when compared lexicographically in ascending order.
78 /// The greater node id when compared lexicographically in ascending order.
82 /// An interface for looking up the node id of a channel counterparty for the purpose of forwarding
83 /// an [`OnionMessage`].
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`.
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.
92 /// [`OnionMessenger`]: crate::onion_message::messenger::OnionMessenger
93 fn next_node_id(&self, short_channel_id: u64) -> Option<PublicKey>;
96 /// A [`NodeIdLookUp`] that always returns `None`.
97 pub struct EmptyNodeIdLookUp {}
99 impl NodeIdLookUp for EmptyNodeIdLookUp {
100 fn next_node_id(&self, _short_channel_id: u64) -> Option<PublicKey> {
105 impl Deref for EmptyNodeIdLookUp {
106 type Target = EmptyNodeIdLookUp;
107 fn deref(&self) -> &Self { self }
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
120 pub encrypted_payload: Vec<u8>,
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)
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.
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)
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");
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,
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
169 /// Create a blinded path for a payment, to be forwarded along `intermediate_nodes`.
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`]
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)
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");
189 let blinded_payinfo = payment::compute_payinfo(
190 intermediate_nodes, &payee_tlvs, htlc_maximum_msat, min_final_cltv_expiry_delta
192 Ok((blinded_payinfo, BlindedPath {
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
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)
211 IntroductionNode::DirectedShortChannelId(direction, scid) => {
214 .map(|c| match direction {
215 Direction::NodeOne => &c.node_one,
216 Direction::NodeTwo => &c.node_two,
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.
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
235 .filter_map(|scid| network_graph.channel(*scid).map(|info| (*scid, info)))
236 .min_by_key(|(scid, _)| scid_utils::block_from_scid(*scid))
238 let direction = if node_id == channel_info.node_one {
241 debug_assert_eq!(node_id, channel_info.node_two);
244 self.introduction_node =
245 IntroductionNode::DirectedShortChannelId(direction, scid);
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) => {
258 Direction::NodeOne => 0u8.write(w)?,
259 Direction::NodeTwo => 1u8.write(w)?,
265 self.blinding_point.write(w)?;
266 (self.blinded_hops.len() as u8).write(w)?;
267 for hop in &self.blinded_hops {
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)?),
282 let mut pubkey_read = core::slice::from_mut(&mut first_byte).chain(r.by_ref());
283 IntroductionNode::NodeId(Readable::read(&mut pubkey_read)?)
285 _ => return Err(DecodeError::InvalidValue),
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)?);
302 impl_writeable!(BlindedHop, {
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 {
311 Direction::NodeOne => core::cmp::min(node_a, node_b),
312 Direction::NodeTwo => core::cmp::max(node_a, node_b),
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) {
324 Direction::NodeOne => node_one,
325 Direction::NodeTwo => node_two,