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