Skip to content

Commit 646acb8

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 a087f75 commit 646acb8

File tree

4 files changed

+101
-1
lines changed

4 files changed

+101
-1
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ 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};
3232
use ln::router::Route;
33-
use ln::features::InitFeatures;
33+
use ln::features::{InitFeatures, NodeFeatures};
3434
use ln::msgs;
3535
use ln::onion_utils;
3636
use ln::msgs::{ChannelMessageHandler, DecodeError, LightningError};
@@ -355,6 +355,10 @@ pub struct ChannelManager<ChanSigner: ChannelKeys, M: Deref> where M::Target: Ma
355355
channel_state: Mutex<ChannelHolder<ChanSigner>>,
356356
our_network_key: SecretKey,
357357

358+
/// Used to track the last value sent in a node_announcement "timestamp" field. We just set
359+
/// them to be monotonically increasing since we don't assume access to a time source.
360+
last_node_announcement_serial: AtomicUsize,
361+
358362
/// The bulk of our storage will eventually be here (channels and message queues and the like).
359363
/// If we are connected to a peer we always at least have an entry here, even if no channels
360364
/// are currently open with that peer.
@@ -649,6 +653,8 @@ impl<ChanSigner: ChannelKeys, M: Deref> ChannelManager<ChanSigner, M> where M::T
649653
}),
650654
our_network_key: keys_manager.get_node_secret(),
651655

656+
last_node_announcement_serial: AtomicUsize::new(0),
657+
652658
per_peer_state: RwLock::new(HashMap::new()),
653659

654660
pending_events: Mutex::new(Vec::new()),
@@ -1317,6 +1323,39 @@ impl<ChanSigner: ChannelKeys, M: Deref> ChannelManager<ChanSigner, M> where M::T
13171323
})
13181324
}
13191325

1326+
/// Generates a signed node_announcement from the given arguments and creates a
1327+
/// BroadcastNodeAnnouncement event.
1328+
///
1329+
/// RGB is a node "color" and alias a printable human-readable string to describe this node to
1330+
/// humans. They carry no in-protocol meaning.
1331+
///
1332+
/// addresses represent the set (possibly empty) of socket addresses on which this node accepts
1333+
/// incoming connections. These will be broadcast to the network, publicly tying these
1334+
/// addresses together. If you wish to preserve user privacy, addresses should likely contain
1335+
/// only Tor Onion addresses.
1336+
pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], addresses: msgs::NetAddressSet) {
1337+
let _ = self.total_consistency_lock.read().unwrap();
1338+
1339+
let announcement = msgs::UnsignedNodeAnnouncement {
1340+
features: NodeFeatures::supported(),
1341+
timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel) as u32,
1342+
node_id: self.get_our_node_id(),
1343+
rgb, alias,
1344+
addresses: addresses.to_vec(),
1345+
excess_address_data: Vec::new(),
1346+
excess_data: Vec::new(),
1347+
};
1348+
let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1349+
1350+
let mut channel_state = self.channel_state.lock().unwrap();
1351+
channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastNodeAnnouncement {
1352+
msg: msgs::NodeAnnouncement {
1353+
signature: self.secp_ctx.sign(&msghash, &self.our_network_key),
1354+
contents: announcement
1355+
},
1356+
});
1357+
}
1358+
13201359
/// Processes HTLCs which are pending waiting on random forward delay.
13211360
///
13221361
/// Should only really ever be called in response to a PendingHTLCsForwardable event.
@@ -2918,6 +2957,7 @@ impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send> ChannelMessageHandler for
29182957
&events::MessageSendEvent::SendShutdown { ref node_id, .. } => node_id != their_node_id,
29192958
&events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => node_id != their_node_id,
29202959
&events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
2960+
&events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
29212961
&events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
29222962
&events::MessageSendEvent::HandleError { ref node_id, .. } => node_id != their_node_id,
29232963
&events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => true,
@@ -3231,6 +3271,8 @@ impl<ChanSigner: ChannelKeys + Writeable, M: Deref> Writeable for ChannelManager
32313271
peer_state.latest_features.write(writer)?;
32323272
}
32333273

3274+
(self.last_node_announcement_serial.load(Ordering::Acquire) as u32).write(writer)?;
3275+
32343276
Ok(())
32353277
}
32363278
}
@@ -3374,6 +3416,8 @@ impl<'a, R : ::std::io::Read, ChanSigner: ChannelKeys + Readable<R>, M: Deref> R
33743416
per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
33753417
}
33763418

