Use wrapper to add context to logging
[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, WithContext};
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                 let logger = WithContext::from(&self.logger, Some(peer.their_node_id.unwrap().0), None);
1257                 if is_gossip_msg(message.type_id()) {
1258                         log_gossip!(logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0));
1259                 } else {
1260                         log_trace!(logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0))
1261                 }
1262                 peer.msgs_sent_since_pong += 1;
1263                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(message));
1264         }
1265
1266         /// Append a message to a peer's pending outbound/write gossip broadcast buffer
1267         fn enqueue_encoded_gossip_broadcast(&self, peer: &mut Peer, encoded_message: MessageBuf) {
1268                 peer.msgs_sent_since_pong += 1;
1269                 debug_assert!(peer.gossip_broadcast_buffer.len() <= OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP);
1270                 peer.gossip_broadcast_buffer.push_back(encoded_message);
1271         }
1272
1273         fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1274                 let mut pause_read = false;
1275                 let peers = self.peers.read().unwrap();
1276                 let mut msgs_to_forward = Vec::new();
1277                 let mut peer_node_id = None;
1278                 match peers.get(peer_descriptor) {
1279                         None => {
1280                                 // This is most likely a simple race condition where the user read some bytes
1281                                 // from the socket, then we told the user to `disconnect_socket()`, then they
1282                                 // called this method. Return an error to make sure we get disconnected.
1283                                 return Err(PeerHandleError { });
1284                         },
1285                         Some(peer_mutex) => {
1286                                 let mut read_pos = 0;
1287                                 while read_pos < data.len() {
1288                                         macro_rules! try_potential_handleerror {
1289                                                 ($peer: expr, $thing: expr) => {
1290                                                         match $thing {
1291                                                                 Ok(x) => x,
1292                                                                 Err(e) => {
1293                                                                         match e.action {
1294                                                                                 msgs::ErrorAction::DisconnectPeer { .. } => {
1295                                                                                         // We may have an `ErrorMessage` to send to the peer,
1296                                                                                         // but writing to the socket while reading can lead to
1297                                                                                         // re-entrant code and possibly unexpected behavior. The
1298                                                                                         // message send is optimistic anyway, and in this case
1299                                                                                         // we immediately disconnect the peer.
1300                                                                                         log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1301                                                                                         return Err(PeerHandleError { });
1302                                                                                 },
1303                                                                                 msgs::ErrorAction::DisconnectPeerWithWarning { .. } => {
1304                                                                                         // We have a `WarningMessage` to send to the peer, but
1305                                                                                         // writing to the socket while reading can lead to
1306                                                                                         // re-entrant code and possibly unexpected behavior. The
1307                                                                                         // message send is optimistic anyway, and in this case
1308                                                                                         // we immediately disconnect the peer.
1309                                                                                         log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1310                                                                                         return Err(PeerHandleError { });
1311                                                                                 },
1312                                                                                 msgs::ErrorAction::IgnoreAndLog(level) => {
1313                                                                                         log_given_level!(self.logger, level, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1314                                                                                         continue
1315                                                                                 },
1316                                                                                 msgs::ErrorAction::IgnoreDuplicateGossip => continue, // Don't even bother logging these
1317                                                                                 msgs::ErrorAction::IgnoreError => {
1318                                                                                         log_debug!(self.logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1319                                                                                         continue;
1320                                                                                 },
1321                                                                                 msgs::ErrorAction::SendErrorMessage { msg } => {
1322                                                                                         log_debug!(self.logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1323                                                                                         self.enqueue_message($peer, &msg);
1324                                                                                         continue;
1325                                                                                 },
1326                                                                                 msgs::ErrorAction::SendWarningMessage { msg, log_level } => {
1327                                                                                         log_given_level!(self.logger, log_level, "Error handling message{}; sending warning message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1328                                                                                         self.enqueue_message($peer, &msg);
1329                                                                                         continue;
1330                                                                                 },
1331                                                                         }
1332                                                                 }
1333                                                         }
1334                                                 }
1335                                         }
1336
1337                                         let mut peer_lock = peer_mutex.lock().unwrap();
1338                                         let peer = &mut *peer_lock;
1339                                         let mut msg_to_handle = None;
1340                                         if peer_node_id.is_none() {
1341                                                 peer_node_id = peer.their_node_id.clone();
1342                                         }
1343
1344                                         assert!(peer.pending_read_buffer.len() > 0);
1345                                         assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
1346
1347                                         {
1348                                                 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
1349                                                 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]);
1350                                                 read_pos += data_to_copy;
1351                                                 peer.pending_read_buffer_pos += data_to_copy;
1352                                         }
1353
1354                                         if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
1355                                                 peer.pending_read_buffer_pos = 0;
1356
1357                                                 macro_rules! insert_node_id {
1358                                                         () => {
1359                                                                 let logger = WithContext::from(&self.logger, Some(peer.their_node_id.unwrap().0), None);
1360                                                                 match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap().0) {
1361                                                                         hash_map::Entry::Occupied(e) => {
1362                                                                                 log_trace!(logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap().0));
1363                                                                                 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
1364                                                                                 // Check that the peers map is consistent with the
1365                                                                                 // node_id_to_descriptor map, as this has been broken
1366                                                                                 // before.
1367                                                                                 debug_assert!(peers.get(e.get()).is_some());
1368                                                                                 return Err(PeerHandleError { })
1369                                                                         },
1370                                                                         hash_map::Entry::Vacant(entry) => {
1371                                                                                 log_debug!(logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap().0));
1372                                                                                 entry.insert(peer_descriptor.clone())
1373                                                                         },
1374                                                                 };
1375                                                         }
1376                                                 }
1377
1378                                                 let next_step = peer.channel_encryptor.get_noise_step();
1379                                                 match next_step {
1380                                                         NextNoiseStep::ActOne => {
1381                                                                 let act_two = try_potential_handleerror!(peer, peer.channel_encryptor
1382                                                                         .process_act_one_with_keys(&peer.pending_read_buffer[..],
1383                                                                                 &self.node_signer, self.get_ephemeral_key(), &self.secp_ctx)).to_vec();
1384                                                                 peer.pending_outbound_buffer.push_back(act_two);
1385                                                                 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
1386                                                         },
1387                                                         NextNoiseStep::ActTwo => {
1388                                                                 let (act_three, their_node_id) = try_potential_handleerror!(peer,
1389                                                                         peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..],
1390                                                                                 &self.node_signer));
1391                                                                 peer.pending_outbound_buffer.push_back(act_three.to_vec());
1392                                                                 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1393                                                                 peer.pending_read_is_header = true;
1394
1395                                                                 peer.set_their_node_id(their_node_id);
1396                                                                 insert_node_id!();
1397                                                                 let features = self.init_features(&their_node_id);
1398                                                                 let networks = self.message_handler.chan_handler.get_chain_hashes();
1399                                                                 let resp = msgs::Init { features, networks, remote_network_address: filter_addresses(peer.their_socket_address.clone()) };
1400                                                                 self.enqueue_message(peer, &resp);
1401                                                                 peer.awaiting_pong_timer_tick_intervals = 0;
1402                                                         },
1403                                                         NextNoiseStep::ActThree => {
1404                                                                 let their_node_id = try_potential_handleerror!(peer,
1405                                                                         peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
1406                                                                 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1407                                                                 peer.pending_read_is_header = true;
1408                                                                 peer.set_their_node_id(their_node_id);
1409                                                                 insert_node_id!();
1410                                                                 let features = self.init_features(&their_node_id);
1411                                                                 let networks = self.message_handler.chan_handler.get_chain_hashes();
1412                                                                 let resp = msgs::Init { features, networks, remote_network_address: filter_addresses(peer.their_socket_address.clone()) };
1413                                                                 self.enqueue_message(peer, &resp);
1414                                                                 peer.awaiting_pong_timer_tick_intervals = 0;
1415                                                         },
1416                                                         NextNoiseStep::NoiseComplete => {
1417                                                                 if peer.pending_read_is_header {
1418                                                                         let msg_len = try_potential_handleerror!(peer,
1419                                                                                 peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
1420                                                                         if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1421                                                                         peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
1422                                                                         if msg_len < 2 { // Need at least the message type tag
1423                                                                                 return Err(PeerHandleError { });
1424                                                                         }
1425                                                                         peer.pending_read_is_header = false;
1426                                                                 } else {
1427                                                                         debug_assert!(peer.pending_read_buffer.len() >= 2 + 16);
1428                                                                         try_potential_handleerror!(peer,
1429                                                                                 peer.channel_encryptor.decrypt_message(&mut peer.pending_read_buffer[..]));
1430
1431                                                                         let mut reader = io::Cursor::new(&peer.pending_read_buffer[..peer.pending_read_buffer.len() - 16]);
1432                                                                         let message_result = wire::read(&mut reader, &*self.message_handler.custom_message_handler);
1433
1434                                                                         // Reset read buffer
1435                                                                         if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1436                                                                         peer.pending_read_buffer.resize(18, 0);
1437                                                                         peer.pending_read_is_header = true;
1438
1439                                                                         let logger = WithContext::from(&self.logger, Some(peer.their_node_id.unwrap().0), None);
1440                                                                         let message = match message_result {
1441                                                                                 Ok(x) => x,
1442                                                                                 Err(e) => {
1443                                                                                         match e {
1444                                                                                                 // Note that to avoid re-entrancy we never call
1445                                                                                                 // `do_attempt_write_data` from here, causing
1446                                                                                                 // the messages enqueued here to not actually
1447                                                                                                 // be sent before the peer is disconnected.
1448                                                                                                 (msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
1449                                                                                                         log_gossip!(logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
1450                                                                                                         continue;
1451                                                                                                 }
1452                                                                                                 (msgs::DecodeError::UnsupportedCompression, _) => {
1453                                                                                                         log_gossip!(logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
1454                                                                                                         self.enqueue_message(peer, &msgs::WarningMessage { channel_id: ChannelId::new_zero(), data: "Unsupported message compression: zlib".to_owned() });
1455                                                                                                         continue;
1456                                                                                                 }
1457                                                                                                 (_, Some(ty)) if is_gossip_msg(ty) => {
1458                                                                                                         log_gossip!(logger, "Got an invalid value while deserializing a gossip message");
1459                                                                                                         self.enqueue_message(peer, &msgs::WarningMessage {
1460                                                                                                                 channel_id: ChannelId::new_zero(),
1461                                                                                                                 data: format!("Unreadable/bogus gossip message of type {}", ty),
1462                                                                                                         });
1463                                                                                                         continue;
1464                                                                                                 }
1465                                                                                                 (msgs::DecodeError::UnknownRequiredFeature, _) => {
1466                                                                                                         log_debug!(logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
1467                                                                                                         return Err(PeerHandleError { });
1468                                                                                                 }
1469                                                                                                 (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { }),
1470                                                                                                 (msgs::DecodeError::InvalidValue, _) => {
1471                                                                                                         log_debug!(logger, "Got an invalid value while deserializing message");
1472                                                                                                         return Err(PeerHandleError { });
1473                                                                                                 }
1474                                                                                                 (msgs::DecodeError::ShortRead, _) => {
1475                                                                                                         log_debug!(logger, "Deserialization failed due to shortness of message");
1476                                                                                                         return Err(PeerHandleError { });
1477                                                                                                 }
1478                                                                                                 (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { }),
1479                                                                                                 (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { }),
1480                                                                                         }
1481                                                                                 }
1482                                                                         };
1483
1484                                                                         msg_to_handle = Some(message);
1485                                                                 }
1486                                                         }
1487                                                 }
1488                                         }
1489                                         pause_read = !self.peer_should_read(peer);
1490
1491                                         if let Some(message) = msg_to_handle {
1492                                                 match self.handle_message(&peer_mutex, peer_lock, message) {
1493                                                         Err(handling_error) => match handling_error {
1494                                                                 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
1495                                                                 MessageHandlingError::LightningError(e) => {
1496                                                                         try_potential_handleerror!(&mut peer_mutex.lock().unwrap(), Err(e));
1497                                                                 },
1498                                                         },
1499                                                         Ok(Some(msg)) => {
1500                                                                 msgs_to_forward.push(msg);
1501                                                         },
1502                                                         Ok(None) => {},
1503                                                 }
1504                                         }
1505                                 }
1506                         }
1507                 }
1508
1509                 for msg in msgs_to_forward.drain(..) {
1510                         self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref().map(|(pk, _)| pk));
1511                 }
1512
1513                 Ok(pause_read)
1514         }
1515
1516         /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
1517         /// Returns the message back if it needs to be broadcasted to all other peers.
1518         fn handle_message(
1519                 &self,
1520                 peer_mutex: &Mutex<Peer>,
1521                 mut peer_lock: MutexGuard<Peer>,
1522                 message: wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>
1523         ) -> Result<Option<wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
1524                 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;
1525                 let logger = WithContext::from(&self.logger, Some(their_node_id), None);
1526                 peer_lock.received_message_since_timer_tick = true;
1527
1528                 // Need an Init as first message
1529                 if let wire::Message::Init(msg) = message {
1530                         // Check if we have any compatible chains if the `networks` field is specified.
1531                         if let Some(networks) = &msg.networks {
1532                                 if let Some(our_chains) = self.message_handler.chan_handler.get_chain_hashes() {
1533                                         let mut have_compatible_chains = false;
1534                                         'our_chains: for our_chain in our_chains.iter() {
1535                                                 for their_chain in networks {
1536                                                         if our_chain == their_chain {
1537                                                                 have_compatible_chains = true;
1538                                                                 break 'our_chains;
1539                                                         }
1540                                                 }
1541                                         }
1542                                         if !have_compatible_chains {
1543                                                 log_debug!(logger, "Peer does not support any of our supported chains");
1544                                                 return Err(PeerHandleError { }.into());
1545                                         }
1546                                 }
1547                         }
1548
1549                         let our_features = self.init_features(&their_node_id);
1550                         if msg.features.requires_unknown_bits_from(&our_features) {
1551                                 log_debug!(logger, "Peer requires features unknown to us");
1552                                 return Err(PeerHandleError { }.into());
1553                         }
1554
1555                         if our_features.requires_unknown_bits_from(&msg.features) {
1556                                 log_debug!(logger, "We require features unknown to our peer");
1557                                 return Err(PeerHandleError { }.into());
1558                         }
1559
1560                         if peer_lock.their_features.is_some() {
1561                                 return Err(PeerHandleError { }.into());
1562                         }
1563
1564                         log_info!(logger, "Received peer Init message from {}: {}", log_pubkey!(their_node_id), msg.features);
1565
1566                         // For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
1567                         if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
1568                                 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1569                         }
1570
1571                         if let Err(()) = self.message_handler.route_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1572                                 log_debug!(logger, "Route 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.chan_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1576                                 log_debug!(logger, "Channel Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1577                                 return Err(PeerHandleError { }.into());
1578                         }
1579                         if let Err(()) = self.message_handler.onion_message_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1580                                 log_debug!(logger, "Onion Message Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1581                                 return Err(PeerHandleError { }.into());
1582                         }
1583
1584                         peer_lock.their_features = Some(msg.features);
1585                         return Ok(None);
1586                 } else if peer_lock.their_features.is_none() {
1587                         log_debug!(logger, "Peer {} sent non-Init first message", log_pubkey!(their_node_id));
1588                         return Err(PeerHandleError { }.into());
1589                 }
1590
1591                 if let wire::Message::GossipTimestampFilter(_msg) = message {
1592                         // When supporting gossip messages, start inital gossip sync only after we receive
1593                         // a GossipTimestampFilter
1594                         if peer_lock.their_features.as_ref().unwrap().supports_gossip_queries() &&
1595                                 !peer_lock.sent_gossip_timestamp_filter {
1596                                 peer_lock.sent_gossip_timestamp_filter = true;
1597                                 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1598                         }
1599                         return Ok(None);
1600                 }
1601
1602                 if let wire::Message::ChannelAnnouncement(ref _msg) = message {
1603                         peer_lock.received_channel_announce_since_backlogged = true;
1604                 }
1605
1606                 mem::drop(peer_lock);
1607
1608                 if is_gossip_msg(message.type_id()) {
1609                         log_gossip!(logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1610                 } else {
1611                         log_trace!(logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1612                 }
1613
1614                 let mut should_forward = None;
1615
1616                 match message {
1617                         // Setup and Control messages:
1618                         wire::Message::Init(_) => {
1619                                 // Handled above
1620                         },
1621                         wire::Message::GossipTimestampFilter(_) => {
1622                                 // Handled above
1623                         },
1624                         wire::Message::Error(msg) => {
1625                                 log_debug!(logger, "Got Err message from {}: {}", log_pubkey!(their_node_id), PrintableString(&msg.data));
1626                                 self.message_handler.chan_handler.handle_error(&their_node_id, &msg);
1627                                 if msg.channel_id.is_zero() {
1628                                         return Err(PeerHandleError { }.into());
1629                                 }
1630                         },
1631                         wire::Message::Warning(msg) => {
1632                                 log_debug!(logger, "Got warning message from {}: {}", log_pubkey!(their_node_id), PrintableString(&msg.data));
1633                         },
1634
1635                         wire::Message::Ping(msg) => {
1636                                 if msg.ponglen < 65532 {
1637                                         let resp = msgs::Pong { byteslen: msg.ponglen };
1638                                         self.enqueue_message(&mut *peer_mutex.lock().unwrap(), &resp);
1639                                 }
1640                         },
1641                         wire::Message::Pong(_msg) => {
1642                                 let mut peer_lock = peer_mutex.lock().unwrap();
1643                                 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1644                                 peer_lock.msgs_sent_since_pong = 0;
1645                         },
1646
1647                         // Channel messages:
1648                         wire::Message::OpenChannel(msg) => {
1649                                 self.message_handler.chan_handler.handle_open_channel(&their_node_id, &msg);
1650                         },
1651                         wire::Message::OpenChannelV2(msg) => {
1652                                 self.message_handler.chan_handler.handle_open_channel_v2(&their_node_id, &msg);
1653                         },
1654                         wire::Message::AcceptChannel(msg) => {
1655                                 self.message_handler.chan_handler.handle_accept_channel(&their_node_id, &msg);
1656                         },
1657                         wire::Message::AcceptChannelV2(msg) => {
1658                                 self.message_handler.chan_handler.handle_accept_channel_v2(&their_node_id, &msg);
1659                         },
1660
1661                         wire::Message::FundingCreated(msg) => {
1662                                 self.message_handler.chan_handler.handle_funding_created(&their_node_id, &msg);
1663                         },
1664                         wire::Message::FundingSigned(msg) => {
1665                                 self.message_handler.chan_handler.handle_funding_signed(&their_node_id, &msg);
1666                         },
1667                         wire::Message::ChannelReady(msg) => {
1668                                 self.message_handler.chan_handler.handle_channel_ready(&their_node_id, &msg);
1669                         },
1670
1671                         // Quiescence messages:
1672                         wire::Message::Stfu(msg) => {
1673                                 self.message_handler.chan_handler.handle_stfu(&their_node_id, &msg);
1674                         }
1675
1676                         // Splicing messages:
1677                         wire::Message::Splice(msg) => {
1678                                 self.message_handler.chan_handler.handle_splice(&their_node_id, &msg);
1679                         }
1680                         wire::Message::SpliceAck(msg) => {
1681                                 self.message_handler.chan_handler.handle_splice_ack(&their_node_id, &msg);
1682                         }
1683                         wire::Message::SpliceLocked(msg) => {
1684                                 self.message_handler.chan_handler.handle_splice_locked(&their_node_id, &msg);
1685                         }
1686
1687                         // Interactive transaction construction messages:
1688                         wire::Message::TxAddInput(msg) => {
1689                                 self.message_handler.chan_handler.handle_tx_add_input(&their_node_id, &msg);
1690                         },
1691                         wire::Message::TxAddOutput(msg) => {
1692                                 self.message_handler.chan_handler.handle_tx_add_output(&their_node_id, &msg);
1693                         },
1694                         wire::Message::TxRemoveInput(msg) => {
1695                                 self.message_handler.chan_handler.handle_tx_remove_input(&their_node_id, &msg);
1696                         },
1697                         wire::Message::TxRemoveOutput(msg) => {
1698                                 self.message_handler.chan_handler.handle_tx_remove_output(&their_node_id, &msg);
1699                         },
1700                         wire::Message::TxComplete(msg) => {
1701                                 self.message_handler.chan_handler.handle_tx_complete(&their_node_id, &msg);
1702                         },
1703                         wire::Message::TxSignatures(msg) => {
1704                                 self.message_handler.chan_handler.handle_tx_signatures(&their_node_id, &msg);
1705                         },
1706                         wire::Message::TxInitRbf(msg) => {
1707                                 self.message_handler.chan_handler.handle_tx_init_rbf(&their_node_id, &msg);
1708                         },
1709                         wire::Message::TxAckRbf(msg) => {
1710                                 self.message_handler.chan_handler.handle_tx_ack_rbf(&their_node_id, &msg);
1711                         },
1712                         wire::Message::TxAbort(msg) => {
1713                                 self.message_handler.chan_handler.handle_tx_abort(&their_node_id, &msg);
1714                         }
1715
1716                         wire::Message::Shutdown(msg) => {
1717                                 self.message_handler.chan_handler.handle_shutdown(&their_node_id, &msg);
1718                         },
1719                         wire::Message::ClosingSigned(msg) => {
1720                                 self.message_handler.chan_handler.handle_closing_signed(&their_node_id, &msg);
1721                         },
1722
1723                         // Commitment messages:
1724                         wire::Message::UpdateAddHTLC(msg) => {
1725                                 self.message_handler.chan_handler.handle_update_add_htlc(&their_node_id, &msg);
1726                         },
1727                         wire::Message::UpdateFulfillHTLC(msg) => {
1728                                 self.message_handler.chan_handler.handle_update_fulfill_htlc(&their_node_id, &msg);
1729                         },
1730                         wire::Message::UpdateFailHTLC(msg) => {
1731                                 self.message_handler.chan_handler.handle_update_fail_htlc(&their_node_id, &msg);
1732                         },
1733                         wire::Message::UpdateFailMalformedHTLC(msg) => {
1734                                 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&their_node_id, &msg);
1735                         },
1736
1737                         wire::Message::CommitmentSigned(msg) => {
1738                                 self.message_handler.chan_handler.handle_commitment_signed(&their_node_id, &msg);
1739                         },
1740                         wire::Message::RevokeAndACK(msg) => {
1741                                 self.message_handler.chan_handler.handle_revoke_and_ack(&their_node_id, &msg);
1742                         },
1743                         wire::Message::UpdateFee(msg) => {
1744                                 self.message_handler.chan_handler.handle_update_fee(&their_node_id, &msg);
1745                         },
1746                         wire::Message::ChannelReestablish(msg) => {
1747                                 self.message_handler.chan_handler.handle_channel_reestablish(&their_node_id, &msg);
1748                         },
1749
1750                         // Routing messages:
1751                         wire::Message::AnnouncementSignatures(msg) => {
1752                                 self.message_handler.chan_handler.handle_announcement_signatures(&their_node_id, &msg);
1753                         },
1754                         wire::Message::ChannelAnnouncement(msg) => {
1755                                 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1756                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1757                                         should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1758                                 }
1759                                 self.update_gossip_backlogged();
1760                         },
1761                         wire::Message::NodeAnnouncement(msg) => {
1762                                 if self.message_handler.route_handler.handle_node_announcement(&msg)
1763                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1764                                         should_forward = Some(wire::Message::NodeAnnouncement(msg));
1765                                 }
1766                                 self.update_gossip_backlogged();
1767                         },
1768                         wire::Message::ChannelUpdate(msg) => {
1769                                 self.message_handler.chan_handler.handle_channel_update(&their_node_id, &msg);
1770                                 if self.message_handler.route_handler.handle_channel_update(&msg)
1771                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1772                                         should_forward = Some(wire::Message::ChannelUpdate(msg));
1773                                 }
1774                                 self.update_gossip_backlogged();
1775                         },
1776                         wire::Message::QueryShortChannelIds(msg) => {
1777                                 self.message_handler.route_handler.handle_query_short_channel_ids(&their_node_id, msg)?;
1778                         },
1779                         wire::Message::ReplyShortChannelIdsEnd(msg) => {
1780                                 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&their_node_id, msg)?;
1781                         },
1782                         wire::Message::QueryChannelRange(msg) => {
1783                                 self.message_handler.route_handler.handle_query_channel_range(&their_node_id, msg)?;
1784                         },
1785                         wire::Message::ReplyChannelRange(msg) => {
1786                                 self.message_handler.route_handler.handle_reply_channel_range(&their_node_id, msg)?;
1787                         },
1788
1789                         // Onion message:
1790                         wire::Message::OnionMessage(msg) => {
1791                                 self.message_handler.onion_message_handler.handle_onion_message(&their_node_id, &msg);
1792                         },
1793
1794                         // Unknown messages:
1795                         wire::Message::Unknown(type_id) if message.is_even() => {
1796                                 log_debug!(logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1797                                 return Err(PeerHandleError { }.into());
1798                         },
1799                         wire::Message::Unknown(type_id) => {
1800                                 log_trace!(logger, "Received unknown odd message of type {}, ignoring", type_id);
1801                         },
1802                         wire::Message::Custom(custom) => {
1803                                 self.message_handler.custom_message_handler.handle_custom_message(custom, &their_node_id)?;
1804                         },
1805                 };
1806                 Ok(should_forward)
1807         }
1808
1809         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>) {
1810                 match msg {
1811                         wire::Message::ChannelAnnouncement(ref msg) => {
1812                                 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1813                                 let encoded_msg = encode_msg!(msg);
1814
1815                                 for (_, peer_mutex) in peers.iter() {
1816                                         let mut peer = peer_mutex.lock().unwrap();
1817                                         let logger = WithContext::from(&self.logger, Some(peer.their_node_id.unwrap().0), None);
1818                                         if !peer.handshake_complete() ||
1819                                                         !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1820                                                 continue
1821                                         }
1822                                         debug_assert!(peer.their_node_id.is_some());
1823                                         debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1824                                         if peer.buffer_full_drop_gossip_broadcast() {
1825                                                 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1826                                                 continue;
1827                                         }
1828                                         if let Some((_, their_node_id)) = peer.their_node_id {
1829                                                 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
1830                                                         continue;
1831                                                 }
1832                                         }
1833                                         if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1834                                                 continue;
1835                                         }
1836                                         self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
1837                                 }
1838                         },
1839                         wire::Message::NodeAnnouncement(ref msg) => {
1840                                 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1841                                 let encoded_msg = encode_msg!(msg);
1842
1843                                 for (_, peer_mutex) in peers.iter() {
1844                                         let mut peer = peer_mutex.lock().unwrap();
1845                                         let logger = WithContext::from(&self.logger, Some(peer.their_node_id.unwrap().0), None);
1846                                         if !peer.handshake_complete() ||
1847                                                         !peer.should_forward_node_announcement(msg.contents.node_id) {
1848                                                 continue
1849                                         }
1850                                         debug_assert!(peer.their_node_id.is_some());
1851                                         debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1852                                         if peer.buffer_full_drop_gossip_broadcast() {
1853                                                 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1854                                                 continue;
1855                                         }
1856                                         if let Some((_, their_node_id)) = peer.their_node_id {
1857                                                 if their_node_id == msg.contents.node_id {
1858                                                         continue;
1859                                                 }
1860                                         }
1861                                         if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1862                                                 continue;
1863                                         }
1864                                         self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
1865                                 }
1866                         },
1867                         wire::Message::ChannelUpdate(ref msg) => {
1868                                 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1869                                 let encoded_msg = encode_msg!(msg);
1870
1871                                 for (_, peer_mutex) in peers.iter() {
1872                                         let mut peer = peer_mutex.lock().unwrap();
1873                                         let logger = WithContext::from(&self.logger, Some(peer.their_node_id.unwrap().0), None);
1874                                         if !peer.handshake_complete() ||
1875                                                         !peer.should_forward_channel_announcement(msg.contents.short_channel_id)  {
1876                                                 continue
1877                                         }
1878                                         debug_assert!(peer.their_node_id.is_some());
1879                                         debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1880                                         if peer.buffer_full_drop_gossip_broadcast() {
1881                                                 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1882                                                 continue;
1883                                         }
1884                                         if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1885                                                 continue;
1886                                         }
1887                                         self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
1888                                 }
1889                         },
1890                         _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1891                 }
1892         }
1893
1894         /// Checks for any events generated by our handlers and processes them. Includes sending most
1895         /// response messages as well as messages generated by calls to handler functions directly (eg
1896         /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1897         ///
1898         /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1899         /// issues!
1900         ///
1901         /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
1902         /// or one of the other clients provided in our language bindings.
1903         ///
1904         /// Note that if there are any other calls to this function waiting on lock(s) this may return
1905         /// without doing any work. All available events that need handling will be handled before the
1906         /// other calls return.
1907         ///
1908         /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1909         /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1910         /// [`send_data`]: SocketDescriptor::send_data
1911         pub fn process_events(&self) {
1912                 if self.event_processing_state.fetch_add(1, Ordering::AcqRel) > 0 {
1913                         // If we're not the first event processor to get here, just return early, the increment
1914                         // we just did will be treated as "go around again" at the end.
1915                         return;
1916                 }
1917
1918                 loop {
1919                         self.update_gossip_backlogged();
1920                         let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
1921
1922                         let mut peers_to_disconnect = HashMap::new();
1923
1924                         {
1925                                 let peers_lock = self.peers.read().unwrap();
1926
1927                                 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
1928                                 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
1929
1930                                 let peers = &*peers_lock;
1931                                 macro_rules! get_peer_for_forwarding {
1932                                         ($node_id: expr) => {
1933                                                 {
1934                                                         if peers_to_disconnect.get($node_id).is_some() {
1935                                                                 // If we've "disconnected" this peer, do not send to it.
1936                                                                 continue;
1937                                                         }
1938                                                         let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().get($node_id).cloned();
1939                                                         match descriptor_opt {
1940                                                                 Some(descriptor) => match peers.get(&descriptor) {
1941                                                                         Some(peer_mutex) => {
1942                                                                                 let peer_lock = peer_mutex.lock().unwrap();
1943                                                                                 if !peer_lock.handshake_complete() {
1944                                                                                         continue;
1945                                                                                 }
1946                                                                                 peer_lock
1947                                                                         },
1948                                                                         None => {
1949                                                                                 debug_assert!(false, "Inconsistent peers set state!");
1950                                                                                 continue;
1951                                                                         }
1952                                                                 },
1953                                                                 None => {
1954                                                                         continue;
1955                                                                 },
1956                                                         }
1957                                                 }
1958                                         }
1959                                 }
1960                                 for event in events_generated.drain(..) {
1961                                         match event {
1962                                                 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1963                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.temporary_channel_id)), "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1964                                                                         log_pubkey!(node_id),
1965                                                                         &msg.temporary_channel_id);
1966                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1967                                                 },
1968                                                 MessageSendEvent::SendAcceptChannelV2 { ref node_id, ref msg } => {
1969                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.temporary_channel_id)), "Handling SendAcceptChannelV2 event in peer_handler for node {} for channel {}",
1970                                                                         log_pubkey!(node_id),
1971                                                                         &msg.temporary_channel_id);
1972                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1973                                                 },
1974                                                 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1975                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.temporary_channel_id)), "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
1976                                                                         log_pubkey!(node_id),
1977                                                                         &msg.temporary_channel_id);
1978                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1979                                                 },
1980                                                 MessageSendEvent::SendOpenChannelV2 { ref node_id, ref msg } => {
1981                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.temporary_channel_id)), "Handling SendOpenChannelV2 event in peer_handler for node {} for channel {}",
1982                                                                         log_pubkey!(node_id),
1983                                                                         &msg.temporary_channel_id);
1984                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1985                                                 },
1986                                                 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
1987                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.temporary_channel_id)), "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
1988                                                                         log_pubkey!(node_id),
1989                                                                         &msg.temporary_channel_id,
1990                                                                         log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
1991                                                         // TODO: If the peer is gone we should generate a DiscardFunding event
1992                                                         // indicating to the wallet that they should just throw away this funding transaction
1993                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1994                                                 },
1995                                                 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
1996                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
1997                                                                         log_pubkey!(node_id),
1998                                                                         &msg.channel_id);
1999                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2000                                                 },
2001                                                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
2002                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendChannelReady event in peer_handler for node {} for channel {}",
2003                                                                         log_pubkey!(node_id),
2004                                                                         &msg.channel_id);
2005                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2006                                                 },
2007                                                 MessageSendEvent::SendStfu { ref node_id, ref msg} => {
2008                                                         log_debug!(self.logger, "Handling SendStfu event in peer_handler for node {} for channel {}",
2009                                                                         log_pubkey!(node_id),
2010                                                                         &msg.channel_id);
2011                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2012                                                 }
2013                                                 MessageSendEvent::SendSplice { ref node_id, ref msg} => {
2014                                                         log_debug!(self.logger, "Handling SendSplice event in peer_handler for node {} for channel {}",
2015                                                                         log_pubkey!(node_id),
2016                                                                         &msg.channel_id);
2017                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2018                                                 }
2019                                                 MessageSendEvent::SendSpliceAck { ref node_id, ref msg} => {
2020                                                         log_debug!(self.logger, "Handling SendSpliceAck event in peer_handler for node {} for channel {}",
2021                                                                         log_pubkey!(node_id),
2022                                                                         &msg.channel_id);
2023                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2024                                                 }
2025                                                 MessageSendEvent::SendSpliceLocked { ref node_id, ref msg} => {
2026                                                         log_debug!(self.logger, "Handling SendSpliceLocked event in peer_handler for node {} for channel {}",
2027                                                                         log_pubkey!(node_id),
2028                                                                         &msg.channel_id);
2029                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2030                                                 }
2031                                                 MessageSendEvent::SendTxAddInput { ref node_id, ref msg } => {
2032                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAddInput event in peer_handler for node {} for channel {}",
2033                                                                         log_pubkey!(node_id),
2034                                                                         &msg.channel_id);
2035                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2036                                                 },
2037                                                 MessageSendEvent::SendTxAddOutput { ref node_id, ref msg } => {
2038                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAddOutput event in peer_handler for node {} for channel {}",
2039                                                                         log_pubkey!(node_id),
2040                                                                         &msg.channel_id);
2041                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2042                                                 },
2043                                                 MessageSendEvent::SendTxRemoveInput { ref node_id, ref msg } => {
2044                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxRemoveInput event in peer_handler for node {} for channel {}",
2045                                                                         log_pubkey!(node_id),
2046                                                                         &msg.channel_id);
2047                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2048                                                 },
2049                                                 MessageSendEvent::SendTxRemoveOutput { ref node_id, ref msg } => {
2050                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxRemoveOutput event in peer_handler for node {} for channel {}",
2051                                                                         log_pubkey!(node_id),
2052                                                                         &msg.channel_id);
2053                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2054                                                 },
2055                                                 MessageSendEvent::SendTxComplete { ref node_id, ref msg } => {
2056                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxComplete event in peer_handler for node {} for channel {}",
2057                                                                         log_pubkey!(node_id),
2058                                                                         &msg.channel_id);
2059                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2060                                                 },
2061                                                 MessageSendEvent::SendTxSignatures { ref node_id, ref msg } => {
2062                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxSignatures event in peer_handler for node {} for channel {}",
2063                                                                         log_pubkey!(node_id),
2064                                                                         &msg.channel_id);
2065                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2066                                                 },
2067                                                 MessageSendEvent::SendTxInitRbf { ref node_id, ref msg } => {
2068                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxInitRbf event in peer_handler for node {} for channel {}",
2069                                                                         log_pubkey!(node_id),
2070                                                                         &msg.channel_id);
2071                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2072                                                 },
2073                                                 MessageSendEvent::SendTxAckRbf { ref node_id, ref msg } => {
2074                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAckRbf event in peer_handler for node {} for channel {}",
2075                                                                         log_pubkey!(node_id),
2076                                                                         &msg.channel_id);
2077                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2078                                                 },
2079                                                 MessageSendEvent::SendTxAbort { ref node_id, ref msg } => {
2080                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAbort event in peer_handler for node {} for channel {}",
2081                                                                         log_pubkey!(node_id),
2082                                                                         &msg.channel_id);
2083                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2084                                                 },
2085                                                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
2086                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
2087                                                                         log_pubkey!(node_id),
2088                                                                         &msg.channel_id);
2089                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2090                                                 },
2091                                                 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 } } => {
2092                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(commitment_signed.channel_id)), "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
2093                                                                         log_pubkey!(node_id),
2094                                                                         update_add_htlcs.len(),
2095                                                                         update_fulfill_htlcs.len(),
2096                                                                         update_fail_htlcs.len(),
2097                                                                         &commitment_signed.channel_id);
2098                                                         let mut peer = get_peer_for_forwarding!(node_id);
2099                                                         for msg in update_add_htlcs {
2100                                                                 self.enqueue_message(&mut *peer, msg);
2101                                                         }
2102                                                         for msg in update_fulfill_htlcs {
2103                                                                 self.enqueue_message(&mut *peer, msg);
2104                                                         }
2105                                                         for msg in update_fail_htlcs {
2106                                                                 self.enqueue_message(&mut *peer, msg);
2107                                                         }
2108                                                         for msg in update_fail_malformed_htlcs {
2109                                                                 self.enqueue_message(&mut *peer, msg);
2110                                                         }
2111                                                         if let &Some(ref msg) = update_fee {
2112                                                                 self.enqueue_message(&mut *peer, msg);
2113                                                         }
2114                                                         self.enqueue_message(&mut *peer, commitment_signed);
2115                                                 },
2116                                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2117                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
2118                                                                         log_pubkey!(node_id),
2119                                                                         &msg.channel_id);
2120                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2121                                                 },
2122                                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
2123                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
2124                                                                         log_pubkey!(node_id),
2125                                                                         &msg.channel_id);
2126                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2127                                                 },
2128                                                 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
2129                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling Shutdown event in peer_handler for node {} for channel {}",
2130                                                                         log_pubkey!(node_id),
2131                                                                         &msg.channel_id);
2132                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2133                                                 },
2134                                                 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
2135                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
2136                                                                         log_pubkey!(node_id),
2137                                                                         &msg.channel_id);
2138                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2139                                                 },
2140                                                 MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, ref update_msg } => {
2141                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), None), "Handling SendChannelAnnouncement event in peer_handler for node {} for short channel id {}",
2142                                                                         log_pubkey!(node_id),
2143                                                                         msg.contents.short_channel_id);
2144                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2145                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), update_msg);
2146                                                 },
2147                                                 MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
2148                                                         log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
2149                                                         match self.message_handler.route_handler.handle_channel_announcement(&msg) {
2150                                                                 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2151                                                                         self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
2152                                                                 _ => {},
2153                                                         }
2154                                                         if let Some(msg) = update_msg {
2155                                                                 match self.message_handler.route_handler.handle_channel_update(&msg) {
2156                                                                         Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2157                                                                                 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2158                                                                         _ => {},
2159                                                                 }
2160                                                         }
2161                                                 },
2162                                                 MessageSendEvent::BroadcastChannelUpdate { msg } => {
2163                                                         log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for contents {:?}", msg.contents);
2164                                                         match self.message_handler.route_handler.handle_channel_update(&msg) {
2165                                                                 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2166                                                                         self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2167                                                                 _ => {},
2168                                                         }
2169                                                 },
2170                                                 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
2171                                                         log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler for node {}", msg.contents.node_id);
2172                                                         match self.message_handler.route_handler.handle_node_announcement(&msg) {
2173                                                                 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2174                                                                         self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None),
2175                                                                 _ => {},
2176                                                         }
2177                                                 },
2178                                                 MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
2179                                                         log_trace!(WithContext::from(&self.logger, Some(*node_id), None), "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
2180                                                                         log_pubkey!(node_id), msg.contents.short_channel_id);
2181                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2182                                                 },
2183                                                 MessageSendEvent::HandleError { node_id, action } => {
2184                                                         let logger = WithContext::from(&self.logger, Some(node_id), None);
2185                                                         match action {
2186                                                                 msgs::ErrorAction::DisconnectPeer { msg } => {
2187                                                                         if let Some(msg) = msg.as_ref() {
2188                                                                                 log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2189                                                                                         log_pubkey!(node_id), msg.data);
2190                                                                         } else {
2191                                                                                 log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {}",
2192                                                                                         log_pubkey!(node_id));
2193                                                                         }
2194                                                                         // We do not have the peers write lock, so we just store that we're
2195                                                                         // about to disconenct the peer and do it after we finish
2196                                                                         // processing most messages.
2197                                                                         let msg = msg.map(|msg| wire::Message::<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>::Error(msg));
2198                                                                         peers_to_disconnect.insert(node_id, msg);
2199                                                                 },
2200                                                                 msgs::ErrorAction::DisconnectPeerWithWarning { msg } => {
2201                                                                         log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2202                                                                                 log_pubkey!(node_id), msg.data);
2203                                                                         // We do not have the peers write lock, so we just store that we're
2204                                                                         // about to disconenct the peer and do it after we finish
2205                                                                         // processing most messages.
2206                                                                         peers_to_disconnect.insert(node_id, Some(wire::Message::Warning(msg)));
2207                                                                 },
2208                                                                 msgs::ErrorAction::IgnoreAndLog(level) => {
2209                                                                         log_given_level!(logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2210                                                                 },
2211                                                                 msgs::ErrorAction::IgnoreDuplicateGossip => {},
2212                                                                 msgs::ErrorAction::IgnoreError => {
2213                                                                                 log_debug!(logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2214                                                                         },
2215                                                                 msgs::ErrorAction::SendErrorMessage { ref msg } => {
2216                                                                         log_trace!(logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
2217                                                                                         log_pubkey!(node_id),
2218                                                                                         msg.data);
2219                                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2220                                                                 },
2221                                                                 msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
2222                                                                         log_given_level!(logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
2223                                                                                         log_pubkey!(node_id),
2224                                                                                         msg.data);
2225                                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2226                                                                 },
2227                                                         }
2228                                                 },
2229                                                 MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
2230                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2231                                                 },
2232                                                 MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
2233                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2234                                                 }
2235                                                 MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
2236                                                         log_gossip!(WithContext::from(&self.logger, Some(*node_id), None), "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
2237                                                                 log_pubkey!(node_id),
2238                                                                 msg.short_channel_ids.len(),
2239                                                                 msg.first_blocknum,
2240                                                                 msg.number_of_blocks,
2241                                                                 msg.sync_complete);
2242                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2243                                                 }
2244                                                 MessageSendEvent::SendGossipTimestampFilter { ref node_id, ref msg } => {
2245                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2246                                                 }
2247                                         }
2248                                 }
2249
2250                                 for (node_id, msg) in self.message_handler.custom_message_handler.get_and_clear_pending_msg() {
2251                                         if peers_to_disconnect.get(&node_id).is_some() { continue; }
2252                                         self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), &msg);
2253                                 }
2254
2255                                 for (descriptor, peer_mutex) in peers.iter() {
2256                                         let mut peer = peer_mutex.lock().unwrap();
2257                                         if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2258                                         self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer, flush_read_disabled);
2259                                 }
2260                         }
2261                         if !peers_to_disconnect.is_empty() {
2262                                 let mut peers_lock = self.peers.write().unwrap();
2263                                 let peers = &mut *peers_lock;
2264                                 for (node_id, msg) in peers_to_disconnect.drain() {
2265                                         // Note that since we are holding the peers *write* lock we can
2266                                         // remove from node_id_to_descriptor immediately (as no other
2267                                         // thread can be holding the peer lock if we have the global write
2268                                         // lock).
2269
2270                                         let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2271                                         if let Some(mut descriptor) = descriptor_opt {
2272                                                 if let Some(peer_mutex) = peers.remove(&descriptor) {
2273                                                         let mut peer = peer_mutex.lock().unwrap();
2274                                                         if let Some(msg) = msg {
2275                                                                 self.enqueue_message(&mut *peer, &msg);
2276                                                                 // This isn't guaranteed to work, but if there is enough free
2277                                                                 // room in the send buffer, put the error message there...
2278                                                                 self.do_attempt_write_data(&mut descriptor, &mut *peer, false);
2279                                                         }
2280                                                         self.do_disconnect(descriptor, &*peer, "DisconnectPeer HandleError");
2281                                                 } else { debug_assert!(false, "Missing connection for peer"); }
2282                                         }
2283                                 }
2284                         }
2285
2286                         if self.event_processing_state.fetch_sub(1, Ordering::AcqRel) != 1 {
2287                                 // If another thread incremented the state while we were running we should go
2288                                 // around again, but only once.
2289                                 self.event_processing_state.store(1, Ordering::Release);
2290                                 continue;
2291                         }
2292                         break;
2293                 }
2294         }
2295
2296         /// Indicates that the given socket descriptor's connection is now closed.
2297         pub fn socket_disconnected(&self, descriptor: &Descriptor) {
2298                 self.disconnect_event_internal(descriptor);
2299         }
2300
2301         fn do_disconnect(&self, mut descriptor: Descriptor, peer: &Peer, reason: &'static str) {
2302                 if !peer.handshake_complete() {
2303                         log_trace!(self.logger, "Disconnecting peer which hasn't completed handshake due to {}", reason);
2304                         descriptor.disconnect_socket();
2305                         return;
2306                 }
2307
2308                 debug_assert!(peer.their_node_id.is_some());
2309                 if let Some((node_id, _)) = peer.their_node_id {
2310                         log_trace!(WithContext::from(&self.logger, Some(node_id), None), "Disconnecting peer with id {} due to {}", node_id, reason);
2311                         self.message_handler.chan_handler.peer_disconnected(&node_id);
2312                         self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2313                 }
2314                 descriptor.disconnect_socket();
2315         }
2316
2317         fn disconnect_event_internal(&self, descriptor: &Descriptor) {
2318                 let mut peers = self.peers.write().unwrap();
2319                 let peer_option = peers.remove(descriptor);
2320                 match peer_option {
2321                         None => {
2322                                 // This is most likely a simple race condition where the user found that the socket
2323                                 // was disconnected, then we told the user to `disconnect_socket()`, then they
2324                                 // called this method. Either way we're disconnected, return.
2325                         },
2326                         Some(peer_lock) => {
2327                                 let peer = peer_lock.lock().unwrap();
2328                                 if let Some((node_id, _)) = peer.their_node_id {
2329                                         log_trace!(WithContext::from(&self.logger, Some(node_id), None), "Handling disconnection of peer {}", log_pubkey!(node_id));
2330                                         let removed = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2331                                         debug_assert!(removed.is_some(), "descriptor maps should be consistent");
2332                                         if !peer.handshake_complete() { return; }
2333                                         self.message_handler.chan_handler.peer_disconnected(&node_id);
2334                                         self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2335                                 }
2336                         }
2337                 };
2338         }
2339
2340         /// Disconnect a peer given its node id.
2341         ///
2342         /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
2343         /// peer. Thus, be very careful about reentrancy issues.
2344         ///
2345         /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
2346         pub fn disconnect_by_node_id(&self, node_id: PublicKey) {
2347                 let mut peers_lock = self.peers.write().unwrap();
2348                 if let Some(descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
2349                         let peer_opt = peers_lock.remove(&descriptor);
2350                         if let Some(peer_mutex) = peer_opt {
2351                                 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request");
2352                         } else { debug_assert!(false, "node_id_to_descriptor thought we had a peer"); }
2353                 }
2354         }
2355
2356         /// Disconnects all currently-connected peers. This is useful on platforms where there may be
2357         /// an indication that TCP sockets have stalled even if we weren't around to time them out
2358         /// using regular ping/pongs.
2359         pub fn disconnect_all_peers(&self) {
2360                 let mut peers_lock = self.peers.write().unwrap();
2361                 self.node_id_to_descriptor.lock().unwrap().clear();
2362                 let peers = &mut *peers_lock;
2363                 for (descriptor, peer_mutex) in peers.drain() {
2364                         self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request to disconnect all peers");
2365                 }
2366         }
2367
2368         /// This is called when we're blocked on sending additional gossip messages until we receive a
2369         /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
2370         /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
2371         fn maybe_send_extra_ping(&self, peer: &mut Peer) {
2372                 if peer.awaiting_pong_timer_tick_intervals == 0 {
2373                         peer.awaiting_pong_timer_tick_intervals = -1;
2374                         let ping = msgs::Ping {
2375                                 ponglen: 0,
2376                                 byteslen: 64,
2377                         };
2378                         self.enqueue_message(peer, &ping);
2379                 }
2380         }
2381
2382         /// Send pings to each peer and disconnect those which did not respond to the last round of
2383         /// pings.
2384         ///
2385         /// This may be called on any timescale you want, however, roughly once every ten seconds is
2386         /// preferred. The call rate determines both how often we send a ping to our peers and how much
2387         /// time they have to respond before we disconnect them.
2388         ///
2389         /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
2390         /// issues!
2391         ///
2392         /// [`send_data`]: SocketDescriptor::send_data
2393         pub fn timer_tick_occurred(&self) {
2394                 let mut descriptors_needing_disconnect = Vec::new();
2395                 {
2396                         let peers_lock = self.peers.read().unwrap();
2397
2398                         self.update_gossip_backlogged();
2399                         let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
2400
2401                         for (descriptor, peer_mutex) in peers_lock.iter() {
2402                                 let mut peer = peer_mutex.lock().unwrap();
2403                                 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2404
2405                                 if !peer.handshake_complete() {
2406                                         // The peer needs to complete its handshake before we can exchange messages. We
2407                                         // give peers one timer tick to complete handshake, reusing
2408                                         // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
2409                                         // for handshake completion.
2410                                         if peer.awaiting_pong_timer_tick_intervals != 0 {
2411                                                 descriptors_needing_disconnect.push(descriptor.clone());
2412                                         } else {
2413                                                 peer.awaiting_pong_timer_tick_intervals = 1;
2414                                         }
2415                                         continue;
2416                                 }
2417                                 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
2418                                 debug_assert!(peer.their_node_id.is_some());
2419
2420                                 loop { // Used as a `goto` to skip writing a Ping message.
2421                                         if peer.awaiting_pong_timer_tick_intervals == -1 {
2422                                                 // Magic value set in `maybe_send_extra_ping`.
2423                                                 peer.awaiting_pong_timer_tick_intervals = 1;
2424                                                 peer.received_message_since_timer_tick = false;
2425                                                 break;
2426                                         }
2427
2428                                         if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
2429                                                 || peer.awaiting_pong_timer_tick_intervals as u64 >
2430                                                         MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64
2431                                         {
2432                                                 descriptors_needing_disconnect.push(descriptor.clone());
2433                                                 break;
2434                                         }
2435                                         peer.received_message_since_timer_tick = false;
2436
2437                                         if peer.awaiting_pong_timer_tick_intervals > 0 {
2438                                                 peer.awaiting_pong_timer_tick_intervals += 1;
2439                                                 break;
2440                                         }
2441
2442                                         peer.awaiting_pong_timer_tick_intervals = 1;
2443                                         let ping = msgs::Ping {
2444                                                 ponglen: 0,
2445                                                 byteslen: 64,
2446                                         };
2447                                         self.enqueue_message(&mut *peer, &ping);
2448                                         break;
2449                                 }
2450                                 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer, flush_read_disabled);
2451                         }
2452                 }
2453
2454                 if !descriptors_needing_disconnect.is_empty() {
2455                         {
2456                                 let mut peers_lock = self.peers.write().unwrap();
2457                                 for descriptor in descriptors_needing_disconnect {
2458                                         if let Some(peer_mutex) = peers_lock.remove(&descriptor) {
2459                                                 let peer = peer_mutex.lock().unwrap();
2460                                                 if let Some((node_id, _)) = peer.their_node_id {
2461                                                         self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2462                                                 }
2463                                                 self.do_disconnect(descriptor, &*peer, "ping/handshake timeout");
2464                                         }
2465                                 }
2466                         }
2467                 }
2468         }
2469
2470         #[allow(dead_code)]
2471         // Messages of up to 64KB should never end up more than half full with addresses, as that would
2472         // be absurd. We ensure this by checking that at least 100 (our stated public contract on when
2473         // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
2474         // message...
2475         const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (SocketAddress::MAX_LEN as u32 + 1) / 2;
2476         #[deny(const_err)]
2477         #[allow(dead_code)]
2478         // ...by failing to compile if the number of addresses that would be half of a message is
2479         // smaller than 100:
2480         const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 100;
2481
2482         /// Generates a signed node_announcement from the given arguments, sending it to all connected
2483         /// peers. Note that peers will likely ignore this message unless we have at least one public
2484         /// channel which has at least six confirmations on-chain.
2485         ///
2486         /// `rgb` is a node "color" and `alias` is a printable human-readable string to describe this
2487         /// node to humans. They carry no in-protocol meaning.
2488         ///
2489         /// `addresses` represent the set (possibly empty) of socket addresses on which this node
2490         /// accepts incoming connections. These will be included in the node_announcement, publicly
2491         /// tying these addresses together and to this node. If you wish to preserve user privacy,
2492         /// addresses should likely contain only Tor Onion addresses.
2493         ///
2494         /// Panics if `addresses` is absurdly large (more than 100).
2495         ///
2496         /// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events
2497         pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], mut addresses: Vec<SocketAddress>) {
2498                 if addresses.len() > 100 {
2499                         panic!("More than half the message size was taken up by public addresses!");
2500                 }
2501
2502                 // While all existing nodes handle unsorted addresses just fine, the spec requires that
2503                 // addresses be sorted for future compatibility.
2504                 addresses.sort_by_key(|addr| addr.get_id());
2505
2506                 let features = self.message_handler.chan_handler.provided_node_features()
2507                         | self.message_handler.route_handler.provided_node_features()
2508                         | self.message_handler.onion_message_handler.provided_node_features()
2509                         | self.message_handler.custom_message_handler.provided_node_features();
2510                 let announcement = msgs::UnsignedNodeAnnouncement {
2511                         features,
2512                         timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel),
2513                         node_id: NodeId::from_pubkey(&self.node_signer.get_node_id(Recipient::Node).unwrap()),
2514                         rgb,
2515                         alias: NodeAlias(alias),
2516                         addresses,
2517                         excess_address_data: Vec::new(),
2518                         excess_data: Vec::new(),
2519                 };
2520                 let node_announce_sig = match self.node_signer.sign_gossip_message(
2521                         msgs::UnsignedGossipMessage::NodeAnnouncement(&announcement)
2522                 ) {
2523                         Ok(sig) => sig,
2524                         Err(_) => {
2525                                 log_error!(self.logger, "Failed to generate signature for node_announcement");
2526                                 return;
2527                         },
2528                 };
2529
2530                 let msg = msgs::NodeAnnouncement {
2531                         signature: node_announce_sig,
2532                         contents: announcement
2533                 };
2534
2535                 log_debug!(self.logger, "Broadcasting NodeAnnouncement after passing it to our own RoutingMessageHandler.");
2536                 let _ = self.message_handler.route_handler.handle_node_announcement(&msg);
2537                 self.forward_broadcast_msg(&*self.peers.read().unwrap(), &wire::Message::NodeAnnouncement(msg), None);
2538         }
2539 }
2540
2541 fn is_gossip_msg(type_id: u16) -> bool {
2542         match type_id {
2543                 msgs::ChannelAnnouncement::TYPE |
2544                 msgs::ChannelUpdate::TYPE |
2545                 msgs::NodeAnnouncement::TYPE |
2546                 msgs::QueryChannelRange::TYPE |
2547                 msgs::ReplyChannelRange::TYPE |
2548                 msgs::QueryShortChannelIds::TYPE |
2549                 msgs::ReplyShortChannelIdsEnd::TYPE => true,
2550                 _ => false
2551         }
2552 }
2553
2554 #[cfg(test)]
2555 mod tests {
2556         use crate::sign::{NodeSigner, Recipient};
2557         use crate::events;
2558         use crate::io;
2559         use crate::ln::ChannelId;
2560         use crate::ln::features::{InitFeatures, NodeFeatures};
2561         use crate::ln::peer_channel_encryptor::PeerChannelEncryptor;
2562         use crate::ln::peer_handler::{CustomMessageHandler, PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses};
2563         use crate::ln::{msgs, wire};
2564         use crate::ln::msgs::{LightningError, SocketAddress};
2565         use crate::util::test_utils;
2566
2567         use bitcoin::Network;
2568         use bitcoin::blockdata::constants::ChainHash;
2569         use bitcoin::secp256k1::{PublicKey, SecretKey};
2570
2571         use crate::prelude::*;
2572         use crate::sync::{Arc, Mutex};
2573         use core::convert::Infallible;
2574         use core::sync::atomic::{AtomicBool, Ordering};
2575
2576         #[derive(Clone)]
2577         struct FileDescriptor {
2578                 fd: u16,
2579                 outbound_data: Arc<Mutex<Vec<u8>>>,
2580                 disconnect: Arc<AtomicBool>,
2581         }
2582         impl PartialEq for FileDescriptor {
2583                 fn eq(&self, other: &Self) -> bool {
2584                         self.fd == other.fd
2585                 }
2586         }
2587         impl Eq for FileDescriptor { }
2588         impl core::hash::Hash for FileDescriptor {
2589                 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
2590                         self.fd.hash(hasher)
2591                 }
2592         }
2593
2594         impl SocketDescriptor for FileDescriptor {
2595                 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
2596                         self.outbound_data.lock().unwrap().extend_from_slice(data);
2597                         data.len()
2598                 }
2599
2600                 fn disconnect_socket(&mut self) { self.disconnect.store(true, Ordering::Release); }
2601         }
2602
2603         struct PeerManagerCfg {
2604                 chan_handler: test_utils::TestChannelMessageHandler,
2605                 routing_handler: test_utils::TestRoutingMessageHandler,
2606                 custom_handler: TestCustomMessageHandler,
2607                 logger: test_utils::TestLogger,
2608                 node_signer: test_utils::TestNodeSigner,
2609         }
2610
2611         struct TestCustomMessageHandler {
2612                 features: InitFeatures,
2613         }
2614
2615         impl wire::CustomMessageReader for TestCustomMessageHandler {
2616                 type CustomMessage = Infallible;
2617                 fn read<R: io::Read>(&self, _: u16, _: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
2618                         Ok(None)
2619                 }
2620         }
2621
2622         impl CustomMessageHandler for TestCustomMessageHandler {
2623                 fn handle_custom_message(&self, _: Infallible, _: &PublicKey) -> Result<(), LightningError> {
2624                         unreachable!();
2625                 }
2626
2627                 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
2628
2629                 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
2630
2631                 fn provided_init_features(&self, _: &PublicKey) -> InitFeatures {
2632                         self.features.clone()
2633                 }
2634         }
2635
2636         fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2637                 let mut cfgs = Vec::new();
2638                 for i in 0..peer_count {
2639                         let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2640                         let features = {
2641                                 let mut feature_bits = vec![0u8; 33];
2642                                 feature_bits[32] = 0b00000001;
2643                                 InitFeatures::from_le_bytes(feature_bits)
2644                         };
2645                         cfgs.push(
2646                                 PeerManagerCfg{
2647                                         chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2648                                         logger: test_utils::TestLogger::new(),
2649                                         routing_handler: test_utils::TestRoutingMessageHandler::new(),
2650                                         custom_handler: TestCustomMessageHandler { features },
2651                                         node_signer: test_utils::TestNodeSigner::new(node_secret),
2652                                 }
2653                         );
2654                 }
2655
2656                 cfgs
2657         }
2658
2659         fn create_feature_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2660                 let mut cfgs = Vec::new();
2661                 for i in 0..peer_count {
2662                         let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2663                         let features = {
2664                                 let mut feature_bits = vec![0u8; 33 + i + 1];
2665                                 feature_bits[33 + i] = 0b00000001;
2666                                 InitFeatures::from_le_bytes(feature_bits)
2667                         };
2668                         cfgs.push(
2669                                 PeerManagerCfg{
2670                                         chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2671                                         logger: test_utils::TestLogger::new(),
2672                                         routing_handler: test_utils::TestRoutingMessageHandler::new(),
2673                                         custom_handler: TestCustomMessageHandler { features },
2674                                         node_signer: test_utils::TestNodeSigner::new(node_secret),
2675                                 }
2676                         );
2677                 }
2678
2679                 cfgs
2680         }
2681
2682         fn create_chain_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2683                 let mut cfgs = Vec::new();
2684                 for i in 0..peer_count {
2685                         let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2686                         let features = InitFeatures::from_le_bytes(vec![0u8; 33]);
2687                         let network = ChainHash::from(&[i as u8; 32]);
2688                         cfgs.push(
2689                                 PeerManagerCfg{
2690                                         chan_handler: test_utils::TestChannelMessageHandler::new(network),
2691                                         logger: test_utils::TestLogger::new(),
2692                                         routing_handler: test_utils::TestRoutingMessageHandler::new(),
2693                                         custom_handler: TestCustomMessageHandler { features },
2694                                         node_signer: test_utils::TestNodeSigner::new(node_secret),
2695                                 }
2696                         );
2697                 }
2698
2699                 cfgs
2700         }
2701
2702         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>> {
2703                 let mut peers = Vec::new();
2704                 for i in 0..peer_count {
2705                         let ephemeral_bytes = [i as u8; 32];
2706                         let msg_handler = MessageHandler {
2707                                 chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler,
2708                                 onion_message_handler: IgnoringMessageHandler {}, custom_message_handler: &cfgs[i].custom_handler
2709                         };
2710                         let peer = PeerManager::new(msg_handler, 0, &ephemeral_bytes, &cfgs[i].logger, &cfgs[i].node_signer);
2711                         peers.push(peer);
2712                 }
2713
2714                 peers
2715         }
2716
2717         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) {
2718                 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2719                 let mut fd_a = FileDescriptor {
2720                         fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2721                         disconnect: Arc::new(AtomicBool::new(false)),
2722                 };
2723                 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2724                 let id_b = peer_b.node_signer.get_node_id(Recipient::Node).unwrap();
2725                 let mut fd_b = FileDescriptor {
2726                         fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2727                         disconnect: Arc::new(AtomicBool::new(false)),
2728                 };
2729                 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2730                 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2731                 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2732                 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2733                 peer_a.process_events();
2734
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                 peer_b.process_events();
2739                 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2740                 assert_eq!(peer_a.read_event(&mut fd_a, &b_data).unwrap(), false);
2741
2742                 peer_a.process_events();
2743                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2744                 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2745
2746                 assert!(peer_a.get_peer_node_ids().contains(&(id_b, Some(addr_b))));
2747                 assert!(peer_b.get_peer_node_ids().contains(&(id_a, Some(addr_a))));
2748
2749                 (fd_a.clone(), fd_b.clone())
2750         }
2751
2752         #[test]
2753         #[cfg(feature = "std")]
2754         fn fuzz_threaded_connections() {
2755                 // Spawn two threads which repeatedly connect two peers together, leading to "got second
2756                 // connection with peer" disconnections and rapid reconnect. This previously found an issue
2757                 // with our internal map consistency, and is a generally good smoke test of disconnection.
2758                 let cfgs = Arc::new(create_peermgr_cfgs(2));
2759                 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
2760                 let peers = Arc::new(create_network(2, unsafe { &*(&*cfgs as *const _) as &'static _ }));
2761
2762                 let start_time = std::time::Instant::now();
2763                 macro_rules! spawn_thread { ($id: expr) => { {
2764                         let peers = Arc::clone(&peers);
2765                         let cfgs = Arc::clone(&cfgs);
2766                         std::thread::spawn(move || {
2767                                 let mut ctr = 0;
2768                                 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2769                                         let id_a = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
2770                                         let mut fd_a = FileDescriptor {
2771                                                 fd: $id  + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2772                                                 disconnect: Arc::new(AtomicBool::new(false)),
2773                                         };
2774                                         let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2775                                         let mut fd_b = FileDescriptor {
2776                                                 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2777                                                 disconnect: Arc::new(AtomicBool::new(false)),
2778                                         };
2779                                         let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2780                                         let initial_data = peers[1].new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2781                                         peers[0].new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2782                                         if peers[0].read_event(&mut fd_a, &initial_data).is_err() { break; }
2783
2784                                         while start_time.elapsed() < std::time::Duration::from_secs(1) {
2785                                                 peers[0].process_events();
2786                                                 if fd_a.disconnect.load(Ordering::Acquire) { break; }
2787                                                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2788                                                 if peers[1].read_event(&mut fd_b, &a_data).is_err() { break; }
2789
2790                                                 peers[1].process_events();
2791                                                 if fd_b.disconnect.load(Ordering::Acquire) { break; }
2792                                                 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2793                                                 if peers[0].read_event(&mut fd_a, &b_data).is_err() { break; }
2794
2795                                                 cfgs[0].chan_handler.pending_events.lock().unwrap()
2796                                                         .push(crate::events::MessageSendEvent::SendShutdown {
2797                                                                 node_id: peers[1].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                                                 cfgs[1].chan_handler.pending_events.lock().unwrap()
2804                                                         .push(crate::events::MessageSendEvent::SendShutdown {
2805                                                                 node_id: peers[0].node_signer.get_node_id(Recipient::Node).unwrap(),
2806                                                                 msg: msgs::Shutdown {
2807                                                                         channel_id: ChannelId::new_zero(),
2808                                                                         scriptpubkey: bitcoin::ScriptBuf::new(),
2809                                                                 },
2810                                                         });
2811
2812                                                 if ctr % 2 == 0 {
2813                                                         peers[0].timer_tick_occurred();
2814                                                         peers[1].timer_tick_occurred();
2815                                                 }
2816                                         }
2817
2818                                         peers[0].socket_disconnected(&fd_a);
2819                                         peers[1].socket_disconnected(&fd_b);
2820                                         ctr += 1;
2821                                         std::thread::sleep(std::time::Duration::from_micros(1));
2822                                 }
2823                         })
2824                 } } }
2825                 let thrd_a = spawn_thread!(1);
2826                 let thrd_b = spawn_thread!(2);
2827
2828                 thrd_a.join().unwrap();
2829                 thrd_b.join().unwrap();
2830         }
2831
2832         #[test]
2833         fn test_feature_incompatible_peers() {
2834                 let cfgs = create_peermgr_cfgs(2);
2835                 let incompatible_cfgs = create_feature_incompatible_peermgr_cfgs(2);
2836
2837                 let peers = create_network(2, &cfgs);
2838                 let incompatible_peers = create_network(2, &incompatible_cfgs);
2839                 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
2840                 for (peer_a, peer_b) in peer_pairs.iter() {
2841                         let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2842                         let mut fd_a = FileDescriptor {
2843                                 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2844                                 disconnect: Arc::new(AtomicBool::new(false)),
2845                         };
2846                         let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2847                         let mut fd_b = FileDescriptor {
2848                                 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2849                                 disconnect: Arc::new(AtomicBool::new(false)),
2850                         };
2851                         let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2852                         let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2853                         peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2854                         assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2855                         peer_a.process_events();
2856
2857                         let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2858                         assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2859
2860                         peer_b.process_events();
2861                         let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2862
2863                         // Should fail because of unknown required features
2864                         assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
2865                 }
2866         }
2867
2868         #[test]
2869         fn test_chain_incompatible_peers() {
2870                 let cfgs = create_peermgr_cfgs(2);
2871                 let incompatible_cfgs = create_chain_incompatible_peermgr_cfgs(2);
2872
2873                 let peers = create_network(2, &cfgs);
2874                 let incompatible_peers = create_network(2, &incompatible_cfgs);
2875                 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
2876                 for (peer_a, peer_b) in peer_pairs.iter() {
2877                         let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2878                         let mut fd_a = FileDescriptor {
2879                                 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2880                                 disconnect: Arc::new(AtomicBool::new(false)),
2881                         };
2882                         let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2883                         let mut fd_b = FileDescriptor {
2884                                 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2885                                 disconnect: Arc::new(AtomicBool::new(false)),
2886                         };
2887                         let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2888                         let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2889                         peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2890                         assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2891                         peer_a.process_events();
2892
2893                         let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2894                         assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2895
2896                         peer_b.process_events();
2897                         let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2898
2899                         // Should fail because of incompatible chains
2900                         assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
2901                 }
2902         }
2903
2904         #[test]
2905         fn test_disconnect_peer() {
2906                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2907                 // push a DisconnectPeer event to remove the node flagged by id
2908                 let cfgs = create_peermgr_cfgs(2);
2909                 let peers = create_network(2, &cfgs);
2910                 establish_connection(&peers[0], &peers[1]);
2911                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2912
2913                 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
2914                 cfgs[0].chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
2915                         node_id: their_id,
2916                         action: msgs::ErrorAction::DisconnectPeer { msg: None },
2917                 });
2918
2919                 peers[0].process_events();
2920                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2921         }
2922
2923         #[test]
2924         fn test_send_simple_msg() {
2925                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2926                 // push a message from one peer to another.
2927                 let cfgs = create_peermgr_cfgs(2);
2928                 let a_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
2929                 let b_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
2930                 let mut peers = create_network(2, &cfgs);
2931                 let (fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2932                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2933
2934                 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
2935
2936                 let msg = msgs::Shutdown { channel_id: ChannelId::from_bytes([42; 32]), scriptpubkey: bitcoin::ScriptBuf::new() };
2937                 a_chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::SendShutdown {
2938                         node_id: their_id, msg: msg.clone()
2939                 });
2940                 peers[0].message_handler.chan_handler = &a_chan_handler;
2941
2942                 b_chan_handler.expect_receive_msg(wire::Message::Shutdown(msg));
2943                 peers[1].message_handler.chan_handler = &b_chan_handler;
2944
2945                 peers[0].process_events();
2946
2947                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2948                 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2949         }
2950
2951         #[test]
2952         fn test_non_init_first_msg() {
2953                 // Simple test of the first message received over a connection being something other than
2954                 // Init. This results in an immediate disconnection, which previously included a spurious
2955                 // peer_disconnected event handed to event handlers (which would panic in
2956                 // `TestChannelMessageHandler` here).
2957                 let cfgs = create_peermgr_cfgs(2);
2958                 let peers = create_network(2, &cfgs);
2959
2960                 let mut fd_dup = FileDescriptor {
2961                         fd: 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2962                         disconnect: Arc::new(AtomicBool::new(false)),
2963                 };
2964                 let addr_dup = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1003};
2965                 let id_a = cfgs[0].node_signer.get_node_id(Recipient::Node).unwrap();
2966                 peers[0].new_inbound_connection(fd_dup.clone(), Some(addr_dup.clone())).unwrap();
2967
2968                 let mut dup_encryptor = PeerChannelEncryptor::new_outbound(id_a, SecretKey::from_slice(&[42; 32]).unwrap());
2969                 let initial_data = dup_encryptor.get_act_one(&peers[1].secp_ctx);
2970                 assert_eq!(peers[0].read_event(&mut fd_dup, &initial_data).unwrap(), false);
2971                 peers[0].process_events();
2972
2973                 let a_data = fd_dup.outbound_data.lock().unwrap().split_off(0);
2974                 let (act_three, _) =
2975                         dup_encryptor.process_act_two(&a_data[..], &&cfgs[1].node_signer).unwrap();
2976                 assert_eq!(peers[0].read_event(&mut fd_dup, &act_three).unwrap(), false);
2977
2978                 let not_init_msg = msgs::Ping { ponglen: 4, byteslen: 0 };
2979                 let msg_bytes = dup_encryptor.encrypt_message(&not_init_msg);
2980                 assert!(peers[0].read_event(&mut fd_dup, &msg_bytes).is_err());
2981         }
2982
2983         #[test]
2984         fn test_disconnect_all_peer() {
2985                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2986                 // then calls disconnect_all_peers
2987                 let cfgs = create_peermgr_cfgs(2);
2988                 let peers = create_network(2, &cfgs);
2989                 establish_connection(&peers[0], &peers[1]);
2990                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2991
2992                 peers[0].disconnect_all_peers();
2993                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2994         }
2995
2996         #[test]
2997         fn test_timer_tick_occurred() {
2998                 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
2999                 let cfgs = create_peermgr_cfgs(2);
3000                 let peers = create_network(2, &cfgs);
3001                 establish_connection(&peers[0], &peers[1]);
3002                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3003
3004                 // peers[0] awaiting_pong is set to true, but the Peer is still connected
3005                 peers[0].timer_tick_occurred();
3006                 peers[0].process_events();
3007                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3008
3009                 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
3010                 peers[0].timer_tick_occurred();
3011                 peers[0].process_events();
3012                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3013         }
3014
3015         #[test]
3016         fn test_do_attempt_write_data() {
3017                 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
3018                 let cfgs = create_peermgr_cfgs(2);
3019                 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
3020                 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
3021                 let peers = create_network(2, &cfgs);
3022
3023                 // By calling establish_connect, we trigger do_attempt_write_data between
3024                 // the peers. Previously this function would mistakenly enter an infinite loop
3025                 // when there were more channel messages available than could fit into a peer's
3026                 // buffer. This issue would now be detected by this test (because we use custom
3027                 // RoutingMessageHandlers that intentionally return more channel messages
3028                 // than can fit into a peer's buffer).
3029                 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
3030
3031                 // Make each peer to read the messages that the other peer just wrote to them. Note that
3032                 // due to the max-message-before-ping limits this may take a few iterations to complete.
3033                 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
3034                         peers[1].process_events();
3035                         let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3036                         assert!(!a_read_data.is_empty());
3037
3038                         peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
3039                         peers[0].process_events();
3040
3041                         let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3042                         assert!(!b_read_data.is_empty());
3043                         peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
3044
3045                         peers[0].process_events();
3046                         assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
3047                 }
3048
3049                 // Check that each peer has received the expected number of channel updates and channel
3050                 // announcements.
3051                 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
3052                 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
3053                 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
3054                 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
3055         }
3056
3057         #[test]
3058         fn test_handshake_timeout() {
3059                 // Tests that we time out a peer still waiting on handshake completion after a full timer
3060                 // tick.
3061                 let cfgs = create_peermgr_cfgs(2);
3062                 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
3063                 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
3064                 let peers = create_network(2, &cfgs);
3065
3066                 let a_id = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
3067                 let mut fd_a = FileDescriptor {
3068                         fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3069                         disconnect: Arc::new(AtomicBool::new(false)),
3070                 };
3071                 let mut fd_b = FileDescriptor {
3072                         fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3073                         disconnect: Arc::new(AtomicBool::new(false)),
3074                 };
3075                 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
3076                 peers[0].new_inbound_connection(fd_a.clone(), None).unwrap();
3077
3078                 // If we get a single timer tick before completion, that's fine
3079                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3080                 peers[0].timer_tick_occurred();
3081                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3082
3083                 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
3084                 peers[0].process_events();
3085                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3086                 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
3087                 peers[1].process_events();
3088
3089                 // ...but if we get a second timer tick, we should disconnect the peer
3090                 peers[0].timer_tick_occurred();
3091                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3092
3093                 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3094                 assert!(peers[0].read_event(&mut fd_a, &b_data).is_err());
3095         }
3096
3097         #[test]
3098         fn test_filter_addresses(){
3099                 // Tests the filter_addresses function.
3100
3101                 // For (10/8)
3102                 let ip_address = SocketAddress::TcpIpV4{addr: [10, 0, 0, 0], port: 1000};
3103                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3104                 let ip_address = SocketAddress::TcpIpV4{addr: [10, 0, 255, 201], port: 1000};
3105                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3106                 let ip_address = SocketAddress::TcpIpV4{addr: [10, 255, 255, 255], port: 1000};
3107                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3108
3109                 // For (0/8)
3110                 let ip_address = SocketAddress::TcpIpV4{addr: [0, 0, 0, 0], port: 1000};
3111                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3112                 let ip_address = SocketAddress::TcpIpV4{addr: [0, 0, 255, 187], port: 1000};
3113                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3114                 let ip_address = SocketAddress::TcpIpV4{addr: [0, 255, 255, 255], port: 1000};
3115                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3116
3117                 // For (100.64/10)
3118                 let ip_address = SocketAddress::TcpIpV4{addr: [100, 64, 0, 0], port: 1000};
3119                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3120                 let ip_address = SocketAddress::TcpIpV4{addr: [100, 78, 255, 0], port: 1000};
3121                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3122                 let ip_address = SocketAddress::TcpIpV4{addr: [100, 127, 255, 255], port: 1000};
3123                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3124
3125                 // For (127/8)
3126                 let ip_address = SocketAddress::TcpIpV4{addr: [127, 0, 0, 0], port: 1000};
3127                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3128                 let ip_address = SocketAddress::TcpIpV4{addr: [127, 65, 73, 0], port: 1000};
3129                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3130                 let ip_address = SocketAddress::TcpIpV4{addr: [127, 255, 255, 255], port: 1000};
3131                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3132
3133                 // For (169.254/16)
3134                 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 0, 0], port: 1000};
3135                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3136                 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 221, 101], port: 1000};
3137                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3138                 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 255, 255], port: 1000};
3139                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3140
3141                 // For (172.16/12)
3142                 let ip_address = SocketAddress::TcpIpV4{addr: [172, 16, 0, 0], port: 1000};
3143                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3144                 let ip_address = SocketAddress::TcpIpV4{addr: [172, 27, 101, 23], port: 1000};
3145                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3146                 let ip_address = SocketAddress::TcpIpV4{addr: [172, 31, 255, 255], port: 1000};
3147                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3148
3149                 // For (192.168/16)
3150                 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 0, 0], port: 1000};
3151                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3152                 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 205, 159], port: 1000};
3153                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3154                 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 255, 255], port: 1000};
3155                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3156
3157                 // For (192.88.99/24)
3158                 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 0], port: 1000};
3159                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3160                 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 140], port: 1000};
3161                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3162                 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 255], port: 1000};
3163                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3164
3165                 // For other IPv4 addresses
3166                 let ip_address = SocketAddress::TcpIpV4{addr: [188, 255, 99, 0], port: 1000};
3167                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3168                 let ip_address = SocketAddress::TcpIpV4{addr: [123, 8, 129, 14], port: 1000};
3169                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3170                 let ip_address = SocketAddress::TcpIpV4{addr: [2, 88, 9, 255], port: 1000};
3171                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3172
3173                 // For (2000::/3)
3174                 let ip_address = SocketAddress::TcpIpV6{addr: [32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], port: 1000};
3175                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3176                 let ip_address = SocketAddress::TcpIpV6{addr: [45, 34, 209, 190, 0, 123, 55, 34, 0, 0, 3, 27, 201, 0, 0, 0], port: 1000};
3177                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3178                 let ip_address = SocketAddress::TcpIpV6{addr: [63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], port: 1000};
3179                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3180
3181                 // For other IPv6 addresses
3182                 let ip_address = SocketAddress::TcpIpV6{addr: [24, 240, 12, 32, 0, 0, 0, 0, 20, 97, 0, 32, 121, 254, 0, 0], port: 1000};
3183                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3184                 let ip_address = SocketAddress::TcpIpV6{addr: [68, 23, 56, 63, 0, 0, 2, 7, 75, 109, 0, 39, 0, 0, 0, 0], port: 1000};
3185                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3186                 let ip_address = SocketAddress::TcpIpV6{addr: [101, 38, 140, 230, 100, 0, 30, 98, 0, 26, 0, 0, 57, 96, 0, 0], port: 1000};
3187                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3188
3189                 // For (None)
3190                 assert_eq!(filter_addresses(None), None);
3191         }
3192
3193         #[test]
3194         #[cfg(feature = "std")]
3195         fn test_process_events_multithreaded() {
3196                 use std::time::{Duration, Instant};
3197                 // Test that `process_events` getting called on multiple threads doesn't generate too many
3198                 // loop iterations.
3199                 // Each time `process_events` goes around the loop we call
3200                 // `get_and_clear_pending_msg_events`, which we count using the `TestMessageHandler`.
3201                 // Because the loop should go around once more after a call which fails to take the
3202                 // single-threaded lock, if we write zero to the counter before calling `process_events` we
3203                 // should never observe there having been more than 2 loop iterations.
3204                 // Further, because the last thread to exit will call `process_events` before returning, we
3205                 // should always have at least one count at the end.
3206                 let cfg = Arc::new(create_peermgr_cfgs(1));
3207                 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
3208                 let peer = Arc::new(create_network(1, unsafe { &*(&*cfg as *const _) as &'static _ }).pop().unwrap());
3209
3210                 let exit_flag = Arc::new(AtomicBool::new(false));
3211                 macro_rules! spawn_thread { () => { {
3212                         let thread_cfg = Arc::clone(&cfg);
3213                         let thread_peer = Arc::clone(&peer);
3214                         let thread_exit = Arc::clone(&exit_flag);
3215                         std::thread::spawn(move || {
3216                                 while !thread_exit.load(Ordering::Acquire) {
3217                                         thread_cfg[0].chan_handler.message_fetch_counter.store(0, Ordering::Release);
3218                                         thread_peer.process_events();
3219                                         std::thread::sleep(Duration::from_micros(1));
3220                                 }
3221                         })
3222                 } } }
3223
3224                 let thread_a = spawn_thread!();
3225                 let thread_b = spawn_thread!();
3226                 let thread_c = spawn_thread!();
3227
3228                 let start_time = Instant::now();
3229                 while start_time.elapsed() < Duration::from_millis(100) {
3230                         let val = cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire);
3231                         assert!(val <= 2);
3232                         std::thread::yield_now(); // Winblowz seemingly doesn't ever interrupt threads?!
3233                 }
3234
3235                 exit_flag.store(true, Ordering::Release);
3236                 thread_a.join().unwrap();
3237                 thread_b.join().unwrap();
3238                 thread_c.join().unwrap();
3239                 assert!(cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire) >= 1);
3240         }
3241 }