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