Skip to content

Commit 3e18dc0

Browse files
committed
Add ability to broadcast our own node_announcement.
This is a somewhat-obvious oversight in the capabilities of rust-lightning, though not a particularly interesting one until we start relying on node_features (eg for variable-length-onions and Base AMP). Sadly its not fully automated as we don't really want to store the list of available addresses from the user. However, with a simple call to ChannelManager::broadcast_node_announcement and a sensible peer_handler, the announcement is made.
1 parent 74ee9ea commit 3e18dc0

File tree

5 files changed

+122
-4
lines changed

5 files changed

+122
-4
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 58 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@ use chain::chaininterface::{BroadcasterInterface,ChainListener,FeeEstimator};
2929
use chain::transaction::OutPoint;
3030
use ln::channel::{Channel, ChannelError};
3131
use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
32+
use ln::features::{InitFeatures, NodeFeatures};
3233
use ln::router::Route;
33-
use ln::features::InitFeatures;
3434
use ln::msgs;
3535
use ln::onion_utils;
3636
use ln::msgs::{ChannelMessageHandler, DecodeError, LightningError};
@@ -368,6 +368,10 @@ pub struct ChannelManager<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref,
368368
channel_state: Mutex<ChannelHolder<ChanSigner>>,
369369
our_network_key: SecretKey,
370370

371+
/// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
372+
/// value increases strictly since we don't assume access to a time source.
373+
last_node_announcement_serial: AtomicUsize,
374+
371375
/// The bulk of our storage will eventually be here (channels and message queues and the like).
372376
/// If we are connected to a peer we always at least have an entry here, even if no channels
373377
/// are currently open with that peer.
@@ -665,6 +669,8 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
665669
}),
666670
our_network_key: keys_manager.get_node_secret(),
667671

672+
last_node_announcement_serial: AtomicUsize::new(0),
673+
668674
per_peer_state: RwLock::new(HashMap::new()),
669675

670676
pending_events: Mutex::new(Vec::new()),
@@ -1334,6 +1340,50 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
13341340
})
13351341
}
13361342

1343+
#[allow(dead_code)]
1344+
const HALF_MESSAGE_IS_ADDRS: u32 = 64*1024 / (msgs::NetAddress::MAX_LEN as u32 + 1) / 2;
1345+
#[deny(const_err)]
1346+
#[allow(dead_code)]
1347+
const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 500; // This will fail to compile if we use half of the message with 500 addresses
1348+
/// Generates a signed node_announcement from the given arguments and creates a
1349+
/// BroadcastNodeAnnouncement event. Note that such messages will be ignored unless peers have
1350+
/// seen a channel_announcement from us (ie unless we have public channels open).
1351+
///
1352+
/// RGB is a node "color" and alias is a printable human-readable string to describe this node
1353+
/// to humans. They carry no in-protocol meaning.
1354+
///
1355+
/// addresses represent the set (possibly empty) of socket addresses on which this node accepts
1356+
/// incoming connections. These will be broadcast to the network, publicly tying these
1357+
/// addresses together. If you wish to preserve user privacy, addresses should likely contain
1358+
/// only Tor Onion addresses.
1359+
///
1360+
/// Panics if addresses is absurdly large (more than 500).
1361+
pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], addresses: Vec<msgs::NetAddress>) {
1362+
let _ = self.total_consistency_lock.read().unwrap();
1363+
1364+
if addresses.len() > 500 {
1365+
panic!("More than half the message size was taken up by public addresses!");
1366+
}
1367+
1368+
let announcement = msgs::UnsignedNodeAnnouncement {
1369+
features: NodeFeatures::supported(),
1370+
timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel) as u32,
1371+
node_id: self.get_our_node_id(),
1372+
rgb, alias, addresses,
1373+
excess_address_data: Vec::new(),
1374+
excess_data: Vec::new(),
1375+
};
1376+
let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1377+
1378+
let mut channel_state = self.channel_state.lock().unwrap();
1379+
channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastNodeAnnouncement {
1380+
msg: msgs::NodeAnnouncement {
1381+
signature: self.secp_ctx.sign(&msghash, &self.our_network_key),
1382+
contents: announcement
1383+
},
1384+
});
1385+
}
1386+
13371387
/// Processes HTLCs which are pending waiting on random forward delay.
13381388
///
13391389
/// Should only really ever be called in response to a PendingHTLCsForwardable event.
@@ -2970,6 +3020,7 @@ impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send, T: Deref + Sync + Send, K:
29703020
&events::MessageSendEvent::SendShutdown { ref node_id, .. } => node_id != their_node_id,
29713021
&events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => node_id != their_node_id,
29723022
&events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
3023+
&events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
29733024
&events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
29743025
&events::MessageSendEvent::HandleError { ref node_id, .. } => node_id != their_node_id,
29753026
&events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => true,
@@ -3288,6 +3339,8 @@ impl<ChanSigner: ChannelKeys + Writeable, M: Deref, T: Deref, K: Deref, F: Deref
32883339
peer_state.latest_features.write(writer)?;
32893340
}
32903341

3342+
(self.last_node_announcement_serial.load(Ordering::Acquire) as u32).write(writer)?;
3343+
32913344
Ok(())
32923345
}
32933346
}
@@ -3459,6 +3512,8 @@ impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: De
34593512
per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
34603513
}
34613514

3515+
let last_node_announcement_serial: u32 = Readable::read(reader)?;
3516+
34623517
let channel_manager = ChannelManager {
34633518
genesis_hash,
34643519
fee_estimator: args.fee_estimator,
@@ -3478,6 +3533,8 @@ impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: De
34783533
}),
34793534
our_network_key: args.keys_manager.get_node_secret(),
34803535

