Skip to content

Commit 625ac49

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 e3a061a commit 625ac49

File tree

4 files changed

+102
-1
lines changed

4 files changed

+102
-1
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 47 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 just set
372+
/// them to be monotonically increasing 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()),
@@ -1333,6 +1339,39 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
13331339
})
13341340
}
13351341

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

3330+
(self.last_node_announcement_serial.load(Ordering::Acquire) as u32).write(writer)?;
3331+
32903332
Ok(())
32913333
}
32923334
}
@@ -3443,6 +3485,8 @@ impl<'a, R : ::std::io::Read, ChanSigner: ChannelKeys + Readable<R>, M: Deref, T
34433485
per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
34443486
}
34453487

3488+
let last_node_announcement_serial: u32 = Readable::read(reader)?;
3489+
34463490
let channel_manager = ChannelManager {
34473491
genesis_hash,
34483492
fee_estimator: args.fee_estimator,
@@ -3462,6 +3506,8 @@ impl<'a, R : ::std::io::Read, ChanSigner: ChannelKeys + Readable<R>, M: Deref, T
34623506
}),
34633507
our_network_key: args.keys_manager.get_node_secret(),
34643508

3509+
last_node_announcement_serial: AtomicUsize::new(last_node_announcement_serial as usize),
3510+
34653511
per_peer_state: RwLock::new(per_peer_state),
34663512

34673513
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
@@ -364,10 +364,33 @@ pub fn create_announced_chan_between_nodes<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'
364364

365365
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) {
366366
let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat, a_flags, b_flags);
367+
368+
nodes[a].node.broadcast_node_announcement([0, 0, 0], [0; 32], msgs::NetAddressSet::new());
369+
let a_events = nodes[a].node.get_and_clear_pending_msg_events();
370+
assert_eq!(a_events.len(), 1);
371+
let a_node_announcement = match a_events[0] {
372+
MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
373+
(*msg).clone()
374+
},
375+
_ => panic!("Unexpected event"),
376+
};
377+
378+
nodes[b].node.broadcast_node_announcement([1, 1, 1], [1; 32], msgs::NetAddressSet::new());
379+
let b_events = nodes[b].node.get_and_clear_pending_msg_events();
380+
assert_eq!(b_events.len(), 1);
381+
let b_node_announcement = match b_events[0] {
382+
MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
383+
(*msg).clone()
384+
},
385+
_ => panic!("Unexpected event"),
386+
};
387+
367388
for node in nodes {
368389
assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
369390
node.router.handle_channel_update(&chan_announcement.1).unwrap();
370391
node.router.handle_channel_update(&chan_announcement.2).unwrap();
392+
node.router.handle_node_announcement(&a_node_announcement).unwrap();
393+
node.router.handle_node_announcement(&b_node_announcement).unwrap();
371394
}
372395
(chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
373396
}

lightning/src/ln/peer_handler.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,15 @@ impl Peer {
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(&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> {
@@ -975,6 +984,21 @@ 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(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() {

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)