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