Merge pull request #2280 from TheBlueMatt/2023-05-event-deadlock
[rust-lightning] / lightning / src / ln / peer_handler.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Top level peer message handling and socket handling logic lives here.
11 //!
12 //! Instead of actually servicing sockets ourselves we require that you implement the
13 //! SocketDescriptor interface and use that to receive actions which you should perform on the
14 //! socket, and call into PeerManager with bytes read from the socket. The PeerManager will then
15 //! call into the provided message handlers (probably a ChannelManager and P2PGossipSync) with
16 //! messages they should handle, and encoding/sending response messages.
17
18 use bitcoin::secp256k1::{self, Secp256k1, SecretKey, PublicKey};
19
20 use crate::sign::{KeysManager, NodeSigner, Recipient};
21 use crate::events::{MessageSendEvent, MessageSendEventsProvider, OnionMessageProvider};
22 use crate::ln::features::{InitFeatures, NodeFeatures};
23 use crate::ln::msgs;
24 use crate::ln::msgs::{ChannelMessageHandler, LightningError, NetAddress, OnionMessageHandler, RoutingMessageHandler};
25 use crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
26 use crate::util::ser::{VecWriter, Writeable, Writer};
27 use crate::ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
28 use crate::ln::wire;
29 use crate::ln::wire::Encode;
30 use crate::onion_message::{CustomOnionMessageContents, CustomOnionMessageHandler, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
31 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, NodeAlias};
32 use crate::util::atomic_counter::AtomicCounter;
33 use crate::util::logger::Logger;
34
35 use crate::prelude::*;
36 use crate::io;
37 use alloc::collections::LinkedList;
38 use crate::sync::{Arc, Mutex, MutexGuard, FairRwLock};
39 use core::sync::atomic::{AtomicBool, AtomicU32, AtomicI32, Ordering};
40 use core::{cmp, hash, fmt, mem};
41 use core::ops::Deref;
42 use core::convert::Infallible;
43 #[cfg(feature = "std")] use std::error;
44
45 use bitcoin::hashes::sha256::Hash as Sha256;
46 use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
47 use bitcoin::hashes::{HashEngine, Hash};
48
49 /// A handler provided to [`PeerManager`] for reading and handling custom messages.
50 ///
51 /// [BOLT 1] specifies a custom message type range for use with experimental or application-specific
52 /// messages. `CustomMessageHandler` allows for user-defined handling of such types. See the
53 /// [`lightning_custom_message`] crate for tools useful in composing more than one custom handler.
54 ///
55 /// [BOLT 1]: https://github.com/lightning/bolts/blob/master/01-messaging.md
56 /// [`lightning_custom_message`]: https://docs.rs/lightning_custom_message/latest/lightning_custom_message
57 pub trait CustomMessageHandler: wire::CustomMessageReader {
58         /// Handles the given message sent from `sender_node_id`, possibly producing messages for
59         /// [`CustomMessageHandler::get_and_clear_pending_msg`] to return and thus for [`PeerManager`]
60         /// to send.
61         fn handle_custom_message(&self, msg: Self::CustomMessage, sender_node_id: &PublicKey) -> Result<(), LightningError>;
62
63         /// Returns the list of pending messages that were generated by the handler, clearing the list
64         /// in the process. Each message is paired with the node id of the intended recipient. If no
65         /// connection to the node exists, then the message is simply not sent.
66         fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)>;
67
68         /// 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 if a second call to
700         /// `process_events` happens while a first call is in progress, one of the two calls needs to
701         /// start from the top to ensure any new messages are also handled.
702         ///
703         /// Because the event handler calls into user code which may block, we don't want to block a
704         /// second thread waiting for another thread to handle events which is then blocked on user
705         /// code, so we store an atomic counter here:
706         ///  * 0 indicates no event processor is running
707         ///  * 1 indicates an event processor is running
708         ///  * > 1 indicates an event processor is running but needs to start again from the top once
709         ///        it finishes as another thread tried to start processing events but returned early.
710         event_processing_state: AtomicI32,
711
712         /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
713         /// value increases strictly since we don't assume access to a time source.
714         last_node_announcement_serial: AtomicU32,
715
716         ephemeral_key_midstate: Sha256Engine,
717
718         peer_counter: AtomicCounter,
719
720         gossip_processing_backlogged: AtomicBool,
721         gossip_processing_backlog_lifted: AtomicBool,
722
723         node_signer: NS,
724
725         logger: L,
726         secp_ctx: Secp256k1<secp256k1::SignOnly>
727 }
728
729 enum MessageHandlingError {
730         PeerHandleError(PeerHandleError),
731         LightningError(LightningError),
732 }
733
734 impl From<PeerHandleError> for MessageHandlingError {
735         fn from(error: PeerHandleError) -> Self {
736                 MessageHandlingError::PeerHandleError(error)
737         }
738 }
739
740 impl From<LightningError> for MessageHandlingError {
741         fn from(error: LightningError) -> Self {
742                 MessageHandlingError::LightningError(error)
743         }
744 }
745
746 macro_rules! encode_msg {
747         ($msg: expr) => {{
748                 let mut buffer = VecWriter(Vec::new());
749                 wire::write($msg, &mut buffer).unwrap();
750                 buffer.0
751         }}
752 }
753
754 impl<Descriptor: SocketDescriptor, CM: Deref, OM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, OM, L, IgnoringMessageHandler, NS> where
755                 CM::Target: ChannelMessageHandler,
756                 OM::Target: OnionMessageHandler,
757                 L::Target: Logger,
758                 NS::Target: NodeSigner {
759         /// Constructs a new `PeerManager` with the given `ChannelMessageHandler` and
760         /// `OnionMessageHandler`. No routing message handler is used and network graph messages are
761         /// ignored.
762         ///
763         /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
764         /// cryptographically secure random bytes.
765         ///
766         /// `current_time` is used as an always-increasing counter that survives across restarts and is
767         /// incremented irregularly internally. In general it is best to simply use the current UNIX
768         /// timestamp, however if it is not available a persistent counter that increases once per
769         /// minute should suffice.
770         ///
771         /// This is not exported to bindings users as we can't export a PeerManager with a dummy route handler
772         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 {
773                 Self::new(MessageHandler {
774                         chan_handler: channel_message_handler,
775                         route_handler: IgnoringMessageHandler{},
776                         onion_message_handler,
777                         custom_message_handler: IgnoringMessageHandler{},
778                 }, current_time, ephemeral_random_data, logger, node_signer)
779         }
780 }
781
782 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, IgnoringMessageHandler, L, IgnoringMessageHandler, NS> where
783                 RM::Target: RoutingMessageHandler,
784                 L::Target: Logger,
785                 NS::Target: NodeSigner {
786         /// Constructs a new `PeerManager` with the given `RoutingMessageHandler`. No channel message
787         /// handler or onion message handler is used and onion and channel messages will be ignored (or
788         /// generate error messages). Note that some other lightning implementations time-out connections
789         /// after some time if no channel is built with the peer.
790         ///
791         /// `current_time` is used as an always-increasing counter that survives across restarts and is
792         /// incremented irregularly internally. In general it is best to simply use the current UNIX
793         /// timestamp, however if it is not available a persistent counter that increases once per
794         /// minute should suffice.
795         ///
796         /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
797         /// cryptographically secure random bytes.
798         ///
799         /// This is not exported to bindings users as we can't export a PeerManager with a dummy channel handler
800         pub fn new_routing_only(routing_message_handler: RM, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
801                 Self::new(MessageHandler {
802                         chan_handler: ErroringMessageHandler::new(),
803                         route_handler: routing_message_handler,
804                         onion_message_handler: IgnoringMessageHandler{},
805                         custom_message_handler: IgnoringMessageHandler{},
806                 }, current_time, ephemeral_random_data, logger, node_signer)
807         }
808 }
809
810 /// A simple wrapper that optionally prints ` from <pubkey>` for an optional pubkey.
811 /// This works around `format!()` taking a reference to each argument, preventing
812 /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
813 /// due to lifetime errors.
814 struct OptionalFromDebugger<'a>(&'a Option<(PublicKey, NodeId)>);
815 impl core::fmt::Display for OptionalFromDebugger<'_> {
816         fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
817                 if let Some((node_id, _)) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
818         }
819 }
820
821 /// A function used to filter out local or private addresses
822 /// <https://www.iana.org./assignments/ipv4-address-space/ipv4-address-space.xhtml>
823 /// <https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml>
824 fn filter_addresses(ip_address: Option<NetAddress>) -> Option<NetAddress> {
825         match ip_address{
826                 // For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8)
827                 Some(NetAddress::IPv4{addr: [10, _, _, _], port: _}) => None,
828                 // For IPv4 range 0.0.0.0 - 0.255.255.255 (0/8)
829                 Some(NetAddress::IPv4{addr: [0, _, _, _], port: _}) => None,
830                 // For IPv4 range 100.64.0.0 - 100.127.255.255 (100.64/10)
831                 Some(NetAddress::IPv4{addr: [100, 64..=127, _, _], port: _}) => None,
832                 // For IPv4 range       127.0.0.0 - 127.255.255.255 (127/8)
833                 Some(NetAddress::IPv4{addr: [127, _, _, _], port: _}) => None,
834                 // For IPv4 range       169.254.0.0 - 169.254.255.255 (169.254/16)
835                 Some(NetAddress::IPv4{addr: [169, 254, _, _], port: _}) => None,
836                 // For IPv4 range 172.16.0.0 - 172.31.255.255 (172.16/12)
837                 Some(NetAddress::IPv4{addr: [172, 16..=31, _, _], port: _}) => None,
838                 // For IPv4 range 192.168.0.0 - 192.168.255.255 (192.168/16)
839                 Some(NetAddress::IPv4{addr: [192, 168, _, _], port: _}) => None,
840                 // For IPv4 range 192.88.99.0 - 192.88.99.255  (192.88.99/24)
841                 Some(NetAddress::IPv4{addr: [192, 88, 99, _], port: _}) => None,
842                 // For IPv6 range 2000:0000:0000:0000:0000:0000:0000:0000 - 3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff (2000::/3)
843                 Some(NetAddress::IPv6{addr: [0x20..=0x3F, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _], port: _}) => ip_address,
844                 // For remaining addresses
845                 Some(NetAddress::IPv6{addr: _, port: _}) => None,
846                 Some(..) => ip_address,
847                 None => None,
848         }
849 }
850
851 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref> PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> where
852                 CM::Target: ChannelMessageHandler,
853                 RM::Target: RoutingMessageHandler,
854                 OM::Target: OnionMessageHandler,
855                 L::Target: Logger,
856                 CMH::Target: CustomMessageHandler,
857                 NS::Target: NodeSigner
858 {
859         /// Constructs a new `PeerManager` with the given message handlers.
860         ///
861         /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
862         /// cryptographically secure random bytes.
863         ///
864         /// `current_time` is used as an always-increasing counter that survives across restarts and is
865         /// incremented irregularly internally. In general it is best to simply use the current UNIX
866         /// timestamp, however if it is not available a persistent counter that increases once per
867         /// minute should suffice.
868         pub fn new(message_handler: MessageHandler<CM, RM, OM, CMH>, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
869                 let mut ephemeral_key_midstate = Sha256::engine();
870                 ephemeral_key_midstate.input(ephemeral_random_data);
871
872                 let mut secp_ctx = Secp256k1::signing_only();
873                 let ephemeral_hash = Sha256::from_engine(ephemeral_key_midstate.clone()).into_inner();
874                 secp_ctx.seeded_randomize(&ephemeral_hash);
875
876                 PeerManager {
877                         message_handler,
878                         peers: FairRwLock::new(HashMap::new()),
879                         node_id_to_descriptor: Mutex::new(HashMap::new()),
880                         event_processing_state: AtomicI32::new(0),
881                         ephemeral_key_midstate,
882                         peer_counter: AtomicCounter::new(),
883                         gossip_processing_backlogged: AtomicBool::new(false),
884                         gossip_processing_backlog_lifted: AtomicBool::new(false),
885                         last_node_announcement_serial: AtomicU32::new(current_time),
886                         logger,
887                         node_signer,
888                         secp_ctx,
889                 }
890         }
891
892         /// Get a list of tuples mapping from node id to network addresses for peers which have
893         /// completed the initial handshake.
894         ///
895         /// For outbound connections, the [`PublicKey`] will be the same as the `their_node_id` parameter
896         /// passed in to [`Self::new_outbound_connection`], however entries will only appear once the initial
897         /// handshake has completed and we are sure the remote peer has the private key for the given
898         /// [`PublicKey`].
899         ///
900         /// The returned `Option`s will only be `Some` if an address had been previously given via
901         /// [`Self::new_outbound_connection`] or [`Self::new_inbound_connection`].
902         pub fn get_peer_node_ids(&self) -> Vec<(PublicKey, Option<NetAddress>)> {
903                 let peers = self.peers.read().unwrap();
904                 peers.values().filter_map(|peer_mutex| {
905                         let p = peer_mutex.lock().unwrap();
906                         if !p.handshake_complete() {
907                                 return None;
908                         }
909                         Some((p.their_node_id.unwrap().0, p.their_net_address.clone()))
910                 }).collect()
911         }
912
913         fn get_ephemeral_key(&self) -> SecretKey {
914                 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
915                 let counter = self.peer_counter.get_increment();
916                 ephemeral_hash.input(&counter.to_le_bytes());
917                 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
918         }
919
920         fn init_features(&self, their_node_id: &PublicKey) -> InitFeatures {
921                 self.message_handler.chan_handler.provided_init_features(their_node_id)
922                         | self.message_handler.route_handler.provided_init_features(their_node_id)
923                         | self.message_handler.onion_message_handler.provided_init_features(their_node_id)
924                         | self.message_handler.custom_message_handler.provided_init_features(their_node_id)
925         }
926
927         /// Indicates a new outbound connection has been established to a node with the given `node_id`
928         /// and an optional remote network address.
929         ///
930         /// The remote network address adds the option to report a remote IP address back to a connecting
931         /// peer using the init message.
932         /// The user should pass the remote network address of the host they are connected to.
933         ///
934         /// If an `Err` is returned here you must disconnect the connection immediately.
935         ///
936         /// Returns a small number of bytes to send to the remote node (currently always 50).
937         ///
938         /// Panics if descriptor is duplicative with some other descriptor which has not yet been
939         /// [`socket_disconnected`].
940         ///
941         /// [`socket_disconnected`]: PeerManager::socket_disconnected
942         pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<Vec<u8>, PeerHandleError> {
943                 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
944                 let res = peer_encryptor.get_act_one(&self.secp_ctx).to_vec();
945                 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
946
947                 let mut peers = self.peers.write().unwrap();
948                 match peers.entry(descriptor) {
949                         hash_map::Entry::Occupied(_) => {
950                                 debug_assert!(false, "PeerManager driver duplicated descriptors!");
951                                 Err(PeerHandleError {})
952                         },
953                         hash_map::Entry::Vacant(e) => {
954                                 e.insert(Mutex::new(Peer {
955                                         channel_encryptor: peer_encryptor,
956                                         their_node_id: None,
957                                         their_features: None,
958                                         their_net_address: remote_network_address,
959
960                                         pending_outbound_buffer: LinkedList::new(),
961                                         pending_outbound_buffer_first_msg_offset: 0,
962                                         gossip_broadcast_buffer: LinkedList::new(),
963                                         awaiting_write_event: false,
964
965                                         pending_read_buffer,
966                                         pending_read_buffer_pos: 0,
967                                         pending_read_is_header: false,
968
969                                         sync_status: InitSyncTracker::NoSyncRequested,
970
971                                         msgs_sent_since_pong: 0,
972                                         awaiting_pong_timer_tick_intervals: 0,
973                                         received_message_since_timer_tick: false,
974                                         sent_gossip_timestamp_filter: false,
975
976                                         received_channel_announce_since_backlogged: false,
977                                         inbound_connection: false,
978                                 }));
979                                 Ok(res)
980                         }
981                 }
982         }
983
984         /// Indicates a new inbound connection has been established to a node with an optional remote
985         /// network address.
986         ///
987         /// The remote network address adds the option to report a remote IP address back to a connecting
988         /// peer using the init message.
989         /// The user should pass the remote network address of the host they are connected to.
990         ///
991         /// May refuse the connection by returning an Err, but will never write bytes to the remote end
992         /// (outbound connector always speaks first). If an `Err` is returned here you must disconnect
993         /// the connection immediately.
994         ///
995         /// Panics if descriptor is duplicative with some other descriptor which has not yet been
996         /// [`socket_disconnected`].
997         ///
998         /// [`socket_disconnected`]: PeerManager::socket_disconnected
999         pub fn new_inbound_connection(&self, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<(), PeerHandleError> {
1000                 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.node_signer);
1001                 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
1002
1003                 let mut peers = self.peers.write().unwrap();
1004                 match peers.entry(descriptor) {
1005                         hash_map::Entry::Occupied(_) => {
1006                                 debug_assert!(false, "PeerManager driver duplicated descriptors!");
1007                                 Err(PeerHandleError {})
1008                         },
1009                         hash_map::Entry::Vacant(e) => {
1010                                 e.insert(Mutex::new(Peer {
1011                                         channel_encryptor: peer_encryptor,
1012                                         their_node_id: None,
1013                                         their_features: None,
1014                                         their_net_address: remote_network_address,
1015
1016                                         pending_outbound_buffer: LinkedList::new(),
1017                                         pending_outbound_buffer_first_msg_offset: 0,
1018                                         gossip_broadcast_buffer: LinkedList::new(),
1019                                         awaiting_write_event: false,
1020
1021                                         pending_read_buffer,
1022                                         pending_read_buffer_pos: 0,
1023                                         pending_read_is_header: false,
1024
1025                                         sync_status: InitSyncTracker::NoSyncRequested,
1026
1027                                         msgs_sent_since_pong: 0,
1028                                         awaiting_pong_timer_tick_intervals: 0,
1029                                         received_message_since_timer_tick: false,
1030                                         sent_gossip_timestamp_filter: false,
1031
1032                                         received_channel_announce_since_backlogged: false,
1033                                         inbound_connection: true,
1034                                 }));
1035                                 Ok(())
1036                         }
1037                 }
1038         }
1039
1040         fn peer_should_read(&self, peer: &mut Peer) -> bool {
1041                 peer.should_read(self.gossip_processing_backlogged.load(Ordering::Relaxed))
1042         }
1043
1044         fn update_gossip_backlogged(&self) {
1045                 let new_state = self.message_handler.route_handler.processing_queue_high();
1046                 let prev_state = self.gossip_processing_backlogged.swap(new_state, Ordering::Relaxed);
1047                 if prev_state && !new_state {
1048                         self.gossip_processing_backlog_lifted.store(true, Ordering::Relaxed);
1049                 }
1050         }
1051
1052         fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer, force_one_write: bool) {
1053                 let mut have_written = false;
1054                 while !peer.awaiting_write_event {
1055                         if peer.should_buffer_onion_message() {
1056                                 if let Some((peer_node_id, _)) = peer.their_node_id {
1057                                         if let Some(next_onion_message) =
1058                                                 self.message_handler.onion_message_handler.next_onion_message_for_peer(peer_node_id) {
1059                                                         self.enqueue_message(peer, &next_onion_message);
1060                                         }
1061                                 }
1062                         }
1063                         if peer.should_buffer_gossip_broadcast() {
1064                                 if let Some(msg) = peer.gossip_broadcast_buffer.pop_front() {
1065                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_buffer(&msg[..]));
1066                                 }
1067                         }
1068                         if peer.should_buffer_gossip_backfill() {
1069                                 match peer.sync_status {
1070                                         InitSyncTracker::NoSyncRequested => {},
1071                                         InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
1072                                                 if let Some((announce, update_a_option, update_b_option)) =
1073                                                         self.message_handler.route_handler.get_next_channel_announcement(c)
1074                                                 {
1075                                                         self.enqueue_message(peer, &announce);
1076                                                         if let Some(update_a) = update_a_option {
1077                                                                 self.enqueue_message(peer, &update_a);
1078                                                         }
1079                                                         if let Some(update_b) = update_b_option {
1080                                                                 self.enqueue_message(peer, &update_b);
1081                                                         }
1082                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
1083                                                 } else {
1084                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
1085                                                 }
1086                                         },
1087                                         InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
1088                                                 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(None) {
1089                                                         self.enqueue_message(peer, &msg);
1090                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
1091                                                 } else {
1092                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
1093                                                 }
1094                                         },
1095                                         InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
1096                                         InitSyncTracker::NodesSyncing(sync_node_id) => {
1097                                                 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(Some(&sync_node_id)) {
1098                                                         self.enqueue_message(peer, &msg);
1099                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
1100                                                 } else {
1101                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
1102                                                 }
1103                                         },
1104                                 }
1105                         }
1106                         if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
1107                                 self.maybe_send_extra_ping(peer);
1108                         }
1109
1110                         let should_read = self.peer_should_read(peer);
1111                         let next_buff = match peer.pending_outbound_buffer.front() {
1112                                 None => {
1113                                         if force_one_write && !have_written {
1114                                                 if should_read {
1115                                                         let data_sent = descriptor.send_data(&[], should_read);
1116                                                         debug_assert_eq!(data_sent, 0, "Can't write more than no data");
1117                                                 }
1118                                         }
1119                                         return
1120                                 },
1121                                 Some(buff) => buff,
1122                         };
1123
1124                         let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
1125                         let data_sent = descriptor.send_data(pending, should_read);
1126                         have_written = true;
1127                         peer.pending_outbound_buffer_first_msg_offset += data_sent;
1128                         if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() {
1129                                 peer.pending_outbound_buffer_first_msg_offset = 0;
1130                                 peer.pending_outbound_buffer.pop_front();
1131                         } else {
1132                                 peer.awaiting_write_event = true;
1133                         }
1134                 }
1135         }
1136
1137         /// Indicates that there is room to write data to the given socket descriptor.
1138         ///
1139         /// May return an Err to indicate that the connection should be closed.
1140         ///
1141         /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
1142         /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
1143         /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
1144         /// ready to call [`write_buffer_space_avail`] again if a write call generated here isn't
1145         /// sufficient!
1146         ///
1147         /// [`send_data`]: SocketDescriptor::send_data
1148         /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
1149         pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
1150                 let peers = self.peers.read().unwrap();
1151                 match peers.get(descriptor) {
1152                         None => {
1153                                 // This is most likely a simple race condition where the user found that the socket
1154                                 // was writeable, then we told the user to `disconnect_socket()`, then they called
1155                                 // this method. Return an error to make sure we get disconnected.
1156                                 return Err(PeerHandleError { });
1157                         },
1158                         Some(peer_mutex) => {
1159                                 let mut peer = peer_mutex.lock().unwrap();
1160                                 peer.awaiting_write_event = false;
1161                                 self.do_attempt_write_data(descriptor, &mut peer, false);
1162                         }
1163                 };
1164                 Ok(())
1165         }
1166
1167         /// Indicates that data was read from the given socket descriptor.
1168         ///
1169         /// May return an Err to indicate that the connection should be closed.
1170         ///
1171         /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
1172         /// Thus, however, you should call [`process_events`] after any `read_event` to generate
1173         /// [`send_data`] calls to handle responses.
1174         ///
1175         /// If `Ok(true)` is returned, further read_events should not be triggered until a
1176         /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
1177         /// send buffer).
1178         ///
1179         /// In order to avoid processing too many messages at once per peer, `data` should be on the
1180         /// order of 4KiB.
1181         ///
1182         /// [`send_data`]: SocketDescriptor::send_data
1183         /// [`process_events`]: PeerManager::process_events
1184         pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1185                 match self.do_read_event(peer_descriptor, data) {
1186                         Ok(res) => Ok(res),
1187                         Err(e) => {
1188                                 log_trace!(self.logger, "Disconnecting peer due to a protocol error (usually a duplicate connection).");
1189                                 self.disconnect_event_internal(peer_descriptor);
1190                                 Err(e)
1191                         }
1192                 }
1193         }
1194
1195         /// Append a message to a peer's pending outbound/write buffer
1196         fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
1197                 if is_gossip_msg(message.type_id()) {
1198                         log_gossip!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0));
1199                 } else {
1200                         log_trace!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0))
1201                 }
1202                 peer.msgs_sent_since_pong += 1;
1203                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(message));
1204         }
1205
1206         /// Append a message to a peer's pending outbound/write gossip broadcast buffer
1207         fn enqueue_encoded_gossip_broadcast(&self, peer: &mut Peer, encoded_message: Vec<u8>) {
1208                 peer.msgs_sent_since_pong += 1;
1209                 peer.gossip_broadcast_buffer.push_back(encoded_message);
1210         }
1211
1212         fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1213                 let mut pause_read = false;
1214                 let peers = self.peers.read().unwrap();
1215                 let mut msgs_to_forward = Vec::new();
1216                 let mut peer_node_id = None;
1217                 match peers.get(peer_descriptor) {
1218                         None => {
1219                                 // This is most likely a simple race condition where the user read some bytes
1220                                 // from the socket, then we told the user to `disconnect_socket()`, then they
1221                                 // called this method. Return an error to make sure we get disconnected.
1222                                 return Err(PeerHandleError { });
1223                         },
1224                         Some(peer_mutex) => {
1225                                 let mut read_pos = 0;
1226                                 while read_pos < data.len() {
1227                                         macro_rules! try_potential_handleerror {
1228                                                 ($peer: expr, $thing: expr) => {
1229                                                         match $thing {
1230                                                                 Ok(x) => x,
1231                                                                 Err(e) => {
1232                                                                         match e.action {
1233                                                                                 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
1234                                                                                         //TODO: Try to push msg
1235                                                                                         log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1236                                                                                         return Err(PeerHandleError { });
1237                                                                                 },
1238                                                                                 msgs::ErrorAction::IgnoreAndLog(level) => {
1239                                                                                         log_given_level!(self.logger, level, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1240                                                                                         continue
1241                                                                                 },
1242                                                                                 msgs::ErrorAction::IgnoreDuplicateGossip => continue, // Don't even bother logging these
1243                                                                                 msgs::ErrorAction::IgnoreError => {
1244                                                                                         log_debug!(self.logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1245                                                                                         continue;
1246                                                                                 },
1247                                                                                 msgs::ErrorAction::SendErrorMessage { msg } => {
1248                                                                                         log_debug!(self.logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1249                                                                                         self.enqueue_message($peer, &msg);
1250                                                                                         continue;
1251                                                                                 },
1252                                                                                 msgs::ErrorAction::SendWarningMessage { msg, log_level } => {
1253                                                                                         log_given_level!(self.logger, log_level, "Error handling message{}; sending warning message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1254                                                                                         self.enqueue_message($peer, &msg);
1255                                                                                         continue;
1256                                                                                 },
1257                                                                         }
1258                                                                 }
1259                                                         }
1260                                                 }
1261                                         }
1262
1263                                         let mut peer_lock = peer_mutex.lock().unwrap();
1264                                         let peer = &mut *peer_lock;
1265                                         let mut msg_to_handle = None;
1266                                         if peer_node_id.is_none() {
1267                                                 peer_node_id = peer.their_node_id.clone();
1268                                         }
1269
1270                                         assert!(peer.pending_read_buffer.len() > 0);
1271                                         assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
1272
1273                                         {
1274                                                 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
1275                                                 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]);
1276                                                 read_pos += data_to_copy;
1277                                                 peer.pending_read_buffer_pos += data_to_copy;
1278                                         }
1279
1280                                         if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
1281                                                 peer.pending_read_buffer_pos = 0;
1282
1283                                                 macro_rules! insert_node_id {
1284                                                         () => {
1285                                                                 match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap().0) {
1286                                                                         hash_map::Entry::Occupied(e) => {
1287                                                                                 log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap().0));
1288                                                                                 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
1289                                                                                 // Check that the peers map is consistent with the
1290                                                                                 // node_id_to_descriptor map, as this has been broken
1291                                                                                 // before.
1292                                                                                 debug_assert!(peers.get(e.get()).is_some());
1293                                                                                 return Err(PeerHandleError { })
1294                                                                         },
1295                                                                         hash_map::Entry::Vacant(entry) => {
1296                                                                                 log_debug!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap().0));
1297                                                                                 entry.insert(peer_descriptor.clone())
1298                                                                         },
1299                                                                 };
1300                                                         }
1301                                                 }
1302
1303                                                 let next_step = peer.channel_encryptor.get_noise_step();
1304                                                 match next_step {
1305                                                         NextNoiseStep::ActOne => {
1306                                                                 let act_two = try_potential_handleerror!(peer, peer.channel_encryptor
1307                                                                         .process_act_one_with_keys(&peer.pending_read_buffer[..],
1308                                                                                 &self.node_signer, self.get_ephemeral_key(), &self.secp_ctx)).to_vec();
1309                                                                 peer.pending_outbound_buffer.push_back(act_two);
1310                                                                 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
1311                                                         },
1312                                                         NextNoiseStep::ActTwo => {
1313                                                                 let (act_three, their_node_id) = try_potential_handleerror!(peer,
1314                                                                         peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..],
1315                                                                                 &self.node_signer));
1316                                                                 peer.pending_outbound_buffer.push_back(act_three.to_vec());
1317                                                                 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1318                                                                 peer.pending_read_is_header = true;
1319
1320                                                                 peer.set_their_node_id(their_node_id);
1321                                                                 insert_node_id!();
1322                                                                 let features = self.init_features(&their_node_id);
1323                                                                 let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
1324                                                                 self.enqueue_message(peer, &resp);
1325                                                                 peer.awaiting_pong_timer_tick_intervals = 0;
1326                                                         },
1327                                                         NextNoiseStep::ActThree => {
1328                                                                 let their_node_id = try_potential_handleerror!(peer,
1329                                                                         peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
1330                                                                 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1331                                                                 peer.pending_read_is_header = true;
1332                                                                 peer.set_their_node_id(their_node_id);
1333                                                                 insert_node_id!();
1334                                                                 let features = self.init_features(&their_node_id);
1335                                                                 let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
1336                                                                 self.enqueue_message(peer, &resp);
1337                                                                 peer.awaiting_pong_timer_tick_intervals = 0;
1338                                                         },
1339                                                         NextNoiseStep::NoiseComplete => {
1340                                                                 if peer.pending_read_is_header {
1341                                                                         let msg_len = try_potential_handleerror!(peer,
1342                                                                                 peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
1343                                                                         if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1344                                                                         peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
1345                                                                         if msg_len < 2 { // Need at least the message type tag
1346                                                                                 return Err(PeerHandleError { });
1347                                                                         }
1348                                                                         peer.pending_read_is_header = false;
1349                                                                 } else {
1350                                                                         let msg_data = try_potential_handleerror!(peer,
1351                                                                                 peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
1352                                                                         assert!(msg_data.len() >= 2);
1353
1354                                                                         // Reset read buffer
1355                                                                         if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1356                                                                         peer.pending_read_buffer.resize(18, 0);
1357                                                                         peer.pending_read_is_header = true;
1358
1359                                                                         let mut reader = io::Cursor::new(&msg_data[..]);
1360                                                                         let message_result = wire::read(&mut reader, &*self.message_handler.custom_message_handler);
1361                                                                         let message = match message_result {
1362                                                                                 Ok(x) => x,
1363                                                                                 Err(e) => {
1364                                                                                         match e {
1365                                                                                                 // Note that to avoid recursion we never call
1366                                                                                                 // `do_attempt_write_data` from here, causing
1367                                                                                                 // the messages enqueued here to not actually
1368                                                                                                 // be sent before the peer is disconnected.
1369                                                                                                 (msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
1370                                                                                                         log_gossip!(self.logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
1371                                                                                                         continue;
1372                                                                                                 }
1373                                                                                                 (msgs::DecodeError::UnsupportedCompression, _) => {
1374                                                                                                         log_gossip!(self.logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
1375                                                                                                         self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: "Unsupported message compression: zlib".to_owned() });
1376                                                                                                         continue;
1377                                                                                                 }
1378                                                                                                 (_, Some(ty)) if is_gossip_msg(ty) => {
1379                                                                                                         log_gossip!(self.logger, "Got an invalid value while deserializing a gossip message");
1380                                                                                                         self.enqueue_message(peer, &msgs::WarningMessage {
1381                                                                                                                 channel_id: [0; 32],
1382                                                                                                                 data: format!("Unreadable/bogus gossip message of type {}", ty),
1383                                                                                                         });
1384                                                                                                         continue;
1385                                                                                                 }
1386                                                                                                 (msgs::DecodeError::UnknownRequiredFeature, ty) => {
1387                                                                                                         log_gossip!(self.logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
1388                                                                                                         self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: format!("Received an unknown required feature/TLV in message type {:?}", ty) });
1389                                                                                                         return Err(PeerHandleError { });
1390                                                                                                 }
1391                                                                                                 (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { }),
1392                                                                                                 (msgs::DecodeError::InvalidValue, _) => {
1393                                                                                                         log_debug!(self.logger, "Got an invalid value while deserializing message");
1394                                                                                                         return Err(PeerHandleError { });
1395                                                                                                 }
1396                                                                                                 (msgs::DecodeError::ShortRead, _) => {
1397                                                                                                         log_debug!(self.logger, "Deserialization failed due to shortness of message");
1398                                                                                                         return Err(PeerHandleError { });
1399                                                                                                 }
1400                                                                                                 (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { }),
1401                                                                                                 (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { }),
1402                                                                                         }
1403                                                                                 }
1404                                                                         };
1405
1406                                                                         msg_to_handle = Some(message);
1407                                                                 }
1408                                                         }
1409                                                 }
1410                                         }
1411                                         pause_read = !self.peer_should_read(peer);
1412
1413                                         if let Some(message) = msg_to_handle {
1414                                                 match self.handle_message(&peer_mutex, peer_lock, message) {
1415                                                         Err(handling_error) => match handling_error {
1416                                                                 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
1417                                                                 MessageHandlingError::LightningError(e) => {
1418                                                                         try_potential_handleerror!(&mut peer_mutex.lock().unwrap(), Err(e));
1419                                                                 },
1420                                                         },
1421                                                         Ok(Some(msg)) => {
1422                                                                 msgs_to_forward.push(msg);
1423                                                         },
1424                                                         Ok(None) => {},
1425                                                 }
1426                                         }
1427                                 }
1428                         }
1429                 }
1430
1431                 for msg in msgs_to_forward.drain(..) {
1432                         self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref().map(|(pk, _)| pk));
1433                 }
1434
1435                 Ok(pause_read)
1436         }
1437
1438         /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
1439         /// Returns the message back if it needs to be broadcasted to all other peers.
1440         fn handle_message(
1441                 &self,
1442                 peer_mutex: &Mutex<Peer>,
1443                 mut peer_lock: MutexGuard<Peer>,
1444                 message: wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>
1445         ) -> Result<Option<wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
1446                 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;
1447                 peer_lock.received_message_since_timer_tick = true;
1448
1449                 // Need an Init as first message
1450                 if let wire::Message::Init(msg) = message {
1451                         let our_features = self.init_features(&their_node_id);
1452                         if msg.features.requires_unknown_bits_from(&our_features) {
1453                                 log_debug!(self.logger, "Peer requires features unknown to us");
1454                                 return Err(PeerHandleError { }.into());
1455                         }
1456
1457                         if our_features.requires_unknown_bits_from(&msg.features) {
1458                                 log_debug!(self.logger, "We require features unknown to our peer");
1459                                 return Err(PeerHandleError { }.into());
1460                         }
1461
1462                         if peer_lock.their_features.is_some() {
1463                                 return Err(PeerHandleError { }.into());
1464                         }
1465
1466                         log_info!(self.logger, "Received peer Init message from {}: {}", log_pubkey!(their_node_id), msg.features);
1467
1468                         // For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
1469                         if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
1470                                 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1471                         }
1472
1473                         if let Err(()) = self.message_handler.route_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1474                                 log_debug!(self.logger, "Route Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1475                                 return Err(PeerHandleError { }.into());
1476                         }
1477                         if let Err(()) = self.message_handler.chan_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1478                                 log_debug!(self.logger, "Channel Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1479                                 return Err(PeerHandleError { }.into());
1480                         }
1481                         if let Err(()) = self.message_handler.onion_message_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1482                                 log_debug!(self.logger, "Onion Message Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1483                                 return Err(PeerHandleError { }.into());
1484                         }
1485
1486                         peer_lock.their_features = Some(msg.features);
1487                         return Ok(None);
1488                 } else if peer_lock.their_features.is_none() {
1489                         log_debug!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(their_node_id));
1490                         return Err(PeerHandleError { }.into());
1491                 }
1492
1493                 if let wire::Message::GossipTimestampFilter(_msg) = message {
1494                         // When supporting gossip messages, start inital gossip sync only after we receive
1495                         // a GossipTimestampFilter
1496                         if peer_lock.their_features.as_ref().unwrap().supports_gossip_queries() &&
1497                                 !peer_lock.sent_gossip_timestamp_filter {
1498                                 peer_lock.sent_gossip_timestamp_filter = true;
1499                                 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1500                         }
1501                         return Ok(None);
1502                 }
1503
1504                 if let wire::Message::ChannelAnnouncement(ref _msg) = message {
1505                         peer_lock.received_channel_announce_since_backlogged = true;
1506                 }
1507
1508                 mem::drop(peer_lock);
1509
1510                 if is_gossip_msg(message.type_id()) {
1511                         log_gossip!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1512                 } else {
1513                         log_trace!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1514                 }
1515
1516                 let mut should_forward = None;
1517
1518                 match message {
1519                         // Setup and Control messages:
1520                         wire::Message::Init(_) => {
1521                                 // Handled above
1522                         },
1523                         wire::Message::GossipTimestampFilter(_) => {
1524                                 // Handled above
1525                         },
1526                         wire::Message::Error(msg) => {
1527                                 let mut data_is_printable = true;
1528                                 for b in msg.data.bytes() {
1529                                         if b < 32 || b > 126 {
1530                                                 data_is_printable = false;
1531                                                 break;
1532                                         }
1533                                 }
1534
1535                                 if data_is_printable {
1536                                         log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(their_node_id), msg.data);
1537                                 } else {
1538                                         log_debug!(self.logger, "Got Err message from {} with non-ASCII error message", log_pubkey!(their_node_id));
1539                                 }
1540                                 self.message_handler.chan_handler.handle_error(&their_node_id, &msg);
1541                                 if msg.channel_id == [0; 32] {
1542                                         return Err(PeerHandleError { }.into());
1543                                 }
1544                         },
1545                         wire::Message::Warning(msg) => {
1546                                 let mut data_is_printable = true;
1547                                 for b in msg.data.bytes() {
1548                                         if b < 32 || b > 126 {
1549                                                 data_is_printable = false;
1550                                                 break;
1551                                         }
1552                                 }
1553
1554                                 if data_is_printable {
1555                                         log_debug!(self.logger, "Got warning message from {}: {}", log_pubkey!(their_node_id), msg.data);
1556                                 } else {
1557                                         log_debug!(self.logger, "Got warning message from {} with non-ASCII error message", log_pubkey!(their_node_id));
1558                                 }
1559                         },
1560
1561                         wire::Message::Ping(msg) => {
1562                                 if msg.ponglen < 65532 {
1563                                         let resp = msgs::Pong { byteslen: msg.ponglen };
1564                                         self.enqueue_message(&mut *peer_mutex.lock().unwrap(), &resp);
1565                                 }
1566                         },
1567                         wire::Message::Pong(_msg) => {
1568                                 let mut peer_lock = peer_mutex.lock().unwrap();
1569                                 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1570                                 peer_lock.msgs_sent_since_pong = 0;
1571                         },
1572
1573                         // Channel messages:
1574                         wire::Message::OpenChannel(msg) => {
1575                                 self.message_handler.chan_handler.handle_open_channel(&their_node_id, &msg);
1576                         },
1577                         wire::Message::OpenChannelV2(msg) => {
1578                                 self.message_handler.chan_handler.handle_open_channel_v2(&their_node_id, &msg);
1579                         },
1580                         wire::Message::AcceptChannel(msg) => {
1581                                 self.message_handler.chan_handler.handle_accept_channel(&their_node_id, &msg);
1582                         },
1583                         wire::Message::AcceptChannelV2(msg) => {
1584                                 self.message_handler.chan_handler.handle_accept_channel_v2(&their_node_id, &msg);
1585                         },
1586
1587                         wire::Message::FundingCreated(msg) => {
1588                                 self.message_handler.chan_handler.handle_funding_created(&their_node_id, &msg);
1589                         },
1590                         wire::Message::FundingSigned(msg) => {
1591                                 self.message_handler.chan_handler.handle_funding_signed(&their_node_id, &msg);
1592                         },
1593                         wire::Message::ChannelReady(msg) => {
1594                                 self.message_handler.chan_handler.handle_channel_ready(&their_node_id, &msg);
1595                         },
1596
1597                         // Interactive transaction construction messages:
1598                         wire::Message::TxAddInput(msg) => {
1599                                 self.message_handler.chan_handler.handle_tx_add_input(&their_node_id, &msg);
1600                         },
1601                         wire::Message::TxAddOutput(msg) => {
1602                                 self.message_handler.chan_handler.handle_tx_add_output(&their_node_id, &msg);
1603                         },
1604                         wire::Message::TxRemoveInput(msg) => {
1605                                 self.message_handler.chan_handler.handle_tx_remove_input(&their_node_id, &msg);
1606                         },
1607                         wire::Message::TxRemoveOutput(msg) => {
1608                                 self.message_handler.chan_handler.handle_tx_remove_output(&their_node_id, &msg);
1609                         },
1610                         wire::Message::TxComplete(msg) => {
1611                                 self.message_handler.chan_handler.handle_tx_complete(&their_node_id, &msg);
1612                         },
1613                         wire::Message::TxSignatures(msg) => {
1614                                 self.message_handler.chan_handler.handle_tx_signatures(&their_node_id, &msg);
1615                         },
1616                         wire::Message::TxInitRbf(msg) => {
1617                                 self.message_handler.chan_handler.handle_tx_init_rbf(&their_node_id, &msg);
1618                         },
1619                         wire::Message::TxAckRbf(msg) => {
1620                                 self.message_handler.chan_handler.handle_tx_ack_rbf(&their_node_id, &msg);
1621                         },
1622                         wire::Message::TxAbort(msg) => {
1623                                 self.message_handler.chan_handler.handle_tx_abort(&their_node_id, &msg);
1624                         }
1625
1626                         wire::Message::Shutdown(msg) => {
1627                                 self.message_handler.chan_handler.handle_shutdown(&their_node_id, &msg);
1628                         },
1629                         wire::Message::ClosingSigned(msg) => {
1630                                 self.message_handler.chan_handler.handle_closing_signed(&their_node_id, &msg);
1631                         },
1632
1633                         // Commitment messages:
1634                         wire::Message::UpdateAddHTLC(msg) => {
1635                                 self.message_handler.chan_handler.handle_update_add_htlc(&their_node_id, &msg);
1636                         },
1637                         wire::Message::UpdateFulfillHTLC(msg) => {
1638                                 self.message_handler.chan_handler.handle_update_fulfill_htlc(&their_node_id, &msg);
1639                         },
1640                         wire::Message::UpdateFailHTLC(msg) => {
1641                                 self.message_handler.chan_handler.handle_update_fail_htlc(&their_node_id, &msg);
1642                         },
1643                         wire::Message::UpdateFailMalformedHTLC(msg) => {
1644                                 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&their_node_id, &msg);
1645                         },
1646
1647                         wire::Message::CommitmentSigned(msg) => {
1648                                 self.message_handler.chan_handler.handle_commitment_signed(&their_node_id, &msg);
1649                         },
1650                         wire::Message::RevokeAndACK(msg) => {
1651                                 self.message_handler.chan_handler.handle_revoke_and_ack(&their_node_id, &msg);
1652                         },
1653                         wire::Message::UpdateFee(msg) => {
1654                                 self.message_handler.chan_handler.handle_update_fee(&their_node_id, &msg);
1655                         },
1656                         wire::Message::ChannelReestablish(msg) => {
1657                                 self.message_handler.chan_handler.handle_channel_reestablish(&their_node_id, &msg);
1658                         },
1659
1660                         // Routing messages:
1661                         wire::Message::AnnouncementSignatures(msg) => {
1662                                 self.message_handler.chan_handler.handle_announcement_signatures(&their_node_id, &msg);
1663                         },
1664                         wire::Message::ChannelAnnouncement(msg) => {
1665                                 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1666                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1667                                         should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1668                                 }
1669                                 self.update_gossip_backlogged();
1670                         },
1671                         wire::Message::NodeAnnouncement(msg) => {
1672                                 if self.message_handler.route_handler.handle_node_announcement(&msg)
1673                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1674                                         should_forward = Some(wire::Message::NodeAnnouncement(msg));
1675                                 }
1676                                 self.update_gossip_backlogged();
1677                         },
1678                         wire::Message::ChannelUpdate(msg) => {
1679                                 self.message_handler.chan_handler.handle_channel_update(&their_node_id, &msg);
1680                                 if self.message_handler.route_handler.handle_channel_update(&msg)
1681                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1682                                         should_forward = Some(wire::Message::ChannelUpdate(msg));
1683                                 }
1684                                 self.update_gossip_backlogged();
1685                         },
1686                         wire::Message::QueryShortChannelIds(msg) => {
1687                                 self.message_handler.route_handler.handle_query_short_channel_ids(&their_node_id, msg)?;
1688                         },
1689                         wire::Message::ReplyShortChannelIdsEnd(msg) => {
1690                                 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&their_node_id, msg)?;
1691                         },
1692                         wire::Message::QueryChannelRange(msg) => {
1693                                 self.message_handler.route_handler.handle_query_channel_range(&their_node_id, msg)?;
1694                         },
1695                         wire::Message::ReplyChannelRange(msg) => {
1696                                 self.message_handler.route_handler.handle_reply_channel_range(&their_node_id, msg)?;
1697                         },
1698
1699                         // Onion message:
1700                         wire::Message::OnionMessage(msg) => {
1701                                 self.message_handler.onion_message_handler.handle_onion_message(&their_node_id, &msg);
1702                         },
1703
1704                         // Unknown messages:
1705                         wire::Message::Unknown(type_id) if message.is_even() => {
1706                                 log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1707                                 return Err(PeerHandleError { }.into());
1708                         },
1709                         wire::Message::Unknown(type_id) => {
1710                                 log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", type_id);
1711                         },
1712                         wire::Message::Custom(custom) => {
1713                                 self.message_handler.custom_message_handler.handle_custom_message(custom, &their_node_id)?;
1714                         },
1715                 };
1716                 Ok(should_forward)
1717         }
1718
1719         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>) {
1720                 match msg {
1721                         wire::Message::ChannelAnnouncement(ref msg) => {
1722                                 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1723                                 let encoded_msg = encode_msg!(msg);
1724
1725                                 for (_, peer_mutex) in peers.iter() {
1726                                         let mut peer = peer_mutex.lock().unwrap();
1727                                         if !peer.handshake_complete() ||
1728                                                         !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1729                                                 continue
1730                                         }
1731                                         debug_assert!(peer.their_node_id.is_some());
1732                                         debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1733                                         if peer.buffer_full_drop_gossip_broadcast() {
1734                                                 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1735                                                 continue;
1736                                         }
1737                                         if let Some((_, their_node_id)) = peer.their_node_id {
1738                                                 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
1739                                                         continue;
1740                                                 }
1741                                         }
1742                                         if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1743                                                 continue;
1744                                         }
1745                                         self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
1746                                 }
1747                         },
1748                         wire::Message::NodeAnnouncement(ref msg) => {
1749                                 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1750                                 let encoded_msg = encode_msg!(msg);
1751
1752                                 for (_, peer_mutex) in peers.iter() {
1753                                         let mut peer = peer_mutex.lock().unwrap();
1754                                         if !peer.handshake_complete() ||
1755                                                         !peer.should_forward_node_announcement(msg.contents.node_id) {
1756                                                 continue
1757                                         }
1758                                         debug_assert!(peer.their_node_id.is_some());
1759                                         debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1760                                         if peer.buffer_full_drop_gossip_broadcast() {
1761                                                 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1762                                                 continue;
1763                                         }
1764                                         if let Some((_, their_node_id)) = peer.their_node_id {
1765                                                 if their_node_id == msg.contents.node_id {
1766                                                         continue;
1767                                                 }
1768                                         }
1769                                         if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1770                                                 continue;
1771                                         }
1772                                         self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
1773                                 }
1774                         },
1775                         wire::Message::ChannelUpdate(ref msg) => {
1776                                 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1777                                 let encoded_msg = encode_msg!(msg);
1778
1779                                 for (_, peer_mutex) in peers.iter() {
1780                                         let mut peer = peer_mutex.lock().unwrap();
1781                                         if !peer.handshake_complete() ||
1782                                                         !peer.should_forward_channel_announcement(msg.contents.short_channel_id)  {
1783                                                 continue
1784                                         }
1785                                         debug_assert!(peer.their_node_id.is_some());
1786                                         debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1787                                         if peer.buffer_full_drop_gossip_broadcast() {
1788                                                 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1789                                                 continue;
1790                                         }
1791                                         if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1792                                                 continue;
1793                                         }
1794                                         self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
1795                                 }
1796                         },
1797                         _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1798                 }
1799         }
1800
1801         /// Checks for any events generated by our handlers and processes them. Includes sending most
1802         /// response messages as well as messages generated by calls to handler functions directly (eg
1803         /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1804         ///
1805         /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1806         /// issues!
1807         ///
1808         /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
1809         /// or one of the other clients provided in our language bindings.
1810         ///
1811         /// Note that if there are any other calls to this function waiting on lock(s) this may return
1812         /// without doing any work. All available events that need handling will be handled before the
1813         /// other calls return.
1814         ///
1815         /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1816         /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1817         /// [`send_data`]: SocketDescriptor::send_data
1818         pub fn process_events(&self) {
1819                 if self.event_processing_state.fetch_add(1, Ordering::AcqRel) > 0 {
1820                         // If we're not the first event processor to get here, just return early, the increment
1821                         // we just did will be treated as "go around again" at the end.
1822                         return;
1823                 }
1824
1825                 loop {
1826                         self.update_gossip_backlogged();
1827                         let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
1828
1829                         let mut peers_to_disconnect = HashMap::new();
1830                         let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
1831                         events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
1832
1833                         {
1834                                 // TODO: There are some DoS attacks here where you can flood someone's outbound send
1835                                 // buffer by doing things like announcing channels on another node. We should be willing to
1836                                 // drop optional-ish messages when send buffers get full!
1837
1838                                 let peers_lock = self.peers.read().unwrap();
1839                                 let peers = &*peers_lock;
1840                                 macro_rules! get_peer_for_forwarding {
1841                                         ($node_id: expr) => {
1842                                                 {
1843                                                         if peers_to_disconnect.get($node_id).is_some() {
1844                                                                 // If we've "disconnected" this peer, do not send to it.
1845                                                                 continue;
1846                                                         }
1847                                                         let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().get($node_id).cloned();
1848                                                         match descriptor_opt {
1849                                                                 Some(descriptor) => match peers.get(&descriptor) {
1850                                                                         Some(peer_mutex) => {
1851                                                                                 let peer_lock = peer_mutex.lock().unwrap();
1852                                                                                 if !peer_lock.handshake_complete() {
1853                                                                                         continue;
1854                                                                                 }
1855                                                                                 peer_lock
1856                                                                         },
1857                                                                         None => {
1858                                                                                 debug_assert!(false, "Inconsistent peers set state!");
1859                                                                                 continue;
1860                                                                         }
1861                                                                 },
1862                                                                 None => {
1863                                                                         continue;
1864                                                                 },
1865                                                         }
1866                                                 }
1867                                         }
1868                                 }
1869                                 for event in events_generated.drain(..) {
1870                                         match event {
1871                                                 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1872                                                         log_debug!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1873                                                                         log_pubkey!(node_id),
1874                                                                         log_bytes!(msg.temporary_channel_id));
1875                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1876                                                 },
1877                                                 MessageSendEvent::SendAcceptChannelV2 { ref node_id, ref msg } => {
1878                                                         log_debug!(self.logger, "Handling SendAcceptChannelV2 event in peer_handler for node {} for channel {}",
1879                                                                         log_pubkey!(node_id),
1880                                                                         log_bytes!(msg.temporary_channel_id));
1881                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1882                                                 },
1883                                                 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1884                                                         log_debug!(self.logger, "Handling SendOpenChannel 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::SendOpenChannelV2 { ref node_id, ref msg } => {
1890                                                         log_debug!(self.logger, "Handling SendOpenChannelV2 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::SendFundingCreated { ref node_id, ref msg } => {
1896                                                         log_debug!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
1897                                                                         log_pubkey!(node_id),
1898                                                                         log_bytes!(msg.temporary_channel_id),
1899                                                                         log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
1900                                                         // TODO: If the peer is gone we should generate a DiscardFunding event
1901                                                         // indicating to the wallet that they should just throw away this funding transaction
1902                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1903                                                 },
1904                                                 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
1905                                                         log_debug!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
1906                                                                         log_pubkey!(node_id),
1907                                                                         log_bytes!(msg.channel_id));
1908                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1909                                                 },
1910                                                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
1911                                                         log_debug!(self.logger, "Handling SendChannelReady event in peer_handler for node {} for channel {}",
1912                                                                         log_pubkey!(node_id),
1913                                                                         log_bytes!(msg.channel_id));
1914                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1915                                                 },
1916                                                 MessageSendEvent::SendTxAddInput { ref node_id, ref msg } => {
1917                                                         log_debug!(self.logger, "Handling SendTxAddInput 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::SendTxAddOutput { ref node_id, ref msg } => {
1923                                                         log_debug!(self.logger, "Handling SendTxAddOutput 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::SendTxRemoveInput { ref node_id, ref msg } => {
1929                                                         log_debug!(self.logger, "Handling SendTxRemoveInput 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::SendTxRemoveOutput { ref node_id, ref msg } => {
1935                                                         log_debug!(self.logger, "Handling SendTxRemoveOutput 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::SendTxComplete { ref node_id, ref msg } => {
1941                                                         log_debug!(self.logger, "Handling SendTxComplete 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::SendTxSignatures { ref node_id, ref msg } => {
1947                                                         log_debug!(self.logger, "Handling SendTxSignatures 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::SendTxInitRbf { ref node_id, ref msg } => {
1953                                                         log_debug!(self.logger, "Handling SendTxInitRbf 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::SendTxAckRbf { ref node_id, ref msg } => {
1959                                                         log_debug!(self.logger, "Handling SendTxAckRbf 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::SendTxAbort { ref node_id, ref msg } => {
1965                                                         log_debug!(self.logger, "Handling SendTxAbort 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::SendAnnouncementSignatures { ref node_id, ref msg } => {
1971                                                         log_debug!(self.logger, "Handling SendAnnouncementSignatures 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::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 } } => {
1977                                                         log_debug!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
1978                                                                         log_pubkey!(node_id),
1979                                                                         update_add_htlcs.len(),
1980                                                                         update_fulfill_htlcs.len(),
1981                                                                         update_fail_htlcs.len(),
1982                                                                         log_bytes!(commitment_signed.channel_id));
1983                                                         let mut peer = get_peer_for_forwarding!(node_id);
1984                                                         for msg in update_add_htlcs {
1985                                                                 self.enqueue_message(&mut *peer, msg);
1986                                                         }
1987                                                         for msg in update_fulfill_htlcs {
1988                                                                 self.enqueue_message(&mut *peer, msg);
1989                                                         }
1990                                                         for msg in update_fail_htlcs {
1991                                                                 self.enqueue_message(&mut *peer, msg);
1992                                                         }
1993                                                         for msg in update_fail_malformed_htlcs {
1994                                                                 self.enqueue_message(&mut *peer, msg);
1995                                                         }
1996                                                         if let &Some(ref msg) = update_fee {
1997                                                                 self.enqueue_message(&mut *peer, msg);
1998                                                         }
1999                                                         self.enqueue_message(&mut *peer, commitment_signed);
2000                                                 },
2001                                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2002                                                         log_debug!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
2003                                                                         log_pubkey!(node_id),
2004                                                                         log_bytes!(msg.channel_id));
2005                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2006                                                 },
2007                                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
2008                                                         log_debug!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
2009                                                                         log_pubkey!(node_id),
2010                                                                         log_bytes!(msg.channel_id));
2011                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2012                                                 },
2013                                                 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
2014                                                         log_debug!(self.logger, "Handling Shutdown 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::SendChannelReestablish { ref node_id, ref msg } => {
2020                                                         log_debug!(self.logger, "Handling SendChannelReestablish 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::SendChannelAnnouncement { ref node_id, ref msg, ref update_msg } => {
2026                                                         log_debug!(self.logger, "Handling SendChannelAnnouncement event in peer_handler for node {} for short channel id {}",
2027                                                                         log_pubkey!(node_id),
2028                                                                         msg.contents.short_channel_id);
2029                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2030                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), update_msg);
2031                                                 },
2032                                                 MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
2033                                                         log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
2034                                                         match self.message_handler.route_handler.handle_channel_announcement(&msg) {
2035                                                                 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2036                                                                         self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
2037                                                                 _ => {},
2038                                                         }
2039                                                         if let Some(msg) = update_msg {
2040                                                                 match self.message_handler.route_handler.handle_channel_update(&msg) {
2041                                                                         Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2042                                                                                 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2043                                                                         _ => {},
2044                                                                 }
2045                                                         }
2046                                                 },
2047                                                 MessageSendEvent::BroadcastChannelUpdate { msg } => {
2048                                                         log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
2049                                                         match self.message_handler.route_handler.handle_channel_update(&msg) {
2050                                                                 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2051                                                                         self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2052                                                                 _ => {},
2053                                                         }
2054                                                 },
2055                                                 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
2056                                                         log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler for node {}", msg.contents.node_id);
2057                                                         match self.message_handler.route_handler.handle_node_announcement(&msg) {
2058                                                                 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2059                                                                         self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None),
2060                                                                 _ => {},
2061                                                         }
2062                                                 },
2063                                                 MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
2064                                                         log_trace!(self.logger, "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
2065                                                                         log_pubkey!(node_id), msg.contents.short_channel_id);
2066                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2067                                                 },
2068                                                 MessageSendEvent::HandleError { ref node_id, ref action } => {
2069                                                         match *action {
2070                                                                 msgs::ErrorAction::DisconnectPeer { ref msg } => {
2071                                                                         // We do not have the peers write lock, so we just store that we're
2072                                                                         // about to disconenct the peer and do it after we finish
2073                                                                         // processing most messages.
2074                                                                         peers_to_disconnect.insert(*node_id, msg.clone());
2075                                                                 },
2076                                                                 msgs::ErrorAction::IgnoreAndLog(level) => {
2077                                                                         log_given_level!(self.logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2078                                                                 },
2079                                                                 msgs::ErrorAction::IgnoreDuplicateGossip => {},
2080                                                                 msgs::ErrorAction::IgnoreError => {
2081                                                                         log_debug!(self.logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2082                                                                 },
2083                                                                 msgs::ErrorAction::SendErrorMessage { ref msg } => {
2084                                                                         log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
2085                                                                                         log_pubkey!(node_id),
2086                                                                                         msg.data);
2087                                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2088                                                                 },
2089                                                                 msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
2090                                                                         log_given_level!(self.logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
2091                                                                                         log_pubkey!(node_id),
2092                                                                                         msg.data);
2093                                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2094                                                                 },
2095                                                         }
2096                                                 },
2097                                                 MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
2098                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2099                                                 },
2100                                                 MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
2101                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2102                                                 }
2103                                                 MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
2104                                                         log_gossip!(self.logger, "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
2105                                                                 log_pubkey!(node_id),
2106                                                                 msg.short_channel_ids.len(),
2107                                                                 msg.first_blocknum,
2108                                                                 msg.number_of_blocks,
2109                                                                 msg.sync_complete);
2110                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2111                                                 }
2112                                                 MessageSendEvent::SendGossipTimestampFilter { ref node_id, ref msg } => {
2113                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2114                                                 }
2115                                         }
2116                                 }
2117
2118                                 for (node_id, msg) in self.message_handler.custom_message_handler.get_and_clear_pending_msg() {
2119                                         if peers_to_disconnect.get(&node_id).is_some() { continue; }
2120                                         self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), &msg);
2121                                 }
2122
2123                                 for (descriptor, peer_mutex) in peers.iter() {
2124                                         let mut peer = peer_mutex.lock().unwrap();
2125                                         if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2126                                         self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer, flush_read_disabled);
2127                                 }
2128                         }
2129                         if !peers_to_disconnect.is_empty() {
2130                                 let mut peers_lock = self.peers.write().unwrap();
2131                                 let peers = &mut *peers_lock;
2132                                 for (node_id, msg) in peers_to_disconnect.drain() {
2133                                         // Note that since we are holding the peers *write* lock we can
2134                                         // remove from node_id_to_descriptor immediately (as no other
2135                                         // thread can be holding the peer lock if we have the global write
2136                                         // lock).
2137
2138                                         let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2139                                         if let Some(mut descriptor) = descriptor_opt {
2140                                                 if let Some(peer_mutex) = peers.remove(&descriptor) {
2141                                                         let mut peer = peer_mutex.lock().unwrap();
2142                                                         if let Some(msg) = msg {
2143                                                                 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2144                                                                                 log_pubkey!(node_id),
2145                                                                                 msg.data);
2146                                                                 self.enqueue_message(&mut *peer, &msg);
2147                                                                 // This isn't guaranteed to work, but if there is enough free
2148                                                                 // room in the send buffer, put the error message there...
2149                                                                 self.do_attempt_write_data(&mut descriptor, &mut *peer, false);
2150                                                         }
2151                                                         self.do_disconnect(descriptor, &*peer, "DisconnectPeer HandleError");
2152                                                 } else { debug_assert!(false, "Missing connection for peer"); }
2153                                         }
2154                                 }
2155                         }
2156
2157                         if self.event_processing_state.fetch_sub(1, Ordering::AcqRel) != 1 {
2158                                 // If another thread incremented the state while we were running we should go
2159                                 // around again, but only once.
2160                                 self.event_processing_state.store(1, Ordering::Release);
2161                                 continue;
2162                         }
2163                         break;
2164                 }
2165         }
2166
2167         /// Indicates that the given socket descriptor's connection is now closed.
2168         pub fn socket_disconnected(&self, descriptor: &Descriptor) {
2169                 self.disconnect_event_internal(descriptor);
2170         }
2171
2172         fn do_disconnect(&self, mut descriptor: Descriptor, peer: &Peer, reason: &'static str) {
2173                 if !peer.handshake_complete() {
2174                         log_trace!(self.logger, "Disconnecting peer which hasn't completed handshake due to {}", reason);
2175                         descriptor.disconnect_socket();
2176                         return;
2177                 }
2178
2179                 debug_assert!(peer.their_node_id.is_some());
2180                 if let Some((node_id, _)) = peer.their_node_id {
2181                         log_trace!(self.logger, "Disconnecting peer with id {} due to {}", node_id, reason);
2182                         self.message_handler.chan_handler.peer_disconnected(&node_id);
2183                         self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2184                 }
2185                 descriptor.disconnect_socket();
2186         }
2187
2188         fn disconnect_event_internal(&self, descriptor: &Descriptor) {
2189                 let mut peers = self.peers.write().unwrap();
2190                 let peer_option = peers.remove(descriptor);
2191                 match peer_option {
2192                         None => {
2193                                 // This is most likely a simple race condition where the user found that the socket
2194                                 // was disconnected, then we told the user to `disconnect_socket()`, then they
2195                                 // called this method. Either way we're disconnected, return.
2196                         },
2197                         Some(peer_lock) => {
2198                                 let peer = peer_lock.lock().unwrap();
2199                                 if let Some((node_id, _)) = peer.their_node_id {
2200                                         log_trace!(self.logger, "Handling disconnection of peer {}", log_pubkey!(node_id));
2201                                         let removed = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2202                                         debug_assert!(removed.is_some(), "descriptor maps should be consistent");
2203                                         if !peer.handshake_complete() { return; }
2204                                         self.message_handler.chan_handler.peer_disconnected(&node_id);
2205                                         self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2206                                 }
2207                         }
2208                 };
2209         }
2210
2211         /// Disconnect a peer given its node id.
2212         ///
2213         /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
2214         /// peer. Thus, be very careful about reentrancy issues.
2215         ///
2216         /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
2217         pub fn disconnect_by_node_id(&self, node_id: PublicKey) {
2218                 let mut peers_lock = self.peers.write().unwrap();
2219                 if let Some(descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
2220                         let peer_opt = peers_lock.remove(&descriptor);
2221                         if let Some(peer_mutex) = peer_opt {
2222                                 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request");
2223                         } else { debug_assert!(false, "node_id_to_descriptor thought we had a peer"); }
2224                 }
2225         }
2226
2227         /// Disconnects all currently-connected peers. This is useful on platforms where there may be
2228         /// an indication that TCP sockets have stalled even if we weren't around to time them out
2229         /// using regular ping/pongs.
2230         pub fn disconnect_all_peers(&self) {
2231                 let mut peers_lock = self.peers.write().unwrap();
2232                 self.node_id_to_descriptor.lock().unwrap().clear();
2233                 let peers = &mut *peers_lock;
2234                 for (descriptor, peer_mutex) in peers.drain() {
2235                         self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request to disconnect all peers");
2236                 }
2237         }
2238
2239         /// This is called when we're blocked on sending additional gossip messages until we receive a
2240         /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
2241         /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
2242         fn maybe_send_extra_ping(&self, peer: &mut Peer) {
2243                 if peer.awaiting_pong_timer_tick_intervals == 0 {
2244                         peer.awaiting_pong_timer_tick_intervals = -1;
2245                         let ping = msgs::Ping {
2246                                 ponglen: 0,
2247                                 byteslen: 64,
2248                         };
2249                         self.enqueue_message(peer, &ping);
2250                 }
2251         }
2252
2253         /// Send pings to each peer and disconnect those which did not respond to the last round of
2254         /// pings.
2255         ///
2256         /// This may be called on any timescale you want, however, roughly once every ten seconds is
2257         /// preferred. The call rate determines both how often we send a ping to our peers and how much
2258         /// time they have to respond before we disconnect them.
2259         ///
2260         /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
2261         /// issues!
2262         ///
2263         /// [`send_data`]: SocketDescriptor::send_data
2264         pub fn timer_tick_occurred(&self) {
2265                 let mut descriptors_needing_disconnect = Vec::new();
2266                 {
2267                         let peers_lock = self.peers.read().unwrap();
2268
2269                         self.update_gossip_backlogged();
2270                         let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
2271
2272                         for (descriptor, peer_mutex) in peers_lock.iter() {
2273                                 let mut peer = peer_mutex.lock().unwrap();
2274                                 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2275
2276                                 if !peer.handshake_complete() {
2277                                         // The peer needs to complete its handshake before we can exchange messages. We
2278                                         // give peers one timer tick to complete handshake, reusing
2279                                         // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
2280                                         // for handshake completion.
2281                                         if peer.awaiting_pong_timer_tick_intervals != 0 {
2282                                                 descriptors_needing_disconnect.push(descriptor.clone());
2283                                         } else {
2284                                                 peer.awaiting_pong_timer_tick_intervals = 1;
2285                                         }
2286                                         continue;
2287                                 }
2288                                 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
2289                                 debug_assert!(peer.their_node_id.is_some());
2290
2291                                 loop { // Used as a `goto` to skip writing a Ping message.
2292                                         if peer.awaiting_pong_timer_tick_intervals == -1 {
2293                                                 // Magic value set in `maybe_send_extra_ping`.
2294                                                 peer.awaiting_pong_timer_tick_intervals = 1;
2295                                                 peer.received_message_since_timer_tick = false;
2296                                                 break;
2297                                         }
2298
2299                                         if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
2300                                                 || peer.awaiting_pong_timer_tick_intervals as u64 >
2301                                                         MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64
2302                                         {
2303                                                 descriptors_needing_disconnect.push(descriptor.clone());
2304                                                 break;
2305                                         }
2306                                         peer.received_message_since_timer_tick = false;
2307
2308                                         if peer.awaiting_pong_timer_tick_intervals > 0 {
2309                                                 peer.awaiting_pong_timer_tick_intervals += 1;
2310                                                 break;
2311                                         }
2312
2313                                         peer.awaiting_pong_timer_tick_intervals = 1;
2314                                         let ping = msgs::Ping {
2315                                                 ponglen: 0,
2316                                                 byteslen: 64,
2317                                         };
2318                                         self.enqueue_message(&mut *peer, &ping);
2319                                         break;
2320                                 }
2321                                 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer, flush_read_disabled);
2322                         }
2323                 }
2324
2325                 if !descriptors_needing_disconnect.is_empty() {
2326                         {
2327                                 let mut peers_lock = self.peers.write().unwrap();
2328                                 for descriptor in descriptors_needing_disconnect {
2329                                         if let Some(peer_mutex) = peers_lock.remove(&descriptor) {
2330                                                 let peer = peer_mutex.lock().unwrap();
2331                                                 if let Some((node_id, _)) = peer.their_node_id {
2332                                                         self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2333                                                 }
2334                                                 self.do_disconnect(descriptor, &*peer, "ping/handshake timeout");
2335                                         }
2336                                 }
2337                         }
2338                 }
2339         }
2340
2341         #[allow(dead_code)]
2342         // Messages of up to 64KB should never end up more than half full with addresses, as that would
2343         // be absurd. We ensure this by checking that at least 100 (our stated public contract on when
2344         // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
2345         // message...
2346         const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2;
2347         #[deny(const_err)]
2348         #[allow(dead_code)]
2349         // ...by failing to compile if the number of addresses that would be half of a message is
2350         // smaller than 100:
2351         const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 100;
2352
2353         /// Generates a signed node_announcement from the given arguments, sending it to all connected
2354         /// peers. Note that peers will likely ignore this message unless we have at least one public
2355         /// channel which has at least six confirmations on-chain.
2356         ///
2357         /// `rgb` is a node "color" and `alias` is a printable human-readable string to describe this
2358         /// node to humans. They carry no in-protocol meaning.
2359         ///
2360         /// `addresses` represent the set (possibly empty) of socket addresses on which this node
2361         /// accepts incoming connections. These will be included in the node_announcement, publicly
2362         /// tying these addresses together and to this node. If you wish to preserve user privacy,
2363         /// addresses should likely contain only Tor Onion addresses.
2364         ///
2365         /// Panics if `addresses` is absurdly large (more than 100).
2366         ///
2367         /// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events
2368         pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], mut addresses: Vec<NetAddress>) {
2369                 if addresses.len() > 100 {
2370                         panic!("More than half the message size was taken up by public addresses!");
2371                 }
2372
2373                 // While all existing nodes handle unsorted addresses just fine, the spec requires that
2374                 // addresses be sorted for future compatibility.
2375                 addresses.sort_by_key(|addr| addr.get_id());
2376
2377                 let features = self.message_handler.chan_handler.provided_node_features()
2378                         | self.message_handler.route_handler.provided_node_features()
2379                         | self.message_handler.onion_message_handler.provided_node_features()
2380                         | self.message_handler.custom_message_handler.provided_node_features();
2381                 let announcement = msgs::UnsignedNodeAnnouncement {
2382                         features,
2383                         timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel),
2384                         node_id: NodeId::from_pubkey(&self.node_signer.get_node_id(Recipient::Node).unwrap()),
2385                         rgb,
2386                         alias: NodeAlias(alias),
2387                         addresses,
2388                         excess_address_data: Vec::new(),
2389                         excess_data: Vec::new(),
2390                 };
2391                 let node_announce_sig = match self.node_signer.sign_gossip_message(
2392                         msgs::UnsignedGossipMessage::NodeAnnouncement(&announcement)
2393                 ) {
2394                         Ok(sig) => sig,
2395                         Err(_) => {
2396                                 log_error!(self.logger, "Failed to generate signature for node_announcement");
2397                                 return;
2398                         },
2399                 };
2400
2401                 let msg = msgs::NodeAnnouncement {
2402                         signature: node_announce_sig,
2403                         contents: announcement
2404                 };
2405
2406                 log_debug!(self.logger, "Broadcasting NodeAnnouncement after passing it to our own RoutingMessageHandler.");
2407                 let _ = self.message_handler.route_handler.handle_node_announcement(&msg);
2408                 self.forward_broadcast_msg(&*self.peers.read().unwrap(), &wire::Message::NodeAnnouncement(msg), None);
2409         }
2410 }
2411
2412 fn is_gossip_msg(type_id: u16) -> bool {
2413         match type_id {
2414                 msgs::ChannelAnnouncement::TYPE |
2415                 msgs::ChannelUpdate::TYPE |
2416                 msgs::NodeAnnouncement::TYPE |
2417                 msgs::QueryChannelRange::TYPE |
2418                 msgs::ReplyChannelRange::TYPE |
2419                 msgs::QueryShortChannelIds::TYPE |
2420                 msgs::ReplyShortChannelIdsEnd::TYPE => true,
2421                 _ => false
2422         }
2423 }
2424
2425 #[cfg(test)]
2426 mod tests {
2427         use crate::sign::{NodeSigner, Recipient};
2428         use crate::events;
2429         use crate::io;
2430         use crate::ln::features::{InitFeatures, NodeFeatures};
2431         use crate::ln::peer_channel_encryptor::PeerChannelEncryptor;
2432         use crate::ln::peer_handler::{CustomMessageHandler, PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses};
2433         use crate::ln::{msgs, wire};
2434         use crate::ln::msgs::{LightningError, NetAddress};
2435         use crate::util::test_utils;
2436
2437         use bitcoin::secp256k1::{PublicKey, SecretKey};
2438
2439         use crate::prelude::*;
2440         use crate::sync::{Arc, Mutex};
2441         use core::convert::Infallible;
2442         use core::sync::atomic::{AtomicBool, Ordering};
2443
2444         #[derive(Clone)]
2445         struct FileDescriptor {
2446                 fd: u16,
2447                 outbound_data: Arc<Mutex<Vec<u8>>>,
2448                 disconnect: Arc<AtomicBool>,
2449         }
2450         impl PartialEq for FileDescriptor {
2451                 fn eq(&self, other: &Self) -> bool {
2452                         self.fd == other.fd
2453                 }
2454         }
2455         impl Eq for FileDescriptor { }
2456         impl core::hash::Hash for FileDescriptor {
2457                 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
2458                         self.fd.hash(hasher)
2459                 }
2460         }
2461
2462         impl SocketDescriptor for FileDescriptor {
2463                 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
2464                         self.outbound_data.lock().unwrap().extend_from_slice(data);
2465                         data.len()
2466                 }
2467
2468                 fn disconnect_socket(&mut self) { self.disconnect.store(true, Ordering::Release); }
2469         }
2470
2471         struct PeerManagerCfg {
2472                 chan_handler: test_utils::TestChannelMessageHandler,
2473                 routing_handler: test_utils::TestRoutingMessageHandler,
2474                 custom_handler: TestCustomMessageHandler,
2475                 logger: test_utils::TestLogger,
2476                 node_signer: test_utils::TestNodeSigner,
2477         }
2478
2479         struct TestCustomMessageHandler {
2480                 features: InitFeatures,
2481         }
2482
2483         impl wire::CustomMessageReader for TestCustomMessageHandler {
2484                 type CustomMessage = Infallible;
2485                 fn read<R: io::Read>(&self, _: u16, _: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
2486                         Ok(None)
2487                 }
2488         }
2489
2490         impl CustomMessageHandler for TestCustomMessageHandler {
2491                 fn handle_custom_message(&self, _: Infallible, _: &PublicKey) -> Result<(), LightningError> {
2492                         unreachable!();
2493                 }
2494
2495                 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
2496
2497                 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
2498
2499                 fn provided_init_features(&self, _: &PublicKey) -> InitFeatures {
2500                         self.features.clone()
2501                 }
2502         }
2503
2504         fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2505                 let mut cfgs = Vec::new();
2506                 for i in 0..peer_count {
2507                         let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2508                         let features = {
2509                                 let mut feature_bits = vec![0u8; 33];
2510                                 feature_bits[32] = 0b00000001;
2511                                 InitFeatures::from_le_bytes(feature_bits)
2512                         };
2513                         cfgs.push(
2514                                 PeerManagerCfg{
2515                                         chan_handler: test_utils::TestChannelMessageHandler::new(),
2516                                         logger: test_utils::TestLogger::new(),
2517                                         routing_handler: test_utils::TestRoutingMessageHandler::new(),
2518                                         custom_handler: TestCustomMessageHandler { features },
2519                                         node_signer: test_utils::TestNodeSigner::new(node_secret),
2520                                 }
2521                         );
2522                 }
2523
2524                 cfgs
2525         }
2526
2527         fn create_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2528                 let mut cfgs = Vec::new();
2529                 for i in 0..peer_count {
2530                         let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2531                         let features = {
2532                                 let mut feature_bits = vec![0u8; 33 + i + 1];
2533                                 feature_bits[33 + i] = 0b00000001;
2534                                 InitFeatures::from_le_bytes(feature_bits)
2535                         };
2536                         cfgs.push(
2537                                 PeerManagerCfg{
2538                                         chan_handler: test_utils::TestChannelMessageHandler::new(),
2539                                         logger: test_utils::TestLogger::new(),
2540                                         routing_handler: test_utils::TestRoutingMessageHandler::new(),
2541                                         custom_handler: TestCustomMessageHandler { features },
2542                                         node_signer: test_utils::TestNodeSigner::new(node_secret),
2543                                 }
2544                         );
2545                 }
2546
2547                 cfgs
2548         }
2549
2550         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>> {
2551                 let mut peers = Vec::new();
2552                 for i in 0..peer_count {
2553                         let ephemeral_bytes = [i as u8; 32];
2554                         let msg_handler = MessageHandler {
2555                                 chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler,
2556                                 onion_message_handler: IgnoringMessageHandler {}, custom_message_handler: &cfgs[i].custom_handler
2557                         };
2558                         let peer = PeerManager::new(msg_handler, 0, &ephemeral_bytes, &cfgs[i].logger, &cfgs[i].node_signer);
2559                         peers.push(peer);
2560                 }
2561
2562                 peers
2563         }
2564
2565         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) {
2566                 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2567                 let mut fd_a = FileDescriptor {
2568                         fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2569                         disconnect: Arc::new(AtomicBool::new(false)),
2570                 };
2571                 let addr_a = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1000};
2572                 let id_b = peer_b.node_signer.get_node_id(Recipient::Node).unwrap();
2573                 let mut fd_b = FileDescriptor {
2574                         fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2575                         disconnect: Arc::new(AtomicBool::new(false)),
2576                 };
2577                 let addr_b = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1001};
2578                 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2579                 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2580                 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2581                 peer_a.process_events();
2582
2583                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2584                 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2585
2586                 peer_b.process_events();
2587                 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2588                 assert_eq!(peer_a.read_event(&mut fd_a, &b_data).unwrap(), false);
2589
2590                 peer_a.process_events();
2591                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2592                 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2593
2594                 assert!(peer_a.get_peer_node_ids().contains(&(id_b, Some(addr_b))));
2595                 assert!(peer_b.get_peer_node_ids().contains(&(id_a, Some(addr_a))));
2596
2597                 (fd_a.clone(), fd_b.clone())
2598         }
2599
2600         #[test]
2601         #[cfg(feature = "std")]
2602         fn fuzz_threaded_connections() {
2603                 // Spawn two threads which repeatedly connect two peers together, leading to "got second
2604                 // connection with peer" disconnections and rapid reconnect. This previously found an issue
2605                 // with our internal map consistency, and is a generally good smoke test of disconnection.
2606                 let cfgs = Arc::new(create_peermgr_cfgs(2));
2607                 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
2608                 let peers = Arc::new(create_network(2, unsafe { &*(&*cfgs as *const _) as &'static _ }));
2609
2610                 let start_time = std::time::Instant::now();
2611                 macro_rules! spawn_thread { ($id: expr) => { {
2612                         let peers = Arc::clone(&peers);
2613                         let cfgs = Arc::clone(&cfgs);
2614                         std::thread::spawn(move || {
2615                                 let mut ctr = 0;
2616                                 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2617                                         let id_a = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
2618                                         let mut fd_a = FileDescriptor {
2619                                                 fd: $id  + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2620                                                 disconnect: Arc::new(AtomicBool::new(false)),
2621                                         };
2622                                         let addr_a = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1000};
2623                                         let mut fd_b = FileDescriptor {
2624                                                 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2625                                                 disconnect: Arc::new(AtomicBool::new(false)),
2626                                         };
2627                                         let addr_b = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1001};
2628                                         let initial_data = peers[1].new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2629                                         peers[0].new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2630                                         if peers[0].read_event(&mut fd_a, &initial_data).is_err() { break; }
2631
2632                                         while start_time.elapsed() < std::time::Duration::from_secs(1) {
2633                                                 peers[0].process_events();
2634                                                 if fd_a.disconnect.load(Ordering::Acquire) { break; }
2635                                                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2636                                                 if peers[1].read_event(&mut fd_b, &a_data).is_err() { break; }
2637
2638                                                 peers[1].process_events();
2639                                                 if fd_b.disconnect.load(Ordering::Acquire) { break; }
2640                                                 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2641                                                 if peers[0].read_event(&mut fd_a, &b_data).is_err() { break; }
2642
2643                                                 cfgs[0].chan_handler.pending_events.lock().unwrap()
2644                                                         .push(crate::events::MessageSendEvent::SendShutdown {
2645                                                                 node_id: peers[1].node_signer.get_node_id(Recipient::Node).unwrap(),
2646                                                                 msg: msgs::Shutdown {
2647                                                                         channel_id: [0; 32],
2648                                                                         scriptpubkey: bitcoin::Script::new(),
2649                                                                 },
2650                                                         });
2651                                                 cfgs[1].chan_handler.pending_events.lock().unwrap()
2652                                                         .push(crate::events::MessageSendEvent::SendShutdown {
2653                                                                 node_id: peers[0].node_signer.get_node_id(Recipient::Node).unwrap(),
2654                                                                 msg: msgs::Shutdown {
2655                                                                         channel_id: [0; 32],
2656                                                                         scriptpubkey: bitcoin::Script::new(),
2657                                                                 },
2658                                                         });
2659
2660                                                 if ctr % 2 == 0 {
2661                                                         peers[0].timer_tick_occurred();
2662                                                         peers[1].timer_tick_occurred();
2663                                                 }
2664                                         }
2665
2666                                         peers[0].socket_disconnected(&fd_a);
2667                                         peers[1].socket_disconnected(&fd_b);
2668                                         ctr += 1;
2669                                         std::thread::sleep(std::time::Duration::from_micros(1));
2670                                 }
2671                         })
2672                 } } }
2673                 let thrd_a = spawn_thread!(1);
2674                 let thrd_b = spawn_thread!(2);
2675
2676                 thrd_a.join().unwrap();
2677                 thrd_b.join().unwrap();
2678         }
2679
2680         #[test]
2681         fn test_incompatible_peers() {
2682                 let cfgs = create_peermgr_cfgs(2);
2683                 let incompatible_cfgs = create_incompatible_peermgr_cfgs(2);
2684
2685                 let peers = create_network(2, &cfgs);
2686                 let incompatible_peers = create_network(2, &incompatible_cfgs);
2687                 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
2688                 for (peer_a, peer_b) in peer_pairs.iter() {
2689                         let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2690                         let mut fd_a = FileDescriptor {
2691                                 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2692                                 disconnect: Arc::new(AtomicBool::new(false)),
2693                         };
2694                         let addr_a = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1000};
2695                         let mut fd_b = FileDescriptor {
2696                                 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2697                                 disconnect: Arc::new(AtomicBool::new(false)),
2698                         };
2699                         let addr_b = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1001};
2700                         let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2701                         peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2702                         assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2703                         peer_a.process_events();
2704
2705                         let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2706                         assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2707
2708                         peer_b.process_events();
2709                         let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2710
2711                         // Should fail because of unknown required features
2712                         assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
2713                 }
2714         }
2715
2716         #[test]
2717         fn test_disconnect_peer() {
2718                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2719                 // push a DisconnectPeer event to remove the node flagged by id
2720                 let cfgs = create_peermgr_cfgs(2);
2721                 let peers = create_network(2, &cfgs);
2722                 establish_connection(&peers[0], &peers[1]);
2723                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2724
2725                 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
2726                 cfgs[0].chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
2727                         node_id: their_id,
2728                         action: msgs::ErrorAction::DisconnectPeer { msg: None },
2729                 });
2730
2731                 peers[0].process_events();
2732                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2733         }
2734
2735         #[test]
2736         fn test_send_simple_msg() {
2737                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2738                 // push a message from one peer to another.
2739                 let cfgs = create_peermgr_cfgs(2);
2740                 let a_chan_handler = test_utils::TestChannelMessageHandler::new();
2741                 let b_chan_handler = test_utils::TestChannelMessageHandler::new();
2742                 let mut peers = create_network(2, &cfgs);
2743                 let (fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2744                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2745
2746                 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
2747
2748                 let msg = msgs::Shutdown { channel_id: [42; 32], scriptpubkey: bitcoin::Script::new() };
2749                 a_chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::SendShutdown {
2750                         node_id: their_id, msg: msg.clone()
2751                 });
2752                 peers[0].message_handler.chan_handler = &a_chan_handler;
2753
2754                 b_chan_handler.expect_receive_msg(wire::Message::Shutdown(msg));
2755                 peers[1].message_handler.chan_handler = &b_chan_handler;
2756
2757                 peers[0].process_events();
2758
2759                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2760                 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2761         }
2762
2763         #[test]
2764         fn test_non_init_first_msg() {
2765                 // Simple test of the first message received over a connection being something other than
2766                 // Init. This results in an immediate disconnection, which previously included a spurious
2767                 // peer_disconnected event handed to event handlers (which would panic in
2768                 // `TestChannelMessageHandler` here).
2769                 let cfgs = create_peermgr_cfgs(2);
2770                 let peers = create_network(2, &cfgs);
2771
2772                 let mut fd_dup = FileDescriptor {
2773                         fd: 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2774                         disconnect: Arc::new(AtomicBool::new(false)),
2775                 };
2776                 let addr_dup = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1003};
2777                 let id_a = cfgs[0].node_signer.get_node_id(Recipient::Node).unwrap();
2778                 peers[0].new_inbound_connection(fd_dup.clone(), Some(addr_dup.clone())).unwrap();
2779
2780                 let mut dup_encryptor = PeerChannelEncryptor::new_outbound(id_a, SecretKey::from_slice(&[42; 32]).unwrap());
2781                 let initial_data = dup_encryptor.get_act_one(&peers[1].secp_ctx);
2782                 assert_eq!(peers[0].read_event(&mut fd_dup, &initial_data).unwrap(), false);
2783                 peers[0].process_events();
2784
2785                 let a_data = fd_dup.outbound_data.lock().unwrap().split_off(0);
2786                 let (act_three, _) =
2787                         dup_encryptor.process_act_two(&a_data[..], &&cfgs[1].node_signer).unwrap();
2788                 assert_eq!(peers[0].read_event(&mut fd_dup, &act_three).unwrap(), false);
2789
2790                 let not_init_msg = msgs::Ping { ponglen: 4, byteslen: 0 };
2791                 let msg_bytes = dup_encryptor.encrypt_message(&not_init_msg);
2792                 assert!(peers[0].read_event(&mut fd_dup, &msg_bytes).is_err());
2793         }
2794
2795         #[test]
2796         fn test_disconnect_all_peer() {
2797                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2798                 // then calls disconnect_all_peers
2799                 let cfgs = create_peermgr_cfgs(2);
2800                 let peers = create_network(2, &cfgs);
2801                 establish_connection(&peers[0], &peers[1]);
2802                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2803
2804                 peers[0].disconnect_all_peers();
2805                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2806         }
2807
2808         #[test]
2809         fn test_timer_tick_occurred() {
2810                 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
2811                 let cfgs = create_peermgr_cfgs(2);
2812                 let peers = create_network(2, &cfgs);
2813                 establish_connection(&peers[0], &peers[1]);
2814                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2815
2816                 // peers[0] awaiting_pong is set to true, but the Peer is still connected
2817                 peers[0].timer_tick_occurred();
2818                 peers[0].process_events();
2819                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2820
2821                 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
2822                 peers[0].timer_tick_occurred();
2823                 peers[0].process_events();
2824                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2825         }
2826
2827         #[test]
2828         fn test_do_attempt_write_data() {
2829                 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
2830                 let cfgs = create_peermgr_cfgs(2);
2831                 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2832                 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2833                 let peers = create_network(2, &cfgs);
2834
2835                 // By calling establish_connect, we trigger do_attempt_write_data between
2836                 // the peers. Previously this function would mistakenly enter an infinite loop
2837                 // when there were more channel messages available than could fit into a peer's
2838                 // buffer. This issue would now be detected by this test (because we use custom
2839                 // RoutingMessageHandlers that intentionally return more channel messages
2840                 // than can fit into a peer's buffer).
2841                 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2842
2843                 // Make each peer to read the messages that the other peer just wrote to them. Note that
2844                 // due to the max-message-before-ping limits this may take a few iterations to complete.
2845                 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
2846                         peers[1].process_events();
2847                         let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2848                         assert!(!a_read_data.is_empty());
2849
2850                         peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
2851                         peers[0].process_events();
2852
2853                         let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2854                         assert!(!b_read_data.is_empty());
2855                         peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
2856
2857                         peers[0].process_events();
2858                         assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
2859                 }
2860
2861                 // Check that each peer has received the expected number of channel updates and channel
2862                 // announcements.
2863                 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2864                 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2865                 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2866                 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2867         }
2868
2869         #[test]
2870         fn test_handshake_timeout() {
2871                 // Tests that we time out a peer still waiting on handshake completion after a full timer
2872                 // tick.
2873                 let cfgs = create_peermgr_cfgs(2);
2874                 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2875                 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2876                 let peers = create_network(2, &cfgs);
2877
2878                 let a_id = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
2879                 let mut fd_a = FileDescriptor {
2880                         fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2881                         disconnect: Arc::new(AtomicBool::new(false)),
2882                 };
2883                 let mut fd_b = FileDescriptor {
2884                         fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2885                         disconnect: Arc::new(AtomicBool::new(false)),
2886                 };
2887                 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
2888                 peers[0].new_inbound_connection(fd_a.clone(), None).unwrap();
2889
2890                 // If we get a single timer tick before completion, that's fine
2891                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2892                 peers[0].timer_tick_occurred();
2893                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2894
2895                 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
2896                 peers[0].process_events();
2897                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2898                 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2899                 peers[1].process_events();
2900
2901                 // ...but if we get a second timer tick, we should disconnect the peer
2902                 peers[0].timer_tick_occurred();
2903                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2904
2905                 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2906                 assert!(peers[0].read_event(&mut fd_a, &b_data).is_err());
2907         }
2908
2909         #[test]
2910         fn test_filter_addresses(){
2911                 // Tests the filter_addresses function.
2912
2913                 // For (10/8)
2914                 let ip_address = NetAddress::IPv4{addr: [10, 0, 0, 0], port: 1000};
2915                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2916                 let ip_address = NetAddress::IPv4{addr: [10, 0, 255, 201], port: 1000};
2917                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2918                 let ip_address = NetAddress::IPv4{addr: [10, 255, 255, 255], port: 1000};
2919                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2920
2921                 // For (0/8)
2922                 let ip_address = NetAddress::IPv4{addr: [0, 0, 0, 0], port: 1000};
2923                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2924                 let ip_address = NetAddress::IPv4{addr: [0, 0, 255, 187], port: 1000};
2925                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2926                 let ip_address = NetAddress::IPv4{addr: [0, 255, 255, 255], port: 1000};
2927                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2928
2929                 // For (100.64/10)
2930                 let ip_address = NetAddress::IPv4{addr: [100, 64, 0, 0], port: 1000};
2931                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2932                 let ip_address = NetAddress::IPv4{addr: [100, 78, 255, 0], port: 1000};
2933                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2934                 let ip_address = NetAddress::IPv4{addr: [100, 127, 255, 255], port: 1000};
2935                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2936
2937                 // For (127/8)
2938                 let ip_address = NetAddress::IPv4{addr: [127, 0, 0, 0], port: 1000};
2939                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2940                 let ip_address = NetAddress::IPv4{addr: [127, 65, 73, 0], port: 1000};
2941                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2942                 let ip_address = NetAddress::IPv4{addr: [127, 255, 255, 255], port: 1000};
2943                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2944
2945                 // For (169.254/16)
2946                 let ip_address = NetAddress::IPv4{addr: [169, 254, 0, 0], port: 1000};
2947                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2948                 let ip_address = NetAddress::IPv4{addr: [169, 254, 221, 101], port: 1000};
2949                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2950                 let ip_address = NetAddress::IPv4{addr: [169, 254, 255, 255], port: 1000};
2951                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2952
2953                 // For (172.16/12)
2954                 let ip_address = NetAddress::IPv4{addr: [172, 16, 0, 0], port: 1000};
2955                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2956                 let ip_address = NetAddress::IPv4{addr: [172, 27, 101, 23], port: 1000};
2957                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2958                 let ip_address = NetAddress::IPv4{addr: [172, 31, 255, 255], port: 1000};
2959                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2960
2961                 // For (192.168/16)
2962                 let ip_address = NetAddress::IPv4{addr: [192, 168, 0, 0], port: 1000};
2963                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2964                 let ip_address = NetAddress::IPv4{addr: [192, 168, 205, 159], port: 1000};
2965                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2966                 let ip_address = NetAddress::IPv4{addr: [192, 168, 255, 255], port: 1000};
2967                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2968
2969                 // For (192.88.99/24)
2970                 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 0], port: 1000};
2971                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2972                 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 140], port: 1000};
2973                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2974                 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 255], port: 1000};
2975                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2976
2977                 // For other IPv4 addresses
2978                 let ip_address = NetAddress::IPv4{addr: [188, 255, 99, 0], port: 1000};
2979                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2980                 let ip_address = NetAddress::IPv4{addr: [123, 8, 129, 14], port: 1000};
2981                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2982                 let ip_address = NetAddress::IPv4{addr: [2, 88, 9, 255], port: 1000};
2983                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2984
2985                 // For (2000::/3)
2986                 let ip_address = NetAddress::IPv6{addr: [32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], port: 1000};
2987                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2988                 let ip_address = NetAddress::IPv6{addr: [45, 34, 209, 190, 0, 123, 55, 34, 0, 0, 3, 27, 201, 0, 0, 0], port: 1000};
2989                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2990                 let ip_address = NetAddress::IPv6{addr: [63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], port: 1000};
2991                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2992
2993                 // For other IPv6 addresses
2994                 let ip_address = NetAddress::IPv6{addr: [24, 240, 12, 32, 0, 0, 0, 0, 20, 97, 0, 32, 121, 254, 0, 0], port: 1000};
2995                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2996                 let ip_address = NetAddress::IPv6{addr: [68, 23, 56, 63, 0, 0, 2, 7, 75, 109, 0, 39, 0, 0, 0, 0], port: 1000};
2997                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2998                 let ip_address = NetAddress::IPv6{addr: [101, 38, 140, 230, 100, 0, 30, 98, 0, 26, 0, 0, 57, 96, 0, 0], port: 1000};
2999                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3000
3001                 // For (None)
3002                 assert_eq!(filter_addresses(None), None);
3003         }
3004
3005         #[test]
3006         #[cfg(feature = "std")]
3007         fn test_process_events_multithreaded() {
3008                 use std::time::{Duration, Instant};
3009                 // Test that `process_events` getting called on multiple threads doesn't generate too many
3010                 // loop iterations.
3011                 // Each time `process_events` goes around the loop we call
3012                 // `get_and_clear_pending_msg_events`, which we count using the `TestMessageHandler`.
3013                 // Because the loop should go around once more after a call which fails to take the
3014                 // single-threaded lock, if we write zero to the counter before calling `process_events` we
3015                 // should never observe there having been more than 2 loop iterations.
3016                 // Further, because the last thread to exit will call `process_events` before returning, we
3017                 // should always have at least one count at the end.
3018                 let cfg = Arc::new(create_peermgr_cfgs(1));
3019                 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
3020                 let peer = Arc::new(create_network(1, unsafe { &*(&*cfg as *const _) as &'static _ }).pop().unwrap());
3021
3022                 let exit_flag = Arc::new(AtomicBool::new(false));
3023                 macro_rules! spawn_thread { () => { {
3024                         let thread_cfg = Arc::clone(&cfg);
3025                         let thread_peer = Arc::clone(&peer);
3026                         let thread_exit = Arc::clone(&exit_flag);
3027                         std::thread::spawn(move || {
3028                                 while !thread_exit.load(Ordering::Acquire) {
3029                                         thread_cfg[0].chan_handler.message_fetch_counter.store(0, Ordering::Release);
3030                                         thread_peer.process_events();
3031                                         std::thread::sleep(Duration::from_micros(1));
3032                                 }
3033                         })
3034                 } } }
3035
3036                 let thread_a = spawn_thread!();
3037                 let thread_b = spawn_thread!();
3038                 let thread_c = spawn_thread!();
3039
3040                 let start_time = Instant::now();
3041                 while start_time.elapsed() < Duration::from_millis(100) {
3042                         let val = cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire);
3043                         assert!(val <= 2);
3044                         std::thread::yield_now(); // Winblowz seemingly doesn't ever interrupt threads?!
3045                 }
3046
3047                 exit_flag.store(true, Ordering::Release);
3048                 thread_a.join().unwrap();
3049                 thread_b.join().unwrap();
3050                 thread_c.join().unwrap();
3051                 assert!(cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire) >= 1);
3052         }
3053 }