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