Skip to content

Commit 989cb06

Browse files
committed
Move broadcast_node_announcement to PeerManager
Some `NodeFeatures` will, in the future, represent features which are not enabled by the `ChannelManager`, but by other message handlers handlers. Thus, it doesn't make sense to determine the node feature bits in the `ChannelManager`. The simplest fix for this is to change to generating the node_announcement in `PeerManager`, asking all the connected handlers which feature bits they support and simply OR'ing them together. While this may not be sufficient in the future as it doesn't consider feature bit dependencies, support for those could be handled at the feature level in the future. This commit moves the `broadcast_node_announcement` function to `PeerHandler` but does not yet implement feature OR'ing.
1 parent 6b0afbe commit 989cb06

File tree

10 files changed

+121
-140
lines changed

10 files changed

+121
-140
lines changed

fuzz/src/full_stack.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -415,7 +415,7 @@ pub fn do_test(data: &[u8], logger: &Arc<dyn Logger>) {
415415
chan_handler: channelmanager.clone(),
416416
route_handler: gossip_sync.clone(),
417417
onion_message_handler: IgnoringMessageHandler {},
418-
}, our_network_key, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 0], Arc::clone(&logger), IgnoringMessageHandler{}));
418+
}, our_network_key, 0, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 0], Arc::clone(&logger), IgnoringMessageHandler{}));
419419

420420
let mut should_forward = false;
421421
let mut payments_received: Vec<PaymentHash> = Vec::new();

lightning-background-processor/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -746,7 +746,7 @@ mod tests {
746746
let p2p_gossip_sync = Arc::new(P2PGossipSync::new(network_graph.clone(), Some(chain_source.clone()), logger.clone()));
747747
let rapid_gossip_sync = Arc::new(RapidGossipSync::new(network_graph.clone()));
748748
let msg_handler = MessageHandler { chan_handler: Arc::new(test_utils::TestChannelMessageHandler::new()), route_handler: Arc::new(test_utils::TestRoutingMessageHandler::new()), onion_message_handler: IgnoringMessageHandler{}};
749-
let peer_manager = Arc::new(PeerManager::new(msg_handler, keys_manager.get_node_secret(Recipient::Node).unwrap(), &seed, logger.clone(), IgnoringMessageHandler{}));
749+
let peer_manager = Arc::new(PeerManager::new(msg_handler, keys_manager.get_node_secret(Recipient::Node).unwrap(), 0, &seed, logger.clone(), IgnoringMessageHandler{}));
750750
let scorer = Arc::new(Mutex::new(test_utils::TestScorer::with_penalty(0)));
751751
let node = Node { node: manager, p2p_gossip_sync, rapid_gossip_sync, peer_manager, chain_monitor, persister, tx_broadcaster, network_graph, logger, best_block, scorer };
752752
nodes.push(node);

lightning-net-tokio/src/lib.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -546,6 +546,7 @@ mod tests {
546546
use lightning::ln::features::*;
547547
use lightning::ln::msgs::*;
548548
use lightning::ln::peer_handler::{MessageHandler, PeerManager};
549+
use lightning::ln::features::NodeFeatures;
549550
use lightning::util::events::*;
550551
use bitcoin::secp256k1::{Secp256k1, SecretKey, PublicKey};
551552

@@ -612,6 +613,7 @@ mod tests {
612613
}
613614
fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, _msg: &ChannelReestablish) {}
614615
fn handle_error(&self, _their_node_id: &PublicKey, _msg: &ErrorMessage) {}
616+
fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::known() }
615617
}
616618
impl MessageSendEventsProvider for MsgHandler {
617619
fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
@@ -657,7 +659,7 @@ mod tests {
657659
chan_handler: Arc::clone(&a_handler),
658660
route_handler: Arc::clone(&a_handler),
659661
onion_message_handler: Arc::new(lightning::ln::peer_handler::IgnoringMessageHandler{}),
660-
}, a_key.clone(), &[1; 32], Arc::new(TestLogger()), Arc::new(lightning::ln::peer_handler::IgnoringMessageHandler{})));
662+
}, a_key.clone(), 0, &[1; 32], Arc::new(TestLogger()), Arc::new(lightning::ln::peer_handler::IgnoringMessageHandler{})));
661663

