Skip to content

Commit 56146e7

Browse files
authored
Merge pull request #2016 from alecchendev/2023-02-gossip-msg-pubkey-to-nodeid
Swap gossip message `PublicKey` for `NodeId`
2 parents ce2ed44 + b156371 commit 56146e7

File tree

10 files changed

+122
-82
lines changed

10 files changed

+122
-82
lines changed

fuzz/src/router.rs

+14-5
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,15 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
149149
}
150150
}
151151

152+
macro_rules! get_pubkey_from_node_id {
153+
($node_id: expr ) => {
154+
match PublicKey::from_slice($node_id.as_slice()) {
155+
Ok(pk) => pk,
156+
Err(_) => return,
157+
}
158+
}
159+
}
160+
152161
macro_rules! get_pubkey {
153162
() => {
154163
match PublicKey::from_slice(get_slice!(33)) {
@@ -175,19 +184,19 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
175184
return;
176185
}
177186
let msg = decode_msg_with_len16!(msgs::UnsignedNodeAnnouncement, 288);
178-
node_pks.insert(msg.node_id);
187+
node_pks.insert(get_pubkey_from_node_id!(msg.node_id));
179188
let _ = net_graph.update_node_from_unsigned_announcement(&msg);
180189
},
181190
1 => {
182191
let msg = decode_msg_with_len16!(msgs::UnsignedChannelAnnouncement, 32+8+33*4);
183-
node_pks.insert(msg.node_id_1);
184-
node_pks.insert(msg.node_id_2);
192+
node_pks.insert(get_pubkey_from_node_id!(msg.node_id_1));
193+
node_pks.insert(get_pubkey_from_node_id!(msg.node_id_2));
185194
let _ = net_graph.update_channel_from_unsigned_announcement::<&FuzzChainSource>(&msg, &None);
186195
},
187196
2 => {
188197
let msg = decode_msg_with_len16!(msgs::UnsignedChannelAnnouncement, 32+8+33*4);
189-
node_pks.insert(msg.node_id_1);
190-
node_pks.insert(msg.node_id_2);
198+
node_pks.insert(get_pubkey_from_node_id!(msg.node_id_1));
199+
node_pks.insert(get_pubkey_from_node_id!(msg.node_id_2));
191200
let _ = net_graph.update_channel_from_unsigned_announcement(&msg, &Some(&FuzzChainSource { input: Arc::clone(&input) }));
192201
},
193202
3 => {

lightning-net-tokio/src/lib.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -584,6 +584,7 @@ mod tests {
584584
use lightning::ln::msgs::*;
585585
use lightning::ln::peer_handler::{MessageHandler, PeerManager};
586586
use lightning::ln::features::NodeFeatures;
587+
use lightning::routing::gossip::NodeId;
587588
use lightning::util::events::*;
588589
use lightning::util::test_utils::TestNodeSigner;
589590
use bitcoin::secp256k1::{Secp256k1, SecretKey, PublicKey};
@@ -614,7 +615,7 @@ mod tests {
614615
fn handle_channel_announcement(&self, _msg: &ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
615616
fn handle_channel_update(&self, _msg: &ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
616617
fn get_next_channel_announcement(&self, _starting_point: u64) -> Option<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> { None }
617-
fn get_next_node_announcement(&self, _starting_point: Option<&PublicKey>) -> Option<NodeAnnouncement> { None }
618+
fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<NodeAnnouncement> { None }
618619
fn peer_connected(&self, _their_node_id: &PublicKey, _init_msg: &Init) -> Result<(), ()> { Ok(()) }
619620
fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
620621
fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }

lightning/src/ln/chan_utils.rs

+9-4
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ use bitcoin::hash_types::{Txid, PubkeyHash};
2323

2424
use crate::ln::{PaymentHash, PaymentPreimage};
2525
use crate::ln::msgs::DecodeError;
26+
use crate::routing::gossip::NodeId;
2627
use crate::util::ser::{Readable, Writeable, Writer};
2728
use crate::util::transaction_utils;
2829

@@ -660,13 +661,17 @@ pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &Pub
660661
let broadcaster_funding_key = broadcaster.serialize();
661662
let countersignatory_funding_key = countersignatory.serialize();
662663

664+
make_funding_redeemscript_from_slices(&broadcaster_funding_key, &countersignatory_funding_key)
665+
}
666+
667+
pub(crate) fn make_funding_redeemscript_from_slices(broadcaster_funding_key: &[u8], countersignatory_funding_key: &[u8]) -> Script {
663668
let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
664669
if broadcaster_funding_key[..] < countersignatory_funding_key[..] {
665-
builder.push_slice(&broadcaster_funding_key)
666-
.push_slice(&countersignatory_funding_key)
670+
builder.push_slice(broadcaster_funding_key)
671+
.push_slice(countersignatory_funding_key)
667672
} else {
668-
builder.push_slice(&countersignatory_funding_key)
669-
.push_slice(&broadcaster_funding_key)
673+
builder.push_slice(countersignatory_funding_key)
674+
.push_slice(broadcaster_funding_key)
670675
}.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
671676
}
672677

lightning/src/ln/channel.rs

+11-9
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ use crate::chain::chaininterface::{FeeEstimator, ConfirmationTarget, LowerBounde
3636
use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, LATENCY_GRACE_PERIOD_BLOCKS};
3737
use crate::chain::transaction::{OutPoint, TransactionData};
3838
use crate::chain::keysinterface::{WriteableEcdsaChannelSigner, EntropySource, ChannelSigner, SignerProvider, NodeSigner, Recipient};
39+
use crate::routing::gossip::NodeId;
3940
use crate::util::events::ClosureReason;
4041
use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer, VecWriter};
4142
use crate::util::logger::Logger;
@@ -5416,18 +5417,19 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
54165417
return Err(ChannelError::Ignore("Cannot get a ChannelAnnouncement if the channel is not currently usable".to_owned()));
54175418
}
54185419

5419-
let node_id = node_signer.get_node_id(Recipient::Node)
5420-
.map_err(|_| ChannelError::Ignore("Failed to retrieve own public key".to_owned()))?;
5421-
let were_node_one = node_id.serialize()[..] < self.counterparty_node_id.serialize()[..];
5420+
let node_id = NodeId::from_pubkey(&node_signer.get_node_id(Recipient::Node)
5421+
.map_err(|_| ChannelError::Ignore("Failed to retrieve own public key".to_owned()))?);
5422+
let counterparty_node_id = NodeId::from_pubkey(&self.get_counterparty_node_id());
5423+
let were_node_one = node_id.as_slice() < counterparty_node_id.as_slice();
54225424

54235425
let msg = msgs::UnsignedChannelAnnouncement {
54245426
features: channelmanager::provided_channel_features(&user_config),
54255427
chain_hash,
54265428
short_channel_id: self.get_short_channel_id().unwrap(),
5427-
node_id_1: if were_node_one { node_id } else { self.get_counterparty_node_id() },
5428-
node_id_2: if were_node_one { self.get_counterparty_node_id() } else { node_id },
5429-
bitcoin_key_1: if were_node_one { self.get_holder_pubkeys().funding_pubkey } else { self.counterparty_funding_pubkey().clone() },
5430-
bitcoin_key_2: if were_node_one { self.counterparty_funding_pubkey().clone() } else { self.get_holder_pubkeys().funding_pubkey },
5429+
node_id_1: if were_node_one { node_id } else { counterparty_node_id },
5430+
node_id_2: if were_node_one { counterparty_node_id } else { node_id },
5431+
bitcoin_key_1: NodeId::from_pubkey(if were_node_one { &self.get_holder_pubkeys().funding_pubkey } else { self.counterparty_funding_pubkey() }),
5432+
bitcoin_key_2: NodeId::from_pubkey(if were_node_one { self.counterparty_funding_pubkey() } else { &self.get_holder_pubkeys().funding_pubkey }),
54315433
excess_data: Vec::new(),
54325434
};
54335435

@@ -5497,8 +5499,8 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
54975499
&self, node_signer: &NS, announcement: msgs::UnsignedChannelAnnouncement
54985500
) -> Result<msgs::ChannelAnnouncement, ChannelError> where NS::Target: NodeSigner {
54995501
if let Some((their_node_sig, their_bitcoin_sig)) = self.announcement_sigs {
5500-
let our_node_key = node_signer.get_node_id(Recipient::Node)
5501-
.map_err(|_| ChannelError::Ignore("Signer failed to retrieve own public key".to_owned()))?;
5502+
let our_node_key = NodeId::from_pubkey(&node_signer.get_node_id(Recipient::Node)
5503+
.map_err(|_| ChannelError::Ignore("Signer failed to retrieve own public key".to_owned()))?);
55025504
let were_node_one = announcement.node_id_1 == our_node_key;
55035505

55045506
let our_node_sig = node_signer.sign_gossip_message(msgs::UnsignedGossipMessage::ChannelAnnouncement(&announcement))

lightning/src/ln/msgs.rs

+15-12
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ use crate::util::ser::{LengthReadable, Readable, ReadableArgs, Writeable, Writer
4646

4747
use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
4848

49+
use crate::routing::gossip::NodeId;
50+
4951
/// 21 million * 10^8 * 1000
5052
pub(crate) const MAX_VALUE_MSAT: u64 = 21_000_000_0000_0000_000;
5153

@@ -663,7 +665,7 @@ pub struct UnsignedNodeAnnouncement {
663665
pub timestamp: u32,
664666
/// The `node_id` this announcement originated from (don't rebroadcast the `node_announcement` back
665667
/// to this node).
666-
pub node_id: PublicKey,
668+
pub node_id: NodeId,
667669
/// An RGB color for UI purposes
668670
pub rgb: [u8; 3],
669671
/// An alias, for UI purposes.
@@ -698,13 +700,13 @@ pub struct UnsignedChannelAnnouncement {
698700
/// The short channel ID
699701
pub short_channel_id: u64,
700702
/// One of the two `node_id`s which are endpoints of this channel
701-
pub node_id_1: PublicKey,
703+
pub node_id_1: NodeId,
702704
/// The other of the two `node_id`s which are endpoints of this channel
703-
pub node_id_2: PublicKey,
705+
pub node_id_2: NodeId,
704706
/// The funding key for the first node
705-
pub bitcoin_key_1: PublicKey,
707+
pub bitcoin_key_1: NodeId,
706708
/// The funding key for the second node
707-
pub bitcoin_key_2: PublicKey,
709+
pub bitcoin_key_2: NodeId,
708710
pub(crate) excess_data: Vec<u8>,
709711
}
710712
/// A [`channel_announcement`] message to be sent to or received from a peer.
@@ -1055,7 +1057,7 @@ pub trait RoutingMessageHandler : MessageSendEventsProvider {
10551057
/// the node *after* the provided pubkey and including up to one announcement immediately
10561058
/// higher (as defined by `<PublicKey as Ord>::cmp`) than `starting_point`.
10571059
/// If `None` is provided for `starting_point`, we start at the first node.
1058-
fn get_next_node_announcement(&self, starting_point: Option<&PublicKey>) -> Option<NodeAnnouncement>;
1060+
fn get_next_node_announcement(&self, starting_point: Option<&NodeId>) -> Option<NodeAnnouncement>;
10591061
/// Called when a connection is established with a peer. This can be used to
10601062
/// perform routing table synchronization using a strategy defined by the
10611063
/// implementor.
@@ -1843,7 +1845,7 @@ impl Readable for UnsignedNodeAnnouncement {
18431845
fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
18441846
let features: NodeFeatures = Readable::read(r)?;
18451847
let timestamp: u32 = Readable::read(r)?;
1846-
let node_id: PublicKey = Readable::read(r)?;
1848+
let node_id: NodeId = Readable::read(r)?;
18471849
let mut rgb = [0; 3];
18481850
r.read_exact(&mut rgb)?;
18491851
let alias: [u8; 32] = Readable::read(r)?;
@@ -2053,6 +2055,7 @@ mod tests {
20532055
use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
20542056
use crate::ln::msgs;
20552057
use crate::ln::msgs::{FinalOnionHopData, OptionalField, OnionErrorPacket, OnionHopDataFormat};
2058+
use crate::routing::gossip::NodeId;
20562059
use crate::util::ser::{Writeable, Readable, Hostname};
20572060

20582061
use bitcoin::hashes::hex::FromHex;
@@ -2160,10 +2163,10 @@ mod tests {
21602163
features,
21612164
chain_hash: BlockHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap(),
21622165
short_channel_id: 2316138423780173,
2163-
node_id_1: pubkey_1,
2164-
node_id_2: pubkey_2,
2165-
bitcoin_key_1: pubkey_3,
2166-
bitcoin_key_2: pubkey_4,
2166+
node_id_1: NodeId::from_pubkey(&pubkey_1),
2167+
node_id_2: NodeId::from_pubkey(&pubkey_2),
2168+
bitcoin_key_1: NodeId::from_pubkey(&pubkey_3),
2169+
bitcoin_key_2: NodeId::from_pubkey(&pubkey_4),
21672170
excess_data: if excess_data { vec![10, 0, 0, 20, 0, 0, 30, 0, 0, 40] } else { Vec::new() },
21682171
};
21692172
let channel_announcement = msgs::ChannelAnnouncement {
@@ -2245,7 +2248,7 @@ mod tests {
22452248
let unsigned_node_announcement = msgs::UnsignedNodeAnnouncement {
22462249
features,
22472250
timestamp: 20190119,
2248-
node_id: pubkey_1,
2251+
node_id: NodeId::from_pubkey(&pubkey_1),
22492252
rgb: [32; 3],
22502253
alias: [16;32],
22512254
addresses,

lightning/src/ln/peer_handler.rs

+17-13
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ use crate::ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
2727
use crate::ln::wire;
2828
use crate::ln::wire::Encode;
2929
use crate::onion_message::{CustomOnionMessageContents, CustomOnionMessageHandler, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
30-
use crate::routing::gossip::{NetworkGraph, P2PGossipSync};
30+
use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId};
3131
use crate::util::atomic_counter::AtomicCounter;
3232
use crate::util::events::{MessageSendEvent, MessageSendEventsProvider, OnionMessageProvider};
3333
use crate::util::logger::Logger;
@@ -71,7 +71,7 @@ impl RoutingMessageHandler for IgnoringMessageHandler {
7171
fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
7272
fn get_next_channel_announcement(&self, _starting_point: u64) ->
7373
Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { None }
74-
fn get_next_node_announcement(&self, _starting_point: Option<&PublicKey>) -> Option<msgs::NodeAnnouncement> { None }
74+
fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> { None }
7575
fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init) -> Result<(), ()> { Ok(()) }
7676
fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
7777
fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
@@ -345,7 +345,7 @@ impl error::Error for PeerHandleError {
345345
enum InitSyncTracker{
346346
NoSyncRequested,
347347
ChannelsSyncing(u64),
348-
NodesSyncing(PublicKey),
348+
NodesSyncing(NodeId),
349349
}
350350

351351
/// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop
@@ -434,15 +434,15 @@ impl Peer {
434434
}
435435

436436
/// Similar to the above, but for node announcements indexed by node_id.
437-
fn should_forward_node_announcement(&self, node_id: PublicKey) -> bool {
437+
fn should_forward_node_announcement(&self, node_id: NodeId) -> bool {
438438
if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
439439
!self.sent_gossip_timestamp_filter {
440440
return false;
441441
}
442442
match self.sync_status {
443443
InitSyncTracker::NoSyncRequested => true,
444444
InitSyncTracker::ChannelsSyncing(_) => false,
445-
InitSyncTracker::NodesSyncing(pk) => pk < node_id,
445+
InitSyncTracker::NodesSyncing(sync_node_id) => sync_node_id.as_slice() < node_id.as_slice(),
446446
}
447447
}
448448

@@ -889,8 +889,8 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CM
889889
}
890890
},
891891
InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
892-
InitSyncTracker::NodesSyncing(key) => {
893-
if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(Some(&key)) {
892+
InitSyncTracker::NodesSyncing(sync_node_id) => {
893+
if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(Some(&sync_node_id)) {
894894
self.enqueue_message(peer, &msg);
895895
peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
896896
} else {
@@ -1467,9 +1467,11 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CM
14671467
log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
14681468
continue;
14691469
}
1470-
if peer.their_node_id.as_ref() == Some(&msg.contents.node_id_1) ||
1471-
peer.their_node_id.as_ref() == Some(&msg.contents.node_id_2) {
1472-
continue;
1470+
if let Some(their_node_id) = peer.their_node_id {
1471+
let their_node_id = NodeId::from_pubkey(&their_node_id);
1472+
if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
1473+
continue;
1474+
}
14731475
}
14741476
if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
14751477
continue;
@@ -1491,8 +1493,10 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CM
14911493
log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
14921494
continue;
14931495
}
1494-
if peer.their_node_id.as_ref() == Some(&msg.contents.node_id) {
1495-
continue;
1496+
if let Some(their_node_id) = peer.their_node_id {
1497+
if NodeId::from_pubkey(&their_node_id) == msg.contents.node_id {
1498+
continue;
1499+
}
14961500
}
14971501
if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
14981502
continue;
@@ -2021,7 +2025,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CM
20212025
let announcement = msgs::UnsignedNodeAnnouncement {
20222026
features,
20232027
timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel),
2024-
node_id: self.node_signer.get_node_id(Recipient::Node).unwrap(),
2028+
node_id: NodeId::from_pubkey(&self.node_signer.get_node_id(Recipient::Node).unwrap()),
20252029
rgb, alias, addresses,
20262030
excess_address_data: Vec::new(),
20272031
excess_data: Vec::new(),

0 commit comments

Comments
 (0)