Skip to content

Commit bede58e

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

File tree

2 files changed

+166
-105
lines changed

2 files changed

+166
-105
lines changed

lightning/src/routing/network_graph.rs

Lines changed: 79 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -50,12 +50,63 @@ 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+
#[derive(Clone, Copy)]
55+
pub struct NodeId(pub [u8; 33]);
56+
57+
impl fmt::Debug for NodeId {
58+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
59+
write!(f, "NodeId({})", log_bytes!(self.0))
60+
}
61+
}
62+
63+
impl core::hash::Hash for NodeId {
64+
fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
65+
self.0.hash(hasher);
66+
}
67+
}
68+
69+
impl Eq for NodeId {}
70+
71+
impl PartialEq for NodeId {
72+
fn eq(&self, other: &NodeId) -> bool {
73+
self.0[..] == other.0[..]
74+
}
75+
}
76+
77+
impl cmp::PartialOrd for NodeId {
78+
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
79+
Some(self.cmp(other))
80+
}
81+
}
82+
83+
impl Ord for NodeId {
84+
fn cmp(&self, other: &NodeId) -> cmp::Ordering {
85+
self.0[..].cmp(&other.0[..])
86+
}
87+
}
88+
89+
impl Writeable for NodeId {
90+
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
91+
writer.write_all(&self.0)?;
92+
Ok(())
93+
}
94+
}
95+
96+
impl Readable for NodeId {
97+
fn read<R: io::Read>(reader: &mut R) -> Result<NodeId, DecodeError> {
98+
let mut buf = [0; 33];
99+
reader.read_exact(&mut buf)?;
100+
Ok(NodeId(buf))
101+
}
102+
}
103+
53104
/// Represents the network as nodes and channels between them
54105
pub struct NetworkGraph {
55106
genesis_hash: BlockHash,
56107
// Lock order: channels -> nodes
57108
channels: RwLock<BTreeMap<u64, ChannelInfo>>,
58-
nodes: RwLock<BTreeMap<PublicKey, NodeInfo>>,
109+
nodes: RwLock<BTreeMap<NodeId, NodeInfo>>,
59110
}
60111

