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