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