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