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