Skip to content

Commit 59778da

Browse files
authored
Merge pull request #2961 from jkczyz/2024-03-compact-blinded-paths
Compact blinded path handling
2 parents 322e1f3 + fe114ef commit 59778da

17 files changed

+534
-189
lines changed

fuzz/src/onion_message.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use bitcoin::secp256k1::ecdh::SharedSecret;
66
use bitcoin::secp256k1::ecdsa::RecoverableSignature;
77
use bitcoin::secp256k1::schnorr;
88

9-
use lightning::blinded_path::BlindedPath;
9+
use lightning::blinded_path::{BlindedPath, EmptyNodeIdLookUp};
1010
use lightning::ln::features::InitFeatures;
1111
use lightning::ln::msgs::{self, DecodeError, OnionMessageHandler};
1212
use lightning::ln::script::ShutdownScript;
@@ -36,12 +36,13 @@ pub fn do_test<L: Logger>(data: &[u8], logger: &L) {
3636
node_secret: secret,
3737
counter: AtomicU64::new(0),
3838
};
39+
let node_id_lookup = EmptyNodeIdLookUp {};
3940
let message_router = TestMessageRouter {};
4041
let offers_msg_handler = TestOffersMessageHandler {};
4142
let custom_msg_handler = TestCustomMessageHandler {};
4243
let onion_messenger = OnionMessenger::new(
43-
&keys_manager, &keys_manager, logger, &message_router, &offers_msg_handler,
44-
&custom_msg_handler
44+
&keys_manager, &keys_manager, logger, &node_id_lookup, &message_router,
45+
&offers_msg_handler, &custom_msg_handler
4546
);
4647

4748
let peer_node_id = {

fuzz/src/router.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use bitcoin::blockdata::constants::ChainHash;
1111
use bitcoin::blockdata::script::Builder;
1212
use bitcoin::blockdata::transaction::TxOut;
1313

14-
use lightning::blinded_path::{BlindedHop, BlindedPath};
14+
use lightning::blinded_path::{BlindedHop, BlindedPath, IntroductionNode};
1515
use lightning::chain::transaction::OutPoint;
1616
use lightning::ln::ChannelId;
1717
use lightning::ln::channelmanager::{self, ChannelDetails, ChannelCounterparty};
@@ -363,7 +363,7 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
363363
});
364364
}
365365
(payinfo, BlindedPath {
366-
introduction_node_id: hop.src_node_id,
366+
introduction_node: IntroductionNode::NodeId(hop.src_node_id),
367367
blinding_point: dummy_pk,
368368
blinded_hops,
369369
})

lightning/src/blinded_path/message.rs

Lines changed: 39 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use bitcoin::secp256k1::{self, PublicKey, Secp256k1, SecretKey};
33
#[allow(unused_imports)]
44
use crate::prelude::*;
55