662664
let (b_connected_sender, mut b_connected) = mpsc::channel(1);
663665
let (b_disconnected_sender, mut b_disconnected) = mpsc::channel(1);
@@ -672,7 +674,7 @@ mod tests {
672674
chan_handler: Arc::clone(&b_handler),
673675
route_handler: Arc::clone(&b_handler),
674676
onion_message_handler: Arc::new(lightning::ln::peer_handler::IgnoringMessageHandler{}),
675-
}, b_key.clone(), &[2; 32], Arc::new(TestLogger()), Arc::new(lightning::ln::peer_handler::IgnoringMessageHandler{})));
677+
}, b_key.clone(), 0, &[2; 32], Arc::new(TestLogger()), Arc::new(lightning::ln::peer_handler::IgnoringMessageHandler{})));
676678

677679
// We bind on localhost, hoping the environment is properly configured with a local
678680
// address. This may not always be the case in containers and the like, so if this test is
@@ -725,7 +727,7 @@ mod tests {
725727
chan_handler: Arc::new(lightning::ln::peer_handler::ErroringMessageHandler::new()),
726728
onion_message_handler: Arc::new(lightning::ln::peer_handler::IgnoringMessageHandler{}),
727729
route_handler: Arc::new(lightning::ln::peer_handler::IgnoringMessageHandler{}),
728-
}, a_key, &[1; 32], Arc::new(TestLogger()), Arc::new(lightning::ln::peer_handler::IgnoringMessageHandler{})));
730+
}, a_key, 0, &[1; 32], Arc::new(TestLogger()), Arc::new(lightning::ln::peer_handler::IgnoringMessageHandler{})));
729731

730732
// Make two connections, one for an inbound and one for an outbound connection
731733
let conn_a = {

lightning/src/ln/channelmanager.rs

Lines changed: 9 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,6 @@ use chain::keysinterface::{Sign, KeysInterface, KeysManager, InMemorySigner, Rec
5454
use util::config::{UserConfig, ChannelConfig};
5555
use util::events::{EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination};
5656
use util::{byte_utils, events};
57-
use util::crypto::sign;
5857
use util::wakers::{Future, Notifier};
5958
use util::scid_utils::fake_scid;
6059
use util::ser::{BigSize, FixedLengthReader, Readable, ReadableArgs, MaybeReadable, Writeable, Writer, VecWriter};
@@ -764,10 +763,6 @@ pub struct ChannelManager<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref,
764763
/// keeping additional state.
765764
probing_cookie_secret: [u8; 32],
766765

767-
/// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
768-
/// value increases strictly since we don't assume access to a time source.
769-
last_node_announcement_serial: AtomicUsize,
770-
771766
/// The highest block timestamp we've seen, which is usually a good guess at the current time.
772767
/// Assuming most miners are generating blocks with reasonable timestamps, this shouldn't be
773768
/// very far in the past, and can only ever be up to two hours in the future.
@@ -1617,7 +1612,6 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
16171612

16181613
probing_cookie_secret: keys_manager.get_secure_random_bytes(),
16191614

1620-
last_node_announcement_serial: AtomicUsize::new(0),
16211615
highest_seen_timestamp: AtomicUsize::new(0),
16221616

16231617
per_peer_state: RwLock::new(HashMap::new()),
@@ -2928,80 +2922,6 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
29282922
})
29292923
}
29302924

