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