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