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