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