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