2931-
#[allow(dead_code)]
2932-
// Messages of up to 64KB should never end up more than half full with addresses, as that would
2933-
// be absurd. We ensure this by checking that at least 100 (our stated public contract on when
2934-
// broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
2935-
// message...
2936-
const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2;
2937-
#[deny(const_err)]
2938-
#[allow(dead_code)]
2939-
// ...by failing to compile if the number of addresses that would be half of a message is
2940-
// smaller than 100:
2941-
const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 100;
2942-
2943-
/// Regenerates channel_announcements and generates a signed node_announcement from the given
2944-
/// arguments, providing them in corresponding events via
2945-
/// [`get_and_clear_pending_msg_events`], if at least one public channel has been confirmed
2946-
/// on-chain. This effectively re-broadcasts all channel announcements and sends our node
2947-
/// announcement to ensure that the lightning P2P network is aware of the channels we have and
2948-
/// our network addresses.
2949-
///
2950-
/// `rgb` is a node "color" and `alias` is a printable human-readable string to describe this
2951-
/// node to humans. They carry no in-protocol meaning.
2952-
///
2953-
/// `addresses` represent the set (possibly empty) of socket addresses on which this node
2954-
/// accepts incoming connections. These will be included in the node_announcement, publicly
2955-
/// tying these addresses together and to this node. If you wish to preserve user privacy,
2956-
/// addresses should likely contain only Tor Onion addresses.
2957-
///
2958-
/// Panics if `addresses` is absurdly large (more than 100).
2959-
///
2960-
/// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events
2961-
pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], mut addresses: Vec<NetAddress>) {
2962-
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2963-
2964-
if addresses.len() > 100 {
2965-
panic!("More than half the message size was taken up by public addresses!");
2966-
}
2967-
2968-
// While all existing nodes handle unsorted addresses just fine, the spec requires that
2969-
// addresses be sorted for future compatibility.
2970-
addresses.sort_by_key(|addr| addr.get_id());
2971-
2972-
let announcement = msgs::UnsignedNodeAnnouncement {
2973-
features: NodeFeatures::known(),
2974-
timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel) as u32,
2975-
node_id: self.get_our_node_id(),
2976-
rgb, alias, addresses,
2977-
excess_address_data: Vec::new(),
2978-
excess_data: Vec::new(),
2979-
};
2980-
let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
2981-
let node_announce_sig = sign(&self.secp_ctx, &msghash, &self.our_network_key);
2982-
2983-
let mut channel_state_lock = self.channel_state.lock().unwrap();
2984-
let channel_state = &mut *channel_state_lock;
2985-
2986-
let mut announced_chans = false;
2987-
for (_, chan) in channel_state.by_id.iter() {
2988-
if chan.get_signed_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone(), self.best_block.read().unwrap().height()).is_some()
2989-
&& self.get_channel_update_for_broadcast(chan).is_ok()
2990-
{
2991-
announced_chans = true;
2992-
}
2993-
}
2994-
2995-
if announced_chans {
2996-
channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastNodeAnnouncement {
2997-
msg: msgs::NodeAnnouncement {
2998-
signature: node_announce_sig,
2999-
contents: announcement
3000-
},
3001-
});
3002-
}
3003-
}
3004-
30052925
/// Atomically updates the [`ChannelConfig`] for the given channels.
30062926
///
30072927
/// Once the updates are applied, each eligible channel (advertised with a known short channel
@@ -5780,7 +5700,6 @@ where
57805700
}
57815701
}
57825702
}
5783-
max_time!(self.last_node_announcement_serial);
57845703
max_time!(self.highest_seen_timestamp);
57855704
let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
57865705
payment_secrets.retain(|_, inbound_payment| {
@@ -6132,7 +6051,6 @@ impl<Signer: Sign, M: Deref , T: Deref , K: Deref , F: Deref , L: Deref >
61326051
&events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => node_id != counterparty_node_id,
61336052
&events::MessageSendEvent::SendChannelAnnouncement { ref node_id, .. } => node_id != counterparty_node_id,
61346053
&events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
6135-
&events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
61366054
&events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
61376055
&events::MessageSendEvent::SendChannelUpdate { ref node_id, .. } => node_id != counterparty_node_id,
61386056
&events::MessageSendEvent::HandleError { ref node_id, .. } => node_id != counterparty_node_id,
@@ -6237,6 +6155,10 @@ impl<Signer: Sign, M: Deref , T: Deref , K: Deref , F: Deref , L: Deref >
62376155
let _ = self.force_close_channel_with_peer(&msg.channel_id, counterparty_node_id, Some(&msg.data), true);
62386156
}
62396157
}
6158+
6159+
fn provided_node_features(&self) -> NodeFeatures {
6160+
NodeFeatures::known()
6161+
}
62406162
}
62416163

