Skip to content

Commit b776501

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 1cab5da commit b776501

File tree

4 files changed

+109
-4
lines changed

4 files changed

+109
-4
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 48 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,40 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
13341340
})
13351341
}
13361342

1343+
/// Generates a signed node_announcement from the given arguments and creates a
1344+
/// BroadcastNodeAnnouncement event. Note that such messages will be ignored unless peers have
1345+
/// seen a channel_announcement from us (ie unless we have public channels open).
1346+
///
1347+
/// RGB is a node "color" and alias is a printable human-readable string to describe this node
1348+
/// to humans. They carry no in-protocol meaning.
1349+
///
1350+
/// addresses represent the set (possibly empty) of socket addresses on which this node accepts
1351+
/// incoming connections. These will be broadcast to the network, publicly tying these
1352+
/// addresses together. If you wish to preserve user privacy, addresses should likely contain
1353+
/// only Tor Onion addresses.
1354+
pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], addresses: msgs::NetAddressSet) {
1355+
let _ = self.total_consistency_lock.read().unwrap();
1356+
1357+
let announcement = msgs::UnsignedNodeAnnouncement {
1358+
features: NodeFeatures::supported(),
1359+
timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel) as u32,
1360+
node_id: self.get_our_node_id(),
1361+
rgb, alias,
1362+
addresses: addresses.into_vec(),
1363+
excess_address_data: Vec::new(),
1364+
excess_data: Vec::new(),
1365+
};
1366+
let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1367+
1368+
let mut channel_state = self.channel_state.lock().unwrap();
1369+
channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastNodeAnnouncement {
1370+
msg: msgs::NodeAnnouncement {
1371+
signature: self.secp_ctx.sign(&msghash, &self.our_network_key),
1372+
contents: announcement
1373+
},
1374+
});
1375+
}
1376+
13371377
/// Processes HTLCs which are pending waiting on random forward delay.
13381378
///
13391379
/// Should only really ever be called in response to a PendingHTLCsForwardable event.
@@ -2970,6 +3010,7 @@ impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send, T: Deref + Sync + Send, K:
29703010
&events::MessageSendEvent::SendShutdown { ref node_id, .. } => node_id != their_node_id,
29713011
&events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => node_id != their_node_id,
29723012
&events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
3013+
&events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
29733014
&events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
29743015
&events::MessageSendEvent::HandleError { ref node_id, .. } => node_id != their_node_id,
29753016
&events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => true,
@@ -3288,6 +3329,8 @@ impl<ChanSigner: ChannelKeys + Writeable, M: Deref, T: Deref, K: Deref, F: Deref
32883329
peer_state.latest_features.write(writer)?;
32893330
}
32903331

3332+
(self.last_node_announcement_serial.load(Ordering::Acquire) as u32).write(writer)?;
3333+
32913334
Ok(())
32923335
}
32933336
}
@@ -3459,6 +3502,8 @@ impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: De
34593502
per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
34603503
}
34613504

3505+
let last_node_announcement_serial: u32 = Readable::read(reader)?;
3506+
34623507
let channel_manager = ChannelManager {
34633508
genesis_hash,
34643509
fee_estimator: args.fee_estimator,
@@ -3478,6 +3523,8 @@ impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: De
34783523
}),
34793524
our_network_key: args.keys_manager.get_node_secret(),
34803525

3526+
last_node_announcement_serial: AtomicUsize::new(last_node_announcement_serial as usize),
3527+
34813528
per_peer_state: RwLock::new(per_peer_state),
34823529

34833530
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], msgs::NetAddressSet::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], msgs::NetAddressSet::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/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> {
@@ -958,7 +967,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref> PeerManager<Descriptor, CM> where
958967

959968
for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
960969
if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
961-
!peer.should_forward_channel(msg.contents.short_channel_id) {
970+
!peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
962971
continue
963972
}
964973
match peer.their_node_id {
@@ -975,14 +984,29 @@ impl<Descriptor: SocketDescriptor, CM: Deref> PeerManager<Descriptor, CM> where
975984
}
976985
}
977986
},
987+
MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
988+
log_trace!(self, "Handling BroadcastNodeAnnouncement event in peer_handler");
989+
if self.message_handler.route_handler.handle_node_announcement(msg).is_ok() {
990+
let encoded_msg = encode_msg!(msg);
991+
992+
for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
993+
if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
994+
!peer.should_forward_node_announcement(msg.contents.node_id) {
995+
continue
996+
}
997+
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
998+
self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
999+
}
1000+
}
1001+
},
9781002
MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9791003
log_trace!(self, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
9801004
if self.message_handler.route_handler.handle_channel_update(msg).is_ok() {
9811005
let encoded_msg = encode_msg!(msg);
9821006

9831007
for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
9841008
if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
985-
!peer.should_forward_channel(msg.contents.short_channel_id) {
1009+
!peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
9861010
continue
9871011
}
9881012
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)