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