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