Skip to content

Commit 059bf1a

Browse files
committed
Replace PublicKey with [u8; 33] in NetworkGraph
1 parent 6582aae commit 059bf1a

File tree

2 files changed

+175
-103
lines changed

2 files changed

+175
-103
lines changed

lightning/src/routing/network_graph.rs

Lines changed: 88 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
//! The top-level network map tracking logic lives here.
1111
12+
use bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE;
1213
use bitcoin::secp256k1::key::PublicKey;
1314
use bitcoin::secp256k1::Secp256k1;
1415
use bitcoin::secp256k1;
@@ -50,12 +51,73 @@ const MAX_EXCESS_BYTES_FOR_RELAY: usize = 1024;
5051
/// This value ensures a reply fits within the 65k payload limit and is consistent with other implementations.
5152
const MAX_SCIDS_PER_REPLY: usize = 8000;
5253

54+
/// Represents the compressed public key of a node
55+
#[derive(Clone, Copy)]
56+
pub struct NodeId([u8; PUBLIC_KEY_SIZE]);
57+
58+
impl NodeId{
59+
pub fn from_pubkey(pubkey: &PublicKey) -> Self {
60+
NodeId(pubkey.serialize())
61+
}
62+
63+
pub fn as_slice(&self) -> &[u8] {
64+
&self.0
65+
}
66+
}
67+
68+
impl fmt::Debug for NodeId {
69+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70+
write!(f, "NodeId({})", log_bytes!(self.0))
71+
}
72+
}
73+
74+
impl core::hash::Hash for NodeId {
75+
fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
76+
self.0.hash(hasher);
77+
}
78+
}
79+
80+
impl Eq for NodeId {}
81+
82+
impl PartialEq for NodeId {
83+
fn eq(&self, other: &Self) -> bool {
84+
self.0[..] == other.0[..]
85+
}
86+
}
87+
88+
impl cmp::PartialOrd for NodeId {
89+
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
90+
Some(self.cmp(other))
91+
}
92+
}
93+
94+
impl Ord for NodeId {
95+
fn cmp(&self, other: &Self) -> cmp::Ordering {
96+
self.0[..].cmp(&other.0[..])
97+
}
98+
}
99+
100+
impl Writeable for NodeId {
101+
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
102+
writer.write_all(&self.0)?;
103+
Ok(())
104+
}
105+
}
106+
107+
impl Readable for NodeId {
108+
fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
109+
let mut buf = [0; PUBLIC_KEY_SIZE];
110+
reader.read_exact(&mut buf)?;
111+
Ok(Self(buf))
112+
}
113+
}
114+
53115
/// Represents the network as nodes and channels between them
54116
pub struct NetworkGraph {
55117
genesis_hash: BlockHash,
56118
// Lock order: channels -> nodes
57119
channels: RwLock<BTreeMap<u64, ChannelInfo>>,
58-
nodes: RwLock<BTreeMap<PublicKey, NodeInfo>>,
120+
nodes: RwLock<BTreeMap<NodeId, NodeInfo>>,
59121
}
60122

