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