Skip to content

Commit 198b089

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 e17765f commit 198b089

File tree

4 files changed

+96
-0
lines changed

4 files changed

+96
-0
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,8 @@ pub struct ChannelManager<ChanSigner: ChannelKeys> {
350350
channel_state: Mutex<ChannelHolder<ChanSigner>>,
351351
our_network_key: SecretKey,
352352

353+
last_node_announcement_serial: AtomicUsize,
354+
353355
/// Per-peer state storage.
354356
/// Because adding or removing an entry is rare, we usually take an outer read lock and then
355357
/// operate on the inner value freely. Sadly, this prevents parallel operation when opening a
@@ -642,6 +644,8 @@ impl<ChanSigner: ChannelKeys> ChannelManager<ChanSigner> {
642644
}),
643645
our_network_key: keys_manager.get_node_secret(),
644646

647+
last_node_announcement_serial: AtomicUsize::new(0),
648+
645649
per_peer_state: RwLock::new(HashMap::new()),
646650

647651
pending_events: Mutex::new(Vec::new()),
@@ -1354,6 +1358,37 @@ impl<ChanSigner: ChannelKeys> ChannelManager<ChanSigner> {
13541358
})
13551359
}
13561360

1361+
/// Generates a signed node_announcement from the given arguments and creates a
1362+
/// BroadcastNodeAnnouncement event.
1363+
///
1364+
/// RGB is a node "color" and alias a printable human-readable string to describe this node to
1365+
/// humans. They carry no in-protocol meaning.
1366+
///
1367+
/// addresses represent the set (possibly empty) of socket addresses on which this node accepts
1368+
/// incoming connections.
1369+
pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], addresses: msgs::NetAddressSet) {
1370+
let _ = self.total_consistency_lock.read().unwrap();
1371+
1372+
let announcement = msgs::UnsignedNodeAnnouncement {
1373+
features: Features::<msgs::FeatureContextNode>::our_features(),
1374+
timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel) as u32,
1375+
node_id: self.get_our_node_id(),
1376+
rgb, alias,
1377+
addresses: addresses.to_vec(),
1378+
excess_address_data: Vec::new(),
1379+
excess_data: Vec::new(),
1380+
};
1381+
let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1382+
1383+
let mut channel_state = self.channel_state.lock().unwrap();
1384+
channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastNodeAnnouncement {
1385+
msg: msgs::NodeAnnouncement {
1386+
signature: self.secp_ctx.sign(&msghash, &self.our_network_key),
1387+
contents: announcement
1388+
},
1389+
});
1390+
}
1391+
13571392
/// Processes HTLCs which are pending waiting on random forward delay.
13581393
///
13591394
/// Should only really ever be called in response to a PendingHTLCsForwardable event.
@@ -2944,6 +2979,7 @@ impl<ChanSigner: ChannelKeys> ChannelMessageHandler for ChannelManager<ChanSigne
29442979
&events::MessageSendEvent::SendShutdown { ref node_id, .. } => node_id != their_node_id,
29452980
&events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => node_id != their_node_id,
29462981
&events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
2982+
&events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
29472983
&events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
29482984
&events::MessageSendEvent::HandleError { ref node_id, .. } => node_id != their_node_id,
29492985
&events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => true,
@@ -3257,6 +3293,8 @@ impl<ChanSigner: ChannelKeys + Writeable> Writeable for ChannelManager<ChanSigne
32573293
peer_state.latest_features.write(writer)?;
32583294
}
32593295

3296+
(self.last_node_announcement_serial.load(Ordering::Acquire) as u32).write(writer)?;
3297+
32603298
Ok(())
32613299
}
32623300
}
@@ -3400,6 +3438,8 @@ impl<'a, R : ::std::io::Read, ChanSigner: ChannelKeys + Readable<R>> ReadableArg
34003438
per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
34013439
}
34023440

3441+
let last_node_announcement_serial: u32 = Readable::read(reader)?;
3442+
34033443
let channel_manager = ChannelManager {
34043444
genesis_hash,
34053445
fee_estimator: args.fee_estimator,
@@ -3419,6 +3459,8 @@ impl<'a, R : ::std::io::Read, ChanSigner: ChannelKeys + Readable<R>> ReadableArg
34193459
}),
34203460
our_network_key: args.keys_manager.get_node_secret(),
34213461

