lightning/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
12pub mod message;
13pub mod payment;
14pub(crate) mod utils;
15
16use bitcoin::secp256k1::PublicKey;
17use core::ops::Deref;
18
19use crate::ln::msgs::DecodeError;
20use crate::routing::gossip::{NodeId, ReadOnlyNetworkGraph};
21use crate::util::ser::{Readable, Writeable, Writer};
22
23use crate::io;
24use crate::prelude::*;
25
26/// Onion messages and payments can be sent and received to blinded paths, which serve to hide the
27/// identity of the recipient.
28#[derive(Clone, Debug, Hash, PartialEq, Eq)]
29pub(crate) struct BlindedPath {
30	/// To send to a blinded path, the sender first finds a route to the unblinded
31	/// `introduction_node`, which can unblind its [`encrypted_payload`] to find out the onion
32	/// message or payment's next hop and forward it along.
33	///
34	/// [`encrypted_payload`]: BlindedHop::encrypted_payload
35	pub introduction_node: IntroductionNode,
36	/// Used by the introduction node to decrypt its [`encrypted_payload`] to forward the onion
37	/// message or payment.
38	///
39	/// [`encrypted_payload`]: BlindedHop::encrypted_payload
40	pub blinding_point: PublicKey,
41	/// The hops composing the blinded path.
42	pub blinded_hops: Vec<BlindedHop>,
43}
44
45/// The unblinded node in a blinded path.
46#[derive(Clone, Debug, Hash, PartialEq, Eq)]
47pub enum IntroductionNode {
48	/// The node id of the introduction node.
49	NodeId(PublicKey),
50	/// The short channel id of the channel leading to the introduction node. The [`Direction`]
51	/// identifies which side of the channel is the introduction node.
52	DirectedShortChannelId(Direction, u64),
53}
54
55/// The side of a channel that is the [`IntroductionNode`] in a blinded path. [BOLT 7] defines which
56/// nodes is which in the [`ChannelAnnouncement`] message.
57///
58/// [BOLT 7]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_announcement-message
59/// [`ChannelAnnouncement`]: crate::ln::msgs::ChannelAnnouncement
60#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
61pub enum Direction {
62	/// The lesser node id when compared lexicographically in ascending order.
63	NodeOne,
64	/// The greater node id when compared lexicographically in ascending order.
65	NodeTwo,
66}
67
68/// An interface for looking up the node id of a channel counterparty for the purpose of forwarding
69/// an [`OnionMessage`].
70///
71/// [`OnionMessage`]: crate::ln::msgs::OnionMessage
72pub trait NodeIdLookUp {
73	/// Returns the node id of the forwarding node's channel counterparty with `short_channel_id`.
74	///
75	/// Here, the forwarding node is referring to the node of the [`OnionMessenger`] parameterized
76	/// by the [`NodeIdLookUp`] and the counterparty to one of that node's peers.
77	///
78	/// [`OnionMessenger`]: crate::onion_message::messenger::OnionMessenger
79	fn next_node_id(&self, short_channel_id: u64) -> Option<PublicKey>;
80}
81
82/// A [`NodeIdLookUp`] that always returns `None`.
83pub struct EmptyNodeIdLookUp {}
84
85impl NodeIdLookUp for EmptyNodeIdLookUp {
86	fn next_node_id(&self, _short_channel_id: u64) -> Option<PublicKey> {
87		None
88	}
89}
90
91impl Deref for EmptyNodeIdLookUp {
92	type Target = EmptyNodeIdLookUp;
93	fn deref(&self) -> &Self {
94		self
95	}
96}
97
98/// An encrypted payload and node id corresponding to a hop in a payment or onion message path, to
99/// be encoded in the sender's onion packet. These hops cannot be identified by outside observers
100/// and thus can be used to hide the identity of the recipient.
101#[derive(Clone, Debug, Hash, PartialEq, Eq)]
102pub struct BlindedHop {
103	/// The blinded node id of this hop in a blinded path.
104	pub blinded_node_id: PublicKey,
105	/// The encrypted payload intended for this hop in a blinded path.
106	// The node sending to this blinded path will later encode this payload into the onion packet for
107	// this hop.
108	pub encrypted_payload: Vec<u8>,
109}
110
111impl BlindedPath {
112	pub(super) fn public_introduction_node_id<'a>(
113		&self, network_graph: &'a ReadOnlyNetworkGraph,
114	) -> Option<&'a NodeId> {
115		match &self.introduction_node {
116			IntroductionNode::NodeId(pubkey) => {
117				let node_id = NodeId::from_pubkey(pubkey);
118				network_graph.nodes().get_key_value(&node_id).map(|(key, _)| key)
119			},
120			IntroductionNode::DirectedShortChannelId(direction, scid) => {
121				network_graph.channel(*scid).map(|c| match direction {
122					Direction::NodeOne => &c.node_one,
123					Direction::NodeTwo => &c.node_two,
124				})
125			},
126		}
127	}
128}
129
130impl Writeable for BlindedPath {
131	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
132		match &self.introduction_node {
133			IntroductionNode::NodeId(pubkey) => pubkey.write(w)?,
134			IntroductionNode::DirectedShortChannelId(direction, scid) => {
135				match direction {
136					Direction::NodeOne => 0u8.write(w)?,
137					Direction::NodeTwo => 1u8.write(w)?,
138				}
139				scid.write(w)?;
140			},
141		}
142
143		self.blinding_point.write(w)?;
144		(self.blinded_hops.len() as u8).write(w)?;
145		for hop in &self.blinded_hops {
146			hop.write(w)?;
147		}
148		Ok(())
149	}
150}
151
152impl Readable for BlindedPath {
153	fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
154		let first_byte: u8 = Readable::read(r)?;
155		let introduction_node = match first_byte {
156			0 => IntroductionNode::DirectedShortChannelId(Direction::NodeOne, Readable::read(r)?),
157			1 => IntroductionNode::DirectedShortChannelId(Direction::NodeTwo, Readable::read(r)?),
158			2 | 3 => {
159				let mut bytes = [0; 33];
160				bytes[0] = first_byte;
161				r.read_exact(&mut bytes[1..])?;
162				IntroductionNode::NodeId(Readable::read(&mut &bytes[..])?)
163			},
164			_ => return Err(DecodeError::InvalidValue),
165		};
166		let blinding_point = Readable::read(r)?;
167		let num_hops: u8 = Readable::read(r)?;
168		if num_hops == 0 {
169			return Err(DecodeError::InvalidValue);
170		}
171		let mut blinded_hops: Vec<BlindedHop> = Vec::with_capacity(num_hops.into());
172		for _ in 0..num_hops {
173			blinded_hops.push(Readable::read(r)?);
174		}
175		Ok(BlindedPath { introduction_node, blinding_point, blinded_hops })
176	}
177}
178
179impl_writeable!(BlindedHop, {
180	blinded_node_id,
181	encrypted_payload
182});
183
184impl Direction {
185	/// Returns the [`NodeId`] from the inputs corresponding to the direction.
186	pub fn select_node_id(&self, node_a: NodeId, node_b: NodeId) -> NodeId {
187		match self {
188			Direction::NodeOne => core::cmp::min(node_a, node_b),
189			Direction::NodeTwo => core::cmp::max(node_a, node_b),
190		}
191	}
192
193	/// Returns the [`PublicKey`] from the inputs corresponding to the direction.
194	pub fn select_pubkey<'a>(&self, node_a: &'a PublicKey, node_b: &'a PublicKey) -> &'a PublicKey {
195		let (node_one, node_two) = if NodeId::from_pubkey(node_a) < NodeId::from_pubkey(node_b) {
196			(node_a, node_b)
197		} else {
198			(node_b, node_a)
199		};
200		match self {
201			Direction::NodeOne => node_one,
202			Direction::NodeTwo => node_two,
203		}
204	}
205}