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