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