Skip to content

Commit c36d6e7

Browse files
committed
Replace PublicKey with [u8; 33] in NetworkGraph
1 parent ab0739e commit c36d6e7

File tree

2 files changed

+117
-104
lines changed

2 files changed

+117
-104
lines changed

lightning/src/routing/network_graph.rs

+30-21
Original file line numberDiff line numberDiff line change
@@ -50,12 +50,15 @@ const MAX_EXCESS_BYTES_FOR_RELAY: usize = 1024;
5050
/// This value ensures a reply fits within the 65k payload limit and is consistent with other implementations.
5151
const MAX_SCIDS_PER_REPLY: usize = 8000;
5252

53+
/// Represents the compressed public key of a node
54+
pub type NodeId = [u8; 33];
55+
5356
/// Represents the network as nodes and channels between them
5457
pub struct NetworkGraph {
5558
genesis_hash: BlockHash,
5659
// Lock order: channels -> nodes
5760
channels: RwLock<BTreeMap<u64, ChannelInfo>>,
58-
nodes: RwLock<BTreeMap<PublicKey, NodeInfo>>,
61+
nodes: RwLock<BTreeMap<NodeId, NodeInfo>>,
5962
}
6063

6164
impl Clone for NetworkGraph {
@@ -73,7 +76,7 @@ impl Clone for NetworkGraph {
7376
/// A read-only view of [`NetworkGraph`].
7477
pub struct ReadOnlyNetworkGraph<'a> {
7578
channels: RwLockReadGuard<'a, BTreeMap<u64, ChannelInfo>>,
76-
nodes: RwLockReadGuard<'a, BTreeMap<PublicKey, NodeInfo>>,
79+
nodes: RwLockReadGuard<'a, BTreeMap<NodeId, NodeInfo>>,
7780
}
7881

7982
/// Update to the [`NetworkGraph`] based on payment failure information conveyed via the Onion
@@ -209,7 +212,7 @@ where C::Target: chain::Access, L::Target: Logger
209212
NetworkUpdate::NodeFailure { ref node_id, is_permanent } => {
210213
let action = if is_permanent { "Removing" } else { "Disabling" };
211214
log_debug!(self.logger, "{} node graph entry for {} due to a payment failure.", action, node_id);
212-
self.network_graph.fail_node(node_id, is_permanent);
215+
self.network_graph.fail_node(&node_id.serialize(), is_permanent);
213216
},
214217
}
215218
}
@@ -277,11 +280,11 @@ where C::Target: chain::Access, L::Target: Logger
277280
let mut result = Vec::with_capacity(batch_amount as usize);
278281
let nodes = self.network_graph.nodes.read().unwrap();
279282
let mut iter = if let Some(pubkey) = starting_point {
280-
let mut iter = nodes.range((*pubkey)..);
283+
let mut iter = nodes.range((pubkey.serialize())..);
281284
iter.next();
282285
iter
283286
} else {
284-
nodes.range(..)
287+
nodes.range::<NodeId, _>(..)
285288
};
286289
while result.len() < batch_amount as usize {
287290
if let Some((_, ref node)) = iter.next() {
@@ -314,7 +317,7 @@ where C::Target: chain::Access, L::Target: Logger
314317
}
315318

316319
// Check if we need to perform a full synchronization with this peer
317-
if !self.should_request_full_sync(their_node_id) {
320+
if !self.should_request_full_sync(&their_node_id) {
318321
return ();
319322
}
320323

@@ -551,11 +554,11 @@ pub struct ChannelInfo {
551554
/// Protocol features of a channel communicated during its announcement
552555
pub features: ChannelFeatures,
553556
/// Source node of the first direction of a channel
554-
pub node_one: PublicKey,
557+
pub node_one: NodeId,
555558
/// Details about the first direction of a channel
556559
pub one_to_two: Option<DirectionalChannelInfo>,
557560
/// Source node of the second direction of a channel
558-
pub node_two: PublicKey,
561+
pub node_two: NodeId,
559562
/// Details about the second direction of a channel
560563
pub two_to_one: Option<DirectionalChannelInfo>,
561564
/// The channel capacity as seen on-chain, if chain lookup is available.
@@ -570,7 +573,7 @@ pub struct ChannelInfo {
570573
impl fmt::Display for ChannelInfo {
571574
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
572575
write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
573-
log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
576+
log_bytes!(self.features.encode()), log_bytes!(self.node_one), self.one_to_two, log_bytes!(self.node_two), self.two_to_one)?;
574577
Ok(())
575578
}
576579
}
@@ -725,7 +728,7 @@ impl fmt::Display for NetworkGraph {
725728
}
726729
writeln!(f, "[Nodes]")?;
727730
for (key, val) in self.nodes.read().unwrap().iter() {
728-
writeln!(f, " {}: {}", log_pubkey!(key), val)?;
731+
writeln!(f, " {}: {}", log_bytes!(*key), val)?;
729732
}
730733
Ok(())
731734
}
@@ -780,7 +783,7 @@ impl NetworkGraph {
780783
}
781784

782785
fn update_node_from_announcement_intern(&self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
783-
match self.nodes.write().unwrap().get_mut(&msg.node_id) {
786+
match self.nodes.write().unwrap().get_mut(&msg.node_id.serialize()) {
784787
None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
785788
Some(node) => {
786789
if let Some(node_info) = node.announcement_info.as_ref() {
@@ -886,9 +889,9 @@ impl NetworkGraph {
886889

887890
let chan_info = ChannelInfo {
888891
features: msg.features.clone(),
889-
node_one: msg.node_id_1.clone(),
892+
node_one: msg.node_id_1.serialize(),
890893
one_to_two: None,
891-
node_two: msg.node_id_2.clone(),
894+
node_two: msg.node_id_2.serialize(),
892895
two_to_one: None,
893896
capacity_sats: utxo_value,
894897
announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
@@ -939,8 +942,8 @@ impl NetworkGraph {
939942
};
940943
}
941944

942-
add_channel_to_node!(msg.node_id_1);
943-
add_channel_to_node!(msg.node_id_2);
945+
add_channel_to_node!(msg.node_id_1.serialize());
946+
add_channel_to_node!(msg.node_id_2.serialize());
944947

945948
Ok(())
946949
}
@@ -969,7 +972,7 @@ impl NetworkGraph {
969972
}
970973

971974
/// Marks a node in the graph as failed.
972-
pub fn fail_node(&self, _node_id: &PublicKey, is_permanent: bool) {
975+
pub fn fail_node(&self, _node_id: &NodeId, is_permanent: bool) {
973976
if is_permanent {
974977
// TODO: Wholly remove the node
975978
} else {
@@ -1050,13 +1053,19 @@ impl NetworkGraph {
10501053
if msg.flags & 1 == 1 {
10511054
dest_node_id = channel.node_one.clone();
10521055
if let Some((sig, ctx)) = sig_info {
1053-
secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_two);
1056+
secp_verify_sig!(ctx, &msg_hash, &sig, &PublicKey::from_slice(&channel.node_two).map_err(|_| LightningError{
1057+
err: "Couldn't parse source node pubkey".to_owned(),
1058+
action: ErrorAction::IgnoreAndLog(Level::Debug)
1059+
})?);
10541060
}
10551061
maybe_update_channel_info!(channel.two_to_one, channel.node_two);
10561062
} else {
10571063
dest_node_id = channel.node_two.clone();
10581064
if let Some((sig, ctx)) = sig_info {
1059-
secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_one);
1065+
secp_verify_sig!(ctx, &msg_hash, &sig, &PublicKey::from_slice(&channel.node_one).map_err(|_| LightningError{
1066+
err: "Couldn't parse destination node pubkey".to_owned(),
1067+
action: ErrorAction::IgnoreAndLog(Level::Debug)
1068+
})?);
10601069
}
10611070
maybe_update_channel_info!(channel.one_to_two, channel.node_one);
10621071
}
@@ -1104,7 +1113,7 @@ impl NetworkGraph {
11041113
Ok(())
11051114
}
11061115

1107-
fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
1116+
fn remove_channel_in_nodes(nodes: &mut BTreeMap<NodeId, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
11081117
macro_rules! remove_from_node {
11091118
($node_id: expr) => {
11101119
if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
@@ -1136,7 +1145,7 @@ impl ReadOnlyNetworkGraph<'_> {
11361145
/// Returns all known nodes' public keys along with announced node info.
11371146
///
11381147
/// (C-not exported) because we have no mapping for `BTreeMap`s
1139-
pub fn nodes(&self) -> &BTreeMap<PublicKey, NodeInfo> {
1148+
pub fn nodes(&self) -> &BTreeMap<NodeId, NodeInfo> {
11401149
&*self.nodes
11411150
}
11421151

@@ -1146,7 +1155,7 @@ impl ReadOnlyNetworkGraph<'_> {
11461155
///
11471156
/// (C-not exported) as there is no practical way to track lifetimes of returned values.
11481157
pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<&Vec<NetAddress>> {
1149-
if let Some(node) = self.nodes.get(pubkey) {
1158+
if let Some(node) = self.nodes.get(&pubkey.serialize()) {
11501159
if let Some(node_info) = node.announcement_info.as_ref() {
11511160
return Some(&node_info.addresses)
11521161
}

0 commit comments

Comments
 (0)