1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Top level peer message handling and socket handling logic lives here.
12 //! Instead of actually servicing sockets ourselves we require that you implement the
13 //! SocketDescriptor interface and use that to receive actions which you should perform on the
14 //! socket, and call into PeerManager with bytes read from the socket. The PeerManager will then
15 //! call into the provided message handlers (probably a ChannelManager and P2PGossipSync) with
16 //! messages they should handle, and encoding/sending response messages.
18 use bitcoin::secp256k1::{self, Secp256k1, SecretKey, PublicKey};
20 use crate::chain::keysinterface::{KeysManager, NodeSigner, Recipient};
21 use crate::events::{MessageSendEvent, MessageSendEventsProvider, OnionMessageProvider};
22 use crate::ln::features::{InitFeatures, NodeFeatures};
24 use crate::ln::msgs::{ChannelMessageHandler, LightningError, NetAddress, OnionMessageHandler, RoutingMessageHandler};
25 use crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
26 use crate::util::ser::{VecWriter, Writeable, Writer};
27 use crate::ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
29 use crate::ln::wire::Encode;
30 use crate::onion_message::{CustomOnionMessageContents, CustomOnionMessageHandler, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
31 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId};
32 use crate::util::atomic_counter::AtomicCounter;
33 use crate::util::logger::Logger;
35 use crate::prelude::*;
37 use alloc::collections::LinkedList;
38 use crate::sync::{Arc, Mutex, MutexGuard, FairRwLock};
39 use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
40 use core::{cmp, hash, fmt, mem};
42 use core::convert::Infallible;
43 #[cfg(feature = "std")] use std::error;
45 use bitcoin::hashes::sha256::Hash as Sha256;
46 use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
47 use bitcoin::hashes::{HashEngine, Hash};
49 /// A handler provided to [`PeerManager`] for reading and handling custom messages.
51 /// [BOLT 1] specifies a custom message type range for use with experimental or application-specific
52 /// messages. `CustomMessageHandler` allows for user-defined handling of such types. See the
53 /// [`lightning_custom_message`] crate for tools useful in composing more than one custom handler.
55 /// [BOLT 1]: https://github.com/lightning/bolts/blob/master/01-messaging.md
56 /// [`lightning_custom_message`]: https://docs.rs/lightning_custom_message/latest/lightning_custom_message
57 pub trait CustomMessageHandler: wire::CustomMessageReader {
58 /// Handles the given message sent from `sender_node_id`, possibly producing messages for
59 /// [`CustomMessageHandler::get_and_clear_pending_msg`] to return and thus for [`PeerManager`]
61 fn handle_custom_message(&self, msg: Self::CustomMessage, sender_node_id: &PublicKey) -> Result<(), LightningError>;
63 /// Returns the list of pending messages that were generated by the handler, clearing the list
64 /// in the process. Each message is paired with the node id of the intended recipient. If no
65 /// connection to the node exists, then the message is simply not sent.
66 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)>;
69 /// A dummy struct which implements `RoutingMessageHandler` without storing any routing information
70 /// or doing any processing. You can provide one of these as the route_handler in a MessageHandler.
71 pub struct IgnoringMessageHandler{}
72 impl MessageSendEventsProvider for IgnoringMessageHandler {
73 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> { Vec::new() }
75 impl RoutingMessageHandler for IgnoringMessageHandler {
76 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
77 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
78 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
79 fn get_next_channel_announcement(&self, _starting_point: u64) ->
80 Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { None }
81 fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> { None }
82 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
83 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
84 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
85 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) }
86 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) }
87 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
88 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
91 fn processing_queue_high(&self) -> bool { false }
93 impl OnionMessageProvider for IgnoringMessageHandler {
94 fn next_onion_message_for_peer(&self, _peer_node_id: PublicKey) -> Option<msgs::OnionMessage> { None }
96 impl OnionMessageHandler for IgnoringMessageHandler {
97 fn handle_onion_message(&self, _their_node_id: &PublicKey, _msg: &msgs::OnionMessage) {}
98 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
99 fn peer_disconnected(&self, _their_node_id: &PublicKey) {}
100 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
101 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
102 InitFeatures::empty()
105 impl CustomOnionMessageHandler for IgnoringMessageHandler {
106 type CustomMessage = Infallible;
107 fn handle_custom_message(&self, _msg: Infallible) {
108 // Since we always return `None` in the read the handle method should never be called.
111 fn read_custom_message<R: io::Read>(&self, _msg_type: u64, _buffer: &mut R) -> Result<Option<Infallible>, msgs::DecodeError> where Self: Sized {
116 impl CustomOnionMessageContents for Infallible {
117 fn tlv_type(&self) -> u64 { unreachable!(); }
120 impl Deref for IgnoringMessageHandler {
121 type Target = IgnoringMessageHandler;
122 fn deref(&self) -> &Self { self }
125 // Implement Type for Infallible, note that it cannot be constructed, and thus you can never call a
126 // method that takes self for it.
127 impl wire::Type for Infallible {
128 fn type_id(&self) -> u16 {
132 impl Writeable for Infallible {
133 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
138 impl wire::CustomMessageReader for IgnoringMessageHandler {
139 type CustomMessage = Infallible;
140 fn read<R: io::Read>(&self, _message_type: u16, _buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
145 impl CustomMessageHandler for IgnoringMessageHandler {
146 fn handle_custom_message(&self, _msg: Infallible, _sender_node_id: &PublicKey) -> Result<(), LightningError> {
147 // Since we always return `None` in the read the handle method should never be called.
151 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
154 /// A dummy struct which implements `ChannelMessageHandler` without having any channels.
155 /// You can provide one of these as the route_handler in a MessageHandler.
156 pub struct ErroringMessageHandler {
157 message_queue: Mutex<Vec<MessageSendEvent>>
159 impl ErroringMessageHandler {
160 /// Constructs a new ErroringMessageHandler
161 pub fn new() -> Self {
162 Self { message_queue: Mutex::new(Vec::new()) }
164 fn push_error(&self, node_id: &PublicKey, channel_id: [u8; 32]) {
165 self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
166 action: msgs::ErrorAction::SendErrorMessage {
167 msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
169 node_id: node_id.clone(),
173 impl MessageSendEventsProvider for ErroringMessageHandler {
174 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
175 let mut res = Vec::new();
176 mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
180 impl ChannelMessageHandler for ErroringMessageHandler {
181 // Any messages which are related to a specific channel generate an error message to let the
182 // peer know we don't care about channels.
183 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
184 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
186 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
187 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
189 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
190 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
192 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
193 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
195 fn handle_channel_ready(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
196 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
198 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) {
199 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
201 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
202 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
204 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
205 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
207 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
208 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
210 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
211 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
213 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
214 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
216 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
217 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
219 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
220 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
222 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
223 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
225 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
226 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
228 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
229 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
231 // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them.
232 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
233 fn peer_disconnected(&self, _their_node_id: &PublicKey) {}
234 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
235 fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
236 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
237 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
238 // Set a number of features which various nodes may require to talk to us. It's totally
239 // reasonable to indicate we "support" all kinds of channel features...we just reject all
241 let mut features = InitFeatures::empty();
242 features.set_data_loss_protect_optional();
243 features.set_upfront_shutdown_script_optional();
244 features.set_variable_length_onion_optional();
245 features.set_static_remote_key_optional();
246 features.set_payment_secret_optional();
247 features.set_basic_mpp_optional();
248 features.set_wumbo_optional();
249 features.set_shutdown_any_segwit_optional();
250 features.set_channel_type_optional();
251 features.set_scid_privacy_optional();
252 features.set_zero_conf_optional();
256 impl Deref for ErroringMessageHandler {
257 type Target = ErroringMessageHandler;
258 fn deref(&self) -> &Self { self }
261 /// Provides references to trait impls which handle different types of messages.
262 pub struct MessageHandler<CM: Deref, RM: Deref, OM: Deref> where
263 CM::Target: ChannelMessageHandler,
264 RM::Target: RoutingMessageHandler,
265 OM::Target: OnionMessageHandler,
267 /// A message handler which handles messages specific to channels. Usually this is just a
268 /// [`ChannelManager`] object or an [`ErroringMessageHandler`].
270 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
271 pub chan_handler: CM,
272 /// A message handler which handles messages updating our knowledge of the network channel
273 /// graph. Usually this is just a [`P2PGossipSync`] object or an [`IgnoringMessageHandler`].
275 /// [`P2PGossipSync`]: crate::routing::gossip::P2PGossipSync
276 pub route_handler: RM,
278 /// A message handler which handles onion messages. For now, this can only be an
279 /// [`IgnoringMessageHandler`].
280 pub onion_message_handler: OM,
283 /// Provides an object which can be used to send data to and which uniquely identifies a connection
284 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
285 /// implement Hash to meet the PeerManager API.
287 /// For efficiency, [`Clone`] should be relatively cheap for this type.
289 /// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original
290 /// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it
291 /// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no
292 /// further calls to the [`PeerManager`] related to the original socket occur. This allows you to
293 /// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish
294 /// to simply use another value which is guaranteed to be globally unique instead.
295 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
296 /// Attempts to send some data from the given slice to the peer.
298 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
299 /// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
300 /// called and further write attempts may occur until that time.
302 /// If the returned size is smaller than `data.len()`, a
303 /// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
304 /// written. Additionally, until a `send_data` event completes fully, no further
305 /// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
306 /// prevent denial-of-service issues, you should not read or buffer any data from the socket
309 /// If a [`PeerManager::read_event`] call on this descriptor had previously returned true
310 /// (indicating that read events should be paused to prevent DoS in the send buffer),
311 /// `resume_read` may be set indicating that read events on this descriptor should resume. A
312 /// `resume_read` of false carries no meaning, and should not cause any action.
313 fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
314 /// Disconnect the socket pointed to by this SocketDescriptor.
316 /// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
317 /// call (doing so is a noop).
318 fn disconnect_socket(&mut self);
321 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
322 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
325 pub struct PeerHandleError { }
326 impl fmt::Debug for PeerHandleError {
327 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
328 formatter.write_str("Peer Sent Invalid Data")
331 impl fmt::Display for PeerHandleError {
332 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
333 formatter.write_str("Peer Sent Invalid Data")
337 #[cfg(feature = "std")]
338 impl error::Error for PeerHandleError {
339 fn description(&self) -> &str {
340 "Peer Sent Invalid Data"
344 enum InitSyncTracker{
346 ChannelsSyncing(u64),
347 NodesSyncing(NodeId),
350 /// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop
351 /// forwarding gossip messages to peers altogether.
352 const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2;
354 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
355 /// we have fewer than this many messages in the outbound buffer again.
356 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
357 /// refilled as we send bytes.
358 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 12;
359 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
361 const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO;
363 /// If we've sent a ping, and are still awaiting a response, we may need to churn our way through
364 /// the socket receive buffer before receiving the ping.
366 /// On a fairly old Arm64 board, with Linux defaults, this can take as long as 20 seconds, not
367 /// including any network delays, outbound traffic, or the same for messages from other peers.
369 /// Thus, to avoid needlessly disconnecting a peer, we allow a peer to take this many timer ticks
370 /// per connected peer to respond to a ping, as long as they send us at least one message during
371 /// each tick, ensuring we aren't actually just disconnected.
372 /// With a timer tick interval of ten seconds, this translates to about 40 seconds per connected
375 /// When we improve parallelism somewhat we should reduce this to e.g. this many timer ticks per
376 /// two connected peers, assuming most LDK-running systems have at least two cores.
377 const MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER: i8 = 4;
379 /// This is the minimum number of messages we expect a peer to be able to handle within one timer
380 /// tick. Once we have sent this many messages since the last ping, we send a ping right away to
381 /// ensures we don't just fill up our send buffer and leave the peer with too many messages to
382 /// process before the next ping.
384 /// Note that we continue responding to other messages even after we've sent this many messages, so
385 /// it's more of a general guideline used for gossip backfill (and gossip forwarding, times
386 /// [`FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO`]) than a hard limit.
387 const BUFFER_DRAIN_MSGS_PER_TICK: usize = 32;
390 channel_encryptor: PeerChannelEncryptor,
391 /// We cache a `NodeId` here to avoid serializing peers' keys every time we forward gossip
392 /// messages in `PeerManager`. Use `Peer::set_their_node_id` to modify this field.
393 their_node_id: Option<(PublicKey, NodeId)>,
394 /// The features provided in the peer's [`msgs::Init`] message.
396 /// This is set only after we've processed the [`msgs::Init`] message and called relevant
397 /// `peer_connected` handler methods. Thus, this field is set *iff* we've finished our
398 /// handshake and can talk to this peer normally (though use [`Peer::handshake_complete`] to
400 their_features: Option<InitFeatures>,
401 their_net_address: Option<NetAddress>,
403 pending_outbound_buffer: LinkedList<Vec<u8>>,
404 pending_outbound_buffer_first_msg_offset: usize,
405 /// Queue gossip broadcasts separately from `pending_outbound_buffer` so we can easily
406 /// prioritize channel messages over them.
408 /// Note that these messages are *not* encrypted/MAC'd, and are only serialized.
409 gossip_broadcast_buffer: LinkedList<Vec<u8>>,
410 awaiting_write_event: bool,
412 pending_read_buffer: Vec<u8>,
413 pending_read_buffer_pos: usize,
414 pending_read_is_header: bool,
416 sync_status: InitSyncTracker,
418 msgs_sent_since_pong: usize,
419 awaiting_pong_timer_tick_intervals: i8,
420 received_message_since_timer_tick: bool,
421 sent_gossip_timestamp_filter: bool,
423 /// Indicates we've received a `channel_announcement` since the last time we had
424 /// [`PeerManager::gossip_processing_backlogged`] set (or, really, that we've received a
425 /// `channel_announcement` at all - we set this unconditionally but unset it every time we
426 /// check if we're gossip-processing-backlogged).
427 received_channel_announce_since_backlogged: bool,
429 inbound_connection: bool,
433 /// True after we've processed the [`msgs::Init`] message and called relevant `peer_connected`
434 /// handler methods. Thus, this implies we've finished our handshake and can talk to this peer
436 fn handshake_complete(&self) -> bool {
437 self.their_features.is_some()
440 /// Returns true if the channel announcements/updates for the given channel should be
441 /// forwarded to this peer.
442 /// If we are sending our routing table to this peer and we have not yet sent channel
443 /// announcements/updates for the given channel_id then we will send it when we get to that
444 /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
445 /// sent the old versions, we should send the update, and so return true here.
446 fn should_forward_channel_announcement(&self, channel_id: u64) -> bool {
447 if !self.handshake_complete() { return false; }
448 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
449 !self.sent_gossip_timestamp_filter {
452 match self.sync_status {
453 InitSyncTracker::NoSyncRequested => true,
454 InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
455 InitSyncTracker::NodesSyncing(_) => true,
459 /// Similar to the above, but for node announcements indexed by node_id.
460 fn should_forward_node_announcement(&self, node_id: NodeId) -> bool {
461 if !self.handshake_complete() { return false; }
462 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
463 !self.sent_gossip_timestamp_filter {
466 match self.sync_status {
467 InitSyncTracker::NoSyncRequested => true,
468 InitSyncTracker::ChannelsSyncing(_) => false,
469 InitSyncTracker::NodesSyncing(sync_node_id) => sync_node_id.as_slice() < node_id.as_slice(),
473 /// Returns whether we should be reading bytes from this peer, based on whether its outbound
474 /// buffer still has space and we don't need to pause reads to get some writes out.
475 fn should_read(&mut self, gossip_processing_backlogged: bool) -> bool {
476 if !gossip_processing_backlogged {
477 self.received_channel_announce_since_backlogged = false;
479 self.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE &&
480 (!gossip_processing_backlogged || !self.received_channel_announce_since_backlogged)
483 /// Determines if we should push additional gossip background sync (aka "backfill") onto a peer's
484 /// outbound buffer. This is checked every time the peer's buffer may have been drained.
485 fn should_buffer_gossip_backfill(&self) -> bool {
486 self.pending_outbound_buffer.is_empty() && self.gossip_broadcast_buffer.is_empty()
487 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
488 && self.handshake_complete()
491 /// Determines if we should push an onion message onto a peer's outbound buffer. This is checked
492 /// every time the peer's buffer may have been drained.
493 fn should_buffer_onion_message(&self) -> bool {
494 self.pending_outbound_buffer.is_empty() && self.handshake_complete()
495 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
498 /// Determines if we should push additional gossip broadcast messages onto a peer's outbound
499 /// buffer. This is checked every time the peer's buffer may have been drained.
500 fn should_buffer_gossip_broadcast(&self) -> bool {
501 self.pending_outbound_buffer.is_empty() && self.handshake_complete()
502 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
505 /// Returns whether this peer's outbound buffers are full and we should drop gossip broadcasts.
506 fn buffer_full_drop_gossip_broadcast(&self) -> bool {
507 let total_outbound_buffered =
508 self.gossip_broadcast_buffer.len() + self.pending_outbound_buffer.len();
510 total_outbound_buffered > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP ||
511 self.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
514 fn set_their_node_id(&mut self, node_id: PublicKey) {
515 self.their_node_id = Some((node_id, NodeId::from_pubkey(&node_id)));
519 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
520 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
521 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
522 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
523 /// issues such as overly long function definitions.
525 /// This is not exported to bindings users as `Arc`s don't make sense in bindings.
526 pub type SimpleArcPeerManager<SD, M, T, F, C, L> = PeerManager<SD, Arc<SimpleArcChannelManager<M, T, F, L>>, Arc<P2PGossipSync<Arc<NetworkGraph<Arc<L>>>, Arc<C>, Arc<L>>>, Arc<SimpleArcOnionMessenger<L>>, Arc<L>, IgnoringMessageHandler, Arc<KeysManager>>;
528 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
529 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
530 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
531 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
532 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
533 /// helps with issues such as long function definitions.
535 /// This is not exported to bindings users as general type aliases don't make sense in bindings.
536 pub type SimpleRefPeerManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k, 'l, 'm, SD, M, T, F, C, L> = PeerManager<SD, SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'm, M, T, F, L>, &'f P2PGossipSync<&'g NetworkGraph<&'f L>, &'h C, &'f L>, &'i SimpleRefOnionMessenger<'j, 'k, L>, &'f L, IgnoringMessageHandler, &'c KeysManager>;
538 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
539 /// socket events into messages which it passes on to its [`MessageHandler`].
541 /// Locks are taken internally, so you must never assume that reentrancy from a
542 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
544 /// Calls to [`read_event`] will decode relevant messages and pass them to the
545 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
546 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
547 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
548 /// calls only after previous ones have returned.
550 /// Rather than using a plain [`PeerManager`], it is preferable to use either a [`SimpleArcPeerManager`]
551 /// a [`SimpleRefPeerManager`], for conciseness. See their documentation for more details, but
552 /// essentially you should default to using a [`SimpleRefPeerManager`], and use a
553 /// [`SimpleArcPeerManager`] when you require a `PeerManager` with a static lifetime, such as when
554 /// you're using lightning-net-tokio.
556 /// [`read_event`]: PeerManager::read_event
557 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref> where
558 CM::Target: ChannelMessageHandler,
559 RM::Target: RoutingMessageHandler,
560 OM::Target: OnionMessageHandler,
562 CMH::Target: CustomMessageHandler,
563 NS::Target: NodeSigner {
564 message_handler: MessageHandler<CM, RM, OM>,
565 /// Connection state for each connected peer - we have an outer read-write lock which is taken
566 /// as read while we're doing processing for a peer and taken write when a peer is being added
569 /// The inner Peer lock is held for sending and receiving bytes, but note that we do *not* hold
570 /// it while we're processing a message. This is fine as [`PeerManager::read_event`] requires
571 /// that there be no parallel calls for a given peer, so mutual exclusion of messages handed to
572 /// the `MessageHandler`s for a given peer is already guaranteed.
573 peers: FairRwLock<HashMap<Descriptor, Mutex<Peer>>>,
574 /// Only add to this set when noise completes.
575 /// Locked *after* peers. When an item is removed, it must be removed with the `peers` write
576 /// lock held. Entries may be added with only the `peers` read lock held (though the
577 /// `Descriptor` value must already exist in `peers`).
578 node_id_to_descriptor: Mutex<HashMap<PublicKey, Descriptor>>,
579 /// We can only have one thread processing events at once, but we don't usually need the full
580 /// `peers` write lock to do so, so instead we block on this empty mutex when entering
581 /// `process_events`.
582 event_processing_lock: Mutex<()>,
583 /// Because event processing is global and always does all available work before returning,
584 /// there is no reason for us to have many event processors waiting on the lock at once.
585 /// Instead, we limit the total blocked event processors to always exactly one by setting this
586 /// when an event process call is waiting.
587 blocked_event_processors: AtomicBool,
589 /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
590 /// value increases strictly since we don't assume access to a time source.
591 last_node_announcement_serial: AtomicU32,
593 ephemeral_key_midstate: Sha256Engine,
594 custom_message_handler: CMH,
596 peer_counter: AtomicCounter,
598 gossip_processing_backlogged: AtomicBool,
599 gossip_processing_backlog_lifted: AtomicBool,
604 secp_ctx: Secp256k1<secp256k1::SignOnly>
607 enum MessageHandlingError {
608 PeerHandleError(PeerHandleError),
609 LightningError(LightningError),
612 impl From<PeerHandleError> for MessageHandlingError {
613 fn from(error: PeerHandleError) -> Self {
614 MessageHandlingError::PeerHandleError(error)
618 impl From<LightningError> for MessageHandlingError {
619 fn from(error: LightningError) -> Self {
620 MessageHandlingError::LightningError(error)
624 macro_rules! encode_msg {
626 let mut buffer = VecWriter(Vec::new());
627 wire::write($msg, &mut buffer).unwrap();
632 impl<Descriptor: SocketDescriptor, CM: Deref, OM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, OM, L, IgnoringMessageHandler, NS> where
633 CM::Target: ChannelMessageHandler,
634 OM::Target: OnionMessageHandler,
636 NS::Target: NodeSigner {
637 /// Constructs a new `PeerManager` with the given `ChannelMessageHandler` and
638 /// `OnionMessageHandler`. No routing message handler is used and network graph messages are
641 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
642 /// cryptographically secure random bytes.
644 /// `current_time` is used as an always-increasing counter that survives across restarts and is
645 /// incremented irregularly internally. In general it is best to simply use the current UNIX
646 /// timestamp, however if it is not available a persistent counter that increases once per
647 /// minute should suffice.
649 /// This is not exported to bindings users as we can't export a PeerManager with a dummy route handler
650 pub fn new_channel_only(channel_message_handler: CM, onion_message_handler: OM, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
651 Self::new(MessageHandler {
652 chan_handler: channel_message_handler,
653 route_handler: IgnoringMessageHandler{},
654 onion_message_handler,
655 }, current_time, ephemeral_random_data, logger, IgnoringMessageHandler{}, node_signer)
659 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, IgnoringMessageHandler, L, IgnoringMessageHandler, NS> where
660 RM::Target: RoutingMessageHandler,
662 NS::Target: NodeSigner {
663 /// Constructs a new `PeerManager` with the given `RoutingMessageHandler`. No channel message
664 /// handler or onion message handler is used and onion and channel messages will be ignored (or
665 /// generate error messages). Note that some other lightning implementations time-out connections
666 /// after some time if no channel is built with the peer.
668 /// `current_time` is used as an always-increasing counter that survives across restarts and is
669 /// incremented irregularly internally. In general it is best to simply use the current UNIX
670 /// timestamp, however if it is not available a persistent counter that increases once per
671 /// minute should suffice.
673 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
674 /// cryptographically secure random bytes.
676 /// This is not exported to bindings users as we can't export a PeerManager with a dummy channel handler
677 pub fn new_routing_only(routing_message_handler: RM, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
678 Self::new(MessageHandler {
679 chan_handler: ErroringMessageHandler::new(),
680 route_handler: routing_message_handler,
681 onion_message_handler: IgnoringMessageHandler{},
682 }, current_time, ephemeral_random_data, logger, IgnoringMessageHandler{}, node_signer)
686 /// A simple wrapper that optionally prints ` from <pubkey>` for an optional pubkey.
687 /// This works around `format!()` taking a reference to each argument, preventing
688 /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
689 /// due to lifetime errors.
690 struct OptionalFromDebugger<'a>(&'a Option<(PublicKey, NodeId)>);
691 impl core::fmt::Display for OptionalFromDebugger<'_> {
692 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
693 if let Some((node_id, _)) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
697 /// A function used to filter out local or private addresses
698 /// <https://www.iana.org./assignments/ipv4-address-space/ipv4-address-space.xhtml>
699 /// <https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml>
700 fn filter_addresses(ip_address: Option<NetAddress>) -> Option<NetAddress> {
702 // For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8)
703 Some(NetAddress::IPv4{addr: [10, _, _, _], port: _}) => None,
704 // For IPv4 range 0.0.0.0 - 0.255.255.255 (0/8)
705 Some(NetAddress::IPv4{addr: [0, _, _, _], port: _}) => None,
706 // For IPv4 range 100.64.0.0 - 100.127.255.255 (100.64/10)
707 Some(NetAddress::IPv4{addr: [100, 64..=127, _, _], port: _}) => None,
708 // For IPv4 range 127.0.0.0 - 127.255.255.255 (127/8)
709 Some(NetAddress::IPv4{addr: [127, _, _, _], port: _}) => None,
710 // For IPv4 range 169.254.0.0 - 169.254.255.255 (169.254/16)
711 Some(NetAddress::IPv4{addr: [169, 254, _, _], port: _}) => None,
712 // For IPv4 range 172.16.0.0 - 172.31.255.255 (172.16/12)
713 Some(NetAddress::IPv4{addr: [172, 16..=31, _, _], port: _}) => None,
714 // For IPv4 range 192.168.0.0 - 192.168.255.255 (192.168/16)
715 Some(NetAddress::IPv4{addr: [192, 168, _, _], port: _}) => None,
716 // For IPv4 range 192.88.99.0 - 192.88.99.255 (192.88.99/24)
717 Some(NetAddress::IPv4{addr: [192, 88, 99, _], port: _}) => None,
718 // For IPv6 range 2000:0000:0000:0000:0000:0000:0000:0000 - 3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff (2000::/3)
719 Some(NetAddress::IPv6{addr: [0x20..=0x3F, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _], port: _}) => ip_address,
720 // For remaining addresses
721 Some(NetAddress::IPv6{addr: _, port: _}) => None,
722 Some(..) => ip_address,
727 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref> PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> where
728 CM::Target: ChannelMessageHandler,
729 RM::Target: RoutingMessageHandler,
730 OM::Target: OnionMessageHandler,
732 CMH::Target: CustomMessageHandler,
733 NS::Target: NodeSigner
735 /// Constructs a new `PeerManager` with the given message handlers.
737 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
738 /// cryptographically secure random bytes.
740 /// `current_time` is used as an always-increasing counter that survives across restarts and is
741 /// incremented irregularly internally. In general it is best to simply use the current UNIX
742 /// timestamp, however if it is not available a persistent counter that increases once per
743 /// minute should suffice.
744 pub fn new(message_handler: MessageHandler<CM, RM, OM>, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, custom_message_handler: CMH, node_signer: NS) -> Self {
745 let mut ephemeral_key_midstate = Sha256::engine();
746 ephemeral_key_midstate.input(ephemeral_random_data);
748 let mut secp_ctx = Secp256k1::signing_only();
749 let ephemeral_hash = Sha256::from_engine(ephemeral_key_midstate.clone()).into_inner();
750 secp_ctx.seeded_randomize(&ephemeral_hash);
754 peers: FairRwLock::new(HashMap::new()),
755 node_id_to_descriptor: Mutex::new(HashMap::new()),
756 event_processing_lock: Mutex::new(()),
757 blocked_event_processors: AtomicBool::new(false),
758 ephemeral_key_midstate,
759 peer_counter: AtomicCounter::new(),
760 gossip_processing_backlogged: AtomicBool::new(false),
761 gossip_processing_backlog_lifted: AtomicBool::new(false),
762 last_node_announcement_serial: AtomicU32::new(current_time),
764 custom_message_handler,
770 /// Get a list of tuples mapping from node id to network addresses for peers which have
771 /// completed the initial handshake.
773 /// For outbound connections, the [`PublicKey`] will be the same as the `their_node_id` parameter
774 /// passed in to [`Self::new_outbound_connection`], however entries will only appear once the initial
775 /// handshake has completed and we are sure the remote peer has the private key for the given
778 /// The returned `Option`s will only be `Some` if an address had been previously given via
779 /// [`Self::new_outbound_connection`] or [`Self::new_inbound_connection`].
780 pub fn get_peer_node_ids(&self) -> Vec<(PublicKey, Option<NetAddress>)> {
781 let peers = self.peers.read().unwrap();
782 peers.values().filter_map(|peer_mutex| {
783 let p = peer_mutex.lock().unwrap();
784 if !p.handshake_complete() {
787 Some((p.their_node_id.unwrap().0, p.their_net_address.clone()))
791 fn get_ephemeral_key(&self) -> SecretKey {
792 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
793 let counter = self.peer_counter.get_increment();
794 ephemeral_hash.input(&counter.to_le_bytes());
795 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
798 /// Indicates a new outbound connection has been established to a node with the given `node_id`
799 /// and an optional remote network address.
801 /// The remote network address adds the option to report a remote IP address back to a connecting
802 /// peer using the init message.
803 /// The user should pass the remote network address of the host they are connected to.
805 /// If an `Err` is returned here you must disconnect the connection immediately.
807 /// Returns a small number of bytes to send to the remote node (currently always 50).
809 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
810 /// [`socket_disconnected`].
812 /// [`socket_disconnected`]: PeerManager::socket_disconnected
813 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<Vec<u8>, PeerHandleError> {
814 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
815 let res = peer_encryptor.get_act_one(&self.secp_ctx).to_vec();
816 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
818 let mut peers = self.peers.write().unwrap();
819 match peers.entry(descriptor) {
820 hash_map::Entry::Occupied(_) => {
821 debug_assert!(false, "PeerManager driver duplicated descriptors!");
822 Err(PeerHandleError {})
824 hash_map::Entry::Vacant(e) => {
825 e.insert(Mutex::new(Peer {
826 channel_encryptor: peer_encryptor,
828 their_features: None,
829 their_net_address: remote_network_address,
831 pending_outbound_buffer: LinkedList::new(),
832 pending_outbound_buffer_first_msg_offset: 0,
833 gossip_broadcast_buffer: LinkedList::new(),
834 awaiting_write_event: false,
837 pending_read_buffer_pos: 0,
838 pending_read_is_header: false,
840 sync_status: InitSyncTracker::NoSyncRequested,
842 msgs_sent_since_pong: 0,
843 awaiting_pong_timer_tick_intervals: 0,
844 received_message_since_timer_tick: false,
845 sent_gossip_timestamp_filter: false,
847 received_channel_announce_since_backlogged: false,
848 inbound_connection: false,
855 /// Indicates a new inbound connection has been established to a node with an optional remote
858 /// The remote network address adds the option to report a remote IP address back to a connecting
859 /// peer using the init message.
860 /// The user should pass the remote network address of the host they are connected to.
862 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
863 /// (outbound connector always speaks first). If an `Err` is returned here you must disconnect
864 /// the connection immediately.
866 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
867 /// [`socket_disconnected`].
869 /// [`socket_disconnected`]: PeerManager::socket_disconnected
870 pub fn new_inbound_connection(&self, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<(), PeerHandleError> {
871 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.node_signer);
872 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
874 let mut peers = self.peers.write().unwrap();
875 match peers.entry(descriptor) {
876 hash_map::Entry::Occupied(_) => {
877 debug_assert!(false, "PeerManager driver duplicated descriptors!");
878 Err(PeerHandleError {})
880 hash_map::Entry::Vacant(e) => {
881 e.insert(Mutex::new(Peer {
882 channel_encryptor: peer_encryptor,
884 their_features: None,
885 their_net_address: remote_network_address,
887 pending_outbound_buffer: LinkedList::new(),
888 pending_outbound_buffer_first_msg_offset: 0,
889 gossip_broadcast_buffer: LinkedList::new(),
890 awaiting_write_event: false,
893 pending_read_buffer_pos: 0,
894 pending_read_is_header: false,
896 sync_status: InitSyncTracker::NoSyncRequested,
898 msgs_sent_since_pong: 0,
899 awaiting_pong_timer_tick_intervals: 0,
900 received_message_since_timer_tick: false,
901 sent_gossip_timestamp_filter: false,
903 received_channel_announce_since_backlogged: false,
904 inbound_connection: true,
911 fn peer_should_read(&self, peer: &mut Peer) -> bool {
912 peer.should_read(self.gossip_processing_backlogged.load(Ordering::Relaxed))
915 fn update_gossip_backlogged(&self) {
916 let new_state = self.message_handler.route_handler.processing_queue_high();
917 let prev_state = self.gossip_processing_backlogged.swap(new_state, Ordering::Relaxed);
918 if prev_state && !new_state {
919 self.gossip_processing_backlog_lifted.store(true, Ordering::Relaxed);
923 fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer, force_one_write: bool) {
924 let mut have_written = false;
925 while !peer.awaiting_write_event {
926 if peer.should_buffer_onion_message() {
927 if let Some((peer_node_id, _)) = peer.their_node_id {
928 if let Some(next_onion_message) =
929 self.message_handler.onion_message_handler.next_onion_message_for_peer(peer_node_id) {
930 self.enqueue_message(peer, &next_onion_message);
934 if peer.should_buffer_gossip_broadcast() {
935 if let Some(msg) = peer.gossip_broadcast_buffer.pop_front() {
936 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_buffer(&msg[..]));
939 if peer.should_buffer_gossip_backfill() {
940 match peer.sync_status {
941 InitSyncTracker::NoSyncRequested => {},
942 InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
943 if let Some((announce, update_a_option, update_b_option)) =
944 self.message_handler.route_handler.get_next_channel_announcement(c)
946 self.enqueue_message(peer, &announce);
947 if let Some(update_a) = update_a_option {
948 self.enqueue_message(peer, &update_a);
950 if let Some(update_b) = update_b_option {
951 self.enqueue_message(peer, &update_b);
953 peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
955 peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
958 InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
959 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(None) {
960 self.enqueue_message(peer, &msg);
961 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
963 peer.sync_status = InitSyncTracker::NoSyncRequested;
966 InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
967 InitSyncTracker::NodesSyncing(sync_node_id) => {
968 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(Some(&sync_node_id)) {
969 self.enqueue_message(peer, &msg);
970 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
972 peer.sync_status = InitSyncTracker::NoSyncRequested;
977 if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
978 self.maybe_send_extra_ping(peer);
981 let should_read = self.peer_should_read(peer);
982 let next_buff = match peer.pending_outbound_buffer.front() {
984 if force_one_write && !have_written {
986 let data_sent = descriptor.send_data(&[], should_read);
987 debug_assert_eq!(data_sent, 0, "Can't write more than no data");
995 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
996 let data_sent = descriptor.send_data(pending, should_read);
998 peer.pending_outbound_buffer_first_msg_offset += data_sent;
999 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() {
1000 peer.pending_outbound_buffer_first_msg_offset = 0;
1001 peer.pending_outbound_buffer.pop_front();
1003 peer.awaiting_write_event = true;
1008 /// Indicates that there is room to write data to the given socket descriptor.
1010 /// May return an Err to indicate that the connection should be closed.
1012 /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
1013 /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
1014 /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
1015 /// ready to call [`write_buffer_space_avail`] again if a write call generated here isn't
1018 /// [`send_data`]: SocketDescriptor::send_data
1019 /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
1020 pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
1021 let peers = self.peers.read().unwrap();
1022 match peers.get(descriptor) {
1024 // This is most likely a simple race condition where the user found that the socket
1025 // was writeable, then we told the user to `disconnect_socket()`, then they called
1026 // this method. Return an error to make sure we get disconnected.
1027 return Err(PeerHandleError { });
1029 Some(peer_mutex) => {
1030 let mut peer = peer_mutex.lock().unwrap();
1031 peer.awaiting_write_event = false;
1032 self.do_attempt_write_data(descriptor, &mut peer, false);
1038 /// Indicates that data was read from the given socket descriptor.
1040 /// May return an Err to indicate that the connection should be closed.
1042 /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
1043 /// Thus, however, you should call [`process_events`] after any `read_event` to generate
1044 /// [`send_data`] calls to handle responses.
1046 /// If `Ok(true)` is returned, further read_events should not be triggered until a
1047 /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
1050 /// In order to avoid processing too many messages at once per peer, `data` should be on the
1053 /// [`send_data`]: SocketDescriptor::send_data
1054 /// [`process_events`]: PeerManager::process_events
1055 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1056 match self.do_read_event(peer_descriptor, data) {
1059 log_trace!(self.logger, "Peer sent invalid data or we decided to disconnect due to a protocol error");
1060 self.disconnect_event_internal(peer_descriptor);
1066 /// Append a message to a peer's pending outbound/write buffer
1067 fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
1068 if is_gossip_msg(message.type_id()) {
1069 log_gossip!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0));
1071 log_trace!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0))
1073 peer.msgs_sent_since_pong += 1;
1074 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(message));
1077 /// Append a message to a peer's pending outbound/write gossip broadcast buffer
1078 fn enqueue_encoded_gossip_broadcast(&self, peer: &mut Peer, encoded_message: Vec<u8>) {
1079 peer.msgs_sent_since_pong += 1;
1080 peer.gossip_broadcast_buffer.push_back(encoded_message);
1083 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1084 let mut pause_read = false;
1085 let peers = self.peers.read().unwrap();
1086 let mut msgs_to_forward = Vec::new();
1087 let mut peer_node_id = None;
1088 match peers.get(peer_descriptor) {
1090 // This is most likely a simple race condition where the user read some bytes
1091 // from the socket, then we told the user to `disconnect_socket()`, then they
1092 // called this method. Return an error to make sure we get disconnected.
1093 return Err(PeerHandleError { });
1095 Some(peer_mutex) => {
1096 let mut read_pos = 0;
1097 while read_pos < data.len() {
1098 macro_rules! try_potential_handleerror {
1099 ($peer: expr, $thing: expr) => {
1104 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
1105 //TODO: Try to push msg
1106 log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1107 return Err(PeerHandleError { });
1109 msgs::ErrorAction::IgnoreAndLog(level) => {
1110 log_given_level!(self.logger, level, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1113 msgs::ErrorAction::IgnoreDuplicateGossip => continue, // Don't even bother logging these
1114 msgs::ErrorAction::IgnoreError => {
1115 log_debug!(self.logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1118 msgs::ErrorAction::SendErrorMessage { msg } => {
1119 log_debug!(self.logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1120 self.enqueue_message($peer, &msg);
1123 msgs::ErrorAction::SendWarningMessage { msg, log_level } => {
1124 log_given_level!(self.logger, log_level, "Error handling message{}; sending warning message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1125 self.enqueue_message($peer, &msg);
1134 let mut peer_lock = peer_mutex.lock().unwrap();
1135 let peer = &mut *peer_lock;
1136 let mut msg_to_handle = None;
1137 if peer_node_id.is_none() {
1138 peer_node_id = peer.their_node_id.clone();
1141 assert!(peer.pending_read_buffer.len() > 0);
1142 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
1145 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
1146 peer.pending_read_buffer[peer.pending_read_buffer_pos..peer.pending_read_buffer_pos + data_to_copy].copy_from_slice(&data[read_pos..read_pos + data_to_copy]);
1147 read_pos += data_to_copy;
1148 peer.pending_read_buffer_pos += data_to_copy;
1151 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
1152 peer.pending_read_buffer_pos = 0;
1154 macro_rules! insert_node_id {
1156 match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap().0) {
1157 hash_map::Entry::Occupied(e) => {
1158 log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap().0));
1159 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
1160 // Check that the peers map is consistent with the
1161 // node_id_to_descriptor map, as this has been broken
1163 debug_assert!(peers.get(e.get()).is_some());
1164 return Err(PeerHandleError { })
1166 hash_map::Entry::Vacant(entry) => {
1167 log_debug!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap().0));
1168 entry.insert(peer_descriptor.clone())
1174 let next_step = peer.channel_encryptor.get_noise_step();
1176 NextNoiseStep::ActOne => {
1177 let act_two = try_potential_handleerror!(peer, peer.channel_encryptor
1178 .process_act_one_with_keys(&peer.pending_read_buffer[..],
1179 &self.node_signer, self.get_ephemeral_key(), &self.secp_ctx)).to_vec();
1180 peer.pending_outbound_buffer.push_back(act_two);
1181 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
1183 NextNoiseStep::ActTwo => {
1184 let (act_three, their_node_id) = try_potential_handleerror!(peer,
1185 peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..],
1186 &self.node_signer));
1187 peer.pending_outbound_buffer.push_back(act_three.to_vec());
1188 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1189 peer.pending_read_is_header = true;
1191 peer.set_their_node_id(their_node_id);
1193 let features = self.message_handler.chan_handler.provided_init_features(&their_node_id)
1194 .or(self.message_handler.route_handler.provided_init_features(&their_node_id))
1195 .or(self.message_handler.onion_message_handler.provided_init_features(&their_node_id));
1196 let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
1197 self.enqueue_message(peer, &resp);
1198 peer.awaiting_pong_timer_tick_intervals = 0;
1200 NextNoiseStep::ActThree => {
1201 let their_node_id = try_potential_handleerror!(peer,
1202 peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
1203 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1204 peer.pending_read_is_header = true;
1205 peer.set_their_node_id(their_node_id);
1207 let features = self.message_handler.chan_handler.provided_init_features(&their_node_id)
1208 .or(self.message_handler.route_handler.provided_init_features(&their_node_id))
1209 .or(self.message_handler.onion_message_handler.provided_init_features(&their_node_id));
1210 let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
1211 self.enqueue_message(peer, &resp);
1212 peer.awaiting_pong_timer_tick_intervals = 0;
1214 NextNoiseStep::NoiseComplete => {
1215 if peer.pending_read_is_header {
1216 let msg_len = try_potential_handleerror!(peer,
1217 peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
1218 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1219 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
1220 if msg_len < 2 { // Need at least the message type tag
1221 return Err(PeerHandleError { });
1223 peer.pending_read_is_header = false;
1225 let msg_data = try_potential_handleerror!(peer,
1226 peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
1227 assert!(msg_data.len() >= 2);
1229 // Reset read buffer
1230 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1231 peer.pending_read_buffer.resize(18, 0);
1232 peer.pending_read_is_header = true;
1234 let mut reader = io::Cursor::new(&msg_data[..]);
1235 let message_result = wire::read(&mut reader, &*self.custom_message_handler);
1236 let message = match message_result {
1240 // Note that to avoid recursion we never call
1241 // `do_attempt_write_data` from here, causing
1242 // the messages enqueued here to not actually
1243 // be sent before the peer is disconnected.
1244 (msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
1245 log_gossip!(self.logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
1248 (msgs::DecodeError::UnsupportedCompression, _) => {
1249 log_gossip!(self.logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
1250 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: "Unsupported message compression: zlib".to_owned() });
1253 (_, Some(ty)) if is_gossip_msg(ty) => {
1254 log_gossip!(self.logger, "Got an invalid value while deserializing a gossip message");
1255 self.enqueue_message(peer, &msgs::WarningMessage {
1256 channel_id: [0; 32],
1257 data: format!("Unreadable/bogus gossip message of type {}", ty),
1261 (msgs::DecodeError::UnknownRequiredFeature, ty) => {
1262 log_gossip!(self.logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
1263 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: format!("Received an unknown required feature/TLV in message type {:?}", ty) });
1264 return Err(PeerHandleError { });
1266 (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { }),
1267 (msgs::DecodeError::InvalidValue, _) => {
1268 log_debug!(self.logger, "Got an invalid value while deserializing message");
1269 return Err(PeerHandleError { });
1271 (msgs::DecodeError::ShortRead, _) => {
1272 log_debug!(self.logger, "Deserialization failed due to shortness of message");
1273 return Err(PeerHandleError { });
1275 (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { }),
1276 (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { }),
1281 msg_to_handle = Some(message);
1286 pause_read = !self.peer_should_read(peer);
1288 if let Some(message) = msg_to_handle {
1289 match self.handle_message(&peer_mutex, peer_lock, message) {
1290 Err(handling_error) => match handling_error {
1291 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
1292 MessageHandlingError::LightningError(e) => {
1293 try_potential_handleerror!(&mut peer_mutex.lock().unwrap(), Err(e));
1297 msgs_to_forward.push(msg);
1306 for msg in msgs_to_forward.drain(..) {
1307 self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref().map(|(pk, _)| pk));
1313 /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
1314 /// Returns the message back if it needs to be broadcasted to all other peers.
1317 peer_mutex: &Mutex<Peer>,
1318 mut peer_lock: MutexGuard<Peer>,
1319 message: wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>
1320 ) -> Result<Option<wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
1321 let their_node_id = peer_lock.their_node_id.clone().expect("We know the peer's public key by the time we receive messages").0;
1322 peer_lock.received_message_since_timer_tick = true;
1324 // Need an Init as first message
1325 if let wire::Message::Init(msg) = message {
1326 if msg.features.requires_unknown_bits() {
1327 log_debug!(self.logger, "Peer features required unknown version bits");
1328 return Err(PeerHandleError { }.into());
1330 if peer_lock.their_features.is_some() {
1331 return Err(PeerHandleError { }.into());
1334 log_info!(self.logger, "Received peer Init message from {}: {}", log_pubkey!(their_node_id), msg.features);
1336 // For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
1337 if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
1338 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1341 if let Err(()) = self.message_handler.route_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1342 log_debug!(self.logger, "Route Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1343 return Err(PeerHandleError { }.into());
1345 if let Err(()) = self.message_handler.chan_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1346 log_debug!(self.logger, "Channel Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1347 return Err(PeerHandleError { }.into());
1349 if let Err(()) = self.message_handler.onion_message_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1350 log_debug!(self.logger, "Onion Message Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1351 return Err(PeerHandleError { }.into());
1354 peer_lock.their_features = Some(msg.features);
1356 } else if peer_lock.their_features.is_none() {
1357 log_debug!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(their_node_id));
1358 return Err(PeerHandleError { }.into());
1361 if let wire::Message::GossipTimestampFilter(_msg) = message {
1362 // When supporting gossip messages, start inital gossip sync only after we receive
1363 // a GossipTimestampFilter
1364 if peer_lock.their_features.as_ref().unwrap().supports_gossip_queries() &&
1365 !peer_lock.sent_gossip_timestamp_filter {
1366 peer_lock.sent_gossip_timestamp_filter = true;
1367 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1372 if let wire::Message::ChannelAnnouncement(ref _msg) = message {
1373 peer_lock.received_channel_announce_since_backlogged = true;
1376 mem::drop(peer_lock);
1378 if is_gossip_msg(message.type_id()) {
1379 log_gossip!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1381 log_trace!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1384 let mut should_forward = None;
1387 // Setup and Control messages:
1388 wire::Message::Init(_) => {
1391 wire::Message::GossipTimestampFilter(_) => {
1394 wire::Message::Error(msg) => {
1395 let mut data_is_printable = true;
1396 for b in msg.data.bytes() {
1397 if b < 32 || b > 126 {
1398 data_is_printable = false;
1403 if data_is_printable {
1404 log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(their_node_id), msg.data);
1406 log_debug!(self.logger, "Got Err message from {} with non-ASCII error message", log_pubkey!(their_node_id));
1408 self.message_handler.chan_handler.handle_error(&their_node_id, &msg);
1409 if msg.channel_id == [0; 32] {
1410 return Err(PeerHandleError { }.into());
1413 wire::Message::Warning(msg) => {
1414 let mut data_is_printable = true;
1415 for b in msg.data.bytes() {
1416 if b < 32 || b > 126 {
1417 data_is_printable = false;
1422 if data_is_printable {
1423 log_debug!(self.logger, "Got warning message from {}: {}", log_pubkey!(their_node_id), msg.data);
1425 log_debug!(self.logger, "Got warning message from {} with non-ASCII error message", log_pubkey!(their_node_id));
1429 wire::Message::Ping(msg) => {
1430 if msg.ponglen < 65532 {
1431 let resp = msgs::Pong { byteslen: msg.ponglen };
1432 self.enqueue_message(&mut *peer_mutex.lock().unwrap(), &resp);
1435 wire::Message::Pong(_msg) => {
1436 let mut peer_lock = peer_mutex.lock().unwrap();
1437 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1438 peer_lock.msgs_sent_since_pong = 0;
1441 // Channel messages:
1442 wire::Message::OpenChannel(msg) => {
1443 self.message_handler.chan_handler.handle_open_channel(&their_node_id, &msg);
1445 wire::Message::AcceptChannel(msg) => {
1446 self.message_handler.chan_handler.handle_accept_channel(&their_node_id, &msg);
1449 wire::Message::FundingCreated(msg) => {
1450 self.message_handler.chan_handler.handle_funding_created(&their_node_id, &msg);
1452 wire::Message::FundingSigned(msg) => {
1453 self.message_handler.chan_handler.handle_funding_signed(&their_node_id, &msg);
1455 wire::Message::ChannelReady(msg) => {
1456 self.message_handler.chan_handler.handle_channel_ready(&their_node_id, &msg);
1459 wire::Message::Shutdown(msg) => {
1460 self.message_handler.chan_handler.handle_shutdown(&their_node_id, &msg);
1462 wire::Message::ClosingSigned(msg) => {
1463 self.message_handler.chan_handler.handle_closing_signed(&their_node_id, &msg);
1466 // Commitment messages:
1467 wire::Message::UpdateAddHTLC(msg) => {
1468 self.message_handler.chan_handler.handle_update_add_htlc(&their_node_id, &msg);
1470 wire::Message::UpdateFulfillHTLC(msg) => {
1471 self.message_handler.chan_handler.handle_update_fulfill_htlc(&their_node_id, &msg);
1473 wire::Message::UpdateFailHTLC(msg) => {
1474 self.message_handler.chan_handler.handle_update_fail_htlc(&their_node_id, &msg);
1476 wire::Message::UpdateFailMalformedHTLC(msg) => {
1477 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&their_node_id, &msg);
1480 wire::Message::CommitmentSigned(msg) => {
1481 self.message_handler.chan_handler.handle_commitment_signed(&their_node_id, &msg);
1483 wire::Message::RevokeAndACK(msg) => {
1484 self.message_handler.chan_handler.handle_revoke_and_ack(&their_node_id, &msg);
1486 wire::Message::UpdateFee(msg) => {
1487 self.message_handler.chan_handler.handle_update_fee(&their_node_id, &msg);
1489 wire::Message::ChannelReestablish(msg) => {
1490 self.message_handler.chan_handler.handle_channel_reestablish(&their_node_id, &msg);
1493 // Routing messages:
1494 wire::Message::AnnouncementSignatures(msg) => {
1495 self.message_handler.chan_handler.handle_announcement_signatures(&their_node_id, &msg);
1497 wire::Message::ChannelAnnouncement(msg) => {
1498 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1499 .map_err(|e| -> MessageHandlingError { e.into() })? {
1500 should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1502 self.update_gossip_backlogged();
1504 wire::Message::NodeAnnouncement(msg) => {
1505 if self.message_handler.route_handler.handle_node_announcement(&msg)
1506 .map_err(|e| -> MessageHandlingError { e.into() })? {
1507 should_forward = Some(wire::Message::NodeAnnouncement(msg));
1509 self.update_gossip_backlogged();
1511 wire::Message::ChannelUpdate(msg) => {
1512 self.message_handler.chan_handler.handle_channel_update(&their_node_id, &msg);
1513 if self.message_handler.route_handler.handle_channel_update(&msg)
1514 .map_err(|e| -> MessageHandlingError { e.into() })? {
1515 should_forward = Some(wire::Message::ChannelUpdate(msg));
1517 self.update_gossip_backlogged();
1519 wire::Message::QueryShortChannelIds(msg) => {
1520 self.message_handler.route_handler.handle_query_short_channel_ids(&their_node_id, msg)?;
1522 wire::Message::ReplyShortChannelIdsEnd(msg) => {
1523 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&their_node_id, msg)?;
1525 wire::Message::QueryChannelRange(msg) => {
1526 self.message_handler.route_handler.handle_query_channel_range(&their_node_id, msg)?;
1528 wire::Message::ReplyChannelRange(msg) => {
1529 self.message_handler.route_handler.handle_reply_channel_range(&their_node_id, msg)?;
1533 wire::Message::OnionMessage(msg) => {
1534 self.message_handler.onion_message_handler.handle_onion_message(&their_node_id, &msg);
1537 // Unknown messages:
1538 wire::Message::Unknown(type_id) if message.is_even() => {
1539 log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1540 return Err(PeerHandleError { }.into());
1542 wire::Message::Unknown(type_id) => {
1543 log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", type_id);
1545 wire::Message::Custom(custom) => {
1546 self.custom_message_handler.handle_custom_message(custom, &their_node_id)?;
1552 fn forward_broadcast_msg(&self, peers: &HashMap<Descriptor, Mutex<Peer>>, msg: &wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>, except_node: Option<&PublicKey>) {
1554 wire::Message::ChannelAnnouncement(ref msg) => {
1555 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1556 let encoded_msg = encode_msg!(msg);
1558 for (_, peer_mutex) in peers.iter() {
1559 let mut peer = peer_mutex.lock().unwrap();
1560 if !peer.handshake_complete() ||
1561 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1564 debug_assert!(peer.their_node_id.is_some());
1565 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1566 if peer.buffer_full_drop_gossip_broadcast() {
1567 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1570 if let Some((_, their_node_id)) = peer.their_node_id {
1571 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
1575 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1578 self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
1581 wire::Message::NodeAnnouncement(ref msg) => {
1582 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1583 let encoded_msg = encode_msg!(msg);
1585 for (_, peer_mutex) in peers.iter() {
1586 let mut peer = peer_mutex.lock().unwrap();
1587 if !peer.handshake_complete() ||
1588 !peer.should_forward_node_announcement(msg.contents.node_id) {
1591 debug_assert!(peer.their_node_id.is_some());
1592 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1593 if peer.buffer_full_drop_gossip_broadcast() {
1594 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1597 if let Some((_, their_node_id)) = peer.their_node_id {
1598 if their_node_id == msg.contents.node_id {
1602 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1605 self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
1608 wire::Message::ChannelUpdate(ref msg) => {
1609 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1610 let encoded_msg = encode_msg!(msg);
1612 for (_, peer_mutex) in peers.iter() {
1613 let mut peer = peer_mutex.lock().unwrap();
1614 if !peer.handshake_complete() ||
1615 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1618 debug_assert!(peer.their_node_id.is_some());
1619 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1620 if peer.buffer_full_drop_gossip_broadcast() {
1621 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1624 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1627 self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
1630 _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1634 /// Checks for any events generated by our handlers and processes them. Includes sending most
1635 /// response messages as well as messages generated by calls to handler functions directly (eg
1636 /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1638 /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1641 /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
1642 /// or one of the other clients provided in our language bindings.
1644 /// Note that if there are any other calls to this function waiting on lock(s) this may return
1645 /// without doing any work. All available events that need handling will be handled before the
1646 /// other calls return.
1648 /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1649 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1650 /// [`send_data`]: SocketDescriptor::send_data
1651 pub fn process_events(&self) {
1652 let mut _single_processor_lock = self.event_processing_lock.try_lock();
1653 if _single_processor_lock.is_err() {
1654 // While we could wake the older sleeper here with a CV and make more even waiting
1655 // times, that would be a lot of overengineering for a simple "reduce total waiter
1657 match self.blocked_event_processors.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) {
1659 debug_assert!(val, "compare_exchange failed spuriously?");
1663 debug_assert!(!val, "compare_exchange succeeded spuriously?");
1664 // We're the only waiter, as the running process_events may have emptied the
1665 // pending events "long" ago and there are new events for us to process, wait until
1666 // its done and process any leftover events before returning.
1667 _single_processor_lock = Ok(self.event_processing_lock.lock().unwrap());
1668 self.blocked_event_processors.store(false, Ordering::Release);
1673 self.update_gossip_backlogged();
1674 let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
1676 let mut peers_to_disconnect = HashMap::new();
1677 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
1678 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
1681 // TODO: There are some DoS attacks here where you can flood someone's outbound send
1682 // buffer by doing things like announcing channels on another node. We should be willing to
1683 // drop optional-ish messages when send buffers get full!
1685 let peers_lock = self.peers.read().unwrap();
1686 let peers = &*peers_lock;
1687 macro_rules! get_peer_for_forwarding {
1688 ($node_id: expr) => {
1690 if peers_to_disconnect.get($node_id).is_some() {
1691 // If we've "disconnected" this peer, do not send to it.
1694 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().get($node_id).cloned();
1695 match descriptor_opt {
1696 Some(descriptor) => match peers.get(&descriptor) {
1697 Some(peer_mutex) => {
1698 let peer_lock = peer_mutex.lock().unwrap();
1699 if !peer_lock.handshake_complete() {
1705 debug_assert!(false, "Inconsistent peers set state!");
1716 for event in events_generated.drain(..) {
1718 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1719 log_debug!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1720 log_pubkey!(node_id),
1721 log_bytes!(msg.temporary_channel_id));
1722 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1724 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1725 log_debug!(self.logger, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
1726 log_pubkey!(node_id),
1727 log_bytes!(msg.temporary_channel_id));
1728 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1730 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
1731 log_debug!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
1732 log_pubkey!(node_id),
1733 log_bytes!(msg.temporary_channel_id),
1734 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
1735 // TODO: If the peer is gone we should generate a DiscardFunding event
1736 // indicating to the wallet that they should just throw away this funding transaction
1737 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1739 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
1740 log_debug!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
1741 log_pubkey!(node_id),
1742 log_bytes!(msg.channel_id));
1743 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1745 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
1746 log_debug!(self.logger, "Handling SendChannelReady event in peer_handler for node {} for channel {}",
1747 log_pubkey!(node_id),
1748 log_bytes!(msg.channel_id));
1749 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1751 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
1752 log_debug!(self.logger, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
1753 log_pubkey!(node_id),
1754 log_bytes!(msg.channel_id));
1755 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1757 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
1758 log_debug!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
1759 log_pubkey!(node_id),
1760 update_add_htlcs.len(),
1761 update_fulfill_htlcs.len(),
1762 update_fail_htlcs.len(),
1763 log_bytes!(commitment_signed.channel_id));
1764 let mut peer = get_peer_for_forwarding!(node_id);
1765 for msg in update_add_htlcs {
1766 self.enqueue_message(&mut *peer, msg);
1768 for msg in update_fulfill_htlcs {
1769 self.enqueue_message(&mut *peer, msg);
1771 for msg in update_fail_htlcs {
1772 self.enqueue_message(&mut *peer, msg);
1774 for msg in update_fail_malformed_htlcs {
1775 self.enqueue_message(&mut *peer, msg);
1777 if let &Some(ref msg) = update_fee {
1778 self.enqueue_message(&mut *peer, msg);
1780 self.enqueue_message(&mut *peer, commitment_signed);
1782 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1783 log_debug!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
1784 log_pubkey!(node_id),
1785 log_bytes!(msg.channel_id));
1786 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1788 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1789 log_debug!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
1790 log_pubkey!(node_id),
1791 log_bytes!(msg.channel_id));
1792 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1794 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1795 log_debug!(self.logger, "Handling Shutdown event in peer_handler for node {} for channel {}",
1796 log_pubkey!(node_id),
1797 log_bytes!(msg.channel_id));
1798 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1800 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
1801 log_debug!(self.logger, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
1802 log_pubkey!(node_id),
1803 log_bytes!(msg.channel_id));
1804 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1806 MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, ref update_msg } => {
1807 log_debug!(self.logger, "Handling SendChannelAnnouncement event in peer_handler for node {} for short channel id {}",
1808 log_pubkey!(node_id),
1809 msg.contents.short_channel_id);
1810 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1811 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), update_msg);
1813 MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
1814 log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1815 match self.message_handler.route_handler.handle_channel_announcement(&msg) {
1816 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1817 self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
1820 if let Some(msg) = update_msg {
1821 match self.message_handler.route_handler.handle_channel_update(&msg) {
1822 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1823 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
1828 MessageSendEvent::BroadcastChannelUpdate { msg } => {
1829 log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1830 match self.message_handler.route_handler.handle_channel_update(&msg) {
1831 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1832 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
1836 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
1837 log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler for node {}", msg.contents.node_id);
1838 match self.message_handler.route_handler.handle_node_announcement(&msg) {
1839 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1840 self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None),
1844 MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
1845 log_trace!(self.logger, "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
1846 log_pubkey!(node_id), msg.contents.short_channel_id);
1847 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1849 MessageSendEvent::HandleError { ref node_id, ref action } => {
1851 msgs::ErrorAction::DisconnectPeer { ref msg } => {
1852 // We do not have the peers write lock, so we just store that we're
1853 // about to disconenct the peer and do it after we finish
1854 // processing most messages.
1855 peers_to_disconnect.insert(*node_id, msg.clone());
1857 msgs::ErrorAction::IgnoreAndLog(level) => {
1858 log_given_level!(self.logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1860 msgs::ErrorAction::IgnoreDuplicateGossip => {},
1861 msgs::ErrorAction::IgnoreError => {
1862 log_debug!(self.logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1864 msgs::ErrorAction::SendErrorMessage { ref msg } => {
1865 log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1866 log_pubkey!(node_id),
1868 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1870 msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
1871 log_given_level!(self.logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
1872 log_pubkey!(node_id),
1874 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1878 MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
1879 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1881 MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
1882 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1884 MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
1885 log_gossip!(self.logger, "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
1886 log_pubkey!(node_id),
1887 msg.short_channel_ids.len(),
1889 msg.number_of_blocks,
1891 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1893 MessageSendEvent::SendGossipTimestampFilter { ref node_id, ref msg } => {
1894 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1899 for (node_id, msg) in self.custom_message_handler.get_and_clear_pending_msg() {
1900 if peers_to_disconnect.get(&node_id).is_some() { continue; }
1901 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), &msg);
1904 for (descriptor, peer_mutex) in peers.iter() {
1905 let mut peer = peer_mutex.lock().unwrap();
1906 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
1907 self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer, flush_read_disabled);
1910 if !peers_to_disconnect.is_empty() {
1911 let mut peers_lock = self.peers.write().unwrap();
1912 let peers = &mut *peers_lock;
1913 for (node_id, msg) in peers_to_disconnect.drain() {
1914 // Note that since we are holding the peers *write* lock we can
1915 // remove from node_id_to_descriptor immediately (as no other
1916 // thread can be holding the peer lock if we have the global write
1919 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
1920 if let Some(mut descriptor) = descriptor_opt {
1921 if let Some(peer_mutex) = peers.remove(&descriptor) {
1922 let mut peer = peer_mutex.lock().unwrap();
1923 if let Some(msg) = msg {
1924 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1925 log_pubkey!(node_id),
1927 self.enqueue_message(&mut *peer, &msg);
1928 // This isn't guaranteed to work, but if there is enough free
1929 // room in the send buffer, put the error message there...
1930 self.do_attempt_write_data(&mut descriptor, &mut *peer, false);
1932 self.do_disconnect(descriptor, &*peer, "DisconnectPeer HandleError");
1933 } else { debug_assert!(false, "Missing connection for peer"); }
1939 /// Indicates that the given socket descriptor's connection is now closed.
1940 pub fn socket_disconnected(&self, descriptor: &Descriptor) {
1941 self.disconnect_event_internal(descriptor);
1944 fn do_disconnect(&self, mut descriptor: Descriptor, peer: &Peer, reason: &'static str) {
1945 if !peer.handshake_complete() {
1946 log_trace!(self.logger, "Disconnecting peer which hasn't completed handshake due to {}", reason);
1947 descriptor.disconnect_socket();
1951 debug_assert!(peer.their_node_id.is_some());
1952 if let Some((node_id, _)) = peer.their_node_id {
1953 log_trace!(self.logger, "Disconnecting peer with id {} due to {}", node_id, reason);
1954 self.message_handler.chan_handler.peer_disconnected(&node_id);
1955 self.message_handler.onion_message_handler.peer_disconnected(&node_id);
1957 descriptor.disconnect_socket();
1960 fn disconnect_event_internal(&self, descriptor: &Descriptor) {
1961 let mut peers = self.peers.write().unwrap();
1962 let peer_option = peers.remove(descriptor);
1965 // This is most likely a simple race condition where the user found that the socket
1966 // was disconnected, then we told the user to `disconnect_socket()`, then they
1967 // called this method. Either way we're disconnected, return.
1969 Some(peer_lock) => {
1970 let peer = peer_lock.lock().unwrap();
1971 if let Some((node_id, _)) = peer.their_node_id {
1972 log_trace!(self.logger, "Handling disconnection of peer {}", log_pubkey!(node_id));
1973 let removed = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
1974 debug_assert!(removed.is_some(), "descriptor maps should be consistent");
1975 if !peer.handshake_complete() { return; }
1976 self.message_handler.chan_handler.peer_disconnected(&node_id);
1977 self.message_handler.onion_message_handler.peer_disconnected(&node_id);
1983 /// Disconnect a peer given its node id.
1985 /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
1986 /// peer. Thus, be very careful about reentrancy issues.
1988 /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
1989 pub fn disconnect_by_node_id(&self, node_id: PublicKey) {
1990 let mut peers_lock = self.peers.write().unwrap();
1991 if let Some(descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
1992 let peer_opt = peers_lock.remove(&descriptor);
1993 if let Some(peer_mutex) = peer_opt {
1994 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request");
1995 } else { debug_assert!(false, "node_id_to_descriptor thought we had a peer"); }
1999 /// Disconnects all currently-connected peers. This is useful on platforms where there may be
2000 /// an indication that TCP sockets have stalled even if we weren't around to time them out
2001 /// using regular ping/pongs.
2002 pub fn disconnect_all_peers(&self) {
2003 let mut peers_lock = self.peers.write().unwrap();
2004 self.node_id_to_descriptor.lock().unwrap().clear();
2005 let peers = &mut *peers_lock;
2006 for (descriptor, peer_mutex) in peers.drain() {
2007 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request to disconnect all peers");
2011 /// This is called when we're blocked on sending additional gossip messages until we receive a
2012 /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
2013 /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
2014 fn maybe_send_extra_ping(&self, peer: &mut Peer) {
2015 if peer.awaiting_pong_timer_tick_intervals == 0 {
2016 peer.awaiting_pong_timer_tick_intervals = -1;
2017 let ping = msgs::Ping {
2021 self.enqueue_message(peer, &ping);
2025 /// Send pings to each peer and disconnect those which did not respond to the last round of
2028 /// This may be called on any timescale you want, however, roughly once every ten seconds is
2029 /// preferred. The call rate determines both how often we send a ping to our peers and how much
2030 /// time they have to respond before we disconnect them.
2032 /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
2035 /// [`send_data`]: SocketDescriptor::send_data
2036 pub fn timer_tick_occurred(&self) {
2037 let mut descriptors_needing_disconnect = Vec::new();
2039 let peers_lock = self.peers.read().unwrap();
2041 self.update_gossip_backlogged();
2042 let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
2044 for (descriptor, peer_mutex) in peers_lock.iter() {
2045 let mut peer = peer_mutex.lock().unwrap();
2046 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2048 if !peer.handshake_complete() {
2049 // The peer needs to complete its handshake before we can exchange messages. We
2050 // give peers one timer tick to complete handshake, reusing
2051 // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
2052 // for handshake completion.
2053 if peer.awaiting_pong_timer_tick_intervals != 0 {
2054 descriptors_needing_disconnect.push(descriptor.clone());
2056 peer.awaiting_pong_timer_tick_intervals = 1;
2060 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
2061 debug_assert!(peer.their_node_id.is_some());
2063 loop { // Used as a `goto` to skip writing a Ping message.
2064 if peer.awaiting_pong_timer_tick_intervals == -1 {
2065 // Magic value set in `maybe_send_extra_ping`.
2066 peer.awaiting_pong_timer_tick_intervals = 1;
2067 peer.received_message_since_timer_tick = false;
2071 if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
2072 || peer.awaiting_pong_timer_tick_intervals as u64 >
2073 MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64
2075 descriptors_needing_disconnect.push(descriptor.clone());
2078 peer.received_message_since_timer_tick = false;
2080 if peer.awaiting_pong_timer_tick_intervals > 0 {
2081 peer.awaiting_pong_timer_tick_intervals += 1;
2085 peer.awaiting_pong_timer_tick_intervals = 1;
2086 let ping = msgs::Ping {
2090 self.enqueue_message(&mut *peer, &ping);
2093 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer, flush_read_disabled);
2097 if !descriptors_needing_disconnect.is_empty() {
2099 let mut peers_lock = self.peers.write().unwrap();
2100 for descriptor in descriptors_needing_disconnect {
2101 if let Some(peer_mutex) = peers_lock.remove(&descriptor) {
2102 let peer = peer_mutex.lock().unwrap();
2103 if let Some((node_id, _)) = peer.their_node_id {
2104 self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2106 self.do_disconnect(descriptor, &*peer, "ping timeout");
2114 // Messages of up to 64KB should never end up more than half full with addresses, as that would
2115 // be absurd. We ensure this by checking that at least 100 (our stated public contract on when
2116 // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
2118 const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2;
2121 // ...by failing to compile if the number of addresses that would be half of a message is
2122 // smaller than 100:
2123 const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 100;
2125 /// Generates a signed node_announcement from the given arguments, sending it to all connected
2126 /// peers. Note that peers will likely ignore this message unless we have at least one public
2127 /// channel which has at least six confirmations on-chain.
2129 /// `rgb` is a node "color" and `alias` is a printable human-readable string to describe this
2130 /// node to humans. They carry no in-protocol meaning.
2132 /// `addresses` represent the set (possibly empty) of socket addresses on which this node
2133 /// accepts incoming connections. These will be included in the node_announcement, publicly
2134 /// tying these addresses together and to this node. If you wish to preserve user privacy,
2135 /// addresses should likely contain only Tor Onion addresses.
2137 /// Panics if `addresses` is absurdly large (more than 100).
2139 /// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events
2140 pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], mut addresses: Vec<NetAddress>) {
2141 if addresses.len() > 100 {
2142 panic!("More than half the message size was taken up by public addresses!");
2145 // While all existing nodes handle unsorted addresses just fine, the spec requires that
2146 // addresses be sorted for future compatibility.
2147 addresses.sort_by_key(|addr| addr.get_id());
2149 let features = self.message_handler.chan_handler.provided_node_features()
2150 .or(self.message_handler.route_handler.provided_node_features())
2151 .or(self.message_handler.onion_message_handler.provided_node_features());
2152 let announcement = msgs::UnsignedNodeAnnouncement {
2154 timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel),
2155 node_id: NodeId::from_pubkey(&self.node_signer.get_node_id(Recipient::Node).unwrap()),
2156 rgb, alias, addresses,
2157 excess_address_data: Vec::new(),
2158 excess_data: Vec::new(),
2160 let node_announce_sig = match self.node_signer.sign_gossip_message(
2161 msgs::UnsignedGossipMessage::NodeAnnouncement(&announcement)
2165 log_error!(self.logger, "Failed to generate signature for node_announcement");
2170 let msg = msgs::NodeAnnouncement {
2171 signature: node_announce_sig,
2172 contents: announcement
2175 log_debug!(self.logger, "Broadcasting NodeAnnouncement after passing it to our own RoutingMessageHandler.");
2176 let _ = self.message_handler.route_handler.handle_node_announcement(&msg);
2177 self.forward_broadcast_msg(&*self.peers.read().unwrap(), &wire::Message::NodeAnnouncement(msg), None);
2181 fn is_gossip_msg(type_id: u16) -> bool {
2183 msgs::ChannelAnnouncement::TYPE |
2184 msgs::ChannelUpdate::TYPE |
2185 msgs::NodeAnnouncement::TYPE |
2186 msgs::QueryChannelRange::TYPE |
2187 msgs::ReplyChannelRange::TYPE |
2188 msgs::QueryShortChannelIds::TYPE |
2189 msgs::ReplyShortChannelIdsEnd::TYPE => true,
2196 use crate::chain::keysinterface::{NodeSigner, Recipient};
2198 use crate::ln::peer_channel_encryptor::PeerChannelEncryptor;
2199 use crate::ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses};
2200 use crate::ln::{msgs, wire};
2201 use crate::ln::msgs::NetAddress;
2202 use crate::util::test_utils;
2204 use bitcoin::secp256k1::SecretKey;
2206 use crate::prelude::*;
2207 use crate::sync::{Arc, Mutex};
2208 use core::sync::atomic::{AtomicBool, Ordering};
2211 struct FileDescriptor {
2213 outbound_data: Arc<Mutex<Vec<u8>>>,
2214 disconnect: Arc<AtomicBool>,
2216 impl PartialEq for FileDescriptor {
2217 fn eq(&self, other: &Self) -> bool {
2221 impl Eq for FileDescriptor { }
2222 impl core::hash::Hash for FileDescriptor {
2223 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
2224 self.fd.hash(hasher)
2228 impl SocketDescriptor for FileDescriptor {
2229 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
2230 self.outbound_data.lock().unwrap().extend_from_slice(data);
2234 fn disconnect_socket(&mut self) { self.disconnect.store(true, Ordering::Release); }
2237 struct PeerManagerCfg {
2238 chan_handler: test_utils::TestChannelMessageHandler,
2239 routing_handler: test_utils::TestRoutingMessageHandler,
2240 logger: test_utils::TestLogger,
2241 node_signer: test_utils::TestNodeSigner,
2244 fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2245 let mut cfgs = Vec::new();
2246 for i in 0..peer_count {
2247 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2250 chan_handler: test_utils::TestChannelMessageHandler::new(),
2251 logger: test_utils::TestLogger::new(),
2252 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2253 node_signer: test_utils::TestNodeSigner::new(node_secret),
2261 fn create_network<'a>(peer_count: usize, cfgs: &'a Vec<PeerManagerCfg>) -> Vec<PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, IgnoringMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler, &'a test_utils::TestNodeSigner>> {
2262 let mut peers = Vec::new();
2263 for i in 0..peer_count {
2264 let ephemeral_bytes = [i as u8; 32];
2265 let msg_handler = MessageHandler { chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler, onion_message_handler: IgnoringMessageHandler {} };
2266 let peer = PeerManager::new(msg_handler, 0, &ephemeral_bytes, &cfgs[i].logger, IgnoringMessageHandler {}, &cfgs[i].node_signer);
2273 fn establish_connection<'a>(peer_a: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, IgnoringMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler, &'a test_utils::TestNodeSigner>, peer_b: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, IgnoringMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler, &'a test_utils::TestNodeSigner>) -> (FileDescriptor, FileDescriptor) {
2274 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2275 let mut fd_a = FileDescriptor {
2276 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2277 disconnect: Arc::new(AtomicBool::new(false)),
2279 let addr_a = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1000};
2280 let id_b = peer_b.node_signer.get_node_id(Recipient::Node).unwrap();
2281 let mut fd_b = FileDescriptor {
2282 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2283 disconnect: Arc::new(AtomicBool::new(false)),
2285 let addr_b = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1001};
2286 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2287 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2288 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2289 peer_a.process_events();
2291 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2292 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2294 peer_b.process_events();
2295 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2296 assert_eq!(peer_a.read_event(&mut fd_a, &b_data).unwrap(), false);
2298 peer_a.process_events();
2299 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2300 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2302 assert!(peer_a.get_peer_node_ids().contains(&(id_b, Some(addr_b))));
2303 assert!(peer_b.get_peer_node_ids().contains(&(id_a, Some(addr_a))));
2305 (fd_a.clone(), fd_b.clone())
2309 #[cfg(feature = "std")]
2310 fn fuzz_threaded_connections() {
2311 // Spawn two threads which repeatedly connect two peers together, leading to "got second
2312 // connection with peer" disconnections and rapid reconnect. This previously found an issue
2313 // with our internal map consistency, and is a generally good smoke test of disconnection.
2314 let cfgs = Arc::new(create_peermgr_cfgs(2));
2315 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
2316 let peers = Arc::new(create_network(2, unsafe { &*(&*cfgs as *const _) as &'static _ }));
2318 let start_time = std::time::Instant::now();
2319 macro_rules! spawn_thread { ($id: expr) => { {
2320 let peers = Arc::clone(&peers);
2321 let cfgs = Arc::clone(&cfgs);
2322 std::thread::spawn(move || {
2324 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2325 let id_a = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
2326 let mut fd_a = FileDescriptor {
2327 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2328 disconnect: Arc::new(AtomicBool::new(false)),
2330 let addr_a = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1000};
2331 let mut fd_b = FileDescriptor {
2332 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2333 disconnect: Arc::new(AtomicBool::new(false)),
2335 let addr_b = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1001};
2336 let initial_data = peers[1].new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2337 peers[0].new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2338 if peers[0].read_event(&mut fd_a, &initial_data).is_err() { break; }
2340 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2341 peers[0].process_events();
2342 if fd_a.disconnect.load(Ordering::Acquire) { break; }
2343 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2344 if peers[1].read_event(&mut fd_b, &a_data).is_err() { break; }
2346 peers[1].process_events();
2347 if fd_b.disconnect.load(Ordering::Acquire) { break; }
2348 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2349 if peers[0].read_event(&mut fd_a, &b_data).is_err() { break; }
2351 cfgs[0].chan_handler.pending_events.lock().unwrap()
2352 .push(crate::events::MessageSendEvent::SendShutdown {
2353 node_id: peers[1].node_signer.get_node_id(Recipient::Node).unwrap(),
2354 msg: msgs::Shutdown {
2355 channel_id: [0; 32],
2356 scriptpubkey: bitcoin::Script::new(),
2359 cfgs[1].chan_handler.pending_events.lock().unwrap()
2360 .push(crate::events::MessageSendEvent::SendShutdown {
2361 node_id: peers[0].node_signer.get_node_id(Recipient::Node).unwrap(),
2362 msg: msgs::Shutdown {
2363 channel_id: [0; 32],
2364 scriptpubkey: bitcoin::Script::new(),
2369 peers[0].timer_tick_occurred();
2370 peers[1].timer_tick_occurred();
2374 peers[0].socket_disconnected(&fd_a);
2375 peers[1].socket_disconnected(&fd_b);
2377 std::thread::sleep(std::time::Duration::from_micros(1));
2381 let thrd_a = spawn_thread!(1);
2382 let thrd_b = spawn_thread!(2);
2384 thrd_a.join().unwrap();
2385 thrd_b.join().unwrap();
2389 fn test_disconnect_peer() {
2390 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2391 // push a DisconnectPeer event to remove the node flagged by id
2392 let cfgs = create_peermgr_cfgs(2);
2393 let peers = create_network(2, &cfgs);
2394 establish_connection(&peers[0], &peers[1]);
2395 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2397 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
2398 cfgs[0].chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
2400 action: msgs::ErrorAction::DisconnectPeer { msg: None },
2403 peers[0].process_events();
2404 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2408 fn test_send_simple_msg() {
2409 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2410 // push a message from one peer to another.
2411 let cfgs = create_peermgr_cfgs(2);
2412 let a_chan_handler = test_utils::TestChannelMessageHandler::new();
2413 let b_chan_handler = test_utils::TestChannelMessageHandler::new();
2414 let mut peers = create_network(2, &cfgs);
2415 let (fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2416 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2418 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
2420 let msg = msgs::Shutdown { channel_id: [42; 32], scriptpubkey: bitcoin::Script::new() };
2421 a_chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::SendShutdown {
2422 node_id: their_id, msg: msg.clone()
2424 peers[0].message_handler.chan_handler = &a_chan_handler;
2426 b_chan_handler.expect_receive_msg(wire::Message::Shutdown(msg));
2427 peers[1].message_handler.chan_handler = &b_chan_handler;
2429 peers[0].process_events();
2431 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2432 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2436 fn test_non_init_first_msg() {
2437 // Simple test of the first message received over a connection being something other than
2438 // Init. This results in an immediate disconnection, which previously included a spurious
2439 // peer_disconnected event handed to event handlers (which would panic in
2440 // `TestChannelMessageHandler` here).
2441 let cfgs = create_peermgr_cfgs(2);
2442 let peers = create_network(2, &cfgs);
2444 let mut fd_dup = FileDescriptor {
2445 fd: 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2446 disconnect: Arc::new(AtomicBool::new(false)),
2448 let addr_dup = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1003};
2449 let id_a = cfgs[0].node_signer.get_node_id(Recipient::Node).unwrap();
2450 peers[0].new_inbound_connection(fd_dup.clone(), Some(addr_dup.clone())).unwrap();
2452 let mut dup_encryptor = PeerChannelEncryptor::new_outbound(id_a, SecretKey::from_slice(&[42; 32]).unwrap());
2453 let initial_data = dup_encryptor.get_act_one(&peers[1].secp_ctx);
2454 assert_eq!(peers[0].read_event(&mut fd_dup, &initial_data).unwrap(), false);
2455 peers[0].process_events();
2457 let a_data = fd_dup.outbound_data.lock().unwrap().split_off(0);
2458 let (act_three, _) =
2459 dup_encryptor.process_act_two(&a_data[..], &&cfgs[1].node_signer).unwrap();
2460 assert_eq!(peers[0].read_event(&mut fd_dup, &act_three).unwrap(), false);
2462 let not_init_msg = msgs::Ping { ponglen: 4, byteslen: 0 };
2463 let msg_bytes = dup_encryptor.encrypt_message(¬_init_msg);
2464 assert!(peers[0].read_event(&mut fd_dup, &msg_bytes).is_err());
2468 fn test_disconnect_all_peer() {
2469 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2470 // then calls disconnect_all_peers
2471 let cfgs = create_peermgr_cfgs(2);
2472 let peers = create_network(2, &cfgs);
2473 establish_connection(&peers[0], &peers[1]);
2474 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2476 peers[0].disconnect_all_peers();
2477 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2481 fn test_timer_tick_occurred() {
2482 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
2483 let cfgs = create_peermgr_cfgs(2);
2484 let peers = create_network(2, &cfgs);
2485 establish_connection(&peers[0], &peers[1]);
2486 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2488 // peers[0] awaiting_pong is set to true, but the Peer is still connected
2489 peers[0].timer_tick_occurred();
2490 peers[0].process_events();
2491 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2493 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
2494 peers[0].timer_tick_occurred();
2495 peers[0].process_events();
2496 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2500 fn test_do_attempt_write_data() {
2501 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
2502 let cfgs = create_peermgr_cfgs(2);
2503 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2504 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2505 let peers = create_network(2, &cfgs);
2507 // By calling establish_connect, we trigger do_attempt_write_data between
2508 // the peers. Previously this function would mistakenly enter an infinite loop
2509 // when there were more channel messages available than could fit into a peer's
2510 // buffer. This issue would now be detected by this test (because we use custom
2511 // RoutingMessageHandlers that intentionally return more channel messages
2512 // than can fit into a peer's buffer).
2513 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2515 // Make each peer to read the messages that the other peer just wrote to them. Note that
2516 // due to the max-message-before-ping limits this may take a few iterations to complete.
2517 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
2518 peers[1].process_events();
2519 let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2520 assert!(!a_read_data.is_empty());
2522 peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
2523 peers[0].process_events();
2525 let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2526 assert!(!b_read_data.is_empty());
2527 peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
2529 peers[0].process_events();
2530 assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
2533 // Check that each peer has received the expected number of channel updates and channel
2535 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2536 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2537 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2538 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2542 fn test_handshake_timeout() {
2543 // Tests that we time out a peer still waiting on handshake completion after a full timer
2545 let cfgs = create_peermgr_cfgs(2);
2546 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2547 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2548 let peers = create_network(2, &cfgs);
2550 let a_id = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
2551 let mut fd_a = FileDescriptor {
2552 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2553 disconnect: Arc::new(AtomicBool::new(false)),
2555 let mut fd_b = FileDescriptor {
2556 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2557 disconnect: Arc::new(AtomicBool::new(false)),
2559 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
2560 peers[0].new_inbound_connection(fd_a.clone(), None).unwrap();
2562 // If we get a single timer tick before completion, that's fine
2563 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2564 peers[0].timer_tick_occurred();
2565 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2567 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
2568 peers[0].process_events();
2569 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2570 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2571 peers[1].process_events();
2573 // ...but if we get a second timer tick, we should disconnect the peer
2574 peers[0].timer_tick_occurred();
2575 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2577 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2578 assert!(peers[0].read_event(&mut fd_a, &b_data).is_err());
2582 fn test_filter_addresses(){
2583 // Tests the filter_addresses function.
2586 let ip_address = NetAddress::IPv4{addr: [10, 0, 0, 0], port: 1000};
2587 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2588 let ip_address = NetAddress::IPv4{addr: [10, 0, 255, 201], port: 1000};
2589 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2590 let ip_address = NetAddress::IPv4{addr: [10, 255, 255, 255], port: 1000};
2591 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2594 let ip_address = NetAddress::IPv4{addr: [0, 0, 0, 0], port: 1000};
2595 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2596 let ip_address = NetAddress::IPv4{addr: [0, 0, 255, 187], port: 1000};
2597 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2598 let ip_address = NetAddress::IPv4{addr: [0, 255, 255, 255], port: 1000};
2599 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2602 let ip_address = NetAddress::IPv4{addr: [100, 64, 0, 0], port: 1000};
2603 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2604 let ip_address = NetAddress::IPv4{addr: [100, 78, 255, 0], port: 1000};
2605 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2606 let ip_address = NetAddress::IPv4{addr: [100, 127, 255, 255], port: 1000};
2607 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2610 let ip_address = NetAddress::IPv4{addr: [127, 0, 0, 0], port: 1000};
2611 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2612 let ip_address = NetAddress::IPv4{addr: [127, 65, 73, 0], port: 1000};
2613 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2614 let ip_address = NetAddress::IPv4{addr: [127, 255, 255, 255], port: 1000};
2615 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2618 let ip_address = NetAddress::IPv4{addr: [169, 254, 0, 0], port: 1000};
2619 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2620 let ip_address = NetAddress::IPv4{addr: [169, 254, 221, 101], port: 1000};
2621 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2622 let ip_address = NetAddress::IPv4{addr: [169, 254, 255, 255], port: 1000};
2623 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2626 let ip_address = NetAddress::IPv4{addr: [172, 16, 0, 0], port: 1000};
2627 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2628 let ip_address = NetAddress::IPv4{addr: [172, 27, 101, 23], port: 1000};
2629 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2630 let ip_address = NetAddress::IPv4{addr: [172, 31, 255, 255], port: 1000};
2631 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2634 let ip_address = NetAddress::IPv4{addr: [192, 168, 0, 0], port: 1000};
2635 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2636 let ip_address = NetAddress::IPv4{addr: [192, 168, 205, 159], port: 1000};
2637 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2638 let ip_address = NetAddress::IPv4{addr: [192, 168, 255, 255], port: 1000};
2639 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2641 // For (192.88.99/24)
2642 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 0], port: 1000};
2643 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2644 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 140], port: 1000};
2645 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2646 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 255], port: 1000};
2647 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2649 // For other IPv4 addresses
2650 let ip_address = NetAddress::IPv4{addr: [188, 255, 99, 0], port: 1000};
2651 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2652 let ip_address = NetAddress::IPv4{addr: [123, 8, 129, 14], port: 1000};
2653 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2654 let ip_address = NetAddress::IPv4{addr: [2, 88, 9, 255], port: 1000};
2655 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2658 let ip_address = NetAddress::IPv6{addr: [32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], port: 1000};
2659 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2660 let ip_address = NetAddress::IPv6{addr: [45, 34, 209, 190, 0, 123, 55, 34, 0, 0, 3, 27, 201, 0, 0, 0], port: 1000};
2661 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2662 let ip_address = NetAddress::IPv6{addr: [63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], port: 1000};
2663 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2665 // For other IPv6 addresses
2666 let ip_address = NetAddress::IPv6{addr: [24, 240, 12, 32, 0, 0, 0, 0, 20, 97, 0, 32, 121, 254, 0, 0], port: 1000};
2667 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2668 let ip_address = NetAddress::IPv6{addr: [68, 23, 56, 63, 0, 0, 2, 7, 75, 109, 0, 39, 0, 0, 0, 0], port: 1000};
2669 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2670 let ip_address = NetAddress::IPv6{addr: [101, 38, 140, 230, 100, 0, 30, 98, 0, 26, 0, 0, 57, 96, 0, 0], port: 1000};
2671 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2674 assert_eq!(filter_addresses(None), None);