3536+
last_node_announcement_serial: AtomicUsize::new(last_node_announcement_serial as usize),
3537+
34813538
per_peer_state: RwLock::new(per_peer_state),
34823539

34833540
pending_events: Mutex::new(Vec::new()),

lightning/src/ln/functional_test_utils.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,10 +394,33 @@ pub fn create_announced_chan_between_nodes<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'
394394

395395
pub fn create_announced_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
396396
let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat, a_flags, b_flags);
397+
398+
nodes[a].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
399+
let a_events = nodes[a].node.get_and_clear_pending_msg_events();
400+
assert_eq!(a_events.len(), 1);
401+
let a_node_announcement = match a_events[0] {
402+
MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
403+
(*msg).clone()
404+
},
405+
_ => panic!("Unexpected event"),
406+
};
407+
408+
nodes[b].node.broadcast_node_announcement([1, 1, 1], [1; 32], Vec::new());
409+
let b_events = nodes[b].node.get_and_clear_pending_msg_events();
410+
assert_eq!(b_events.len(), 1);
411+
let b_node_announcement = match b_events[0] {
412+
MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
413+
(*msg).clone()
414+
},
415+
_ => panic!("Unexpected event"),
416+
};
417+
397418
for node in nodes {
398419
assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
399420
node.router.handle_channel_update(&chan_announcement.1).unwrap();
400421
node.router.handle_channel_update(&chan_announcement.2).unwrap();
422+
node.router.handle_node_announcement(&a_node_announcement).unwrap();
423+
node.router.handle_node_announcement(&b_node_announcement).unwrap();
401424
}
402425
(chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
403426
}

lightning/src/ln/msgs.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,9 @@ impl NetAddress {
302302
&NetAddress::OnionV3 { .. } => { 37 },
303303
}
304304
}
305+
306+
/// The maximum length of any address descriptor, not including the 1-byte type
307+
pub(crate) const MAX_LEN: u16 = 37;
305308
}
306309

307310
impl Writeable for NetAddress {

lightning/src/ln/peer_handler.rs

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -133,13 +133,22 @@ impl Peer {
133133
/// announcements/updates for the given channel_id then we will send it when we get to that
134134
/// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
135135
/// sent the old versions, we should send the update, and so return true here.
136-
fn should_forward_channel(&self, channel_id: u64)->bool{
136+
fn should_forward_channel_announcement(&self, channel_id: u64)->bool{
137137
match self.sync_status {
138138
InitSyncTracker::NoSyncRequested => true,
139139
InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
140140
InitSyncTracker::NodesSyncing(_) => true,
141141
}
142142
}
143+
144+
/// Similar to the above, but for node announcements indexed by node_id.
145+
fn should_forward_node_announcement(&self, node_id: PublicKey) -> bool {
146+
match self.sync_status {
147+
InitSyncTracker::NoSyncRequested => true,
148+
InitSyncTracker::ChannelsSyncing(_) => false,
149+
InitSyncTracker::NodesSyncing(pk) => pk < node_id,
150+
}
151+
}
143152
}
144153

145154
struct PeerHolder<Descriptor: SocketDescriptor> {
@@ -954,7 +963,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref> PeerManager<Descriptor, CM> where
954963

955964
for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
956965
if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
957-
!peer.should_forward_channel(msg.contents.short_channel_id) {
966+
!peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
958967
continue
959968
}
960969
match peer.their_node_id {
@@ -971,14 +980,29 @@ impl<Descriptor: SocketDescriptor, CM: Deref> PeerManager<Descriptor, CM> where
971980
}
972981
}
973982
},
983+
MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
984+
log_trace!(self, "Handling BroadcastNodeAnnouncement event in peer_handler");
985+
if self.message_handler.route_handler.handle_node_announcement(msg).is_ok() {
986+
let encoded_msg = encode_msg!(msg);
987+
988+
for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
989+
if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
990+
!peer.should_forward_node_announcement(msg.contents.node_id) {
991+
continue
992+
}
993+
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
994+
self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
995+
}
996+
}
997+
},
974998
MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
975999
log_trace!(self, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
9761000
if self.message_handler.route_handler.handle_channel_update(msg).is_ok() {
9771001
let encoded_msg = encode_msg!(msg);
9781002

9791003
for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
9801004
if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
981-
!peer.should_forward_channel(msg.contents.short_channel_id) {
1005+
!peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
9821006
continue
9831007
}
9841008
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));

lightning/src/util/events.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,12 +278,23 @@ pub enum MessageSendEvent {
278278
},
279279
/// Used to indicate that a channel_announcement and channel_update should be broadcast to all
280280
/// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
281+
///
282+
/// Note that after doing so, you very likely (unless you did so very recently) want to call
283+
/// ChannelManager::broadcast_node_announcement to trigger a BroadcastNodeAnnouncement event.
284+
/// This ensures that any nodes which see our channel_announcement also have a relevant
285+
/// node_announcement, including relevant feature flags which may be important for routing
286+
/// through or to us.
281287
BroadcastChannelAnnouncement {
282288
/// The channel_announcement which should be sent.
283289
msg: msgs::ChannelAnnouncement,
284290
/// The followup channel_update which should be sent.
285291
update_msg: msgs::ChannelUpdate,
286292
},
293+
/// Used to indicate that a node_announcement should be broadcast to all peers.
294+
BroadcastNodeAnnouncement {
295+
/// The node_announcement which should be sent.
296+
msg: msgs::NodeAnnouncement,
297+
},
287298
/// Used to indicate that a channel_update should be broadcast to all peers.
288299
BroadcastChannelUpdate {
289300
/// The channel_update which should be sent.

0 commit comments

Comments
 (0)