3462+
last_node_announcement_serial: AtomicUsize::new(last_node_announcement_serial as usize),
3463+
34223464
per_peer_state: RwLock::new(per_peer_state),
34233465

34243466
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
@@ -296,10 +296,33 @@ pub fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize
296296

297297
pub fn create_announced_chan_between_nodes_with_value(nodes: &Vec<Node>, a: usize, b: usize, channel_value: u64, push_msat: u64, a_flags: Features<FeatureContextInit>, b_flags: Features<FeatureContextInit>) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
298298
let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat, a_flags, b_flags);
299+
300+
nodes[a].node.broadcast_node_announcement([0, 0, 0], [0; 32], msgs::NetAddressSet::new());
301+
let a_events = nodes[a].node.get_and_clear_pending_msg_events();
302+
assert_eq!(a_events.len(), 1);
303+
let a_node_announcement = match a_events[0] {
304+
MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
305+
(*msg).clone()
306+
},
307+
_ => panic!("Unexpected event"),
308+
};
309+
310+
nodes[b].node.broadcast_node_announcement([1, 1, 1], [1; 32], msgs::NetAddressSet::new());
311+
let b_events = nodes[b].node.get_and_clear_pending_msg_events();
312+
assert_eq!(b_events.len(), 1);
313+
let b_node_announcement = match b_events[0] {
314+
MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
315+
(*msg).clone()
316+
},
317+
_ => panic!("Unexpected event"),
318+
};
319+
299320
for node in nodes {
300321
assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
301322
node.router.handle_channel_update(&chan_announcement.1).unwrap();
302323
node.router.handle_channel_update(&chan_announcement.2).unwrap();
324+
node.router.handle_node_announcement(&a_node_announcement).unwrap();
325+
node.router.handle_node_announcement(&b_node_announcement).unwrap();
303326
}
304327
(chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
305328
}

lightning/src/ln/peer_handler.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,14 @@ impl Peer {
130130
InitSyncTracker::NodesSyncing(_) => true,
131131
}
132132
}
133+
134+
fn should_forward_node(&self, node_id: PublicKey) -> bool {
135+
match self.sync_status {
136+
InitSyncTracker::NoSyncRequested => true,
137+
InitSyncTracker::ChannelsSyncing(_) => false,
138+
InitSyncTracker::NodesSyncing(pk) => pk < node_id,
139+
}
140+
}
133141
}
134142

135143
struct PeerHolder<Descriptor: SocketDescriptor> {
@@ -990,6 +998,21 @@ impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
990998
}
991999
}
9921000
},
1001+
MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
1002+
log_trace!(self, "Handling BroadcastNodeAnnouncement event in peer_handler");
1003+
if self.message_handler.route_handler.handle_node_announcement(msg).is_ok() {
1004+
let encoded_msg = encode_msg!(msg, 257);
1005+
1006+
for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
1007+
if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1008+
!peer.should_forward_node(msg.contents.node_id) {
1009+
continue
1010+
}
1011+
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
1012+
self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
1013+
}
1014+
}
1015+
},
9931016
MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9941017
log_trace!(self, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
9951018
if self.message_handler.route_handler.handle_channel_update(msg).is_ok() {

lightning/src/util/events.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,12 +194,20 @@ pub enum MessageSendEvent {
194194
},
195195
/// Used to indicate that a channel_announcement and channel_update should be broadcast to all
196196
/// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
197+
///
198+
/// Note that after doing so, you very likely (unless you did so very recently) want to call
199+
/// ChannelManager::broadcast_node_announcement to trigger a BroadcastNodeAnnouncement event.
197200
BroadcastChannelAnnouncement {
198201
/// The channel_announcement which should be sent.
199202
msg: msgs::ChannelAnnouncement,
200203
/// The followup channel_update which should be sent.
201204
update_msg: msgs::ChannelUpdate,
202205
},
206+
/// Used to indicate that a node_announcement should be broadcast to all peers.
207+
BroadcastNodeAnnouncement {
208+
/// The node_announcement which should be sent.
209+
msg: msgs::NodeAnnouncement,
210+
},
203211
/// Used to indicate that a channel_update should be broadcast to all peers.
204212
BroadcastChannelUpdate {
205213
/// The channel_update which should be sent.

0 commit comments

Comments
 (0)