61112
impl Clone for NetworkGraph {
@@ -73,7 +124,7 @@ impl Clone for NetworkGraph {
73124
/// A read-only view of [`NetworkGraph`].
74125
pub struct ReadOnlyNetworkGraph<'a> {
75126
channels: RwLockReadGuard<'a, BTreeMap<u64, ChannelInfo>>,
76-
nodes: RwLockReadGuard<'a, BTreeMap<PublicKey, NodeInfo>>,
127+
nodes: RwLockReadGuard<'a, BTreeMap<NodeId, NodeInfo>>,
77128
}
78129

79130
/// Update to the [`NetworkGraph`] based on payment failure information conveyed via the Onion
@@ -209,7 +260,7 @@ where C::Target: chain::Access, L::Target: Logger
209260
NetworkUpdate::NodeFailure { ref node_id, is_permanent } => {
210261
let action = if is_permanent { "Removing" } else { "Disabling" };
211262
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);
263+
self.network_graph.fail_node(&NodeId(node_id.serialize()), is_permanent);
213264
},
214265
}
215266
}
@@ -277,11 +328,11 @@ where C::Target: chain::Access, L::Target: Logger
277328
let mut result = Vec::with_capacity(batch_amount as usize);
278329
let nodes = self.network_graph.nodes.read().unwrap();
279330
let mut iter = if let Some(pubkey) = starting_point {
280-
let mut iter = nodes.range((*pubkey)..);
331+
let mut iter = nodes.range(NodeId(pubkey.serialize())..);
281332
iter.next();
282333
iter
283334
} else {
284-
nodes.range(..)
335+
nodes.range::<NodeId, _>(..)
285336
};
286337
while result.len() < batch_amount as usize {
287338
if let Some((_, ref node)) = iter.next() {
@@ -314,7 +365,7 @@ where C::Target: chain::Access, L::Target: Logger
314365
}
315366

316367
// Check if we need to perform a full synchronization with this peer
317-
if !self.should_request_full_sync(their_node_id) {
368+
if !self.should_request_full_sync(&their_node_id) {
318369
return ();
319370
}
320371

@@ -551,11 +602,11 @@ pub struct ChannelInfo {
551602
/// Protocol features of a channel communicated during its announcement
552603
pub features: ChannelFeatures,
553604
/// Source node of the first direction of a channel
554-
pub node_one: PublicKey,
605+
pub node_one: NodeId,
555606
/// Details about the first direction of a channel
556607
pub one_to_two: Option<DirectionalChannelInfo>,
557608
/// Source node of the second direction of a channel
558-
pub node_two: PublicKey,
609+
pub node_two: NodeId,
559610
/// Details about the second direction of a channel
560611
pub two_to_one: Option<DirectionalChannelInfo>,
561612
/// The channel capacity as seen on-chain, if chain lookup is available.
@@ -570,7 +621,7 @@ pub struct ChannelInfo {
570621
impl fmt::Display for ChannelInfo {
571622
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
572623
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)?;
624+
log_bytes!(self.features.encode()), log_bytes!(self.node_one.0), self.one_to_two, log_bytes!(self.node_two.0), self.two_to_one)?;
574625
Ok(())
575626
}
576627
}
@@ -724,8 +775,8 @@ impl fmt::Display for NetworkGraph {
724775
writeln!(f, " {}: {}", key, val)?;
725776
}
726777
writeln!(f, "[Nodes]")?;
727-
for (key, val) in self.nodes.read().unwrap().iter() {
728-
writeln!(f, " {}: {}", log_pubkey!(key), val)?;
778+
for (&node_id, val) in self.nodes.read().unwrap().iter() {
779+
writeln!(f, " {}: {}", log_bytes!(node_id.0), val)?;
729780
}
730781
Ok(())
731782
}
@@ -780,7 +831,7 @@ impl NetworkGraph {
780831
}
781832

782833
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) {
834+
match self.nodes.write().unwrap().get_mut(&NodeId(msg.node_id.serialize())) {
784835
None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
785836
Some(node) => {
786837
if let Some(node_info) = node.announcement_info.as_ref() {
@@ -886,9 +937,9 @@ impl NetworkGraph {
886937

887938
let chan_info = ChannelInfo {
888939
features: msg.features.clone(),
889-
node_one: msg.node_id_1.clone(),
940+
node_one: NodeId(msg.node_id_1.serialize()),
890941
one_to_two: None,
891-
node_two: msg.node_id_2.clone(),
942+
node_two: NodeId(msg.node_id_2.serialize()),
892943
two_to_one: None,
893944
capacity_sats: utxo_value,
894945
announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
@@ -939,8 +990,8 @@ impl NetworkGraph {
939990
};
940991
}
941992

942-
add_channel_to_node!(msg.node_id_1);
943-
add_channel_to_node!(msg.node_id_2);
993+
add_channel_to_node!(NodeId(msg.node_id_1.serialize()));
994+
add_channel_to_node!(NodeId(msg.node_id_2.serialize()));
944995

945996
Ok(())
946997
}
@@ -969,7 +1020,7 @@ impl NetworkGraph {
9691020
}
9701021

9711022
/// Marks a node in the graph as failed.
972-
pub fn fail_node(&self, _node_id: &PublicKey, is_permanent: bool) {
1023+
pub fn fail_node(&self, _node_id: &NodeId, is_permanent: bool) {
9731024
if is_permanent {
9741025
// TODO: Wholly remove the node
9751026
} else {
@@ -1050,13 +1101,19 @@ impl NetworkGraph {
10501101
if msg.flags & 1 == 1 {
10511102
dest_node_id = channel.node_one.clone();
10521103
if let Some((sig, ctx)) = sig_info {
1053-
secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_two);
1104+
secp_verify_sig!(ctx, &msg_hash, &sig, &PublicKey::from_slice(&channel.node_two.0).map_err(|_| LightningError{
1105+
err: "Couldn't parse source node pubkey".to_owned(),
1106+
action: ErrorAction::IgnoreAndLog(Level::Debug)
1107+
})?);
10541108
}
10551109
maybe_update_channel_info!(channel.two_to_one, channel.node_two);
10561110
} else {
10571111
dest_node_id = channel.node_two.clone();
10581112
if let Some((sig, ctx)) = sig_info {
1059-
secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_one);
1113+
secp_verify_sig!(ctx, &msg_hash, &sig, &PublicKey::from_slice(&channel.node_one.0).map_err(|_| LightningError{
1114+
err: "Couldn't parse destination node pubkey".to_owned(),
1115+
action: ErrorAction::IgnoreAndLog(Level::Debug)
1116+
})?);
10601117
}
10611118
maybe_update_channel_info!(channel.one_to_two, channel.node_one);
10621119
}
@@ -1104,7 +1161,7 @@ impl NetworkGraph {
11041161
Ok(())
11051162
}
11061163

1107-
fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
1164+
fn remove_channel_in_nodes(nodes: &mut BTreeMap<NodeId, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
11081165
macro_rules! remove_from_node {
11091166
($node_id: expr) => {
11101167
if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
@@ -1136,7 +1193,7 @@ impl ReadOnlyNetworkGraph<'_> {
11361193
/// Returns all known nodes' public keys along with announced node info.
11371194
///
11381195
/// (C-not exported) because we have no mapping for `BTreeMap`s
1139-
pub fn nodes(&self) -> &BTreeMap<PublicKey, NodeInfo> {
1196+
pub fn nodes(&self) -> &BTreeMap<NodeId, NodeInfo> {
11401197
&*self.nodes
11411198
}
11421199

@@ -1146,7 +1203,7 @@ impl ReadOnlyNetworkGraph<'_> {
11461203
///
11471204
/// (C-not exported) as there is no practical way to track lifetimes of returned values.
11481205
pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<&Vec<NetAddress>> {
1149-
if let Some(node) = self.nodes.get(pubkey) {
1206+
if let Some(node) = self.nodes.get(&NodeId(pubkey.serialize())) {
11501207
if let Some(node_info) = node.announcement_info.as_ref() {
11511208
return Some(&node_info.addresses)
11521209
}

0 commit comments

Comments
 (0)