3419+
let last_node_announcement_serial: u32 = Readable::read(reader)?;
3420+
33773421
let channel_manager = ChannelManager {
33783422
genesis_hash,
33793423
fee_estimator: args.fee_estimator,
@@ -3393,6 +3437,8 @@ impl<'a, R : ::std::io::Read, ChanSigner: ChannelKeys + Readable<R>, M: Deref> R
33933437
}),
33943438
our_network_key: args.keys_manager.get_node_secret(),
33953439

3440+
last_node_announcement_serial: AtomicUsize::new(last_node_announcement_serial as usize),
3441+
33963442
per_peer_state: RwLock::new(per_peer_state),
33973443

33983444
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
@@ -310,10 +310,33 @@ pub fn create_announced_chan_between_nodes<'a, 'b, 'c>(nodes: &'a Vec<Node<'b, '
310310

311311
pub fn create_announced_chan_between_nodes_with_value<'a, 'b, 'c>(nodes: &'a Vec<Node<'b, 'c>>, a: usize, b: usize, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
312312
let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat, a_flags, b_flags);
313+
314+
nodes[a].node.broadcast_node_announcement([0, 0, 0], [0; 32], msgs::NetAddressSet::new());
315+
let a_events = nodes[a].node.get_and_clear_pending_msg_events();
316+
assert_eq!(a_events.len(), 1);
317+
let a_node_announcement = match a_events[0] {
318+
MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
319+
(*msg).clone()
320+
},
321+
_ => panic!("Unexpected event"),
322+
};
323+
324+
nodes[b].node.broadcast_node_announcement([1, 1, 1], [1; 32], msgs::NetAddressSet::new());
325+
let b_events = nodes[b].node.get_and_clear_pending_msg_events();
326+
assert_eq!(b_events.len(), 1);
327+
let b_node_announcement = match b_events[0] {
328+
MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
329+
(*msg).clone()
330+
},
331+
_ => panic!("Unexpected event"),
332+
};
333+
313334
for node in nodes {
314335
assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
315336
node.router.handle_channel_update(&chan_announcement.1).unwrap();
316337
node.router.handle_channel_update(&chan_announcement.2).unwrap();
338+
node.router.handle_node_announcement(&a_node_announcement).unwrap();
339+
node.router.handle_node_announcement(&b_node_announcement).unwrap();
317340
}
318341
(chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
319342
}

lightning/src/ln/peer_handler.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,14 @@ impl Peer {
138138
InitSyncTracker::NodesSyncing(_) => true,
139139
}
140140
}
141+
142+
fn should_forward_node(&self, node_id: PublicKey) -> bool {
143+
match self.sync_status {
144+
InitSyncTracker::NoSyncRequested => true,
145+
InitSyncTracker::ChannelsSyncing(_) => false,
146+
InitSyncTracker::NodesSyncing(pk) => pk < node_id,
147+
}
148+
}
141149
}
142150

143151
struct PeerHolder<Descriptor: SocketDescriptor> {
@@ -969,6 +977,21 @@ impl<Descriptor: SocketDescriptor, CM: Deref> PeerManager<Descriptor, CM> where
969977
}
970978
}
971979
},
980+
MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
981+
log_trace!(self, "Handling BroadcastNodeAnnouncement event in peer_handler");
982+
if self.message_handler.route_handler.handle_node_announcement(msg).is_ok() {
983+
let encoded_msg = encode_msg!(msg);
984+
985+
for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
986+
if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
987+
!peer.should_forward_node(msg.contents.node_id) {
988+
continue
989+
}
990+
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
991+
self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
992+
}
993+
}
994+
},
972995
MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
973996
log_trace!(self, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
974997
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
@@ -195,12 +195,20 @@ pub enum MessageSendEvent {
195195
},
196196
/// Used to indicate that a channel_announcement and channel_update should be broadcast to all
197197
/// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
198+
///
199+
/// Note that after doing so, you very likely (unless you did so very recently) want to call
200+
/// ChannelManager::broadcast_node_announcement to trigger a BroadcastNodeAnnouncement event.
198201
BroadcastChannelAnnouncement {
199202
/// The channel_announcement which should be sent.
200203
msg: msgs::ChannelAnnouncement,
201204
/// The followup channel_update which should be sent.
202205
update_msg: msgs::ChannelUpdate,
203206
},
207+
/// Used to indicate that a node_announcement should be broadcast to all peers.
208+
BroadcastNodeAnnouncement {
209+
/// The node_announcement which should be sent.
210+
msg: msgs::NodeAnnouncement,
211+
},
204212
/// Used to indicate that a channel_update should be broadcast to all peers.
205213
BroadcastChannelUpdate {
206214
/// The channel_update which should be sent.

0 commit comments

Comments
 (0)