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