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