6-
use crate::blinded_path::{BlindedHop, BlindedPath};
6+
use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode, NodeIdLookUp};
77
use crate::blinded_path::utils;
88
use crate::io;
99
use crate::io::Cursor;
@@ -19,8 +19,8 @@ use core::ops::Deref;
1919
/// TLVs to encode in an intermediate onion message packet's hop data. When provided in a blinded
2020
/// route, they are encoded into [`BlindedHop::encrypted_payload`].
2121
pub(crate) struct ForwardTlvs {
22-
/// The node id of the next hop in the onion message's path.
23-
pub(crate) next_node_id: PublicKey,
22+
/// The next hop in the onion message's path.
23+
pub(crate) next_hop: NextHop,
2424
/// Senders to a blinded path use this value to concatenate the route they find to the
2525
/// introduction node with the blinded path.
2626
pub(crate) next_blinding_override: Option<PublicKey>,
@@ -34,11 +34,25 @@ pub(crate) struct ReceiveTlvs {
3434
pub(crate) path_id: Option<[u8; 32]>,
3535
}
3636

37+
/// The next hop to forward the onion message along its path.
38+
#[derive(Debug)]
39+
pub enum NextHop {
40+
/// The node id of the next hop.
41+
NodeId(PublicKey),
42+
/// The short channel id leading to the next hop.
43+
ShortChannelId(u64),
44+
}
45+
3746
impl Writeable for ForwardTlvs {
3847
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
48+
let (next_node_id, short_channel_id) = match self.next_hop {
49+
NextHop::NodeId(pubkey) => (Some(pubkey), None),
50+
NextHop::ShortChannelId(scid) => (None, Some(scid)),
51+
};
3952
// TODO: write padding
4053
encode_tlv_stream!(writer, {
41-
(4, self.next_node_id, required),
54+
(2, short_channel_id, option),
55+
(4, next_node_id, option),
4256
(8, self.next_blinding_override, option)
4357
});
4458
Ok(())
@@ -61,28 +75,39 @@ pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
6175
) -> Result<Vec<BlindedHop>, secp256k1::Error> {
6276
let blinded_tlvs = unblinded_path.iter()
6377
.skip(1) // The first node's TLVs contains the next node's pubkey
64-
.map(|pk| {
65-
ControlTlvs::Forward(ForwardTlvs { next_node_id: *pk, next_blinding_override: None })
66-
})
78+
.map(|pk| ForwardTlvs { next_hop: NextHop::NodeId(*pk), next_blinding_override: None })
79+
.map(|tlvs| ControlTlvs::Forward(tlvs))
6780
.chain(core::iter::once(ControlTlvs::Receive(ReceiveTlvs { path_id: None })));
6881

6982
utils::construct_blinded_hops(secp_ctx, unblinded_path.iter(), blinded_tlvs, session_priv)
7083
}
7184

7285
// Advance the blinded onion message path by one hop, so make the second hop into the new
7386
// introduction node.
74-
pub(crate) fn advance_path_by_one<NS: Deref, T: secp256k1::Signing + secp256k1::Verification>(
75-
path: &mut BlindedPath, node_signer: &NS, secp_ctx: &Secp256k1<T>
76-
) -> Result<(), ()> where NS::Target: NodeSigner {
87+
pub(crate) fn advance_path_by_one<NS: Deref, NL: Deref, T>(
88+
path: &mut BlindedPath, node_signer: &NS, node_id_lookup: &NL, secp_ctx: &Secp256k1<T>
89+
) -> Result<(), ()>
90+
where
91+
NS::Target: NodeSigner,
92+
NL::Target: NodeIdLookUp,
93+
T: secp256k1::Signing + secp256k1::Verification,
94+
{
7795
let control_tlvs_ss = node_signer.ecdh(Recipient::Node, &path.blinding_point, None)?;
7896
let rho = onion_utils::gen_rho_from_shared_secret(&control_tlvs_ss.secret_bytes());
7997
let encrypted_control_tlvs = path.blinded_hops.remove(0).encrypted_payload;
8098
let mut s = Cursor::new(&encrypted_control_tlvs);
8199
let mut reader = FixedLengthReader::new(&mut s, encrypted_control_tlvs.len() as u64);
82100
match ChaChaPolyReadAdapter::read(&mut reader, rho) {
83-
Ok(ChaChaPolyReadAdapter { readable: ControlTlvs::Forward(ForwardTlvs {
84-
mut next_node_id, next_blinding_override,
85-
})}) => {
101+
Ok(ChaChaPolyReadAdapter {
102+
readable: ControlTlvs::Forward(ForwardTlvs { next_hop, next_blinding_override })
103+
}) => {
104+
let next_node_id = match next_hop {
105+
NextHop::NodeId(pubkey) => pubkey,
106+
NextHop::ShortChannelId(scid) => match node_id_lookup.next_node_id(scid) {
107+
Some(pubkey) => pubkey,
108+
None => return Err(()),
109+
},
110+
};
86111
let mut new_blinding_point = match next_blinding_override {
87112
Some(blinding_point) => blinding_point,
88113
None => {
@@ -91,7 +116,7 @@ pub(crate) fn advance_path_by_one<NS: Deref, T: secp256k1::Signing + secp256k1::
91116
}
92117
};
93118
mem::swap(&mut path.blinding_point, &mut new_blinding_point);
94-
mem::swap(&mut path.introduction_node_id, &mut next_node_id);
119+
path.introduction_node = IntroductionNode::NodeId(next_node_id);
95120
Ok(())
96121
},
97122
_ => Err(())

lightning/src/blinded_path/mod.rs

Lines changed: 121 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ use bitcoin::secp256k1::{self, PublicKey, Secp256k1, SecretKey};
1717

1818
use crate::ln::msgs::DecodeError;
1919
use crate::offers::invoice::BlindedPayInfo;
20+
use crate::routing::gossip::{NodeId, ReadOnlyNetworkGraph};
2021
use crate::sign::EntropySource;
2122
use crate::util::ser::{Readable, Writeable, Writer};
2223

@@ -28,11 +29,11 @@ use crate::prelude::*;
2829
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
2930
pub struct BlindedPath {
3031
/// To send to a blinded path, the sender first finds a route to the unblinded
31-
/// `introduction_node_id`, which can unblind its [`encrypted_payload`] to find out the onion
32+
/// `introduction_node`, which can unblind its [`encrypted_payload`] to find out the onion
3233
/// message or payment's next hop and forward it along.
3334
///
3435
/// [`encrypted_payload`]: BlindedHop::encrypted_payload
35-
pub introduction_node_id: PublicKey,
36+
pub introduction_node: IntroductionNode,
3637
/// Used by the introduction node to decrypt its [`encrypted_payload`] to forward the onion
3738
/// message or payment.
3839
///
@@ -42,6 +43,52 @@ pub struct BlindedPath {
4243
pub blinded_hops: Vec<BlindedHop>,
4344
}
4445

46+
/// The unblinded node in a [`BlindedPath`].
47+
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
48+
pub enum IntroductionNode {
49+
/// The node id of the introduction node.
50+
NodeId(PublicKey),
51+
/// The short channel id of the channel leading to the introduction node. The [`Direction`]
52+
/// identifies which side of the channel is the introduction node.
53+
DirectedShortChannelId(Direction, u64),
54+
}
55+
56+
/// The side of a channel that is the [`IntroductionNode`] in a [`BlindedPath`]. [BOLT 7] defines
57+
/// which nodes is which in the [`ChannelAnnouncement`] message.
58+
///
59+
/// [BOLT 7]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_announcement-message
60+
/// [`ChannelAnnouncement`]: crate::ln::msgs::ChannelAnnouncement
61+
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
62+
pub enum Direction {
63+
/// The lesser node id when compared lexicographically in ascending order.
64+
NodeOne,
65+
/// The greater node id when compared lexicographically in ascending order.
66+
NodeTwo,
67+
}
68+
69+
/// An interface for looking up the node id of a channel counterparty for the purpose of forwarding
70+
/// an [`OnionMessage`].
71+
///
72+
/// [`OnionMessage`]: crate::ln::msgs::OnionMessage
73+
pub trait NodeIdLookUp {
74+
/// Returns the node id of the forwarding node's channel counterparty with `short_channel_id`.
75+
///
76+
/// Here, the forwarding node is referring to the node of the [`OnionMessenger`] parameterized
77+
/// by the [`NodeIdLookUp`] and the counterparty to one of that node's peers.
78+
///
79+
/// [`OnionMessenger`]: crate::onion_message::messenger::OnionMessenger
80+
fn next_node_id(&self, short_channel_id: u64) -> Option<PublicKey>;
81+
}
82+
83+
/// A [`NodeIdLookUp`] that always returns `None`.
84+
pub struct EmptyNodeIdLookUp {}
85+
86+
impl NodeIdLookUp for EmptyNodeIdLookUp {
87+
fn next_node_id(&self, _short_channel_id: u64) -> Option<PublicKey> {
88+
None
89+
}
90+
}
91+
4592
/// An encrypted payload and node id corresponding to a hop in a payment or onion message path, to
4693
/// be encoded in the sender's onion packet. These hops cannot be identified by outside observers
4794
/// and thus can be used to hide the identity of the recipient.
@@ -74,10 +121,10 @@ impl BlindedPath {
74121
if node_pks.is_empty() { return Err(()) }
75122
let blinding_secret_bytes = entropy_source.get_secure_random_bytes();
76123
let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
77-
let introduction_node_id = node_pks[0];
124+
let introduction_node = IntroductionNode::NodeId(node_pks[0]);
78125

79126
Ok(BlindedPath {
80-
introduction_node_id,
127+
introduction_node,
81128
blinding_point: PublicKey::from_secret_key(secp_ctx, &blinding_secret),
82129
blinded_hops: message::blinded_hops(secp_ctx, node_pks, &blinding_secret).map_err(|_| ())?,
83130
})
@@ -111,25 +158,59 @@ impl BlindedPath {
111158
payee_tlvs: payment::ReceiveTlvs, htlc_maximum_msat: u64, min_final_cltv_expiry_delta: u16,
112159
entropy_source: &ES, secp_ctx: &Secp256k1<T>
113160
) -> Result<(BlindedPayInfo, Self), ()> {
161+
let introduction_node = IntroductionNode::NodeId(
162+
intermediate_nodes.first().map_or(payee_node_id, |n| n.node_id)
163+
);
114164
let blinding_secret_bytes = entropy_source.get_secure_random_bytes();
115165
let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
116166

117167
let blinded_payinfo = payment::compute_payinfo(
118168
intermediate_nodes, &payee_tlvs, htlc_maximum_msat, min_final_cltv_expiry_delta
119169
)?;
120170
Ok((blinded_payinfo, BlindedPath {
121-
introduction_node_id: intermediate_nodes.first().map_or(payee_node_id, |n| n.node_id),
171+
introduction_node,
122172
blinding_point: PublicKey::from_secret_key(secp_ctx, &blinding_secret),
123173
blinded_hops: payment::blinded_hops(
124174
secp_ctx, intermediate_nodes, payee_node_id, payee_tlvs, &blinding_secret
125175
).map_err(|_| ())?,
126176
}))
127177
}
178+
179+
/// Returns the introduction [`NodeId`] of the blinded path, if it is publicly reachable (i.e.,
180+
/// it is found in the network graph).
181+
pub fn public_introduction_node_id<'a>(
182+
&self, network_graph: &'a ReadOnlyNetworkGraph
183+
) -> Option<&'a NodeId> {
184+
match &self.introduction_node {
185+
IntroductionNode::NodeId(pubkey) => {
186+
let node_id = NodeId::from_pubkey(pubkey);
187+
network_graph.nodes().get_key_value(&node_id).map(|(key, _)| key)
188+
},
189+
IntroductionNode::DirectedShortChannelId(direction, scid) => {
190+
network_graph
191+
.channel(*scid)
192+
.map(|c| match direction {
193+
Direction::NodeOne => &c.node_one,
194+
Direction::NodeTwo => &c.node_two,
195+
})
196+
},
197+
}
198+
}
128199
}
129200

130201
impl Writeable for BlindedPath {
131202
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
132-
self.introduction_node_id.write(w)?;
203+
match &self.introduction_node {
204+
IntroductionNode::NodeId(pubkey) => pubkey.write(w)?,
205+
IntroductionNode::DirectedShortChannelId(direction, scid) => {
206+
match direction {
207+
Direction::NodeOne => 0u8.write(w)?,
208+
Direction::NodeTwo => 1u8.write(w)?,
209+
}
210+
scid.write(w)?;
211+
},
212+
}
213+
133214
self.blinding_point.write(w)?;
134215
(self.blinded_hops.len() as u8).write(w)?;
135216
for hop in &self.blinded_hops {
@@ -141,7 +222,17 @@ impl Writeable for BlindedPath {
141222

142223
impl Readable for BlindedPath {
143224
fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
144-
let introduction_node_id = Readable::read(r)?;
225+
let mut first_byte: u8 = Readable::read(r)?;
226+
let introduction_node = match first_byte {
227+
0 => IntroductionNode::DirectedShortChannelId(Direction::NodeOne, Readable::read(r)?),
228+
1 => IntroductionNode::DirectedShortChannelId(Direction::NodeTwo, Readable::read(r)?),
229+
2|3 => {
230+
use io::Read;
231+
let mut pubkey_read = core::slice::from_mut(&mut first_byte).chain(r.by_ref());
232+
IntroductionNode::NodeId(Readable::read(&mut pubkey_read)?)
233+
},
234+
_ => return Err(DecodeError::InvalidValue),
235+
};
145236
let blinding_point = Readable::read(r)?;
146237
let num_hops: u8 = Readable::read(r)?;
147238
if num_hops == 0 { return Err(DecodeError::InvalidValue) }
@@ -150,7 +241,7 @@ impl Readable for BlindedPath {
150241
blinded_hops.push(Readable::read(r)?);
151242
}
152243
Ok(BlindedPath {
153-
introduction_node_id,
244+
introduction_node,
154245
blinding_point,
155246
blinded_hops,
156247
})
@@ -162,3 +253,25 @@ impl_writeable!(BlindedHop, {
162253
encrypted_payload
163254
});
164255

256+
impl Direction {
257+
/// Returns the [`NodeId`] from the inputs corresponding to the direction.
258+
pub fn select_node_id<'a>(&self, node_a: &'a NodeId, node_b: &'a NodeId) -> &'a NodeId {
259+
match self {
260+
Direction::NodeOne => core::cmp::min(node_a, node_b),
261+
Direction::NodeTwo => core::cmp::max(node_a, node_b),
262+
}
263+
}
264+
265+
/// Returns the [`PublicKey`] from the inputs corresponding to the direction.
266+
pub fn select_pubkey<'a>(&self, node_a: &'a PublicKey, node_b: &'a PublicKey) -> &'a PublicKey {
267+
let (node_one, node_two) = if NodeId::from_pubkey(node_a) < NodeId::from_pubkey(node_b) {
268+
(node_a, node_b)
269+
} else {
270+
(node_b, node_a)
271+
};
272+
match self {
273+
Direction::NodeOne => node_one,
274+
Direction::NodeTwo => node_two,
275+
}
276+
}
277+
}

lightning/src/ln/channelmanager.rs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ use bitcoin::secp256k1::{SecretKey,PublicKey};
3131
use bitcoin::secp256k1::Secp256k1;
3232
use bitcoin::{secp256k1, Sequence};
3333

34-
use crate::blinded_path::BlindedPath;
34+
use crate::blinded_path::{BlindedPath, NodeIdLookUp};
3535
use crate::blinded_path::payment::{PaymentConstraints, ReceiveTlvs};
3636
use crate::chain;
3737
use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock};
@@ -10433,6 +10433,23 @@ where
1043310433
}
1043410434
}
1043510435

10436+
impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10437+
NodeIdLookUp for ChannelManager<M, T, ES, NS, SP, F, R, L>
10438+
where
10439+
M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
10440+
T::Target: BroadcasterInterface,
10441+
ES::Target: EntropySource,
10442+
NS::Target: NodeSigner,
10443+
SP::Target: SignerProvider,
10444+
F::Target: FeeEstimator,
10445+
R::Target: Router,
10446+
L::Target: Logger,
10447+
{
10448+
fn next_node_id(&self, short_channel_id: u64) -> Option<PublicKey> {
10449+
self.short_to_chan_info.read().unwrap().get(&short_channel_id).map(|(pubkey, _)| *pubkey)
10450+
}
10451+
}
10452+
1043610453
/// Fetches the set of [`NodeFeatures`] flags that are provided by or required by
1043710454
/// [`ChannelManager`].
1043810455
pub(crate) fn provided_node_features(config: &UserConfig) -> NodeFeatures {

0 commit comments

Comments
 (0)