61123
impl Clone for NetworkGraph {
@@ -73,7 +135,7 @@ impl Clone for NetworkGraph {
73135
/// A read-only view of [`NetworkGraph`].
74136
pub struct ReadOnlyNetworkGraph<'a> {
75137
channels: RwLockReadGuard<'a, BTreeMap<u64, ChannelInfo>>,
76-
nodes: RwLockReadGuard<'a, BTreeMap<PublicKey, NodeInfo>>,
138+
nodes: RwLockReadGuard<'a, BTreeMap<NodeId, NodeInfo>>,
77139
}
78140

79141
/// Update to the [`NetworkGraph`] based on payment failure information conveyed via the Onion
@@ -277,11 +339,11 @@ where C::Target: chain::Access, L::Target: Logger
277339
let mut result = Vec::with_capacity(batch_amount as usize);
278340
let nodes = self.network_graph.nodes.read().unwrap();
279341
let mut iter = if let Some(pubkey) = starting_point {
280-
let mut iter = nodes.range((*pubkey)..);
342+
let mut iter = nodes.range(NodeId::from_pubkey(pubkey)..);
281343
iter.next();
282344
iter
283345
} else {
284-
nodes.range(..)
346+
nodes.range::<NodeId, _>(..)
285347
};
286348
while result.len() < batch_amount as usize {
287349
if let Some((_, ref node)) = iter.next() {
@@ -314,7 +376,7 @@ where C::Target: chain::Access, L::Target: Logger
314376
}
315377

316378
// Check if we need to perform a full synchronization with this peer
317-
if !self.should_request_full_sync(their_node_id) {
379+
if !self.should_request_full_sync(&their_node_id) {
318380
return ();
319381
}
320382

@@ -551,11 +613,11 @@ pub struct ChannelInfo {
551613
/// Protocol features of a channel communicated during its announcement
552614
pub features: ChannelFeatures,
553615
/// Source node of the first direction of a channel
554-
pub node_one: PublicKey,
616+
pub node_one: NodeId,
555617
/// Details about the first direction of a channel
556618
pub one_to_two: Option<DirectionalChannelInfo>,
557619
/// Source node of the second direction of a channel
558-
pub node_two: PublicKey,
620+
pub node_two: NodeId,
559621
/// Details about the second direction of a channel
560622
pub two_to_one: Option<DirectionalChannelInfo>,
561623
/// The channel capacity as seen on-chain, if chain lookup is available.
@@ -570,7 +632,7 @@ pub struct ChannelInfo {
570632
impl fmt::Display for ChannelInfo {
571633
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
572634
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)?;
635+
log_bytes!(self.features.encode()), log_bytes!(self.node_one.as_slice()), self.one_to_two, log_bytes!(self.node_two.as_slice()), self.two_to_one)?;
574636
Ok(())
575637
}
576638
}
@@ -724,8 +786,8 @@ impl fmt::Display for NetworkGraph {
724786
writeln!(f, " {}: {}", key, val)?;
725787
}
726788
writeln!(f, "[Nodes]")?;
727-
for (key, val) in self.nodes.read().unwrap().iter() {
728-
writeln!(f, " {}: {}", log_pubkey!(key), val)?;
789+
for (&node_id, val) in self.nodes.read().unwrap().iter() {
790+
writeln!(f, " {}: {}", log_bytes!(node_id.as_slice()), val)?;
729791
}
730792
Ok(())
731793
}
@@ -780,7 +842,7 @@ impl NetworkGraph {
780842
}
781843

782844
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) {
845+
match self.nodes.write().unwrap().get_mut(&NodeId::from_pubkey(&msg.node_id)) {
784846
None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
785847
Some(node) => {
786848
if let Some(node_info) = node.announcement_info.as_ref() {
@@ -886,9 +948,9 @@ impl NetworkGraph {
886948

887949
let chan_info = ChannelInfo {
888950
features: msg.features.clone(),
889-
node_one: msg.node_id_1.clone(),
951+
node_one: NodeId::from_pubkey(&msg.node_id_1),
890952
one_to_two: None,
891-
node_two: msg.node_id_2.clone(),
953+
node_two: NodeId::from_pubkey(&msg.node_id_2),
892954
two_to_one: None,
893955
capacity_sats: utxo_value,
894956
announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
@@ -939,8 +1001,8 @@ impl NetworkGraph {
9391001
};
9401002
}
9411003

942-
add_channel_to_node!(msg.node_id_1);
943-
add_channel_to_node!(msg.node_id_2);
1004+
add_channel_to_node!(NodeId::from_pubkey(&msg.node_id_1));
1005+
add_channel_to_node!(NodeId::from_pubkey(&msg.node_id_2));
9441006

9451007
Ok(())
9461008
}
@@ -1050,13 +1112,19 @@ impl NetworkGraph {
10501112
if msg.flags & 1 == 1 {
10511113
dest_node_id = channel.node_one.clone();
10521114
if let Some((sig, ctx)) = sig_info {
1053-
secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_two);
1115+
secp_verify_sig!(ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_two.as_slice()).map_err(|_| LightningError{
1116+
err: "Couldn't parse source node pubkey".to_owned(),
1117+
action: ErrorAction::IgnoreAndLog(Level::Debug)
1118+
})?);
10541119
}
10551120
maybe_update_channel_info!(channel.two_to_one, channel.node_two);
10561121
} else {
10571122
dest_node_id = channel.node_two.clone();
10581123
if let Some((sig, ctx)) = sig_info {
1059-
secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_one);
1124+
secp_verify_sig!(ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_one.as_slice()).map_err(|_| LightningError{
1125+
err: "Couldn't parse destination node pubkey".to_owned(),
1126+
action: ErrorAction::IgnoreAndLog(Level::Debug)
1127+
})?);
10601128
}
10611129
maybe_update_channel_info!(channel.one_to_two, channel.node_one);
10621130
}
@@ -1104,7 +1172,7 @@ impl NetworkGraph {
11041172
Ok(())
11051173
}
11061174

1107-
fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
1175+
fn remove_channel_in_nodes(nodes: &mut BTreeMap<NodeId, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
11081176
macro_rules! remove_from_node {
11091177
($node_id: expr) => {
11101178
if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
@@ -1136,7 +1204,7 @@ impl ReadOnlyNetworkGraph<'_> {
11361204
/// Returns all known nodes' public keys along with announced node info.
11371205
///
11381206
/// (C-not exported) because we have no mapping for `BTreeMap`s
1139-
pub fn nodes(&self) -> &BTreeMap<PublicKey, NodeInfo> {
1207+
pub fn nodes(&self) -> &BTreeMap<NodeId, NodeInfo> {
11401208
&*self.nodes
11411209
}
11421210

@@ -1146,7 +1214,7 @@ impl ReadOnlyNetworkGraph<'_> {
11461214
///
11471215
/// (C-not exported) as there is no practical way to track lifetimes of returned values.
11481216
pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<&Vec<NetAddress>> {
1149-
if let Some(node) = self.nodes.get(pubkey) {
1217+
if let Some(node) = self.nodes.get(&NodeId::from_pubkey(&pubkey)) {
11501218
if let Some(node_info) = node.announcement_info.as_ref() {
11511219
return Some(&node_info.addresses)
11521220
}

0 commit comments

Comments
 (0)