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