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