62426164
const SERIALIZATION_VERSION: u8 = 1;
@@ -6659,7 +6581,10 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Writeable f
66596581
}
66606582
}
66616583

6662-
(self.last_node_announcement_serial.load(Ordering::Acquire) as u32).write(writer)?;
6584+
// Prior to 0.0.111 we tracked node_announcement serials here, however that now happens in
6585+
// `PeerManager`, and thus we simply write the `highest_seen_timestamp` twice, which is
6586+
// likely to be identical.
6587+
(self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
66636588
(self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
66646589

66656590
(pending_inbound_payments.len() as u64).write(writer)?;
@@ -6978,7 +6903,7 @@ impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
69786903
}
69796904
}
69806905

6981-
let last_node_announcement_serial: u32 = Readable::read(reader)?;
6906+
let _last_node_announcement_serial: u32 = Readable::read(reader)?; // Only used < 0.0.111
69826907
let highest_seen_timestamp: u32 = Readable::read(reader)?;
69836908

69846909
let pending_inbound_payment_count: u64 = Readable::read(reader)?;
@@ -7239,7 +7164,6 @@ impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
72397164
our_network_pubkey,
72407165
secp_ctx,
72417166

7242-
last_node_announcement_serial: AtomicUsize::new(last_node_announcement_serial as usize),
72437167
highest_seen_timestamp: AtomicUsize::new(highest_seen_timestamp as usize),
72447168

72457169
per_peer_state: RwLock::new(per_peer_state),

lightning/src/ln/functional_test_utils.rs

Lines changed: 0 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -892,34 +892,10 @@ pub fn create_unannounced_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(nodes: &
892892
}
893893

894894
pub fn update_nodes_with_chan_announce<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, ann: &msgs::ChannelAnnouncement, upd_1: &msgs::ChannelUpdate, upd_2: &msgs::ChannelUpdate) {
895-
nodes[a].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
896-
let a_events = nodes[a].node.get_and_clear_pending_msg_events();
897-
assert_eq!(a_events.len(), 1);
898-
899-
let a_node_announcement = match a_events.last().unwrap() {
900-
MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
901-
(*msg).clone()
902-
},
903-
_ => panic!("Unexpected event"),
904-
};
905-
906-
nodes[b].node.broadcast_node_announcement([1, 1, 1], [1; 32], Vec::new());
907-
let b_events = nodes[b].node.get_and_clear_pending_msg_events();
908-
assert_eq!(b_events.len(), 1);
909-
910-
let b_node_announcement = match b_events.last().unwrap() {
911-
MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
912-
(*msg).clone()
913-
},
914-
_ => panic!("Unexpected event"),
915-
};
916-
917895
for node in nodes {
918896
assert!(node.gossip_sync.handle_channel_announcement(ann).unwrap());
919897
node.gossip_sync.handle_channel_update(upd_1).unwrap();
920898
node.gossip_sync.handle_channel_update(upd_2).unwrap();
921-
node.gossip_sync.handle_node_announcement(&a_node_announcement).unwrap();
922-
node.gossip_sync.handle_node_announcement(&b_node_announcement).unwrap();
923899

924900
// Note that channel_updates are also delivered to ChannelManagers to ensure we have
925901
// forwarding info for local channels even if its not accepted in the network graph.

lightning/src/ln/msgs.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -896,6 +896,12 @@ pub trait ChannelMessageHandler : MessageSendEventsProvider {
896896
// Error:
897897
/// Handle an incoming error message from the given peer.
898898
fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
899+
900+
// Handler information:
901+
/// Gets the node feature flags which this handler itself supports. All available handlers are
902+
/// queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`]
903+
/// which are broadcasted in our node_announcement message.
904+
fn provided_node_features(&self) -> NodeFeatures;
899905
}
900906

901907
/// A trait to describe an object which can receive routing messages.

lightning/src/ln/payment_tests.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -676,7 +676,7 @@ fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
676676
// Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
677677
// error, as the channel has hit the chain.
678678
nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
679-
let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
679+
let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
680680
nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
681681
let as_err = nodes[0].node.get_and_clear_pending_msg_events();
682682
assert_eq!(as_err.len(), 1);

0 commit comments

Comments
 (0)