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 payment;
13pub mod message;
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 { self }
94}
95
96/// An encrypted payload and node id corresponding to a hop in a payment or onion message path, to
97/// be encoded in the sender's onion packet. These hops cannot be identified by outside observers
98/// and thus can be used to hide the identity of the recipient.
99#[derive(Clone, Debug, Hash, PartialEq, Eq)]
100pub struct BlindedHop {
101	/// The blinded node id of this hop in a blinded path.
102	pub blinded_node_id: PublicKey,
103	/// The encrypted payload intended for this hop in a blinded path.
104	// The node sending to this blinded path will later encode this payload into the onion packet for
105	// this hop.
106	pub encrypted_payload: Vec<u8>,
107}
108
109impl BlindedPath {
110	pub(super) fn public_introduction_node_id<'a>(
111		&self, network_graph: &'a ReadOnlyNetworkGraph
112	) -> Option<&'a NodeId> {
113		match &self.introduction_node {
114			IntroductionNode::NodeId(pubkey) => {
115				let node_id = NodeId::from_pubkey(pubkey);
116				network_graph.nodes().get_key_value(&node_id).map(|(key, _)| key)
117			},
118			IntroductionNode::DirectedShortChannelId(direction, scid) => {
119				network_graph
120					.channel(*scid)
121					.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 { return Err(DecodeError::InvalidValue) }
169		let mut blinded_hops: Vec<BlindedHop> = Vec::with_capacity(num_hops.into());
170		for _ in 0..num_hops {
171			blinded_hops.push(Readable::read(r)?);
172		}
173		Ok(BlindedPath {
174			introduction_node,
175			blinding_point,
176			blinded_hops,
177		})
178	}
179}
180
181impl_writeable!(BlindedHop, {
182	blinded_node_id,
183	encrypted_payload
184});
185
186impl Direction {
187	/// Returns the [`NodeId`] from the inputs corresponding to the direction.
188	pub fn select_node_id(&self, node_a: NodeId, node_b: NodeId) -> NodeId {
189		match self {
190			Direction::NodeOne => core::cmp::min(node_a, node_b),
191			Direction::NodeTwo => core::cmp::max(node_a, node_b),
192		}
193	}
194
195	/// Returns the [`PublicKey`] from the inputs corresponding to the direction.
196	pub fn select_pubkey<'a>(&self, node_a: &'a PublicKey, node_b: &'a PublicKey) -> &'a PublicKey {
197		let (node_one, node_two) = if NodeId::from_pubkey(node_a) < NodeId::from_pubkey(node_b) {
198			(node_a, node_b)
199		} else {
200			(node_b, node_a)
201		};
202		match self {
203			Direction::NodeOne => node_one,
204			Direction::NodeTwo => node_two,
205		}
206	}
207}