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