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};
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};
26 use crate::prelude::*;
28 /// The next hop to forward an onion message along its path.
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.
35 /// The short channel id leading to the next hop.
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.
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.
52 /// [`encrypted_payload`]: BlindedHop::encrypted_payload
53 pub blinding_point: PublicKey,
54 /// The hops composing the blinded path.
55 pub blinded_hops: Vec<BlindedHop>,
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.
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),
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.
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)]
75 /// The lesser node id when compared lexicographically in ascending order.
77 /// The greater node id when compared lexicographically in ascending order.
81 /// An interface for looking up the node id of a channel counterparty for the purpose of forwarding
82 /// an [`OnionMessage`].
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`.
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.
91 /// [`OnionMessenger`]: crate::onion_message::messenger::OnionMessenger
92 fn next_node_id(&self, short_channel_id: u64) -> Option<PublicKey>;
95 /// A [`NodeIdLookUp`] that always returns `None`.
96 pub struct EmptyNodeIdLookUp {}
98 impl NodeIdLookUp for EmptyNodeIdLookUp {
99 fn next_node_id(&self, _short_channel_id: u64) -> Option<PublicKey> {
104 impl Deref for EmptyNodeIdLookUp {
105 type Target = EmptyNodeIdLookUp;
106 fn deref(&self) -> &Self { self }
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
119 pub encrypted_payload: Vec<u8>,
123 /// Create a one-hop blinded path for a message.
124 pub fn one_hop_for_message<ES: Deref, T: secp256k1::Signing + secp256k1::Verification>(
125 recipient_node_id: PublicKey, entropy_source: ES, secp_ctx: &Secp256k1<T>
126 ) -> Result<Self, ()> where ES::Target: EntropySource {
127 Self::new_for_message(&[recipient_node_id], entropy_source, secp_ctx)
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.
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: Deref, T: secp256k1::Signing + secp256k1::Verification>(
136 node_pks: &[PublicKey], entropy_source: ES, secp_ctx: &Secp256k1<T>
137 ) -> Result<Self, ()> where ES::Target: EntropySource {
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]);
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(|_| ())?,
150 /// Create a one-hop blinded path for a payment.
151 pub fn one_hop_for_payment<ES: Deref, 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), ()> where ES::Target: EntropySource {
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
164 /// Create a blinded path for a payment, to be forwarded along `intermediate_nodes`.
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`]
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: Deref, 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), ()> where ES::Target: EntropySource {
178 let introduction_node = IntroductionNode::NodeId(
179 intermediate_nodes.first().map_or(payee_node_id, |n| n.node_id)
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");
184 let blinded_payinfo = payment::compute_payinfo(
185 intermediate_nodes, &payee_tlvs, htlc_maximum_msat, min_final_cltv_expiry_delta
187 Ok((blinded_payinfo, BlindedPath {
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
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)
206 IntroductionNode::DirectedShortChannelId(direction, scid) => {
209 .map(|c| match direction {
210 Direction::NodeOne => &c.node_one,
211 Direction::NodeTwo => &c.node_two,
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) => {
224 Direction::NodeOne => 0u8.write(w)?,
225 Direction::NodeTwo => 1u8.write(w)?,
231 self.blinding_point.write(w)?;
232 (self.blinded_hops.len() as u8).write(w)?;
233 for hop in &self.blinded_hops {
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)?),
248 let mut pubkey_read = core::slice::from_mut(&mut first_byte).chain(r.by_ref());
249 IntroductionNode::NodeId(Readable::read(&mut pubkey_read)?)
251 _ => return Err(DecodeError::InvalidValue),
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)?);
268 impl_writeable!(BlindedHop, {
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 {
277 Direction::NodeOne => core::cmp::min(node_a, node_b),
278 Direction::NodeTwo => core::cmp::max(node_a, node_b),
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) {
290 Direction::NodeOne => node_one,
291 Direction::NodeTwo => node_two,