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