rgb_lightning/ln/
peer_handler.rs

1// This file is Copyright its original authors, visible in version control
2// history.
3//
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
8// licenses.
9
10//! Top level peer message handling and socket handling logic lives here.
11//!
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.
17
18use bitcoin::secp256k1::{self, Secp256k1, SecretKey, PublicKey};
19
20use crate::ln::features::{InitFeatures, NodeFeatures};
21use crate::ln::msgs;
22use crate::ln::msgs::{ChannelMessageHandler, LightningError, NetAddress, OnionMessageHandler, RoutingMessageHandler};
23use crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
24use crate::util::ser::{VecWriter, Writeable, Writer};
25use crate::ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
26use crate::ln::wire;
27use crate::ln::wire::Encode;
28use crate::onion_message::{CustomOnionMessageContents, CustomOnionMessageHandler, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
29use crate::routing::gossip::{NetworkGraph, P2PGossipSync};
30use crate::util::atomic_counter::AtomicCounter;
31use crate::util::crypto::sign;
32use crate::util::events::{MessageSendEvent, MessageSendEventsProvider, OnionMessageProvider};
33use crate::util::logger::Logger;
34
35use crate::prelude::*;
36use crate::io;
37use alloc::collections::LinkedList;
38use crate::sync::{Arc, Mutex, MutexGuard, FairRwLock};
39use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
40use core::{cmp, hash, fmt, mem};
41use core::ops::Deref;
42use core::convert::Infallible;
43#[cfg(feature = "std")] use std::error;
44
45use bitcoin::hashes::sha256::Hash as Sha256;
46use bitcoin::hashes::sha256d::Hash as Sha256dHash;
47use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
48use bitcoin::hashes::{HashEngine, Hash};
49
50/// Handler for BOLT1-compliant messages.
51pub trait CustomMessageHandler: wire::CustomMessageReader {
52	/// Called with the message type that was received and the buffer to be read.
53	/// Can return a `MessageHandlingError` if the message could not be handled.
54	fn handle_custom_message(&self, msg: Self::CustomMessage, sender_node_id: &PublicKey) -> Result<(), LightningError>;
55
56	/// Gets the list of pending messages which were generated by the custom message
57	/// handler, clearing the list in the process. The first tuple element must
58	/// correspond to the intended recipients node ids. If no connection to one of the
59	/// specified node does not exist, the message is simply not sent to it.
60	fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)>;
61}
62
63/// A dummy struct which implements `RoutingMessageHandler` without storing any routing information
64/// or doing any processing. You can provide one of these as the route_handler in a MessageHandler.
65pub struct IgnoringMessageHandler{}
66impl MessageSendEventsProvider for IgnoringMessageHandler {
67	fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> { Vec::new() }
68}
69impl RoutingMessageHandler for IgnoringMessageHandler {
70	fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
71	fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
72	fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
73	fn get_next_channel_announcement(&self, _starting_point: u64) ->
74		Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { None }
75	fn get_next_node_announcement(&self, _starting_point: Option<&PublicKey>) -> Option<msgs::NodeAnnouncement> { None }
76	fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init) -> Result<(), ()> { Ok(()) }
77	fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
78	fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
79	fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) }
80	fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) }
81	fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
82	fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
83		InitFeatures::empty()
84	}
85}
86impl OnionMessageProvider for IgnoringMessageHandler {
87	fn next_onion_message_for_peer(&self, _peer_node_id: PublicKey) -> Option<msgs::OnionMessage> { None }
88}
89impl OnionMessageHandler for IgnoringMessageHandler {
90	fn handle_onion_message(&self, _their_node_id: &PublicKey, _msg: &msgs::OnionMessage) {}
91	fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init) -> Result<(), ()> { Ok(()) }
92	fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
93	fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
94	fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
95		InitFeatures::empty()
96	}
97}
98impl CustomOnionMessageHandler for IgnoringMessageHandler {
99	type CustomMessage = Infallible;
100	fn handle_custom_message(&self, _msg: Infallible) {
101		// Since we always return `None` in the read the handle method should never be called.
102		unreachable!();
103	}
104	fn read_custom_message<R: io::Read>(&self, _msg_type: u64, _buffer: &mut R) -> Result<Option<Infallible>, msgs::DecodeError> where Self: Sized {
105		Ok(None)
106	}
107}
108
109impl CustomOnionMessageContents for Infallible {
110	fn tlv_type(&self) -> u64 { unreachable!(); }
111}
112
113impl Deref for IgnoringMessageHandler {
114	type Target = IgnoringMessageHandler;
115	fn deref(&self) -> &Self { self }
116}
117
118// Implement Type for Infallible, note that it cannot be constructed, and thus you can never call a
119// method that takes self for it.
120impl wire::Type for Infallible {
121	fn type_id(&self) -> u16 {
122		unreachable!();
123	}
124}
125impl Writeable for Infallible {
126	fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
127		unreachable!();
128	}
129}
130
131impl wire::CustomMessageReader for IgnoringMessageHandler {
132	type CustomMessage = Infallible;
133	fn read<R: io::Read>(&self, _message_type: u16, _buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
134		Ok(None)
135	}
136}
137
138impl CustomMessageHandler for IgnoringMessageHandler {
139	fn handle_custom_message(&self, _msg: Infallible, _sender_node_id: &PublicKey) -> Result<(), LightningError> {
140		// Since we always return `None` in the read the handle method should never be called.
141		unreachable!();
142	}
143
144	fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
145}
146
147/// A dummy struct which implements `ChannelMessageHandler` without having any channels.
148/// You can provide one of these as the route_handler in a MessageHandler.
149pub struct ErroringMessageHandler {
150	message_queue: Mutex<Vec<MessageSendEvent>>
151}
152impl ErroringMessageHandler {
153	/// Constructs a new ErroringMessageHandler
154	pub fn new() -> Self {
155		Self { message_queue: Mutex::new(Vec::new()) }
156	}
157	fn push_error(&self, node_id: &PublicKey, channel_id: [u8; 32]) {
158		self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
159			action: msgs::ErrorAction::SendErrorMessage {
160				msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
161			},
162			node_id: node_id.clone(),
163		});
164	}
165}
166impl MessageSendEventsProvider for ErroringMessageHandler {
167	fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
168		let mut res = Vec::new();
169		mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
170		res
171	}
172}
173impl ChannelMessageHandler for ErroringMessageHandler {
174	// Any messages which are related to a specific channel generate an error message to let the
175	// peer know we don't care about channels.
176	fn handle_open_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::OpenChannel) {
177		ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
178	}
179	fn handle_accept_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::AcceptChannel) {
180		ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
181	}
182	fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
183		ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
184	}
185	fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
186		ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
187	}
188	fn handle_channel_ready(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
189		ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
190	}
191	fn handle_shutdown(&self, their_node_id: &PublicKey, _their_features: &InitFeatures, msg: &msgs::Shutdown) {
192		ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
193	}
194	fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
195		ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
196	}
197	fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
198		ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
199	}
200	fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
201		ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
202	}
203	fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
204		ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
205	}
206	fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
207		ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
208	}
209	fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
210		ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
211	}
212	fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
213		ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
214	}
215	fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
216		ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
217	}
218	fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
219		ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
220	}
221	fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
222		ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
223	}
224	// msgs::ChannelUpdate does not contain the channel_id field, so we just drop them.
225	fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
226	fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
227	fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init) -> Result<(), ()> { Ok(()) }
228	fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
229	fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
230	fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
231		// Set a number of features which various nodes may require to talk to us. It's totally
232		// reasonable to indicate we "support" all kinds of channel features...we just reject all
233		// channels.
234		let mut features = InitFeatures::empty();
235		features.set_data_loss_protect_optional();
236		features.set_upfront_shutdown_script_optional();
237		features.set_variable_length_onion_optional();
238		features.set_static_remote_key_optional();
239		features.set_payment_secret_optional();
240		features.set_basic_mpp_optional();
241		features.set_wumbo_optional();
242		features.set_shutdown_any_segwit_optional();
243		features.set_channel_type_optional();
244		features.set_scid_privacy_optional();
245		features.set_zero_conf_optional();
246		features
247	}
248}
249impl Deref for ErroringMessageHandler {
250	type Target = ErroringMessageHandler;
251	fn deref(&self) -> &Self { self }
252}
253
254/// Provides references to trait impls which handle different types of messages.
255pub struct MessageHandler<CM: Deref, RM: Deref, OM: Deref> where
256		CM::Target: ChannelMessageHandler,
257		RM::Target: RoutingMessageHandler,
258		OM::Target: OnionMessageHandler,
259{
260	/// A message handler which handles messages specific to channels. Usually this is just a
261	/// [`ChannelManager`] object or an [`ErroringMessageHandler`].
262	///
263	/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
264	pub chan_handler: CM,
265	/// A message handler which handles messages updating our knowledge of the network channel
266	/// graph. Usually this is just a [`P2PGossipSync`] object or an [`IgnoringMessageHandler`].
267	///
268	/// [`P2PGossipSync`]: crate::routing::gossip::P2PGossipSync
269	pub route_handler: RM,
270
271	/// A message handler which handles onion messages. For now, this can only be an
272	/// [`IgnoringMessageHandler`].
273	pub onion_message_handler: OM,
274}
275
276/// Provides an object which can be used to send data to and which uniquely identifies a connection
277/// to a remote host. You will need to be able to generate multiple of these which meet Eq and
278/// implement Hash to meet the PeerManager API.
279///
280/// For efficiency, Clone should be relatively cheap for this type.
281///
282/// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original
283/// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it
284/// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no
285/// further calls to the [`PeerManager`] related to the original socket occur. This allows you to
286/// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish
287/// to simply use another value which is guaranteed to be globally unique instead.
288pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
289	/// Attempts to send some data from the given slice to the peer.
290	///
291	/// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
292	/// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
293	/// called and further write attempts may occur until that time.
294	///
295	/// If the returned size is smaller than `data.len()`, a
296	/// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
297	/// written. Additionally, until a `send_data` event completes fully, no further
298	/// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
299	/// prevent denial-of-service issues, you should not read or buffer any data from the socket
300	/// until then.
301	///
302	/// If a [`PeerManager::read_event`] call on this descriptor had previously returned true
303	/// (indicating that read events should be paused to prevent DoS in the send buffer),
304	/// `resume_read` may be set indicating that read events on this descriptor should resume. A
305	/// `resume_read` of false carries no meaning, and should not cause any action.
306	fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
307	/// Disconnect the socket pointed to by this SocketDescriptor.
308	///
309	/// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
310	/// call (doing so is a noop).
311	fn disconnect_socket(&mut self);
312}
313
314/// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
315/// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
316/// descriptor.
317#[derive(Clone)]
318pub struct PeerHandleError {
319	/// Used to indicate that we probably can't make any future connections to this peer (e.g.
320	/// because we required features that our peer was missing, or vice versa).
321	///
322	/// While LDK's [`ChannelManager`] will not do it automatically, you likely wish to force-close
323	/// any channels with this peer or check for new versions of LDK.
324	///
325	/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
326	pub no_connection_possible: bool,
327}
328impl fmt::Debug for PeerHandleError {
329	fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
330		formatter.write_str("Peer Sent Invalid Data")
331	}
332}
333impl fmt::Display for PeerHandleError {
334	fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
335		formatter.write_str("Peer Sent Invalid Data")
336	}
337}
338
339#[cfg(feature = "std")]
340impl error::Error for PeerHandleError {
341	fn description(&self) -> &str {
342		"Peer Sent Invalid Data"
343	}
344}
345
346enum InitSyncTracker{
347	NoSyncRequested,
348	ChannelsSyncing(u64),
349	NodesSyncing(PublicKey),
350}
351
352/// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop
353/// forwarding gossip messages to peers altogether.
354const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2;
355
356/// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
357/// we have fewer than this many messages in the outbound buffer again.
358/// We also use this as the target number of outbound gossip messages to keep in the write buffer,
359/// refilled as we send bytes.
360const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 12;
361/// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
362/// the peer.
363const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO;
364
365/// If we've sent a ping, and are still awaiting a response, we may need to churn our way through
366/// the socket receive buffer before receiving the ping.
367///
368/// On a fairly old Arm64 board, with Linux defaults, this can take as long as 20 seconds, not
369/// including any network delays, outbound traffic, or the same for messages from other peers.
370///
371/// Thus, to avoid needlessly disconnecting a peer, we allow a peer to take this many timer ticks
372/// per connected peer to respond to a ping, as long as they send us at least one message during
373/// each tick, ensuring we aren't actually just disconnected.
374/// With a timer tick interval of ten seconds, this translates to about 40 seconds per connected
375/// peer.
376///
377/// When we improve parallelism somewhat we should reduce this to e.g. this many timer ticks per
378/// two connected peers, assuming most LDK-running systems have at least two cores.
379const MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER: i8 = 4;
380
381/// This is the minimum number of messages we expect a peer to be able to handle within one timer
382/// tick. Once we have sent this many messages since the last ping, we send a ping right away to
383/// ensures we don't just fill up our send buffer and leave the peer with too many messages to
384/// process before the next ping.
385///
386/// Note that we continue responding to other messages even after we've sent this many messages, so
387/// it's more of a general guideline used for gossip backfill (and gossip forwarding, times
388/// [`FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO`]) than a hard limit.
389const BUFFER_DRAIN_MSGS_PER_TICK: usize = 32;
390
391struct Peer {
392	channel_encryptor: PeerChannelEncryptor,
393	their_node_id: Option<PublicKey>,
394	their_features: Option<InitFeatures>,
395	their_net_address: Option<NetAddress>,
396
397	pending_outbound_buffer: LinkedList<Vec<u8>>,
398	pending_outbound_buffer_first_msg_offset: usize,
399	/// Queue gossip broadcasts separately from `pending_outbound_buffer` so we can easily
400	/// prioritize channel messages over them.
401	///
402	/// Note that these messages are *not* encrypted/MAC'd, and are only serialized.
403	gossip_broadcast_buffer: LinkedList<Vec<u8>>,
404	awaiting_write_event: bool,
405
406	pending_read_buffer: Vec<u8>,
407	pending_read_buffer_pos: usize,
408	pending_read_is_header: bool,
409
410	sync_status: InitSyncTracker,
411
412	msgs_sent_since_pong: usize,
413	awaiting_pong_timer_tick_intervals: i8,
414	received_message_since_timer_tick: bool,
415	sent_gossip_timestamp_filter: bool,
416}
417
418impl Peer {
419	/// Returns true if the channel announcements/updates for the given channel should be
420	/// forwarded to this peer.
421	/// If we are sending our routing table to this peer and we have not yet sent channel
422	/// announcements/updates for the given channel_id then we will send it when we get to that
423	/// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
424	/// sent the old versions, we should send the update, and so return true here.
425	fn should_forward_channel_announcement(&self, channel_id: u64) -> bool {
426		if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
427			!self.sent_gossip_timestamp_filter {
428				return false;
429			}
430		match self.sync_status {
431			InitSyncTracker::NoSyncRequested => true,
432			InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
433			InitSyncTracker::NodesSyncing(_) => true,
434		}
435	}
436
437	/// Similar to the above, but for node announcements indexed by node_id.
438	fn should_forward_node_announcement(&self, node_id: PublicKey) -> bool {
439		if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
440			!self.sent_gossip_timestamp_filter {
441				return false;
442			}
443		match self.sync_status {
444			InitSyncTracker::NoSyncRequested => true,
445			InitSyncTracker::ChannelsSyncing(_) => false,
446			InitSyncTracker::NodesSyncing(pk) => pk < node_id,
447		}
448	}
449
450	/// Returns whether we should be reading bytes from this peer, based on whether its outbound
451	/// buffer still has space and we don't need to pause reads to get some writes out.
452	fn should_read(&self) -> bool {
453		self.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE
454	}
455
456	/// Determines if we should push additional gossip background sync (aka "backfill") onto a peer's
457	/// outbound buffer. This is checked every time the peer's buffer may have been drained.
458	fn should_buffer_gossip_backfill(&self) -> bool {
459		self.pending_outbound_buffer.is_empty() && self.gossip_broadcast_buffer.is_empty()
460			&& self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
461	}
462
463	/// Determines if we should push an onion message onto a peer's outbound buffer. This is checked
464	/// every time the peer's buffer may have been drained.
465	fn should_buffer_onion_message(&self) -> bool {
466		self.pending_outbound_buffer.is_empty()
467			&& self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
468	}
469
470	/// Determines if we should push additional gossip broadcast messages onto a peer's outbound
471	/// buffer. This is checked every time the peer's buffer may have been drained.
472	fn should_buffer_gossip_broadcast(&self) -> bool {
473		self.pending_outbound_buffer.is_empty()
474			&& self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
475	}
476
477	/// Returns whether this peer's outbound buffers are full and we should drop gossip broadcasts.
478	fn buffer_full_drop_gossip_broadcast(&self) -> bool {
479		let total_outbound_buffered =
480			self.gossip_broadcast_buffer.len() + self.pending_outbound_buffer.len();
481
482		total_outbound_buffered > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP ||
483			self.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
484	}
485}
486
487/// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
488/// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
489/// lifetimes). Other times you can afford a reference, which is more efficient, in which case
490/// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
491/// issues such as overly long function definitions.
492///
493/// (C-not exported) as `Arc`s don't make sense in bindings.
494pub 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>;
495
496/// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
497/// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
498/// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
499/// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
500/// But if this is not necessary, using a reference is more efficient. Defining these type aliases
501/// helps with issues such as long function definitions.
502///
503/// (C-not exported) as general type aliases don't make sense in bindings.
504pub type SimpleRefPeerManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k, SD, M, T, F, C, L> = PeerManager<SD, SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L>, &'e P2PGossipSync<&'g NetworkGraph<&'f L>, &'h C, &'f L>, &'i SimpleRefOnionMessenger<'j, 'k, L>, &'f L, IgnoringMessageHandler>;
505
506/// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
507/// socket events into messages which it passes on to its [`MessageHandler`].
508///
509/// Locks are taken internally, so you must never assume that reentrancy from a
510/// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
511///
512/// Calls to [`read_event`] will decode relevant messages and pass them to the
513/// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
514/// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
515/// [`PeerManager`] functions related to the same connection must occur only in serial, making new
516/// calls only after previous ones have returned.
517///
518/// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
519/// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
520/// essentially you should default to using a SimpleRefPeerManager, and use a
521/// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
522/// you're using lightning-net-tokio.
523///
524/// [`read_event`]: PeerManager::read_event
525pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref> where
526		CM::Target: ChannelMessageHandler,
527		RM::Target: RoutingMessageHandler,
528		OM::Target: OnionMessageHandler,
529		L::Target: Logger,
530		CMH::Target: CustomMessageHandler {
531	message_handler: MessageHandler<CM, RM, OM>,
532	/// Connection state for each connected peer - we have an outer read-write lock which is taken
533	/// as read while we're doing processing for a peer and taken write when a peer is being added
534	/// or removed.
535	///
536	/// The inner Peer lock is held for sending and receiving bytes, but note that we do *not* hold
537	/// it while we're processing a message. This is fine as [`PeerManager::read_event`] requires
538	/// that there be no parallel calls for a given peer, so mutual exclusion of messages handed to
539	/// the `MessageHandler`s for a given peer is already guaranteed.
540	peers: FairRwLock<HashMap<Descriptor, Mutex<Peer>>>,
541	/// Only add to this set when noise completes.
542	/// Locked *after* peers. When an item is removed, it must be removed with the `peers` write
543	/// lock held. Entries may be added with only the `peers` read lock held (though the
544	/// `Descriptor` value must already exist in `peers`).
545	node_id_to_descriptor: Mutex<HashMap<PublicKey, Descriptor>>,
546	/// We can only have one thread processing events at once, but we don't usually need the full
547	/// `peers` write lock to do so, so instead we block on this empty mutex when entering
548	/// `process_events`.
549	event_processing_lock: Mutex<()>,
550	/// Because event processing is global and always does all available work before returning,
551	/// there is no reason for us to have many event processors waiting on the lock at once.
552	/// Instead, we limit the total blocked event processors to always exactly one by setting this
553	/// when an event process call is waiting.
554	blocked_event_processors: AtomicBool,
555
556	/// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
557	/// value increases strictly since we don't assume access to a time source.
558	last_node_announcement_serial: AtomicU32,
559
560	our_node_secret: SecretKey,
561	ephemeral_key_midstate: Sha256Engine,
562	custom_message_handler: CMH,
563
564	peer_counter: AtomicCounter,
565
566	logger: L,
567	secp_ctx: Secp256k1<secp256k1::SignOnly>
568}
569
570enum MessageHandlingError {
571	PeerHandleError(PeerHandleError),
572	LightningError(LightningError),
573}
574
575impl From<PeerHandleError> for MessageHandlingError {
576	fn from(error: PeerHandleError) -> Self {
577		MessageHandlingError::PeerHandleError(error)
578	}
579}
580
581impl From<LightningError> for MessageHandlingError {
582	fn from(error: LightningError) -> Self {
583		MessageHandlingError::LightningError(error)
584	}
585}
586
587macro_rules! encode_msg {
588	($msg: expr) => {{
589		let mut buffer = VecWriter(Vec::new());
590		wire::write($msg, &mut buffer).unwrap();
591		buffer.0
592	}}
593}
594
595impl<Descriptor: SocketDescriptor, CM: Deref, OM: Deref, L: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, OM, L, IgnoringMessageHandler> where
596		CM::Target: ChannelMessageHandler,
597		OM::Target: OnionMessageHandler,
598		L::Target: Logger {
599	/// Constructs a new `PeerManager` with the given `ChannelMessageHandler` and
600	/// `OnionMessageHandler`. No routing message handler is used and network graph messages are
601	/// ignored.
602	///
603	/// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
604	/// cryptographically secure random bytes.
605	///
606	/// `current_time` is used as an always-increasing counter that survives across restarts and is
607	/// incremented irregularly internally. In general it is best to simply use the current UNIX
608	/// timestamp, however if it is not available a persistent counter that increases once per
609	/// minute should suffice.
610	///
611	/// (C-not exported) as we can't export a PeerManager with a dummy route handler
612	pub fn new_channel_only(channel_message_handler: CM, onion_message_handler: OM, our_node_secret: SecretKey, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
613		Self::new(MessageHandler {
614			chan_handler: channel_message_handler,
615			route_handler: IgnoringMessageHandler{},
616			onion_message_handler,
617		}, our_node_secret, current_time, ephemeral_random_data, logger, IgnoringMessageHandler{})
618	}
619}
620
621impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, IgnoringMessageHandler, L, IgnoringMessageHandler> where
622		RM::Target: RoutingMessageHandler,
623		L::Target: Logger {
624	/// Constructs a new `PeerManager` with the given `RoutingMessageHandler`. No channel message
625	/// handler or onion message handler is used and onion and channel messages will be ignored (or
626	/// generate error messages). Note that some other lightning implementations time-out connections
627	/// after some time if no channel is built with the peer.
628	///
629	/// `current_time` is used as an always-increasing counter that survives across restarts and is
630	/// incremented irregularly internally. In general it is best to simply use the current UNIX
631	/// timestamp, however if it is not available a persistent counter that increases once per
632	/// minute should suffice.
633	///
634	/// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
635	/// cryptographically secure random bytes.
636	///
637	/// (C-not exported) as we can't export a PeerManager with a dummy channel handler
638	pub fn new_routing_only(routing_message_handler: RM, our_node_secret: SecretKey, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
639		Self::new(MessageHandler {
640			chan_handler: ErroringMessageHandler::new(),
641			route_handler: routing_message_handler,
642			onion_message_handler: IgnoringMessageHandler{},
643		}, our_node_secret, current_time, ephemeral_random_data, logger, IgnoringMessageHandler{})
644	}
645}
646
647/// A simple wrapper that optionally prints " from <pubkey>" for an optional pubkey.
648/// This works around `format!()` taking a reference to each argument, preventing
649/// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
650/// due to lifetime errors.
651struct OptionalFromDebugger<'a>(&'a Option<PublicKey>);
652impl core::fmt::Display for OptionalFromDebugger<'_> {
653	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
654		if let Some(node_id) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
655	}
656}
657
658/// A function used to filter out local or private addresses
659/// https://www.iana.org./assignments/ipv4-address-space/ipv4-address-space.xhtml
660/// https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml
661fn filter_addresses(ip_address: Option<NetAddress>) -> Option<NetAddress> {
662	match ip_address{
663		// For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8)
664		Some(NetAddress::IPv4{addr: [10, _, _, _], port: _}) => None,
665		// For IPv4 range 0.0.0.0 - 0.255.255.255 (0/8)
666		Some(NetAddress::IPv4{addr: [0, _, _, _], port: _}) => None,
667		// For IPv4 range 100.64.0.0 - 100.127.255.255 (100.64/10)
668		Some(NetAddress::IPv4{addr: [100, 64..=127, _, _], port: _}) => None,
669		// For IPv4 range  	127.0.0.0 - 127.255.255.255 (127/8)
670		Some(NetAddress::IPv4{addr: [127, _, _, _], port: _}) => None,
671		// For IPv4 range  	169.254.0.0 - 169.254.255.255 (169.254/16)
672		Some(NetAddress::IPv4{addr: [169, 254, _, _], port: _}) => None,
673		// For IPv4 range 172.16.0.0 - 172.31.255.255 (172.16/12)
674		Some(NetAddress::IPv4{addr: [172, 16..=31, _, _], port: _}) => None,
675		// For IPv4 range 192.168.0.0 - 192.168.255.255 (192.168/16)
676		Some(NetAddress::IPv4{addr: [192, 168, _, _], port: _}) => None,
677		// For IPv4 range 192.88.99.0 - 192.88.99.255  (192.88.99/24)
678		Some(NetAddress::IPv4{addr: [192, 88, 99, _], port: _}) => None,
679		// For IPv6 range 2000:0000:0000:0000:0000:0000:0000:0000 - 3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff (2000::/3)
680		Some(NetAddress::IPv6{addr: [0x20..=0x3F, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _], port: _}) => ip_address,
681		// For remaining addresses
682		Some(NetAddress::IPv6{addr: _, port: _}) => None,
683		Some(..) => ip_address,
684		None => None,
685	}
686}
687
688impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref> PeerManager<Descriptor, CM, RM, OM, L, CMH> where
689		CM::Target: ChannelMessageHandler,
690		RM::Target: RoutingMessageHandler,
691		OM::Target: OnionMessageHandler,
692		L::Target: Logger,
693		CMH::Target: CustomMessageHandler {
694	/// Constructs a new PeerManager with the given message handlers and node_id secret key
695	/// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
696	/// cryptographically secure random bytes.
697	///
698	/// `current_time` is used as an always-increasing counter that survives across restarts and is
699	/// incremented irregularly internally. In general it is best to simply use the current UNIX
700	/// timestamp, however if it is not available a persistent counter that increases once per
701	/// minute should suffice.
702	pub fn new(message_handler: MessageHandler<CM, RM, OM>, our_node_secret: SecretKey, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, custom_message_handler: CMH) -> Self {
703		let mut ephemeral_key_midstate = Sha256::engine();
704		ephemeral_key_midstate.input(ephemeral_random_data);
705
706		let mut secp_ctx = Secp256k1::signing_only();
707		let ephemeral_hash = Sha256::from_engine(ephemeral_key_midstate.clone()).into_inner();
708		secp_ctx.seeded_randomize(&ephemeral_hash);
709
710		PeerManager {
711			message_handler,
712			peers: FairRwLock::new(HashMap::new()),
713			node_id_to_descriptor: Mutex::new(HashMap::new()),
714			event_processing_lock: Mutex::new(()),
715			blocked_event_processors: AtomicBool::new(false),
716			our_node_secret,
717			ephemeral_key_midstate,
718			peer_counter: AtomicCounter::new(),
719			last_node_announcement_serial: AtomicU32::new(current_time),
720			logger,
721			custom_message_handler,
722			secp_ctx,
723		}
724	}
725
726	/// Get the list of node ids for peers which have completed the initial handshake.
727	///
728	/// For outbound connections, this will be the same as the their_node_id parameter passed in to
729	/// new_outbound_connection, however entries will only appear once the initial handshake has
730	/// completed and we are sure the remote peer has the private key for the given node_id.
731	pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
732		let peers = self.peers.read().unwrap();
733		peers.values().filter_map(|peer_mutex| {
734			let p = peer_mutex.lock().unwrap();
735			if !p.channel_encryptor.is_ready_for_encryption() || p.their_features.is_none() {
736				return None;
737			}
738			p.their_node_id
739		}).collect()
740	}
741
742	fn get_ephemeral_key(&self) -> SecretKey {
743		let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
744		let counter = self.peer_counter.get_increment();
745		ephemeral_hash.input(&counter.to_le_bytes());
746		SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
747	}
748
749	/// Indicates a new outbound connection has been established to a node with the given node_id
750	/// and an optional remote network address.
751	///
752	/// The remote network address adds the option to report a remote IP address back to a connecting
753	/// peer using the init message.
754	/// The user should pass the remote network address of the host they are connected to.
755	///
756	/// If an `Err` is returned here you must disconnect the connection immediately.
757	///
758	/// Returns a small number of bytes to send to the remote node (currently always 50).
759	///
760	/// Panics if descriptor is duplicative with some other descriptor which has not yet been
761	/// [`socket_disconnected()`].
762	///
763	/// [`socket_disconnected()`]: PeerManager::socket_disconnected
764	pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<Vec<u8>, PeerHandleError> {
765		let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
766		let res = peer_encryptor.get_act_one(&self.secp_ctx).to_vec();
767		let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
768
769		let mut peers = self.peers.write().unwrap();
770		if peers.insert(descriptor, Mutex::new(Peer {
771			channel_encryptor: peer_encryptor,
772			their_node_id: None,
773			their_features: None,
774			their_net_address: remote_network_address,
775
776			pending_outbound_buffer: LinkedList::new(),
777			pending_outbound_buffer_first_msg_offset: 0,
778			gossip_broadcast_buffer: LinkedList::new(),
779			awaiting_write_event: false,
780
781			pending_read_buffer,
782			pending_read_buffer_pos: 0,
783			pending_read_is_header: false,
784
785			sync_status: InitSyncTracker::NoSyncRequested,
786
787			msgs_sent_since_pong: 0,
788			awaiting_pong_timer_tick_intervals: 0,
789			received_message_since_timer_tick: false,
790			sent_gossip_timestamp_filter: false,
791		})).is_some() {
792			panic!("PeerManager driver duplicated descriptors!");
793		};
794		Ok(res)
795	}
796
797	/// Indicates a new inbound connection has been established to a node with an optional remote
798	/// network address.
799	///
800	/// The remote network address adds the option to report a remote IP address back to a connecting
801	/// peer using the init message.
802	/// The user should pass the remote network address of the host they are connected to.
803	///
804	/// May refuse the connection by returning an Err, but will never write bytes to the remote end
805	/// (outbound connector always speaks first). If an `Err` is returned here you must disconnect
806	/// the connection immediately.
807	///
808	/// Panics if descriptor is duplicative with some other descriptor which has not yet been
809	/// [`socket_disconnected()`].
810	///
811	/// [`socket_disconnected()`]: PeerManager::socket_disconnected
812	pub fn new_inbound_connection(&self, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<(), PeerHandleError> {
813		let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret, &self.secp_ctx);
814		let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
815
816		let mut peers = self.peers.write().unwrap();
817		if peers.insert(descriptor, Mutex::new(Peer {
818			channel_encryptor: peer_encryptor,
819			their_node_id: None,
820			their_features: None,
821			their_net_address: remote_network_address,
822
823			pending_outbound_buffer: LinkedList::new(),
824			pending_outbound_buffer_first_msg_offset: 0,
825			gossip_broadcast_buffer: LinkedList::new(),
826			awaiting_write_event: false,
827
828			pending_read_buffer,
829			pending_read_buffer_pos: 0,
830			pending_read_is_header: false,
831
832			sync_status: InitSyncTracker::NoSyncRequested,
833
834			msgs_sent_since_pong: 0,
835			awaiting_pong_timer_tick_intervals: 0,
836			received_message_since_timer_tick: false,
837			sent_gossip_timestamp_filter: false,
838		})).is_some() {
839			panic!("PeerManager driver duplicated descriptors!");
840		};
841		Ok(())
842	}
843
844	fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
845		while !peer.awaiting_write_event {
846			if peer.should_buffer_onion_message() {
847				if let Some(peer_node_id) = peer.their_node_id {
848					if let Some(next_onion_message) =
849						self.message_handler.onion_message_handler.next_onion_message_for_peer(peer_node_id) {
850							self.enqueue_message(peer, &next_onion_message);
851					}
852				}
853			}
854			if peer.should_buffer_gossip_broadcast() {
855				if let Some(msg) = peer.gossip_broadcast_buffer.pop_front() {
856					peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_buffer(&msg[..]));
857				}
858			}
859			if peer.should_buffer_gossip_backfill() {
860				match peer.sync_status {
861					InitSyncTracker::NoSyncRequested => {},
862					InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
863						if let Some((announce, update_a_option, update_b_option)) =
864							self.message_handler.route_handler.get_next_channel_announcement(c)
865						{
866							self.enqueue_message(peer, &announce);
867							if let Some(update_a) = update_a_option {
868								self.enqueue_message(peer, &update_a);
869							}
870							if let Some(update_b) = update_b_option {
871								self.enqueue_message(peer, &update_b);
872							}
873							peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
874						} else {
875							peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
876						}
877					},
878					InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
879						if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(None) {
880							self.enqueue_message(peer, &msg);
881							peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
882						} else {
883							peer.sync_status = InitSyncTracker::NoSyncRequested;
884						}
885					},
886					InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
887					InitSyncTracker::NodesSyncing(key) => {
888						if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(Some(&key)) {
889							self.enqueue_message(peer, &msg);
890							peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
891						} else {
892							peer.sync_status = InitSyncTracker::NoSyncRequested;
893						}
894					},
895				}
896			}
897			if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
898				self.maybe_send_extra_ping(peer);
899			}
900
901			let next_buff = match peer.pending_outbound_buffer.front() {
902				None => return,
903				Some(buff) => buff,
904			};
905
906			let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
907			let data_sent = descriptor.send_data(pending, peer.should_read());
908			peer.pending_outbound_buffer_first_msg_offset += data_sent;
909			if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() {
910				peer.pending_outbound_buffer_first_msg_offset = 0;
911				peer.pending_outbound_buffer.pop_front();
912			} else {
913				peer.awaiting_write_event = true;
914			}
915		}
916	}
917
918	/// Indicates that there is room to write data to the given socket descriptor.
919	///
920	/// May return an Err to indicate that the connection should be closed.
921	///
922	/// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
923	/// returning. Thus, be very careful with reentrancy issues! The invariants around calling
924	/// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
925	/// ready to call `[write_buffer_space_avail`] again if a write call generated here isn't
926	/// sufficient!
927	///
928	/// [`send_data`]: SocketDescriptor::send_data
929	/// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
930	pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
931		let peers = self.peers.read().unwrap();
932		match peers.get(descriptor) {
933			None => {
934				// This is most likely a simple race condition where the user found that the socket
935				// was writeable, then we told the user to `disconnect_socket()`, then they called
936				// this method. Return an error to make sure we get disconnected.
937				return Err(PeerHandleError { no_connection_possible: false });
938			},
939			Some(peer_mutex) => {
940				let mut peer = peer_mutex.lock().unwrap();
941				peer.awaiting_write_event = false;
942				self.do_attempt_write_data(descriptor, &mut peer);
943			}
944		};
945		Ok(())
946	}
947
948	/// Indicates that data was read from the given socket descriptor.
949	///
950	/// May return an Err to indicate that the connection should be closed.
951	///
952	/// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
953	/// Thus, however, you should call [`process_events`] after any `read_event` to generate
954	/// [`send_data`] calls to handle responses.
955	///
956	/// If `Ok(true)` is returned, further read_events should not be triggered until a
957	/// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
958	/// send buffer).
959	///
960	/// [`send_data`]: SocketDescriptor::send_data
961	/// [`process_events`]: PeerManager::process_events
962	pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
963		match self.do_read_event(peer_descriptor, data) {
964			Ok(res) => Ok(res),
965			Err(e) => {
966				log_trace!(self.logger, "Peer sent invalid data or we decided to disconnect due to a protocol error");
967				self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
968				Err(e)
969			}
970		}
971	}
972
973	/// Append a message to a peer's pending outbound/write buffer
974	fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
975		if is_gossip_msg(message.type_id()) {
976			log_gossip!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()));
977		} else {
978			log_trace!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()))
979		}
980		peer.msgs_sent_since_pong += 1;
981		peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(message));
982	}
983
984	/// Append a message to a peer's pending outbound/write gossip broadcast buffer
985	fn enqueue_encoded_gossip_broadcast(&self, peer: &mut Peer, encoded_message: Vec<u8>) {
986		peer.msgs_sent_since_pong += 1;
987		peer.gossip_broadcast_buffer.push_back(encoded_message);
988	}
989
990	fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
991		let mut pause_read = false;
992		let peers = self.peers.read().unwrap();
993		let mut msgs_to_forward = Vec::new();
994		let mut peer_node_id = None;
995		match peers.get(peer_descriptor) {
996			None => {
997				// This is most likely a simple race condition where the user read some bytes
998				// from the socket, then we told the user to `disconnect_socket()`, then they
999				// called this method. Return an error to make sure we get disconnected.
1000				return Err(PeerHandleError { no_connection_possible: false });
1001			},
1002			Some(peer_mutex) => {
1003				let mut read_pos = 0;
1004				while read_pos < data.len() {
1005					macro_rules! try_potential_handleerror {
1006						($peer: expr, $thing: expr) => {
1007							match $thing {
1008								Ok(x) => x,
1009								Err(e) => {
1010									match e.action {
1011										msgs::ErrorAction::DisconnectPeer { msg: _ } => {
1012											//TODO: Try to push msg
1013											log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1014											return Err(PeerHandleError{ no_connection_possible: false });
1015										},
1016										msgs::ErrorAction::IgnoreAndLog(level) => {
1017											log_given_level!(self.logger, level, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1018											continue
1019										},
1020										msgs::ErrorAction::IgnoreDuplicateGossip => continue, // Don't even bother logging these
1021										msgs::ErrorAction::IgnoreError => {
1022											log_debug!(self.logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1023											continue;
1024										},
1025										msgs::ErrorAction::SendErrorMessage { msg } => {
1026											log_debug!(self.logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1027											self.enqueue_message($peer, &msg);
1028											continue;
1029										},
1030										msgs::ErrorAction::SendWarningMessage { msg, log_level } => {
1031											log_given_level!(self.logger, log_level, "Error handling message{}; sending warning message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1032											self.enqueue_message($peer, &msg);
1033											continue;
1034										},
1035									}
1036								}
1037							}
1038						}
1039					}
1040
1041					let mut peer_lock = peer_mutex.lock().unwrap();
1042					let peer = &mut *peer_lock;
1043					let mut msg_to_handle = None;
1044					if peer_node_id.is_none() {
1045						peer_node_id = peer.their_node_id.clone();
1046					}
1047
1048					assert!(peer.pending_read_buffer.len() > 0);
1049					assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
1050
1051					{
1052						let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
1053						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]);
1054						read_pos += data_to_copy;
1055						peer.pending_read_buffer_pos += data_to_copy;
1056					}
1057
1058					if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
1059						peer.pending_read_buffer_pos = 0;
1060
1061						macro_rules! insert_node_id {
1062							() => {
1063								match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap()) {
1064									hash_map::Entry::Occupied(_) => {
1065										log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
1066										peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
1067										return Err(PeerHandleError{ no_connection_possible: false })
1068									},
1069									hash_map::Entry::Vacant(entry) => {
1070										log_debug!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
1071										entry.insert(peer_descriptor.clone())
1072									},
1073								};
1074							}
1075						}
1076
1077						let next_step = peer.channel_encryptor.get_noise_step();
1078						match next_step {
1079							NextNoiseStep::ActOne => {
1080								let act_two = try_potential_handleerror!(peer, peer.channel_encryptor
1081									.process_act_one_with_keys(&peer.pending_read_buffer[..],
1082										&self.our_node_secret, self.get_ephemeral_key(), &self.secp_ctx)).to_vec();
1083								peer.pending_outbound_buffer.push_back(act_two);
1084								peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
1085							},
1086							NextNoiseStep::ActTwo => {
1087								let (act_three, their_node_id) = try_potential_handleerror!(peer,
1088									peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..],
1089										&self.our_node_secret, &self.secp_ctx));
1090								peer.pending_outbound_buffer.push_back(act_three.to_vec());
1091								peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1092								peer.pending_read_is_header = true;
1093
1094								peer.their_node_id = Some(their_node_id);
1095								insert_node_id!();
1096								let features = self.message_handler.chan_handler.provided_init_features(&their_node_id)
1097									.or(self.message_handler.route_handler.provided_init_features(&their_node_id))
1098									.or(self.message_handler.onion_message_handler.provided_init_features(&their_node_id));
1099								let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
1100								self.enqueue_message(peer, &resp);
1101								peer.awaiting_pong_timer_tick_intervals = 0;
1102							},
1103							NextNoiseStep::ActThree => {
1104								let their_node_id = try_potential_handleerror!(peer,
1105									peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
1106								peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1107								peer.pending_read_is_header = true;
1108								peer.their_node_id = Some(their_node_id);
1109								insert_node_id!();
1110								let features = self.message_handler.chan_handler.provided_init_features(&their_node_id)
1111									.or(self.message_handler.route_handler.provided_init_features(&their_node_id))
1112									.or(self.message_handler.onion_message_handler.provided_init_features(&their_node_id));
1113								let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
1114								self.enqueue_message(peer, &resp);
1115								peer.awaiting_pong_timer_tick_intervals = 0;
1116							},
1117							NextNoiseStep::NoiseComplete => {
1118								if peer.pending_read_is_header {
1119									let msg_len = try_potential_handleerror!(peer,
1120										peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
1121									if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1122									peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
1123									if msg_len < 2 { // Need at least the message type tag
1124										return Err(PeerHandleError{ no_connection_possible: false });
1125									}
1126									peer.pending_read_is_header = false;
1127								} else {
1128									let msg_data = try_potential_handleerror!(peer,
1129										peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
1130									assert!(msg_data.len() >= 2);
1131
1132									// Reset read buffer
1133									if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1134									peer.pending_read_buffer.resize(18, 0);
1135									peer.pending_read_is_header = true;
1136
1137									let mut reader = io::Cursor::new(&msg_data[..]);
1138									let message_result = wire::read(&mut reader, &*self.custom_message_handler);
1139									let message = match message_result {
1140										Ok(x) => x,
1141										Err(e) => {
1142											match e {
1143												// Note that to avoid recursion we never call
1144												// `do_attempt_write_data` from here, causing
1145												// the messages enqueued here to not actually
1146												// be sent before the peer is disconnected.
1147												(msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
1148													log_gossip!(self.logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
1149													continue;
1150												}
1151												(msgs::DecodeError::UnsupportedCompression, _) => {
1152													log_gossip!(self.logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
1153													self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: "Unsupported message compression: zlib".to_owned() });
1154													continue;
1155												}
1156												(_, Some(ty)) if is_gossip_msg(ty) => {
1157													log_gossip!(self.logger, "Got an invalid value while deserializing a gossip message");
1158													self.enqueue_message(peer, &msgs::WarningMessage {
1159														channel_id: [0; 32],
1160														data: format!("Unreadable/bogus gossip message of type {}", ty),
1161													});
1162													continue;
1163												}
1164												(msgs::DecodeError::UnknownRequiredFeature, ty) => {
1165													log_gossip!(self.logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
1166													self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: format!("Received an unknown required feature/TLV in message type {:?}", ty) });
1167													return Err(PeerHandleError { no_connection_possible: false });
1168												}
1169												(msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { no_connection_possible: false }),
1170												(msgs::DecodeError::InvalidValue, _) => {
1171													log_debug!(self.logger, "Got an invalid value while deserializing message");
1172													return Err(PeerHandleError { no_connection_possible: false });
1173												}
1174												(msgs::DecodeError::ShortRead, _) => {
1175													log_debug!(self.logger, "Deserialization failed due to shortness of message");
1176													return Err(PeerHandleError { no_connection_possible: false });
1177												}
1178												(msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { no_connection_possible: false }),
1179												(msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { no_connection_possible: false }),
1180											}
1181										}
1182									};
1183
1184									msg_to_handle = Some(message);
1185								}
1186							}
1187						}
1188					}
1189					pause_read = !peer.should_read();
1190
1191					if let Some(message) = msg_to_handle {
1192						match self.handle_message(&peer_mutex, peer_lock, message) {
1193							Err(handling_error) => match handling_error {
1194								MessageHandlingError::PeerHandleError(e) => { return Err(e) },
1195								MessageHandlingError::LightningError(e) => {
1196									try_potential_handleerror!(&mut peer_mutex.lock().unwrap(), Err(e));
1197								},
1198							},
1199							Ok(Some(msg)) => {
1200								msgs_to_forward.push(msg);
1201							},
1202							Ok(None) => {},
1203						}
1204					}
1205				}
1206			}
1207		}
1208
1209		for msg in msgs_to_forward.drain(..) {
1210			self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref());
1211		}
1212
1213		Ok(pause_read)
1214	}
1215
1216	/// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
1217	/// Returns the message back if it needs to be broadcasted to all other peers.
1218	fn handle_message(
1219		&self,
1220		peer_mutex: &Mutex<Peer>,
1221		mut peer_lock: MutexGuard<Peer>,
1222		message: wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>
1223	) -> Result<Option<wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
1224		let their_node_id = peer_lock.their_node_id.clone().expect("We know the peer's public key by the time we receive messages");
1225		peer_lock.received_message_since_timer_tick = true;
1226
1227		// Need an Init as first message
1228		if let wire::Message::Init(msg) = message {
1229			if msg.features.requires_unknown_bits() {
1230				log_debug!(self.logger, "Peer features required unknown version bits");
1231				return Err(PeerHandleError{ no_connection_possible: true }.into());
1232			}
1233			if peer_lock.their_features.is_some() {
1234				return Err(PeerHandleError{ no_connection_possible: false }.into());
1235			}
1236
1237			log_info!(self.logger, "Received peer Init message from {}: {}", log_pubkey!(their_node_id), msg.features);
1238
1239			// For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
1240			if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
1241				peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1242			}
1243
1244			if let Err(()) = self.message_handler.route_handler.peer_connected(&their_node_id, &msg) {
1245				log_debug!(self.logger, "Route Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1246				return Err(PeerHandleError{ no_connection_possible: true }.into());
1247			}
1248			if let Err(()) = self.message_handler.chan_handler.peer_connected(&their_node_id, &msg) {
1249				log_debug!(self.logger, "Channel Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1250				return Err(PeerHandleError{ no_connection_possible: true }.into());
1251			}
1252			if let Err(()) = self.message_handler.onion_message_handler.peer_connected(&their_node_id, &msg) {
1253				log_debug!(self.logger, "Onion Message Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1254				return Err(PeerHandleError{ no_connection_possible: true }.into());
1255			}
1256
1257			peer_lock.their_features = Some(msg.features);
1258			return Ok(None);
1259		} else if peer_lock.their_features.is_none() {
1260			log_debug!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(their_node_id));
1261			return Err(PeerHandleError{ no_connection_possible: false }.into());
1262		}
1263
1264		if let wire::Message::GossipTimestampFilter(_msg) = message {
1265			// When supporting gossip messages, start inital gossip sync only after we receive
1266			// a GossipTimestampFilter
1267			if peer_lock.their_features.as_ref().unwrap().supports_gossip_queries() &&
1268				!peer_lock.sent_gossip_timestamp_filter {
1269				peer_lock.sent_gossip_timestamp_filter = true;
1270				peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1271			}
1272			return Ok(None);
1273		}
1274
1275		let their_features = peer_lock.their_features.clone();
1276		mem::drop(peer_lock);
1277
1278		if is_gossip_msg(message.type_id()) {
1279			log_gossip!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1280		} else {
1281			log_trace!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1282		}
1283
1284		let mut should_forward = None;
1285
1286		match message {
1287			// Setup and Control messages:
1288			wire::Message::Init(_) => {
1289				// Handled above
1290			},
1291			wire::Message::GossipTimestampFilter(_) => {
1292				// Handled above
1293			},
1294			wire::Message::Error(msg) => {
1295				let mut data_is_printable = true;
1296				for b in msg.data.bytes() {
1297					if b < 32 || b > 126 {
1298						data_is_printable = false;
1299						break;
1300					}
1301				}
1302
1303				if data_is_printable {
1304					log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(their_node_id), msg.data);
1305				} else {
1306					log_debug!(self.logger, "Got Err message from {} with non-ASCII error message", log_pubkey!(their_node_id));
1307				}
1308				self.message_handler.chan_handler.handle_error(&their_node_id, &msg);
1309				if msg.channel_id == [0; 32] {
1310					return Err(PeerHandleError{ no_connection_possible: true }.into());
1311				}
1312			},
1313			wire::Message::Warning(msg) => {
1314				let mut data_is_printable = true;
1315				for b in msg.data.bytes() {
1316					if b < 32 || b > 126 {
1317						data_is_printable = false;
1318						break;
1319					}
1320				}
1321
1322				if data_is_printable {
1323					log_debug!(self.logger, "Got warning message from {}: {}", log_pubkey!(their_node_id), msg.data);
1324				} else {
1325					log_debug!(self.logger, "Got warning message from {} with non-ASCII error message", log_pubkey!(their_node_id));
1326				}
1327			},
1328
1329			wire::Message::Ping(msg) => {
1330				if msg.ponglen < 65532 {
1331					let resp = msgs::Pong { byteslen: msg.ponglen };
1332					self.enqueue_message(&mut *peer_mutex.lock().unwrap(), &resp);
1333				}
1334			},
1335			wire::Message::Pong(_msg) => {
1336				let mut peer_lock = peer_mutex.lock().unwrap();
1337				peer_lock.awaiting_pong_timer_tick_intervals = 0;
1338				peer_lock.msgs_sent_since_pong = 0;
1339			},
1340
1341			// Channel messages:
1342			wire::Message::OpenChannel(msg) => {
1343				self.message_handler.chan_handler.handle_open_channel(&their_node_id, their_features.clone().unwrap(), &msg);
1344			},
1345			wire::Message::AcceptChannel(msg) => {
1346				self.message_handler.chan_handler.handle_accept_channel(&their_node_id, their_features.clone().unwrap(), &msg);
1347			},
1348
1349			wire::Message::FundingCreated(msg) => {
1350				self.message_handler.chan_handler.handle_funding_created(&their_node_id, &msg);
1351			},
1352			wire::Message::FundingSigned(msg) => {
1353				self.message_handler.chan_handler.handle_funding_signed(&their_node_id, &msg);
1354			},
1355			wire::Message::ChannelReady(msg) => {
1356				self.message_handler.chan_handler.handle_channel_ready(&their_node_id, &msg);
1357			},
1358
1359			wire::Message::Shutdown(msg) => {
1360				self.message_handler.chan_handler.handle_shutdown(&their_node_id, their_features.as_ref().unwrap(), &msg);
1361			},
1362			wire::Message::ClosingSigned(msg) => {
1363				self.message_handler.chan_handler.handle_closing_signed(&their_node_id, &msg);
1364			},
1365
1366			// Commitment messages:
1367			wire::Message::UpdateAddHTLC(msg) => {
1368				self.message_handler.chan_handler.handle_update_add_htlc(&their_node_id, &msg);
1369			},
1370			wire::Message::UpdateFulfillHTLC(msg) => {
1371				self.message_handler.chan_handler.handle_update_fulfill_htlc(&their_node_id, &msg);
1372			},
1373			wire::Message::UpdateFailHTLC(msg) => {
1374				self.message_handler.chan_handler.handle_update_fail_htlc(&their_node_id, &msg);
1375			},
1376			wire::Message::UpdateFailMalformedHTLC(msg) => {
1377				self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&their_node_id, &msg);
1378			},
1379
1380			wire::Message::CommitmentSigned(msg) => {
1381				self.message_handler.chan_handler.handle_commitment_signed(&their_node_id, &msg);
1382			},
1383			wire::Message::RevokeAndACK(msg) => {
1384				self.message_handler.chan_handler.handle_revoke_and_ack(&their_node_id, &msg);
1385			},
1386			wire::Message::UpdateFee(msg) => {
1387				self.message_handler.chan_handler.handle_update_fee(&their_node_id, &msg);
1388			},
1389			wire::Message::ChannelReestablish(msg) => {
1390				self.message_handler.chan_handler.handle_channel_reestablish(&their_node_id, &msg);
1391			},
1392
1393			// Routing messages:
1394			wire::Message::AnnouncementSignatures(msg) => {
1395				self.message_handler.chan_handler.handle_announcement_signatures(&their_node_id, &msg);
1396			},
1397			wire::Message::ChannelAnnouncement(msg) => {
1398				if self.message_handler.route_handler.handle_channel_announcement(&msg)
1399						.map_err(|e| -> MessageHandlingError { e.into() })? {
1400					should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1401				}
1402			},
1403			wire::Message::NodeAnnouncement(msg) => {
1404				if self.message_handler.route_handler.handle_node_announcement(&msg)
1405						.map_err(|e| -> MessageHandlingError { e.into() })? {
1406					should_forward = Some(wire::Message::NodeAnnouncement(msg));
1407				}
1408			},
1409			wire::Message::ChannelUpdate(msg) => {
1410				self.message_handler.chan_handler.handle_channel_update(&their_node_id, &msg);
1411				if self.message_handler.route_handler.handle_channel_update(&msg)
1412						.map_err(|e| -> MessageHandlingError { e.into() })? {
1413					should_forward = Some(wire::Message::ChannelUpdate(msg));
1414				}
1415			},
1416			wire::Message::QueryShortChannelIds(msg) => {
1417				self.message_handler.route_handler.handle_query_short_channel_ids(&their_node_id, msg)?;
1418			},
1419			wire::Message::ReplyShortChannelIdsEnd(msg) => {
1420				self.message_handler.route_handler.handle_reply_short_channel_ids_end(&their_node_id, msg)?;
1421			},
1422			wire::Message::QueryChannelRange(msg) => {
1423				self.message_handler.route_handler.handle_query_channel_range(&their_node_id, msg)?;
1424			},
1425			wire::Message::ReplyChannelRange(msg) => {
1426				self.message_handler.route_handler.handle_reply_channel_range(&their_node_id, msg)?;
1427			},
1428
1429			// Onion message:
1430			wire::Message::OnionMessage(msg) => {
1431				self.message_handler.onion_message_handler.handle_onion_message(&their_node_id, &msg);
1432			},
1433
1434			// Unknown messages:
1435			wire::Message::Unknown(type_id) if message.is_even() => {
1436				log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1437				// Fail the channel if message is an even, unknown type as per BOLT #1.
1438				return Err(PeerHandleError{ no_connection_possible: true }.into());
1439			},
1440			wire::Message::Unknown(type_id) => {
1441				log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", type_id);
1442			},
1443			wire::Message::Custom(custom) => {
1444				self.custom_message_handler.handle_custom_message(custom, &their_node_id)?;
1445			},
1446		};
1447		Ok(should_forward)
1448	}
1449
1450	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>) {
1451		match msg {
1452			wire::Message::ChannelAnnouncement(ref msg) => {
1453				log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1454				let encoded_msg = encode_msg!(msg);
1455
1456				for (_, peer_mutex) in peers.iter() {
1457					let mut peer = peer_mutex.lock().unwrap();
1458					if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1459							!peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1460						continue
1461					}
1462					if peer.buffer_full_drop_gossip_broadcast() {
1463						log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1464						continue;
1465					}
1466					if peer.their_node_id.as_ref() == Some(&msg.contents.node_id_1) ||
1467					   peer.their_node_id.as_ref() == Some(&msg.contents.node_id_2) {
1468						continue;
1469					}
1470					if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1471						continue;
1472					}
1473					self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
1474				}
1475			},
1476			wire::Message::NodeAnnouncement(ref msg) => {
1477				log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1478				let encoded_msg = encode_msg!(msg);
1479
1480				for (_, peer_mutex) in peers.iter() {
1481					let mut peer = peer_mutex.lock().unwrap();
1482					if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1483							!peer.should_forward_node_announcement(msg.contents.node_id) {
1484						continue
1485					}
1486					if peer.buffer_full_drop_gossip_broadcast() {
1487						log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1488						continue;
1489					}
1490					if peer.their_node_id.as_ref() == Some(&msg.contents.node_id) {
1491						continue;
1492					}
1493					if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1494						continue;
1495					}
1496					self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
1497				}
1498			},
1499			wire::Message::ChannelUpdate(ref msg) => {
1500				log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1501				let encoded_msg = encode_msg!(msg);
1502
1503				for (_, peer_mutex) in peers.iter() {
1504					let mut peer = peer_mutex.lock().unwrap();
1505					if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1506							!peer.should_forward_channel_announcement(msg.contents.short_channel_id)  {
1507						continue
1508					}
1509					if peer.buffer_full_drop_gossip_broadcast() {
1510						log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1511						continue;
1512					}
1513					if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1514						continue;
1515					}
1516					self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
1517				}
1518			},
1519			_ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1520		}
1521	}
1522
1523	/// Checks for any events generated by our handlers and processes them. Includes sending most
1524	/// response messages as well as messages generated by calls to handler functions directly (eg
1525	/// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1526	///
1527	/// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1528	/// issues!
1529	///
1530	/// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
1531	/// or one of the other clients provided in our language bindings.
1532	///
1533	/// Note that if there are any other calls to this function waiting on lock(s) this may return
1534	/// without doing any work. All available events that need handling will be handled before the
1535	/// other calls return.
1536	///
1537	/// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1538	/// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1539	/// [`send_data`]: SocketDescriptor::send_data
1540	pub fn process_events(&self) {
1541		let mut _single_processor_lock = self.event_processing_lock.try_lock();
1542		if _single_processor_lock.is_err() {
1543			// While we could wake the older sleeper here with a CV and make more even waiting
1544			// times, that would be a lot of overengineering for a simple "reduce total waiter
1545			// count" goal.
1546			match self.blocked_event_processors.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) {
1547				Err(val) => {
1548					debug_assert!(val, "compare_exchange failed spuriously?");
1549					return;
1550				},
1551				Ok(val) => {
1552					debug_assert!(!val, "compare_exchange succeeded spuriously?");
1553					// We're the only waiter, as the running process_events may have emptied the
1554					// pending events "long" ago and there are new events for us to process, wait until
1555					// its done and process any leftover events before returning.
1556					_single_processor_lock = Ok(self.event_processing_lock.lock().unwrap());
1557					self.blocked_event_processors.store(false, Ordering::Release);
1558				}
1559			}
1560		}
1561
1562		let mut peers_to_disconnect = HashMap::new();
1563		let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
1564		events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
1565
1566		{
1567			// TODO: There are some DoS attacks here where you can flood someone's outbound send
1568			// buffer by doing things like announcing channels on another node. We should be willing to
1569			// drop optional-ish messages when send buffers get full!
1570
1571			let peers_lock = self.peers.read().unwrap();
1572			let peers = &*peers_lock;
1573			macro_rules! get_peer_for_forwarding {
1574				($node_id: expr) => {
1575					{
1576						if peers_to_disconnect.get($node_id).is_some() {
1577							// If we've "disconnected" this peer, do not send to it.
1578							continue;
1579						}
1580						let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().get($node_id).cloned();
1581						match descriptor_opt {
1582							Some(descriptor) => match peers.get(&descriptor) {
1583								Some(peer_mutex) => {
1584									let peer_lock = peer_mutex.lock().unwrap();
1585									if peer_lock.their_features.is_none() {
1586										continue;
1587									}
1588									peer_lock
1589								},
1590								None => {
1591									debug_assert!(false, "Inconsistent peers set state!");
1592									continue;
1593								}
1594							},
1595							None => {
1596								continue;
1597							},
1598						}
1599					}
1600				}
1601			}
1602			for event in events_generated.drain(..) {
1603				match event {
1604					MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1605						log_debug!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1606								log_pubkey!(node_id),
1607								log_bytes!(msg.temporary_channel_id));
1608						self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1609					},
1610					MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1611						log_debug!(self.logger, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
1612								log_pubkey!(node_id),
1613								log_bytes!(msg.temporary_channel_id));
1614						self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1615					},
1616					MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
1617						log_debug!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
1618								log_pubkey!(node_id),
1619								log_bytes!(msg.temporary_channel_id),
1620								log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
1621						// TODO: If the peer is gone we should generate a DiscardFunding event
1622						// indicating to the wallet that they should just throw away this funding transaction
1623						self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1624					},
1625					MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
1626						log_debug!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
1627								log_pubkey!(node_id),
1628								log_bytes!(msg.channel_id));
1629						self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1630					},
1631					MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
1632						log_debug!(self.logger, "Handling SendChannelReady event in peer_handler for node {} for channel {}",
1633								log_pubkey!(node_id),
1634								log_bytes!(msg.channel_id));
1635						self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1636					},
1637					MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
1638						log_debug!(self.logger, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
1639								log_pubkey!(node_id),
1640								log_bytes!(msg.channel_id));
1641						self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1642					},
1643					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 } } => {
1644						log_debug!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
1645								log_pubkey!(node_id),
1646								update_add_htlcs.len(),
1647								update_fulfill_htlcs.len(),
1648								update_fail_htlcs.len(),
1649								log_bytes!(commitment_signed.channel_id));
1650						let mut peer = get_peer_for_forwarding!(node_id);
1651						for msg in update_add_htlcs {
1652							self.enqueue_message(&mut *peer, msg);
1653						}
1654						for msg in update_fulfill_htlcs {
1655							self.enqueue_message(&mut *peer, msg);
1656						}
1657						for msg in update_fail_htlcs {
1658							self.enqueue_message(&mut *peer, msg);
1659						}
1660						for msg in update_fail_malformed_htlcs {
1661							self.enqueue_message(&mut *peer, msg);
1662						}
1663						if let &Some(ref msg) = update_fee {
1664							self.enqueue_message(&mut *peer, msg);
1665						}
1666						self.enqueue_message(&mut *peer, commitment_signed);
1667					},
1668					MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1669						log_debug!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
1670								log_pubkey!(node_id),
1671								log_bytes!(msg.channel_id));
1672						self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1673					},
1674					MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1675						log_debug!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
1676								log_pubkey!(node_id),
1677								log_bytes!(msg.channel_id));
1678						self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1679					},
1680					MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1681						log_debug!(self.logger, "Handling Shutdown event in peer_handler for node {} for channel {}",
1682								log_pubkey!(node_id),
1683								log_bytes!(msg.channel_id));
1684						self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1685					},
1686					MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
1687						log_debug!(self.logger, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
1688								log_pubkey!(node_id),
1689								log_bytes!(msg.channel_id));
1690						self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1691					},
1692					MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, ref update_msg } => {
1693						log_debug!(self.logger, "Handling SendChannelAnnouncement event in peer_handler for node {} for short channel id {}",
1694								log_pubkey!(node_id),
1695								msg.contents.short_channel_id);
1696						self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1697						self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), update_msg);
1698					},
1699					MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
1700						log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1701						match self.message_handler.route_handler.handle_channel_announcement(&msg) {
1702							Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1703								self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
1704							_ => {},
1705						}
1706						match self.message_handler.route_handler.handle_channel_update(&update_msg) {
1707							Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1708								self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(update_msg), None),
1709							_ => {},
1710						}
1711					},
1712					MessageSendEvent::BroadcastChannelUpdate { msg } => {
1713						log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1714						match self.message_handler.route_handler.handle_channel_update(&msg) {
1715							Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1716								self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
1717							_ => {},
1718						}
1719					},
1720					MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
1721						log_trace!(self.logger, "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
1722								log_pubkey!(node_id), msg.contents.short_channel_id);
1723						self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1724					},
1725					MessageSendEvent::HandleError { ref node_id, ref action } => {
1726						match *action {
1727							msgs::ErrorAction::DisconnectPeer { ref msg } => {
1728								// We do not have the peers write lock, so we just store that we're
1729								// about to disconenct the peer and do it after we finish
1730								// processing most messages.
1731								peers_to_disconnect.insert(*node_id, msg.clone());
1732							},
1733							msgs::ErrorAction::IgnoreAndLog(level) => {
1734								log_given_level!(self.logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1735							},
1736							msgs::ErrorAction::IgnoreDuplicateGossip => {},
1737							msgs::ErrorAction::IgnoreError => {
1738								log_debug!(self.logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1739							},
1740							msgs::ErrorAction::SendErrorMessage { ref msg } => {
1741								log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1742										log_pubkey!(node_id),
1743										msg.data);
1744								self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1745							},
1746							msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
1747								log_given_level!(self.logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
1748										log_pubkey!(node_id),
1749										msg.data);
1750								self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1751							},
1752						}
1753					},
1754					MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
1755						self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1756					},
1757					MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
1758						self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1759					}
1760					MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
1761						log_gossip!(self.logger, "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
1762							log_pubkey!(node_id),
1763							msg.short_channel_ids.len(),
1764							msg.first_blocknum,
1765							msg.number_of_blocks,
1766							msg.sync_complete);
1767						self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1768					}
1769					MessageSendEvent::SendGossipTimestampFilter { ref node_id, ref msg } => {
1770						self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1771					}
1772				}
1773			}
1774
1775			for (node_id, msg) in self.custom_message_handler.get_and_clear_pending_msg() {
1776				if peers_to_disconnect.get(&node_id).is_some() { continue; }
1777				self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), &msg);
1778			}
1779
1780			for (descriptor, peer_mutex) in peers.iter() {
1781				self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer_mutex.lock().unwrap());
1782			}
1783		}
1784		if !peers_to_disconnect.is_empty() {
1785			let mut peers_lock = self.peers.write().unwrap();
1786			let peers = &mut *peers_lock;
1787			for (node_id, msg) in peers_to_disconnect.drain() {
1788				// Note that since we are holding the peers *write* lock we can
1789				// remove from node_id_to_descriptor immediately (as no other
1790				// thread can be holding the peer lock if we have the global write
1791				// lock).
1792
1793				if let Some(mut descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
1794					if let Some(peer_mutex) = peers.remove(&descriptor) {
1795						if let Some(msg) = msg {
1796							log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1797									log_pubkey!(node_id),
1798									msg.data);
1799							let mut peer = peer_mutex.lock().unwrap();
1800							self.enqueue_message(&mut *peer, &msg);
1801							// This isn't guaranteed to work, but if there is enough free
1802							// room in the send buffer, put the error message there...
1803							self.do_attempt_write_data(&mut descriptor, &mut *peer);
1804						} else {
1805							log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1806						}
1807					}
1808					descriptor.disconnect_socket();
1809					self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1810					self.message_handler.onion_message_handler.peer_disconnected(&node_id, false);
1811				}
1812			}
1813		}
1814	}
1815
1816	/// Indicates that the given socket descriptor's connection is now closed.
1817	pub fn socket_disconnected(&self, descriptor: &Descriptor) {
1818		self.disconnect_event_internal(descriptor, false);
1819	}
1820
1821	fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1822		let mut peers = self.peers.write().unwrap();
1823		let peer_option = peers.remove(descriptor);
1824		match peer_option {
1825			None => {
1826				// This is most likely a simple race condition where the user found that the socket
1827				// was disconnected, then we told the user to `disconnect_socket()`, then they
1828				// called this method. Either way we're disconnected, return.
1829			},
1830			Some(peer_lock) => {
1831				let peer = peer_lock.lock().unwrap();
1832				if let Some(node_id) = peer.their_node_id {
1833					log_trace!(self.logger,
1834						"Handling disconnection of peer {}, with {}future connection to the peer possible.",
1835						log_pubkey!(node_id), if no_connection_possible { "no " } else { "" });
1836					self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
1837					self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1838					self.message_handler.onion_message_handler.peer_disconnected(&node_id, no_connection_possible);
1839				}
1840			}
1841		};
1842	}
1843
1844	/// Disconnect a peer given its node id.
1845	///
1846	/// Set `no_connection_possible` to true to prevent any further connection with this peer,
1847	/// force-closing any channels we have with it.
1848	///
1849	/// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
1850	/// peer. Thus, be very careful about reentrancy issues.
1851	///
1852	/// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
1853	pub fn disconnect_by_node_id(&self, node_id: PublicKey, no_connection_possible: bool) {
1854		let mut peers_lock = self.peers.write().unwrap();
1855		if let Some(mut descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
1856			log_trace!(self.logger, "Disconnecting peer with id {} due to client request", node_id);
1857			peers_lock.remove(&descriptor);
1858			self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1859			self.message_handler.onion_message_handler.peer_disconnected(&node_id, no_connection_possible);
1860			descriptor.disconnect_socket();
1861		}
1862	}
1863
1864	/// Disconnects all currently-connected peers. This is useful on platforms where there may be
1865	/// an indication that TCP sockets have stalled even if we weren't around to time them out
1866	/// using regular ping/pongs.
1867	pub fn disconnect_all_peers(&self) {
1868		let mut peers_lock = self.peers.write().unwrap();
1869		self.node_id_to_descriptor.lock().unwrap().clear();
1870		let peers = &mut *peers_lock;
1871		for (mut descriptor, peer) in peers.drain() {
1872			if let Some(node_id) = peer.lock().unwrap().their_node_id {
1873				log_trace!(self.logger, "Disconnecting peer with id {} due to client request to disconnect all peers", node_id);
1874				self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1875				self.message_handler.onion_message_handler.peer_disconnected(&node_id, false);
1876			}
1877			descriptor.disconnect_socket();
1878		}
1879	}
1880
1881	/// This is called when we're blocked on sending additional gossip messages until we receive a
1882	/// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
1883	/// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
1884	fn maybe_send_extra_ping(&self, peer: &mut Peer) {
1885		if peer.awaiting_pong_timer_tick_intervals == 0 {
1886			peer.awaiting_pong_timer_tick_intervals = -1;
1887			let ping = msgs::Ping {
1888				ponglen: 0,
1889				byteslen: 64,
1890			};
1891			self.enqueue_message(peer, &ping);
1892		}
1893	}
1894
1895	/// Send pings to each peer and disconnect those which did not respond to the last round of
1896	/// pings.
1897	///
1898	/// This may be called on any timescale you want, however, roughly once every ten seconds is
1899	/// preferred. The call rate determines both how often we send a ping to our peers and how much
1900	/// time they have to respond before we disconnect them.
1901	///
1902	/// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1903	/// issues!
1904	///
1905	/// [`send_data`]: SocketDescriptor::send_data
1906	pub fn timer_tick_occurred(&self) {
1907		let mut descriptors_needing_disconnect = Vec::new();
1908		{
1909			let peers_lock = self.peers.read().unwrap();
1910
1911			for (descriptor, peer_mutex) in peers_lock.iter() {
1912				let mut peer = peer_mutex.lock().unwrap();
1913				if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_node_id.is_none() {
1914					// The peer needs to complete its handshake before we can exchange messages. We
1915					// give peers one timer tick to complete handshake, reusing
1916					// `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
1917					// for handshake completion.
1918					if peer.awaiting_pong_timer_tick_intervals != 0 {
1919						descriptors_needing_disconnect.push(descriptor.clone());
1920					} else {
1921						peer.awaiting_pong_timer_tick_intervals = 1;
1922					}
1923					continue;
1924				}
1925
1926				if peer.awaiting_pong_timer_tick_intervals == -1 {
1927					// Magic value set in `maybe_send_extra_ping`.
1928					peer.awaiting_pong_timer_tick_intervals = 1;
1929					peer.received_message_since_timer_tick = false;
1930					continue;
1931				}
1932
1933				if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
1934					|| peer.awaiting_pong_timer_tick_intervals as u64 >
1935						MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64
1936				{
1937					descriptors_needing_disconnect.push(descriptor.clone());
1938					continue;
1939				}
1940				peer.received_message_since_timer_tick = false;
1941
1942				if peer.awaiting_pong_timer_tick_intervals > 0 {
1943					peer.awaiting_pong_timer_tick_intervals += 1;
1944					continue;
1945				}
1946
1947				peer.awaiting_pong_timer_tick_intervals = 1;
1948				let ping = msgs::Ping {
1949					ponglen: 0,
1950					byteslen: 64,
1951				};
1952				self.enqueue_message(&mut *peer, &ping);
1953				self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer);
1954			}
1955		}
1956
1957		if !descriptors_needing_disconnect.is_empty() {
1958			{
1959				let mut peers_lock = self.peers.write().unwrap();
1960				for descriptor in descriptors_needing_disconnect.iter() {
1961					if let Some(peer) = peers_lock.remove(descriptor) {
1962						if let Some(node_id) = peer.lock().unwrap().their_node_id {
1963							log_trace!(self.logger, "Disconnecting peer with id {} due to ping timeout", node_id);
1964							self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
1965							self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1966							self.message_handler.onion_message_handler.peer_disconnected(&node_id, false);
1967						}
1968					}
1969				}
1970			}
1971
1972			for mut descriptor in descriptors_needing_disconnect.drain(..) {
1973				descriptor.disconnect_socket();
1974			}
1975		}
1976	}
1977
1978	#[allow(dead_code)]
1979	// Messages of up to 64KB should never end up more than half full with addresses, as that would
1980	// be absurd. We ensure this by checking that at least 100 (our stated public contract on when
1981	// broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
1982	// message...
1983	const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2;
1984	#[deny(const_err)]
1985	#[allow(dead_code)]
1986	// ...by failing to compile if the number of addresses that would be half of a message is
1987	// smaller than 100:
1988	const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 100;
1989
1990	/// Generates a signed node_announcement from the given arguments, sending it to all connected
1991	/// peers. Note that peers will likely ignore this message unless we have at least one public
1992	/// channel which has at least six confirmations on-chain.
1993	///
1994	/// `rgb` is a node "color" and `alias` is a printable human-readable string to describe this
1995	/// node to humans. They carry no in-protocol meaning.
1996	///
1997	/// `addresses` represent the set (possibly empty) of socket addresses on which this node
1998	/// accepts incoming connections. These will be included in the node_announcement, publicly
1999	/// tying these addresses together and to this node. If you wish to preserve user privacy,
2000	/// addresses should likely contain only Tor Onion addresses.
2001	///
2002	/// Panics if `addresses` is absurdly large (more than 100).
2003	///
2004	/// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events
2005	pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], mut addresses: Vec<NetAddress>) {
2006		if addresses.len() > 100 {
2007			panic!("More than half the message size was taken up by public addresses!");
2008		}
2009
2010		// While all existing nodes handle unsorted addresses just fine, the spec requires that
2011		// addresses be sorted for future compatibility.
2012		addresses.sort_by_key(|addr| addr.get_id());
2013
2014		let features = self.message_handler.chan_handler.provided_node_features()
2015			.or(self.message_handler.route_handler.provided_node_features())
2016			.or(self.message_handler.onion_message_handler.provided_node_features());
2017		let announcement = msgs::UnsignedNodeAnnouncement {
2018			features,
2019			timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel),
2020			node_id: PublicKey::from_secret_key(&self.secp_ctx, &self.our_node_secret),
2021			rgb, alias, addresses,
2022			excess_address_data: Vec::new(),
2023			excess_data: Vec::new(),
2024		};
2025		let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
2026		let node_announce_sig = sign(&self.secp_ctx, &msghash, &self.our_node_secret);
2027
2028		let msg = msgs::NodeAnnouncement {
2029			signature: node_announce_sig,
2030			contents: announcement
2031		};
2032
2033		log_debug!(self.logger, "Broadcasting NodeAnnouncement after passing it to our own RoutingMessageHandler.");
2034		let _ = self.message_handler.route_handler.handle_node_announcement(&msg);
2035		self.forward_broadcast_msg(&*self.peers.read().unwrap(), &wire::Message::NodeAnnouncement(msg), None);
2036	}
2037}
2038
2039fn is_gossip_msg(type_id: u16) -> bool {
2040	match type_id {
2041		msgs::ChannelAnnouncement::TYPE |
2042		msgs::ChannelUpdate::TYPE |
2043		msgs::NodeAnnouncement::TYPE |
2044		msgs::QueryChannelRange::TYPE |
2045		msgs::ReplyChannelRange::TYPE |
2046		msgs::QueryShortChannelIds::TYPE |
2047		msgs::ReplyShortChannelIdsEnd::TYPE => true,
2048		_ => false
2049	}
2050}
2051
2052#[cfg(test)]
2053mod tests {
2054	use crate::ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses};
2055	use crate::ln::{msgs, wire};
2056	use crate::ln::msgs::NetAddress;
2057	use crate::util::events;
2058	use crate::util::test_utils;
2059
2060	use bitcoin::secp256k1::Secp256k1;
2061	use bitcoin::secp256k1::{SecretKey, PublicKey};
2062
2063	use crate::prelude::*;
2064	use crate::sync::{Arc, Mutex};
2065	use core::sync::atomic::Ordering;
2066
2067	#[derive(Clone)]
2068	struct FileDescriptor {
2069		fd: u16,
2070		outbound_data: Arc<Mutex<Vec<u8>>>,
2071	}
2072	impl PartialEq for FileDescriptor {
2073		fn eq(&self, other: &Self) -> bool {
2074			self.fd == other.fd
2075		}
2076	}
2077	impl Eq for FileDescriptor { }
2078	impl core::hash::Hash for FileDescriptor {
2079		fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
2080			self.fd.hash(hasher)
2081		}
2082	}
2083
2084	impl SocketDescriptor for FileDescriptor {
2085		fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
2086			self.outbound_data.lock().unwrap().extend_from_slice(data);
2087			data.len()
2088		}
2089
2090		fn disconnect_socket(&mut self) {}
2091	}
2092
2093	struct PeerManagerCfg {
2094		chan_handler: test_utils::TestChannelMessageHandler,
2095		routing_handler: test_utils::TestRoutingMessageHandler,
2096		logger: test_utils::TestLogger,
2097	}
2098
2099	fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2100		let mut cfgs = Vec::new();
2101		for _ in 0..peer_count {
2102			cfgs.push(
2103				PeerManagerCfg{
2104					chan_handler: test_utils::TestChannelMessageHandler::new(),
2105					logger: test_utils::TestLogger::new(),
2106					routing_handler: test_utils::TestRoutingMessageHandler::new(),
2107				}
2108			);
2109		}
2110
2111		cfgs
2112	}
2113
2114	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>> {
2115		let mut peers = Vec::new();
2116		for i in 0..peer_count {
2117			let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2118			let ephemeral_bytes = [i as u8; 32];
2119			let msg_handler = MessageHandler { chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler, onion_message_handler: IgnoringMessageHandler {} };
2120			let peer = PeerManager::new(msg_handler, node_secret, 0, &ephemeral_bytes, &cfgs[i].logger, IgnoringMessageHandler {});
2121			peers.push(peer);
2122		}
2123
2124		peers
2125	}
2126
2127	fn establish_connection<'a>(peer_a: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, IgnoringMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler>, peer_b: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, IgnoringMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler>) -> (FileDescriptor, FileDescriptor) {
2128		let secp_ctx = Secp256k1::new();
2129		let a_id = PublicKey::from_secret_key(&secp_ctx, &peer_a.our_node_secret);
2130		let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2131		let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2132		let initial_data = peer_b.new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
2133		peer_a.new_inbound_connection(fd_a.clone(), None).unwrap();
2134		assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2135		peer_a.process_events();
2136
2137		let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2138		assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2139
2140		peer_b.process_events();
2141		let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2142		assert_eq!(peer_a.read_event(&mut fd_a, &b_data).unwrap(), false);
2143
2144		peer_a.process_events();
2145		let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2146		assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2147
2148		(fd_a.clone(), fd_b.clone())
2149	}
2150
2151	#[test]
2152	fn test_disconnect_peer() {
2153		// Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2154		// push a DisconnectPeer event to remove the node flagged by id
2155		let cfgs = create_peermgr_cfgs(2);
2156		let chan_handler = test_utils::TestChannelMessageHandler::new();
2157		let mut peers = create_network(2, &cfgs);
2158		establish_connection(&peers[0], &peers[1]);
2159		assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2160
2161		let secp_ctx = Secp256k1::new();
2162		let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
2163
2164		chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
2165			node_id: their_id,
2166			action: msgs::ErrorAction::DisconnectPeer { msg: None },
2167		});
2168		assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
2169		peers[0].message_handler.chan_handler = &chan_handler;
2170
2171		peers[0].process_events();
2172		assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2173	}
2174
2175	#[test]
2176	fn test_send_simple_msg() {
2177		// Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2178		// push a message from one peer to another.
2179		let cfgs = create_peermgr_cfgs(2);
2180		let a_chan_handler = test_utils::TestChannelMessageHandler::new();
2181		let b_chan_handler = test_utils::TestChannelMessageHandler::new();
2182		let mut peers = create_network(2, &cfgs);
2183		let (fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2184		assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2185
2186		let secp_ctx = Secp256k1::new();
2187		let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
2188
2189		let msg = msgs::Shutdown { channel_id: [42; 32], scriptpubkey: bitcoin::Script::new() };
2190		a_chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::SendShutdown {
2191			node_id: their_id, msg: msg.clone()
2192		});
2193		peers[0].message_handler.chan_handler = &a_chan_handler;
2194
2195		b_chan_handler.expect_receive_msg(wire::Message::Shutdown(msg));
2196		peers[1].message_handler.chan_handler = &b_chan_handler;
2197
2198		peers[0].process_events();
2199
2200		let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2201		assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2202	}
2203
2204	#[test]
2205	fn test_disconnect_all_peer() {
2206		// Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2207		// then calls disconnect_all_peers
2208		let cfgs = create_peermgr_cfgs(2);
2209		let peers = create_network(2, &cfgs);
2210		establish_connection(&peers[0], &peers[1]);
2211		assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2212
2213		peers[0].disconnect_all_peers();
2214		assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2215	}
2216
2217	#[test]
2218	fn test_timer_tick_occurred() {
2219		// Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
2220		let cfgs = create_peermgr_cfgs(2);
2221		let peers = create_network(2, &cfgs);
2222		establish_connection(&peers[0], &peers[1]);
2223		assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2224
2225		// peers[0] awaiting_pong is set to true, but the Peer is still connected
2226		peers[0].timer_tick_occurred();
2227		peers[0].process_events();
2228		assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2229
2230		// Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
2231		peers[0].timer_tick_occurred();
2232		peers[0].process_events();
2233		assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2234	}
2235
2236	#[test]
2237	fn test_do_attempt_write_data() {
2238		// Create 2 peers with custom TestRoutingMessageHandlers and connect them.
2239		let cfgs = create_peermgr_cfgs(2);
2240		cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2241		cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2242		let peers = create_network(2, &cfgs);
2243
2244		// By calling establish_connect, we trigger do_attempt_write_data between
2245		// the peers. Previously this function would mistakenly enter an infinite loop
2246		// when there were more channel messages available than could fit into a peer's
2247		// buffer. This issue would now be detected by this test (because we use custom
2248		// RoutingMessageHandlers that intentionally return more channel messages
2249		// than can fit into a peer's buffer).
2250		let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2251
2252		// Make each peer to read the messages that the other peer just wrote to them. Note that
2253		// due to the max-message-before-ping limits this may take a few iterations to complete.
2254		for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
2255			peers[1].process_events();
2256			let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2257			assert!(!a_read_data.is_empty());
2258
2259			peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
2260			peers[0].process_events();
2261
2262			let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2263			assert!(!b_read_data.is_empty());
2264			peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
2265
2266			peers[0].process_events();
2267			assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
2268		}
2269
2270		// Check that each peer has received the expected number of channel updates and channel
2271		// announcements.
2272		assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2273		assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2274		assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2275		assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2276	}
2277
2278	#[test]
2279	fn test_handshake_timeout() {
2280		// Tests that we time out a peer still waiting on handshake completion after a full timer
2281		// tick.
2282		let cfgs = create_peermgr_cfgs(2);
2283		cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2284		cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2285		let peers = create_network(2, &cfgs);
2286
2287		let secp_ctx = Secp256k1::new();
2288		let a_id = PublicKey::from_secret_key(&secp_ctx, &peers[0].our_node_secret);
2289		let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2290		let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2291		let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
2292		peers[0].new_inbound_connection(fd_a.clone(), None).unwrap();
2293
2294		// If we get a single timer tick before completion, that's fine
2295		assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2296		peers[0].timer_tick_occurred();
2297		assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2298
2299		assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
2300		peers[0].process_events();
2301		let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2302		assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2303		peers[1].process_events();
2304
2305		// ...but if we get a second timer tick, we should disconnect the peer
2306		peers[0].timer_tick_occurred();
2307		assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2308
2309		let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2310		assert!(peers[0].read_event(&mut fd_a, &b_data).is_err());
2311	}
2312
2313	#[test]
2314	fn test_filter_addresses(){
2315		// Tests the filter_addresses function.
2316
2317		// For (10/8)
2318		let ip_address = NetAddress::IPv4{addr: [10, 0, 0, 0], port: 1000};
2319		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2320		let ip_address = NetAddress::IPv4{addr: [10, 0, 255, 201], port: 1000};
2321		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2322		let ip_address = NetAddress::IPv4{addr: [10, 255, 255, 255], port: 1000};
2323		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2324
2325		// For (0/8)
2326		let ip_address = NetAddress::IPv4{addr: [0, 0, 0, 0], port: 1000};
2327		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2328		let ip_address = NetAddress::IPv4{addr: [0, 0, 255, 187], port: 1000};
2329		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2330		let ip_address = NetAddress::IPv4{addr: [0, 255, 255, 255], port: 1000};
2331		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2332
2333		// For (100.64/10)
2334		let ip_address = NetAddress::IPv4{addr: [100, 64, 0, 0], port: 1000};
2335		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2336		let ip_address = NetAddress::IPv4{addr: [100, 78, 255, 0], port: 1000};
2337		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2338		let ip_address = NetAddress::IPv4{addr: [100, 127, 255, 255], port: 1000};
2339		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2340
2341		// For (127/8)
2342		let ip_address = NetAddress::IPv4{addr: [127, 0, 0, 0], port: 1000};
2343		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2344		let ip_address = NetAddress::IPv4{addr: [127, 65, 73, 0], port: 1000};
2345		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2346		let ip_address = NetAddress::IPv4{addr: [127, 255, 255, 255], port: 1000};
2347		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2348
2349		// For (169.254/16)
2350		let ip_address = NetAddress::IPv4{addr: [169, 254, 0, 0], port: 1000};
2351		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2352		let ip_address = NetAddress::IPv4{addr: [169, 254, 221, 101], port: 1000};
2353		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2354		let ip_address = NetAddress::IPv4{addr: [169, 254, 255, 255], port: 1000};
2355		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2356
2357		// For (172.16/12)
2358		let ip_address = NetAddress::IPv4{addr: [172, 16, 0, 0], port: 1000};
2359		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2360		let ip_address = NetAddress::IPv4{addr: [172, 27, 101, 23], port: 1000};
2361		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2362		let ip_address = NetAddress::IPv4{addr: [172, 31, 255, 255], port: 1000};
2363		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2364
2365		// For (192.168/16)
2366		let ip_address = NetAddress::IPv4{addr: [192, 168, 0, 0], port: 1000};
2367		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2368		let ip_address = NetAddress::IPv4{addr: [192, 168, 205, 159], port: 1000};
2369		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2370		let ip_address = NetAddress::IPv4{addr: [192, 168, 255, 255], port: 1000};
2371		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2372
2373		// For (192.88.99/24)
2374		let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 0], port: 1000};
2375		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2376		let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 140], port: 1000};
2377		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2378		let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 255], port: 1000};
2379		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2380
2381		// For other IPv4 addresses
2382		let ip_address = NetAddress::IPv4{addr: [188, 255, 99, 0], port: 1000};
2383		assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2384		let ip_address = NetAddress::IPv4{addr: [123, 8, 129, 14], port: 1000};
2385		assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2386		let ip_address = NetAddress::IPv4{addr: [2, 88, 9, 255], port: 1000};
2387		assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2388
2389		// For (2000::/3)
2390		let ip_address = NetAddress::IPv6{addr: [32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], port: 1000};
2391		assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2392		let ip_address = NetAddress::IPv6{addr: [45, 34, 209, 190, 0, 123, 55, 34, 0, 0, 3, 27, 201, 0, 0, 0], port: 1000};
2393		assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2394		let ip_address = NetAddress::IPv6{addr: [63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], port: 1000};
2395		assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2396
2397		// For other IPv6 addresses
2398		let ip_address = NetAddress::IPv6{addr: [24, 240, 12, 32, 0, 0, 0, 0, 20, 97, 0, 32, 121, 254, 0, 0], port: 1000};
2399		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2400		let ip_address = NetAddress::IPv6{addr: [68, 23, 56, 63, 0, 0, 2, 7, 75, 109, 0, 39, 0, 0, 0, 0], port: 1000};
2401		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2402		let ip_address = NetAddress::IPv6{addr: [101, 38, 140, 230, 100, 0, 30, 98, 0, 26, 0, 0, 57, 96, 0, 0], port: 1000};
2403		assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2404
2405		// For (None)
2406		assert_eq!(filter_addresses(None), None);
2407	}
2408}