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