Add tx_signatures.tlvs field (splicing-specific field in dual funding message)
[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(dual_funding)]
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(dual_funding)]
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(dual_funding)]
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                                                                 peer.awaiting_pong_timer_tick_intervals = 0;
1482                                                         },
1483                                                         NextNoiseStep::ActThree => {
1484                                                                 let their_node_id = try_potential_handleerror!(peer,
1485                                                                         peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
1486                                                                 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1487                                                                 peer.pending_read_is_header = true;
1488                                                                 peer.set_their_node_id(their_node_id);
1489                                                                 insert_node_id!();
1490                                                                 let features = self.init_features(&their_node_id);
1491                                                                 let networks = self.message_handler.chan_handler.get_chain_hashes();
1492                                                                 let resp = msgs::Init { features, networks, remote_network_address: filter_addresses(peer.their_socket_address.clone()) };
1493                                                                 self.enqueue_message(peer, &resp);
1494                                                                 peer.awaiting_pong_timer_tick_intervals = 0;
1495                                                         },
1496                                                         NextNoiseStep::NoiseComplete => {
1497                                                                 if peer.pending_read_is_header {
1498                                                                         let msg_len = try_potential_handleerror!(peer,
1499                                                                                 peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
1500                                                                         if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1501                                                                         peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
1502                                                                         if msg_len < 2 { // Need at least the message type tag
1503                                                                                 return Err(PeerHandleError { });
1504                                                                         }
1505                                                                         peer.pending_read_is_header = false;
1506                                                                 } else {
1507                                                                         debug_assert!(peer.pending_read_buffer.len() >= 2 + 16);
1508                                                                         try_potential_handleerror!(peer,
1509                                                                                 peer.channel_encryptor.decrypt_message(&mut peer.pending_read_buffer[..]));
1510
1511                                                                         let mut reader = io::Cursor::new(&peer.pending_read_buffer[..peer.pending_read_buffer.len() - 16]);
1512                                                                         let message_result = wire::read(&mut reader, &*self.message_handler.custom_message_handler);
1513
1514                                                                         // Reset read buffer
1515                                                                         if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1516                                                                         peer.pending_read_buffer.resize(18, 0);
1517                                                                         peer.pending_read_is_header = true;
1518
1519                                                                         let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1520                                                                         let message = match message_result {
1521                                                                                 Ok(x) => x,
1522                                                                                 Err(e) => {
1523                                                                                         match e {
1524                                                                                                 // Note that to avoid re-entrancy we never call
1525                                                                                                 // `do_attempt_write_data` from here, causing
1526                                                                                                 // the messages enqueued here to not actually
1527                                                                                                 // be sent before the peer is disconnected.
1528                                                                                                 (msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
1529                                                                                                         log_gossip!(logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
1530                                                                                                         continue;
1531                                                                                                 }
1532                                                                                                 (msgs::DecodeError::UnsupportedCompression, _) => {
1533                                                                                                         log_gossip!(logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
1534                                                                                                         self.enqueue_message(peer, &msgs::WarningMessage { channel_id: ChannelId::new_zero(), data: "Unsupported message compression: zlib".to_owned() });
1535                                                                                                         continue;
1536                                                                                                 }
1537                                                                                                 (_, Some(ty)) if is_gossip_msg(ty) => {
1538                                                                                                         log_gossip!(logger, "Got an invalid value while deserializing a gossip message");
1539                                                                                                         self.enqueue_message(peer, &msgs::WarningMessage {
1540                                                                                                                 channel_id: ChannelId::new_zero(),
1541                                                                                                                 data: format!("Unreadable/bogus gossip message of type {}", ty),
1542                                                                                                         });
1543                                                                                                         continue;
1544                                                                                                 }
1545                                                                                                 (msgs::DecodeError::UnknownRequiredFeature, _) => {
1546                                                                                                         log_debug!(logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
1547                                                                                                         return Err(PeerHandleError { });
1548                                                                                                 }
1549                                                                                                 (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { }),
1550                                                                                                 (msgs::DecodeError::InvalidValue, _) => {
1551                                                                                                         log_debug!(logger, "Got an invalid value while deserializing message");
1552                                                                                                         return Err(PeerHandleError { });
1553                                                                                                 }
1554                                                                                                 (msgs::DecodeError::ShortRead, _) => {
1555                                                                                                         log_debug!(logger, "Deserialization failed due to shortness of message");
1556                                                                                                         return Err(PeerHandleError { });
1557                                                                                                 }
1558                                                                                                 (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { }),
1559                                                                                                 (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { }),
1560                                                                                                 (msgs::DecodeError::DangerousValue, _) => return Err(PeerHandleError { }),
1561                                                                                         }
1562                                                                                 }
1563                                                                         };
1564
1565                                                                         msg_to_handle = Some(message);
1566                                                                 }
1567                                                         }
1568                                                 }
1569                                         }
1570                                         pause_read = !self.peer_should_read(peer);
1571
1572                                         if let Some(message) = msg_to_handle {
1573                                                 match self.handle_message(&peer_mutex, peer_lock, message) {
1574                                                         Err(handling_error) => match handling_error {
1575                                                                 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
1576                                                                 MessageHandlingError::LightningError(e) => {
1577                                                                         try_potential_handleerror!(&mut peer_mutex.lock().unwrap(), Err(e));
1578                                                                 },
1579                                                         },
1580                                                         Ok(Some(msg)) => {
1581                                                                 msgs_to_forward.push(msg);
1582                                                         },
1583                                                         Ok(None) => {},
1584                                                 }
1585                                         }
1586                                 }
1587                         }
1588                 }
1589
1590                 for msg in msgs_to_forward.drain(..) {
1591                         self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref().map(|(pk, _)| pk));
1592                 }
1593
1594                 Ok(pause_read)
1595         }
1596
1597         /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
1598         ///
1599         /// Returns the message back if it needs to be broadcasted to all other peers.
1600         fn handle_message(
1601                 &self,
1602                 peer_mutex: &Mutex<Peer>,
1603                 peer_lock: MutexGuard<Peer>,
1604                 message: wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>
1605         ) -> Result<Option<wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
1606                 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;
1607                 let logger = WithContext::from(&self.logger, Some(their_node_id), None);
1608
1609                 let message = match self.do_handle_message_holding_peer_lock(peer_lock, message, &their_node_id, &logger)? {
1610                         Some(processed_message) => processed_message,
1611                         None => return Ok(None),
1612                 };
1613
1614                 self.do_handle_message_without_peer_lock(peer_mutex, message, &their_node_id, &logger)
1615         }
1616
1617         // Conducts all message processing that requires us to hold the `peer_lock`.
1618         //
1619         // Returns `None` if the message was fully processed and otherwise returns the message back to
1620         // allow it to be subsequently processed by `do_handle_message_without_peer_lock`.
1621         fn do_handle_message_holding_peer_lock<'a>(
1622                 &self,
1623                 mut peer_lock: MutexGuard<Peer>,
1624                 message: wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>,
1625                 their_node_id: &PublicKey,
1626                 logger: &WithContext<'a, L>
1627         ) -> Result<Option<wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError>
1628         {
1629                 peer_lock.received_message_since_timer_tick = true;
1630
1631                 // Need an Init as first message
1632                 if let wire::Message::Init(msg) = message {
1633                         // Check if we have any compatible chains if the `networks` field is specified.
1634                         if let Some(networks) = &msg.networks {
1635                                 if let Some(our_chains) = self.message_handler.chan_handler.get_chain_hashes() {
1636                                         let mut have_compatible_chains = false;
1637                                         'our_chains: for our_chain in our_chains.iter() {
1638                                                 for their_chain in networks {
1639                                                         if our_chain == their_chain {
1640                                                                 have_compatible_chains = true;
1641                                                                 break 'our_chains;
1642                                                         }
1643                                                 }
1644                                         }
1645                                         if !have_compatible_chains {
1646                                                 log_debug!(logger, "Peer does not support any of our supported chains");
1647                                                 return Err(PeerHandleError { }.into());
1648                                         }
1649                                 }
1650                         }
1651
1652                         let our_features = self.init_features(&their_node_id);
1653                         if msg.features.requires_unknown_bits_from(&our_features) {
1654                                 log_debug!(logger, "Peer requires features unknown to us");
1655                                 return Err(PeerHandleError { }.into());
1656                         }
1657
1658                         if our_features.requires_unknown_bits_from(&msg.features) {
1659                                 log_debug!(logger, "We require features unknown to our peer");
1660                                 return Err(PeerHandleError { }.into());
1661                         }
1662
1663                         if peer_lock.their_features.is_some() {
1664                                 return Err(PeerHandleError { }.into());
1665                         }
1666
1667                         log_info!(logger, "Received peer Init message from {}: {}", log_pubkey!(their_node_id), msg.features);
1668
1669                         // For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
1670                         if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
1671                                 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1672                         }
1673
1674                         if let Err(()) = self.message_handler.route_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1675                                 log_debug!(logger, "Route Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1676                                 return Err(PeerHandleError { }.into());
1677                         }
1678                         if let Err(()) = self.message_handler.chan_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1679                                 log_debug!(logger, "Channel Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1680                                 return Err(PeerHandleError { }.into());
1681                         }
1682                         if let Err(()) = self.message_handler.onion_message_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1683                                 log_debug!(logger, "Onion Message Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1684                                 return Err(PeerHandleError { }.into());
1685                         }
1686
1687                         peer_lock.their_features = Some(msg.features);
1688                         return Ok(None);
1689                 } else if peer_lock.their_features.is_none() {
1690                         log_debug!(logger, "Peer {} sent non-Init first message", log_pubkey!(their_node_id));
1691                         return Err(PeerHandleError { }.into());
1692                 }
1693
1694                 if let wire::Message::GossipTimestampFilter(_msg) = message {
1695                         // When supporting gossip messages, start initial gossip sync only after we receive
1696                         // a GossipTimestampFilter
1697                         if peer_lock.their_features.as_ref().unwrap().supports_gossip_queries() &&
1698                                 !peer_lock.sent_gossip_timestamp_filter {
1699                                 peer_lock.sent_gossip_timestamp_filter = true;
1700                                 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1701                         }
1702                         return Ok(None);
1703                 }
1704
1705                 if let wire::Message::ChannelAnnouncement(ref _msg) = message {
1706                         peer_lock.received_channel_announce_since_backlogged = true;
1707                 }
1708
1709                 Ok(Some(message))
1710         }
1711
1712         // Conducts all message processing that doesn't require us to hold the `peer_lock`.
1713         //
1714         // Returns the message back if it needs to be broadcasted to all other peers.
1715         fn do_handle_message_without_peer_lock<'a>(
1716                 &self,
1717                 peer_mutex: &Mutex<Peer>,
1718                 message: wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>,
1719                 their_node_id: &PublicKey,
1720                 logger: &WithContext<'a, L>
1721         ) -> Result<Option<wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError>
1722         {
1723                 if is_gossip_msg(message.type_id()) {
1724                         log_gossip!(logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1725                 } else {
1726                         log_trace!(logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1727                 }
1728
1729                 let mut should_forward = None;
1730
1731                 match message {
1732                         // Setup and Control messages:
1733                         wire::Message::Init(_) => {
1734                                 // Handled above
1735                         },
1736                         wire::Message::GossipTimestampFilter(_) => {
1737                                 // Handled above
1738                         },
1739                         wire::Message::Error(msg) => {
1740                                 log_debug!(logger, "Got Err message from {}: {}", log_pubkey!(their_node_id), PrintableString(&msg.data));
1741                                 self.message_handler.chan_handler.handle_error(&their_node_id, &msg);
1742                                 if msg.channel_id.is_zero() {
1743                                         return Err(PeerHandleError { }.into());
1744                                 }
1745                         },
1746                         wire::Message::Warning(msg) => {
1747                                 log_debug!(logger, "Got warning message from {}: {}", log_pubkey!(their_node_id), PrintableString(&msg.data));
1748                         },
1749
1750                         wire::Message::Ping(msg) => {
1751                                 if msg.ponglen < 65532 {
1752                                         let resp = msgs::Pong { byteslen: msg.ponglen };
1753                                         self.enqueue_message(&mut *peer_mutex.lock().unwrap(), &resp);
1754                                 }
1755                         },
1756                         wire::Message::Pong(_msg) => {
1757                                 let mut peer_lock = peer_mutex.lock().unwrap();
1758                                 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1759                                 peer_lock.msgs_sent_since_pong = 0;
1760                         },
1761
1762                         // Channel messages:
1763                         wire::Message::OpenChannel(msg) => {
1764                                 self.message_handler.chan_handler.handle_open_channel(&their_node_id, &msg);
1765                         },
1766                         wire::Message::OpenChannelV2(msg) => {
1767                                 self.message_handler.chan_handler.handle_open_channel_v2(&their_node_id, &msg);
1768                         },
1769                         wire::Message::AcceptChannel(msg) => {
1770                                 self.message_handler.chan_handler.handle_accept_channel(&their_node_id, &msg);
1771                         },
1772                         wire::Message::AcceptChannelV2(msg) => {
1773                                 self.message_handler.chan_handler.handle_accept_channel_v2(&their_node_id, &msg);
1774                         },
1775
1776                         wire::Message::FundingCreated(msg) => {
1777                                 self.message_handler.chan_handler.handle_funding_created(&their_node_id, &msg);
1778                         },
1779                         wire::Message::FundingSigned(msg) => {
1780                                 self.message_handler.chan_handler.handle_funding_signed(&their_node_id, &msg);
1781                         },
1782                         wire::Message::ChannelReady(msg) => {
1783                                 self.message_handler.chan_handler.handle_channel_ready(&their_node_id, &msg);
1784                         },
1785
1786                         // Quiescence messages:
1787                         wire::Message::Stfu(msg) => {
1788                                 self.message_handler.chan_handler.handle_stfu(&their_node_id, &msg);
1789                         }
1790
1791                         #[cfg(dual_funding)]
1792                         // Splicing messages:
1793                         wire::Message::Splice(msg) => {
1794                                 self.message_handler.chan_handler.handle_splice(&their_node_id, &msg);
1795                         }
1796                         #[cfg(dual_funding)]
1797                         wire::Message::SpliceAck(msg) => {
1798                                 self.message_handler.chan_handler.handle_splice_ack(&their_node_id, &msg);
1799                         }
1800                         #[cfg(dual_funding)]
1801                         wire::Message::SpliceLocked(msg) => {
1802                                 self.message_handler.chan_handler.handle_splice_locked(&their_node_id, &msg);
1803                         }
1804
1805                         // Interactive transaction construction messages:
1806                         wire::Message::TxAddInput(msg) => {
1807                                 self.message_handler.chan_handler.handle_tx_add_input(&their_node_id, &msg);
1808                         },
1809                         wire::Message::TxAddOutput(msg) => {
1810                                 self.message_handler.chan_handler.handle_tx_add_output(&their_node_id, &msg);
1811                         },
1812                         wire::Message::TxRemoveInput(msg) => {
1813                                 self.message_handler.chan_handler.handle_tx_remove_input(&their_node_id, &msg);
1814                         },
1815                         wire::Message::TxRemoveOutput(msg) => {
1816                                 self.message_handler.chan_handler.handle_tx_remove_output(&their_node_id, &msg);
1817                         },
1818                         wire::Message::TxComplete(msg) => {
1819                                 self.message_handler.chan_handler.handle_tx_complete(&their_node_id, &msg);
1820                         },
1821                         wire::Message::TxSignatures(msg) => {
1822                                 self.message_handler.chan_handler.handle_tx_signatures(&their_node_id, &msg);
1823                         },
1824                         wire::Message::TxInitRbf(msg) => {
1825                                 self.message_handler.chan_handler.handle_tx_init_rbf(&their_node_id, &msg);
1826                         },
1827                         wire::Message::TxAckRbf(msg) => {
1828                                 self.message_handler.chan_handler.handle_tx_ack_rbf(&their_node_id, &msg);
1829                         },
1830                         wire::Message::TxAbort(msg) => {
1831                                 self.message_handler.chan_handler.handle_tx_abort(&their_node_id, &msg);
1832                         }
1833
1834                         wire::Message::Shutdown(msg) => {
1835                                 self.message_handler.chan_handler.handle_shutdown(&their_node_id, &msg);
1836                         },
1837                         wire::Message::ClosingSigned(msg) => {
1838                                 self.message_handler.chan_handler.handle_closing_signed(&their_node_id, &msg);
1839                         },
1840
1841                         // Commitment messages:
1842                         wire::Message::UpdateAddHTLC(msg) => {
1843                                 self.message_handler.chan_handler.handle_update_add_htlc(&their_node_id, &msg);
1844                         },
1845                         wire::Message::UpdateFulfillHTLC(msg) => {
1846                                 self.message_handler.chan_handler.handle_update_fulfill_htlc(&their_node_id, &msg);
1847                         },
1848                         wire::Message::UpdateFailHTLC(msg) => {
1849                                 self.message_handler.chan_handler.handle_update_fail_htlc(&their_node_id, &msg);
1850                         },
1851                         wire::Message::UpdateFailMalformedHTLC(msg) => {
1852                                 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&their_node_id, &msg);
1853                         },
1854
1855                         wire::Message::CommitmentSigned(msg) => {
1856                                 self.message_handler.chan_handler.handle_commitment_signed(&their_node_id, &msg);
1857                         },
1858                         wire::Message::RevokeAndACK(msg) => {
1859                                 self.message_handler.chan_handler.handle_revoke_and_ack(&their_node_id, &msg);
1860                         },
1861                         wire::Message::UpdateFee(msg) => {
1862                                 self.message_handler.chan_handler.handle_update_fee(&their_node_id, &msg);
1863                         },
1864                         wire::Message::ChannelReestablish(msg) => {
1865                                 self.message_handler.chan_handler.handle_channel_reestablish(&their_node_id, &msg);
1866                         },
1867
1868                         // Routing messages:
1869                         wire::Message::AnnouncementSignatures(msg) => {
1870                                 self.message_handler.chan_handler.handle_announcement_signatures(&their_node_id, &msg);
1871                         },
1872                         wire::Message::ChannelAnnouncement(msg) => {
1873                                 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1874                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1875                                         should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1876                                 }
1877                                 self.update_gossip_backlogged();
1878                         },
1879                         wire::Message::NodeAnnouncement(msg) => {
1880                                 if self.message_handler.route_handler.handle_node_announcement(&msg)
1881                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1882                                         should_forward = Some(wire::Message::NodeAnnouncement(msg));
1883                                 }
1884                                 self.update_gossip_backlogged();
1885                         },
1886                         wire::Message::ChannelUpdate(msg) => {
1887                                 self.message_handler.chan_handler.handle_channel_update(&their_node_id, &msg);
1888                                 if self.message_handler.route_handler.handle_channel_update(&msg)
1889                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1890                                         should_forward = Some(wire::Message::ChannelUpdate(msg));
1891                                 }
1892                                 self.update_gossip_backlogged();
1893                         },
1894                         wire::Message::QueryShortChannelIds(msg) => {
1895                                 self.message_handler.route_handler.handle_query_short_channel_ids(&their_node_id, msg)?;
1896                         },
1897                         wire::Message::ReplyShortChannelIdsEnd(msg) => {
1898                                 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&their_node_id, msg)?;
1899                         },
1900                         wire::Message::QueryChannelRange(msg) => {
1901                                 self.message_handler.route_handler.handle_query_channel_range(&their_node_id, msg)?;
1902                         },
1903                         wire::Message::ReplyChannelRange(msg) => {
1904                                 self.message_handler.route_handler.handle_reply_channel_range(&their_node_id, msg)?;
1905                         },
1906
1907                         // Onion message:
1908                         wire::Message::OnionMessage(msg) => {
1909                                 self.message_handler.onion_message_handler.handle_onion_message(&their_node_id, &msg);
1910                         },
1911
1912                         // Unknown messages:
1913                         wire::Message::Unknown(type_id) if message.is_even() => {
1914                                 log_debug!(logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1915                                 return Err(PeerHandleError { }.into());
1916                         },
1917                         wire::Message::Unknown(type_id) => {
1918                                 log_trace!(logger, "Received unknown odd message of type {}, ignoring", type_id);
1919                         },
1920                         wire::Message::Custom(custom) => {
1921                                 self.message_handler.custom_message_handler.handle_custom_message(custom, &their_node_id)?;
1922                         },
1923                 };
1924                 Ok(should_forward)
1925         }
1926
1927         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>) {
1928                 match msg {
1929                         wire::Message::ChannelAnnouncement(ref msg) => {
1930                                 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1931                                 let encoded_msg = encode_msg!(msg);
1932
1933                                 for (_, peer_mutex) in peers.iter() {
1934                                         let mut peer = peer_mutex.lock().unwrap();
1935                                         if !peer.handshake_complete() ||
1936                                                         !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1937                                                 continue
1938                                         }
1939                                         debug_assert!(peer.their_node_id.is_some());
1940                                         debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1941                                         let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1942                                         if peer.buffer_full_drop_gossip_broadcast() {
1943                                                 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1944                                                 continue;
1945                                         }
1946                                         if let Some((_, their_node_id)) = peer.their_node_id {
1947                                                 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
1948                                                         continue;
1949                                                 }
1950                                         }
1951                                         if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1952                                                 continue;
1953                                         }
1954                                         self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
1955                                 }
1956                         },
1957                         wire::Message::NodeAnnouncement(ref msg) => {
1958                                 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1959                                 let encoded_msg = encode_msg!(msg);
1960
1961                                 for (_, peer_mutex) in peers.iter() {
1962                                         let mut peer = peer_mutex.lock().unwrap();
1963                                         if !peer.handshake_complete() ||
1964                                                         !peer.should_forward_node_announcement(msg.contents.node_id) {
1965                                                 continue
1966                                         }
1967                                         debug_assert!(peer.their_node_id.is_some());
1968                                         debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1969                                         let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1970                                         if peer.buffer_full_drop_gossip_broadcast() {
1971                                                 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1972                                                 continue;
1973                                         }
1974                                         if let Some((_, their_node_id)) = peer.their_node_id {
1975                                                 if their_node_id == msg.contents.node_id {
1976                                                         continue;
1977                                                 }
1978                                         }
1979                                         if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1980                                                 continue;
1981                                         }
1982                                         self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
1983                                 }
1984                         },
1985                         wire::Message::ChannelUpdate(ref msg) => {
1986                                 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1987                                 let encoded_msg = encode_msg!(msg);
1988
1989                                 for (_, peer_mutex) in peers.iter() {
1990                                         let mut peer = peer_mutex.lock().unwrap();
1991                                         if !peer.handshake_complete() ||
1992                                                         !peer.should_forward_channel_announcement(msg.contents.short_channel_id)  {
1993                                                 continue
1994                                         }
1995                                         debug_assert!(peer.their_node_id.is_some());
1996                                         debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1997                                         let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1998                                         if peer.buffer_full_drop_gossip_broadcast() {
1999                                                 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
2000                                                 continue;
2001                                         }
2002                                         if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
2003                                                 continue;
2004                                         }
2005                                         self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
2006                                 }
2007                         },
2008                         _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
2009                 }
2010         }
2011
2012         /// Checks for any events generated by our handlers and processes them. Includes sending most
2013         /// response messages as well as messages generated by calls to handler functions directly (eg
2014         /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
2015         ///
2016         /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
2017         /// issues!
2018         ///
2019         /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
2020         /// or one of the other clients provided in our language bindings.
2021         ///
2022         /// Note that if there are any other calls to this function waiting on lock(s) this may return
2023         /// without doing any work. All available events that need handling will be handled before the
2024         /// other calls return.
2025         ///
2026         /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
2027         /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
2028         /// [`send_data`]: SocketDescriptor::send_data
2029         pub fn process_events(&self) {
2030                 if self.event_processing_state.fetch_add(1, Ordering::AcqRel) > 0 {
2031                         // If we're not the first event processor to get here, just return early, the increment
2032                         // we just did will be treated as "go around again" at the end.
2033                         return;
2034                 }
2035
2036                 loop {
2037                         self.update_gossip_backlogged();
2038                         let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
2039
2040                         let mut peers_to_disconnect = new_hash_map();
2041
2042                         {
2043                                 let peers_lock = self.peers.read().unwrap();
2044
2045                                 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
2046                                 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
2047
2048                                 let peers = &*peers_lock;
2049                                 macro_rules! get_peer_for_forwarding {
2050                                         ($node_id: expr) => {
2051                                                 {
2052                                                         if peers_to_disconnect.get($node_id).is_some() {
2053                                                                 // If we've "disconnected" this peer, do not send to it.
2054                                                                 continue;
2055                                                         }
2056                                                         let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().get($node_id).cloned();
2057                                                         match descriptor_opt {
2058                                                                 Some(descriptor) => match peers.get(&descriptor) {
2059                                                                         Some(peer_mutex) => {
2060                                                                                 let peer_lock = peer_mutex.lock().unwrap();
2061                                                                                 if !peer_lock.handshake_complete() {
2062                                                                                         continue;
2063                                                                                 }
2064                                                                                 peer_lock
2065                                                                         },
2066                                                                         None => {
2067                                                                                 debug_assert!(false, "Inconsistent peers set state!");
2068                                                                                 continue;
2069                                                                         }
2070                                                                 },
2071                                                                 None => {
2072                                                                         continue;
2073                                                                 },
2074                                                         }
2075                                                 }
2076                                         }
2077                                 }
2078                                 for event in events_generated.drain(..) {
2079                                         match event {
2080                                                 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
2081                                                         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 {}",
2082                                                                         log_pubkey!(node_id),
2083                                                                         &msg.common_fields.temporary_channel_id);
2084                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2085                                                 },
2086                                                 MessageSendEvent::SendAcceptChannelV2 { ref node_id, ref msg } => {
2087                                                         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 {}",
2088                                                                         log_pubkey!(node_id),
2089                                                                         &msg.common_fields.temporary_channel_id);
2090                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2091                                                 },
2092                                                 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
2093                                                         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 {}",
2094                                                                         log_pubkey!(node_id),
2095                                                                         &msg.common_fields.temporary_channel_id);
2096                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2097                                                 },
2098                                                 MessageSendEvent::SendOpenChannelV2 { ref node_id, ref msg } => {
2099                                                         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 {}",
2100                                                                         log_pubkey!(node_id),
2101                                                                         &msg.common_fields.temporary_channel_id);
2102                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2103                                                 },
2104                                                 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
2105                                                         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 {})",
2106                                                                         log_pubkey!(node_id),
2107                                                                         &msg.temporary_channel_id,
2108                                                                         ChannelId::v1_from_funding_txid(msg.funding_txid.as_byte_array(), msg.funding_output_index));
2109                                                         // TODO: If the peer is gone we should generate a DiscardFunding event
2110                                                         // indicating to the wallet that they should just throw away this funding transaction
2111                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2112                                                 },
2113                                                 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
2114                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
2115                                                                         log_pubkey!(node_id),
2116                                                                         &msg.channel_id);
2117                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2118                                                 },
2119                                                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
2120                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendChannelReady event in peer_handler for node {} for channel {}",
2121                                                                         log_pubkey!(node_id),
2122                                                                         &msg.channel_id);
2123                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2124                                                 },
2125                                                 MessageSendEvent::SendStfu { ref node_id, ref msg} => {
2126                                                         let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id));
2127                                                         log_debug!(logger, "Handling SendStfu event in peer_handler for node {} for channel {}",
2128                                                                         log_pubkey!(node_id),
2129                                                                         &msg.channel_id);
2130                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2131                                                 }
2132                                                 MessageSendEvent::SendSplice { ref node_id, ref msg} => {
2133                                                         let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id));
2134                                                         log_debug!(logger, "Handling SendSplice event in peer_handler for node {} for channel {}",
2135                                                                         log_pubkey!(node_id),
2136                                                                         &msg.channel_id);
2137                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2138                                                 }
2139                                                 MessageSendEvent::SendSpliceAck { ref node_id, ref msg} => {
2140                                                         let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id));
2141                                                         log_debug!(logger, "Handling SendSpliceAck event in peer_handler for node {} for channel {}",
2142                                                                         log_pubkey!(node_id),
2143                                                                         &msg.channel_id);
2144                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2145                                                 }
2146                                                 MessageSendEvent::SendSpliceLocked { ref node_id, ref msg} => {
2147                                                         let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id));
2148                                                         log_debug!(logger, "Handling SendSpliceLocked event in peer_handler for node {} for channel {}",
2149                                                                         log_pubkey!(node_id),
2150                                                                         &msg.channel_id);
2151                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2152                                                 }
2153                                                 MessageSendEvent::SendTxAddInput { ref node_id, ref msg } => {
2154                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAddInput event in peer_handler for node {} for channel {}",
2155                                                                         log_pubkey!(node_id),
2156                                                                         &msg.channel_id);
2157                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2158                                                 },
2159                                                 MessageSendEvent::SendTxAddOutput { ref node_id, ref msg } => {
2160                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAddOutput event in peer_handler for node {} for channel {}",
2161                                                                         log_pubkey!(node_id),
2162                                                                         &msg.channel_id);
2163                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2164                                                 },
2165                                                 MessageSendEvent::SendTxRemoveInput { ref node_id, ref msg } => {
2166                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxRemoveInput event in peer_handler for node {} for channel {}",
2167                                                                         log_pubkey!(node_id),
2168                                                                         &msg.channel_id);
2169                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2170                                                 },
2171                                                 MessageSendEvent::SendTxRemoveOutput { ref node_id, ref msg } => {
2172                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxRemoveOutput event in peer_handler for node {} for channel {}",
2173                                                                         log_pubkey!(node_id),
2174                                                                         &msg.channel_id);
2175                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2176                                                 },
2177                                                 MessageSendEvent::SendTxComplete { ref node_id, ref msg } => {
2178                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxComplete event in peer_handler for node {} for channel {}",
2179                                                                         log_pubkey!(node_id),
2180                                                                         &msg.channel_id);
2181                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2182                                                 },
2183                                                 MessageSendEvent::SendTxSignatures { ref node_id, ref msg } => {
2184                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxSignatures event in peer_handler for node {} for channel {}",
2185                                                                         log_pubkey!(node_id),
2186                                                                         &msg.channel_id);
2187                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2188                                                 },
2189                                                 MessageSendEvent::SendTxInitRbf { ref node_id, ref msg } => {
2190                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxInitRbf event in peer_handler for node {} for channel {}",
2191                                                                         log_pubkey!(node_id),
2192                                                                         &msg.channel_id);
2193                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2194                                                 },
2195                                                 MessageSendEvent::SendTxAckRbf { ref node_id, ref msg } => {
2196                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAckRbf event in peer_handler for node {} for channel {}",
2197                                                                         log_pubkey!(node_id),
2198                                                                         &msg.channel_id);
2199                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2200                                                 },
2201                                                 MessageSendEvent::SendTxAbort { ref node_id, ref msg } => {
2202                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAbort event in peer_handler for node {} for channel {}",
2203                                                                         log_pubkey!(node_id),
2204                                                                         &msg.channel_id);
2205                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2206                                                 },
2207                                                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
2208                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
2209                                                                         log_pubkey!(node_id),
2210                                                                         &msg.channel_id);
2211                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2212                                                 },
2213                                                 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 } } => {
2214                                                         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 {}",
2215                                                                         log_pubkey!(node_id),
2216                                                                         update_add_htlcs.len(),
2217                                                                         update_fulfill_htlcs.len(),
2218                                                                         update_fail_htlcs.len(),
2219                                                                         &commitment_signed.channel_id);
2220                                                         let mut peer = get_peer_for_forwarding!(node_id);
2221                                                         for msg in update_add_htlcs {
2222                                                                 self.enqueue_message(&mut *peer, msg);
2223                                                         }
2224                                                         for msg in update_fulfill_htlcs {
2225                                                                 self.enqueue_message(&mut *peer, msg);
2226                                                         }
2227                                                         for msg in update_fail_htlcs {
2228                                                                 self.enqueue_message(&mut *peer, msg);
2229                                                         }
2230                                                         for msg in update_fail_malformed_htlcs {
2231                                                                 self.enqueue_message(&mut *peer, msg);
2232                                                         }
2233                                                         if let &Some(ref msg) = update_fee {
2234                                                                 self.enqueue_message(&mut *peer, msg);
2235                                                         }
2236                                                         self.enqueue_message(&mut *peer, commitment_signed);
2237                                                 },
2238                                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2239                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
2240                                                                         log_pubkey!(node_id),
2241                                                                         &msg.channel_id);
2242                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2243                                                 },
2244                                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
2245                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
2246                                                                         log_pubkey!(node_id),
2247                                                                         &msg.channel_id);
2248                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2249                                                 },
2250                                                 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
2251                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling Shutdown event in peer_handler for node {} for channel {}",
2252                                                                         log_pubkey!(node_id),
2253                                                                         &msg.channel_id);
2254                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2255                                                 },
2256                                                 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
2257                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
2258                                                                         log_pubkey!(node_id),
2259                                                                         &msg.channel_id);
2260                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2261                                                 },
2262                                                 MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, ref update_msg } => {
2263                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), None), "Handling SendChannelAnnouncement event in peer_handler for node {} for short channel id {}",
2264                                                                         log_pubkey!(node_id),
2265                                                                         msg.contents.short_channel_id);
2266                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2267                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), update_msg);
2268                                                 },
2269                                                 MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
2270                                                         log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
2271                                                         match self.message_handler.route_handler.handle_channel_announcement(&msg) {
2272                                                                 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2273                                                                         self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
2274                                                                 _ => {},
2275                                                         }
2276                                                         if let Some(msg) = update_msg {
2277                                                                 match self.message_handler.route_handler.handle_channel_update(&msg) {
2278                                                                         Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2279                                                                                 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2280                                                                         _ => {},
2281                                                                 }
2282                                                         }
2283                                                 },
2284                                                 MessageSendEvent::BroadcastChannelUpdate { msg } => {
2285                                                         log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for contents {:?}", msg.contents);
2286                                                         match self.message_handler.route_handler.handle_channel_update(&msg) {
2287                                                                 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2288                                                                         self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2289                                                                 _ => {},
2290                                                         }
2291                                                 },
2292                                                 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
2293                                                         log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler for node {}", msg.contents.node_id);
2294                                                         match self.message_handler.route_handler.handle_node_announcement(&msg) {
2295                                                                 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2296                                                                         self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None),
2297                                                                 _ => {},
2298                                                         }
2299                                                 },
2300                                                 MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
2301                                                         log_trace!(WithContext::from(&self.logger, Some(*node_id), None), "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
2302                                                                         log_pubkey!(node_id), msg.contents.short_channel_id);
2303                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2304                                                 },
2305                                                 MessageSendEvent::HandleError { node_id, action } => {
2306                                                         let logger = WithContext::from(&self.logger, Some(node_id), None);
2307                                                         match action {
2308                                                                 msgs::ErrorAction::DisconnectPeer { msg } => {
2309                                                                         if let Some(msg) = msg.as_ref() {
2310                                                                                 log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2311                                                                                         log_pubkey!(node_id), msg.data);
2312                                                                         } else {
2313                                                                                 log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {}",
2314                                                                                         log_pubkey!(node_id));
2315                                                                         }
2316                                                                         // We do not have the peers write lock, so we just store that we're
2317                                                                         // about to disconnect the peer and do it after we finish
2318                                                                         // processing most messages.
2319                                                                         let msg = msg.map(|msg| wire::Message::<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>::Error(msg));
2320                                                                         peers_to_disconnect.insert(node_id, msg);
2321                                                                 },
2322                                                                 msgs::ErrorAction::DisconnectPeerWithWarning { msg } => {
2323                                                                         log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2324                                                                                 log_pubkey!(node_id), msg.data);
2325                                                                         // We do not have the peers write lock, so we just store that we're
2326                                                                         // about to disconnect the peer and do it after we finish
2327                                                                         // processing most messages.
2328                                                                         peers_to_disconnect.insert(node_id, Some(wire::Message::Warning(msg)));
2329                                                                 },
2330                                                                 msgs::ErrorAction::IgnoreAndLog(level) => {
2331                                                                         log_given_level!(logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2332                                                                 },
2333                                                                 msgs::ErrorAction::IgnoreDuplicateGossip => {},
2334                                                                 msgs::ErrorAction::IgnoreError => {
2335                                                                                 log_debug!(logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2336                                                                         },
2337                                                                 msgs::ErrorAction::SendErrorMessage { ref msg } => {
2338                                                                         log_trace!(logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
2339                                                                                         log_pubkey!(node_id),
2340                                                                                         msg.data);
2341                                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2342                                                                 },
2343                                                                 msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
2344                                                                         log_given_level!(logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
2345                                                                                         log_pubkey!(node_id),
2346                                                                                         msg.data);
2347                                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2348                                                                 },
2349                                                         }
2350                                                 },
2351                                                 MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
2352                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2353                                                 },
2354                                                 MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
2355                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2356                                                 }
2357                                                 MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
2358                                                         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={}",
2359                                                                 log_pubkey!(node_id),
2360                                                                 msg.short_channel_ids.len(),
2361                                                                 msg.first_blocknum,
2362                                                                 msg.number_of_blocks,
2363                                                                 msg.sync_complete);
2364                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2365                                                 }
2366                                                 MessageSendEvent::SendGossipTimestampFilter { ref node_id, ref msg } => {
2367                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2368                                                 }
2369                                         }
2370                                 }
2371
2372                                 for (node_id, msg) in self.message_handler.custom_message_handler.get_and_clear_pending_msg() {
2373                                         if peers_to_disconnect.get(&node_id).is_some() { continue; }
2374                                         self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), &msg);
2375                                 }
2376
2377                                 for (descriptor, peer_mutex) in peers.iter() {
2378                                         let mut peer = peer_mutex.lock().unwrap();
2379                                         if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2380                                         self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer, flush_read_disabled);
2381                                 }
2382                         }
2383                         if !peers_to_disconnect.is_empty() {
2384                                 let mut peers_lock = self.peers.write().unwrap();
2385                                 let peers = &mut *peers_lock;
2386                                 for (node_id, msg) in peers_to_disconnect.drain() {
2387                                         // Note that since we are holding the peers *write* lock we can
2388                                         // remove from node_id_to_descriptor immediately (as no other
2389                                         // thread can be holding the peer lock if we have the global write
2390                                         // lock).
2391
2392                                         let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2393                                         if let Some(mut descriptor) = descriptor_opt {
2394                                                 if let Some(peer_mutex) = peers.remove(&descriptor) {
2395                                                         let mut peer = peer_mutex.lock().unwrap();
2396                                                         if let Some(msg) = msg {
2397                                                                 self.enqueue_message(&mut *peer, &msg);
2398                                                                 // This isn't guaranteed to work, but if there is enough free
2399                                                                 // room in the send buffer, put the error message there...
2400                                                                 self.do_attempt_write_data(&mut descriptor, &mut *peer, false);
2401                                                         }
2402                                                         self.do_disconnect(descriptor, &*peer, "DisconnectPeer HandleError");
2403                                                 } else { debug_assert!(false, "Missing connection for peer"); }
2404                                         }
2405                                 }
2406                         }
2407
2408                         if self.event_processing_state.fetch_sub(1, Ordering::AcqRel) != 1 {
2409                                 // If another thread incremented the state while we were running we should go
2410                                 // around again, but only once.
2411                                 self.event_processing_state.store(1, Ordering::Release);
2412                                 continue;
2413                         }
2414                         break;
2415                 }
2416         }
2417
2418         /// Indicates that the given socket descriptor's connection is now closed.
2419         pub fn socket_disconnected(&self, descriptor: &Descriptor) {
2420                 self.disconnect_event_internal(descriptor);
2421         }
2422
2423         fn do_disconnect(&self, mut descriptor: Descriptor, peer: &Peer, reason: &'static str) {
2424                 if !peer.handshake_complete() {
2425                         log_trace!(self.logger, "Disconnecting peer which hasn't completed handshake due to {}", reason);
2426                         descriptor.disconnect_socket();
2427                         return;
2428                 }
2429
2430                 debug_assert!(peer.their_node_id.is_some());
2431                 if let Some((node_id, _)) = peer.their_node_id {
2432                         log_trace!(WithContext::from(&self.logger, Some(node_id), None), "Disconnecting peer with id {} due to {}", node_id, reason);
2433                         self.message_handler.chan_handler.peer_disconnected(&node_id);
2434                         self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2435                 }
2436                 descriptor.disconnect_socket();
2437         }
2438
2439         fn disconnect_event_internal(&self, descriptor: &Descriptor) {
2440                 let mut peers = self.peers.write().unwrap();
2441                 let peer_option = peers.remove(descriptor);
2442                 match peer_option {
2443                         None => {
2444                                 // This is most likely a simple race condition where the user found that the socket
2445                                 // was disconnected, then we told the user to `disconnect_socket()`, then they
2446                                 // called this method. Either way we're disconnected, return.
2447                         },
2448                         Some(peer_lock) => {
2449                                 let peer = peer_lock.lock().unwrap();
2450                                 if let Some((node_id, _)) = peer.their_node_id {
2451                                         log_trace!(WithContext::from(&self.logger, Some(node_id), None), "Handling disconnection of peer {}", log_pubkey!(node_id));
2452                                         let removed = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2453                                         debug_assert!(removed.is_some(), "descriptor maps should be consistent");
2454                                         if !peer.handshake_complete() { return; }
2455                                         self.message_handler.chan_handler.peer_disconnected(&node_id);
2456                                         self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2457                                 }
2458                         }
2459                 };
2460         }
2461
2462         /// Disconnect a peer given its node id.
2463         ///
2464         /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
2465         /// peer. Thus, be very careful about reentrancy issues.
2466         ///
2467         /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
2468         pub fn disconnect_by_node_id(&self, node_id: PublicKey) {
2469                 let mut peers_lock = self.peers.write().unwrap();
2470                 if let Some(descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
2471                         let peer_opt = peers_lock.remove(&descriptor);
2472                         if let Some(peer_mutex) = peer_opt {
2473                                 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request");
2474                         } else { debug_assert!(false, "node_id_to_descriptor thought we had a peer"); }
2475                 }
2476         }
2477
2478         /// Disconnects all currently-connected peers. This is useful on platforms where there may be
2479         /// an indication that TCP sockets have stalled even if we weren't around to time them out
2480         /// using regular ping/pongs.
2481         pub fn disconnect_all_peers(&self) {
2482                 let mut peers_lock = self.peers.write().unwrap();
2483                 self.node_id_to_descriptor.lock().unwrap().clear();
2484                 let peers = &mut *peers_lock;
2485                 for (descriptor, peer_mutex) in peers.drain() {
2486                         self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request to disconnect all peers");
2487                 }
2488         }
2489
2490         /// This is called when we're blocked on sending additional gossip messages until we receive a
2491         /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
2492         /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
2493         fn maybe_send_extra_ping(&self, peer: &mut Peer) {
2494                 if peer.awaiting_pong_timer_tick_intervals == 0 {
2495                         peer.awaiting_pong_timer_tick_intervals = -1;
2496                         let ping = msgs::Ping {
2497                                 ponglen: 0,
2498                                 byteslen: 64,
2499                         };
2500                         self.enqueue_message(peer, &ping);
2501                 }
2502         }
2503
2504         /// Send pings to each peer and disconnect those which did not respond to the last round of
2505         /// pings.
2506         ///
2507         /// This may be called on any timescale you want, however, roughly once every ten seconds is
2508         /// preferred. The call rate determines both how often we send a ping to our peers and how much
2509         /// time they have to respond before we disconnect them.
2510         ///
2511         /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
2512         /// issues!
2513         ///
2514         /// [`send_data`]: SocketDescriptor::send_data
2515         pub fn timer_tick_occurred(&self) {
2516                 let mut descriptors_needing_disconnect = Vec::new();
2517                 {
2518                         let peers_lock = self.peers.read().unwrap();
2519
2520                         self.update_gossip_backlogged();
2521                         let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
2522
2523                         for (descriptor, peer_mutex) in peers_lock.iter() {
2524                                 let mut peer = peer_mutex.lock().unwrap();
2525                                 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2526
2527                                 if !peer.handshake_complete() {
2528                                         // The peer needs to complete its handshake before we can exchange messages. We
2529                                         // give peers one timer tick to complete handshake, reusing
2530                                         // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
2531                                         // for handshake completion.
2532                                         if peer.awaiting_pong_timer_tick_intervals != 0 {
2533                                                 descriptors_needing_disconnect.push(descriptor.clone());
2534                                         } else {
2535                                                 peer.awaiting_pong_timer_tick_intervals = 1;
2536                                         }
2537                                         continue;
2538                                 }
2539                                 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
2540                                 debug_assert!(peer.their_node_id.is_some());
2541
2542                                 loop { // Used as a `goto` to skip writing a Ping message.
2543                                         if peer.awaiting_pong_timer_tick_intervals == -1 {
2544                                                 // Magic value set in `maybe_send_extra_ping`.
2545                                                 peer.awaiting_pong_timer_tick_intervals = 1;
2546                                                 peer.received_message_since_timer_tick = false;
2547                                                 break;
2548                                         }
2549
2550                                         if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
2551                                                 || peer.awaiting_pong_timer_tick_intervals as u64 >
2552                                                         MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64
2553                                         {
2554                                                 descriptors_needing_disconnect.push(descriptor.clone());
2555                                                 break;
2556                                         }
2557                                         peer.received_message_since_timer_tick = false;
2558
2559                                         if peer.awaiting_pong_timer_tick_intervals > 0 {
2560                                                 peer.awaiting_pong_timer_tick_intervals += 1;
2561                                                 break;
2562                                         }
2563
2564                                         peer.awaiting_pong_timer_tick_intervals = 1;
2565                                         let ping = msgs::Ping {
2566                                                 ponglen: 0,
2567                                                 byteslen: 64,
2568                                         };
2569                                         self.enqueue_message(&mut *peer, &ping);
2570                                         break;
2571                                 }
2572                                 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer, flush_read_disabled);
2573                         }
2574                 }
2575
2576                 if !descriptors_needing_disconnect.is_empty() {
2577                         {
2578                                 let mut peers_lock = self.peers.write().unwrap();
2579                                 for descriptor in descriptors_needing_disconnect {
2580                                         if let Some(peer_mutex) = peers_lock.remove(&descriptor) {
2581                                                 let peer = peer_mutex.lock().unwrap();
2582                                                 if let Some((node_id, _)) = peer.their_node_id {
2583                                                         self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2584                                                 }
2585                                                 self.do_disconnect(descriptor, &*peer, "ping/handshake timeout");
2586                                         }
2587                                 }
2588                         }
2589                 }
2590         }
2591
2592         #[allow(dead_code)]
2593         // Messages of up to 64KB should never end up more than half full with addresses, as that would
2594         // be absurd. We ensure this by checking that at least 100 (our stated public contract on when
2595         // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
2596         // message...
2597         const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (SocketAddress::MAX_LEN as u32 + 1) / 2;
2598         #[allow(dead_code)]
2599         // ...by failing to compile if the number of addresses that would be half of a message is
2600         // smaller than 100:
2601         const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 100;
2602
2603         /// Generates a signed node_announcement from the given arguments, sending it to all connected
2604         /// peers. Note that peers will likely ignore this message unless we have at least one public
2605         /// channel which has at least six confirmations on-chain.
2606         ///
2607         /// `rgb` is a node "color" and `alias` is a printable human-readable string to describe this
2608         /// node to humans. They carry no in-protocol meaning.
2609         ///
2610         /// `addresses` represent the set (possibly empty) of socket addresses on which this node
2611         /// accepts incoming connections. These will be included in the node_announcement, publicly
2612         /// tying these addresses together and to this node. If you wish to preserve user privacy,
2613         /// addresses should likely contain only Tor Onion addresses.
2614         ///
2615         /// Panics if `addresses` is absurdly large (more than 100).
2616         ///
2617         /// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events
2618         pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], mut addresses: Vec<SocketAddress>) {
2619                 if addresses.len() > 100 {
2620                         panic!("More than half the message size was taken up by public addresses!");
2621                 }
2622
2623                 // While all existing nodes handle unsorted addresses just fine, the spec requires that
2624                 // addresses be sorted for future compatibility.
2625                 addresses.sort_by_key(|addr| addr.get_id());
2626
2627                 let features = self.message_handler.chan_handler.provided_node_features()
2628                         | self.message_handler.route_handler.provided_node_features()
2629                         | self.message_handler.onion_message_handler.provided_node_features()
2630                         | self.message_handler.custom_message_handler.provided_node_features();
2631                 let announcement = msgs::UnsignedNodeAnnouncement {
2632                         features,
2633                         timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel),
2634                         node_id: NodeId::from_pubkey(&self.node_signer.get_node_id(Recipient::Node).unwrap()),
2635                         rgb,
2636                         alias: NodeAlias(alias),
2637                         addresses,
2638                         excess_address_data: Vec::new(),
2639                         excess_data: Vec::new(),
2640                 };
2641                 let node_announce_sig = match self.node_signer.sign_gossip_message(
2642                         msgs::UnsignedGossipMessage::NodeAnnouncement(&announcement)
2643                 ) {
2644                         Ok(sig) => sig,
2645                         Err(_) => {
2646                                 log_error!(self.logger, "Failed to generate signature for node_announcement");
2647                                 return;
2648                         },
2649                 };
2650
2651                 let msg = msgs::NodeAnnouncement {
2652                         signature: node_announce_sig,
2653                         contents: announcement
2654                 };
2655
2656                 log_debug!(self.logger, "Broadcasting NodeAnnouncement after passing it to our own RoutingMessageHandler.");
2657                 let _ = self.message_handler.route_handler.handle_node_announcement(&msg);
2658                 self.forward_broadcast_msg(&*self.peers.read().unwrap(), &wire::Message::NodeAnnouncement(msg), None);
2659         }
2660 }
2661
2662 fn is_gossip_msg(type_id: u16) -> bool {
2663         match type_id {
2664                 msgs::ChannelAnnouncement::TYPE |
2665                 msgs::ChannelUpdate::TYPE |
2666                 msgs::NodeAnnouncement::TYPE |
2667                 msgs::QueryChannelRange::TYPE |
2668                 msgs::ReplyChannelRange::TYPE |
2669                 msgs::QueryShortChannelIds::TYPE |
2670                 msgs::ReplyShortChannelIdsEnd::TYPE => true,
2671                 _ => false
2672         }
2673 }
2674
2675 #[cfg(test)]
2676 mod tests {
2677         use crate::sign::{NodeSigner, Recipient};
2678         use crate::events;
2679         use crate::io;
2680         use crate::ln::ChannelId;
2681         use crate::ln::features::{InitFeatures, NodeFeatures};
2682         use crate::ln::peer_channel_encryptor::PeerChannelEncryptor;
2683         use crate::ln::peer_handler::{CustomMessageHandler, PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses};
2684         use crate::ln::{msgs, wire};
2685         use crate::ln::msgs::{LightningError, SocketAddress};
2686         use crate::util::test_utils;
2687
2688         use bitcoin::Network;
2689         use bitcoin::blockdata::constants::ChainHash;
2690         use bitcoin::secp256k1::{PublicKey, SecretKey};
2691
2692         use crate::sync::{Arc, Mutex};
2693         use core::convert::Infallible;
2694         use core::sync::atomic::{AtomicBool, Ordering};
2695
2696         #[allow(unused_imports)]
2697         use crate::prelude::*;
2698
2699         #[derive(Clone)]
2700         struct FileDescriptor {
2701                 fd: u16,
2702                 outbound_data: Arc<Mutex<Vec<u8>>>,
2703                 disconnect: Arc<AtomicBool>,
2704         }
2705         impl PartialEq for FileDescriptor {
2706                 fn eq(&self, other: &Self) -> bool {
2707                         self.fd == other.fd
2708                 }
2709         }
2710         impl Eq for FileDescriptor { }
2711         impl core::hash::Hash for FileDescriptor {
2712                 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
2713                         self.fd.hash(hasher)
2714                 }
2715         }
2716
2717         impl SocketDescriptor for FileDescriptor {
2718                 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
2719                         self.outbound_data.lock().unwrap().extend_from_slice(data);
2720                         data.len()
2721                 }
2722
2723                 fn disconnect_socket(&mut self) { self.disconnect.store(true, Ordering::Release); }
2724         }
2725
2726         struct PeerManagerCfg {
2727                 chan_handler: test_utils::TestChannelMessageHandler,
2728                 routing_handler: test_utils::TestRoutingMessageHandler,
2729                 custom_handler: TestCustomMessageHandler,
2730                 logger: test_utils::TestLogger,
2731                 node_signer: test_utils::TestNodeSigner,
2732         }
2733
2734         struct TestCustomMessageHandler {
2735                 features: InitFeatures,
2736         }
2737
2738         impl wire::CustomMessageReader for TestCustomMessageHandler {
2739                 type CustomMessage = Infallible;
2740                 fn read<R: io::Read>(&self, _: u16, _: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
2741                         Ok(None)
2742                 }
2743         }
2744
2745         impl CustomMessageHandler for TestCustomMessageHandler {
2746                 fn handle_custom_message(&self, _: Infallible, _: &PublicKey) -> Result<(), LightningError> {
2747                         unreachable!();
2748                 }
2749
2750                 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
2751
2752                 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
2753
2754                 fn provided_init_features(&self, _: &PublicKey) -> InitFeatures {
2755                         self.features.clone()
2756                 }
2757         }
2758
2759         fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2760                 let mut cfgs = Vec::new();
2761                 for i in 0..peer_count {
2762                         let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2763                         let features = {
2764                                 let mut feature_bits = vec![0u8; 33];
2765                                 feature_bits[32] = 0b00000001;
2766                                 InitFeatures::from_le_bytes(feature_bits)
2767                         };
2768                         cfgs.push(
2769                                 PeerManagerCfg{
2770                                         chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2771                                         logger: test_utils::TestLogger::new(),
2772                                         routing_handler: test_utils::TestRoutingMessageHandler::new(),
2773                                         custom_handler: TestCustomMessageHandler { features },
2774                                         node_signer: test_utils::TestNodeSigner::new(node_secret),
2775                                 }
2776                         );
2777                 }
2778
2779                 cfgs
2780         }
2781
2782         fn create_feature_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2783                 let mut cfgs = Vec::new();
2784                 for i in 0..peer_count {
2785                         let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2786                         let features = {
2787                                 let mut feature_bits = vec![0u8; 33 + i + 1];
2788                                 feature_bits[33 + i] = 0b00000001;
2789                                 InitFeatures::from_le_bytes(feature_bits)
2790                         };
2791                         cfgs.push(
2792                                 PeerManagerCfg{
2793                                         chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2794                                         logger: test_utils::TestLogger::new(),
2795                                         routing_handler: test_utils::TestRoutingMessageHandler::new(),
2796                                         custom_handler: TestCustomMessageHandler { features },
2797                                         node_signer: test_utils::TestNodeSigner::new(node_secret),
2798                                 }
2799                         );
2800                 }
2801
2802                 cfgs
2803         }
2804
2805         fn create_chain_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2806                 let mut cfgs = Vec::new();
2807                 for i in 0..peer_count {
2808                         let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2809                         let features = InitFeatures::from_le_bytes(vec![0u8; 33]);
2810                         let network = ChainHash::from(&[i as u8; 32]);
2811                         cfgs.push(
2812                                 PeerManagerCfg{
2813                                         chan_handler: test_utils::TestChannelMessageHandler::new(network),
2814                                         logger: test_utils::TestLogger::new(),
2815                                         routing_handler: test_utils::TestRoutingMessageHandler::new(),
2816                                         custom_handler: TestCustomMessageHandler { features },
2817                                         node_signer: test_utils::TestNodeSigner::new(node_secret),
2818                                 }
2819                         );
2820                 }
2821
2822                 cfgs
2823         }
2824
2825         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>> {
2826                 let mut peers = Vec::new();
2827                 for i in 0..peer_count {
2828                         let ephemeral_bytes = [i as u8; 32];
2829                         let msg_handler = MessageHandler {
2830                                 chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler,
2831                                 onion_message_handler: IgnoringMessageHandler {}, custom_message_handler: &cfgs[i].custom_handler
2832                         };
2833                         let peer = PeerManager::new(msg_handler, 0, &ephemeral_bytes, &cfgs[i].logger, &cfgs[i].node_signer);
2834                         peers.push(peer);
2835                 }
2836
2837                 peers
2838         }
2839
2840         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) {
2841                 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2842                 let mut fd_a = FileDescriptor {
2843                         fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2844                         disconnect: Arc::new(AtomicBool::new(false)),
2845                 };
2846                 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2847                 let id_b = peer_b.node_signer.get_node_id(Recipient::Node).unwrap();
2848                 let features_a = peer_a.init_features(&id_b);
2849                 let features_b = peer_b.init_features(&id_a);
2850                 let mut fd_b = FileDescriptor {
2851                         fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2852                         disconnect: Arc::new(AtomicBool::new(false)),
2853                 };
2854                 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2855                 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2856                 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2857                 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2858                 peer_a.process_events();
2859
2860                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2861                 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2862
2863                 peer_b.process_events();
2864                 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2865                 assert_eq!(peer_a.read_event(&mut fd_a, &b_data).unwrap(), false);
2866
2867                 peer_a.process_events();
2868                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2869                 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2870
2871                 assert_eq!(peer_a.peer_by_node_id(&id_b).unwrap().counterparty_node_id, id_b);
2872                 assert_eq!(peer_a.peer_by_node_id(&id_b).unwrap().socket_address, Some(addr_b));
2873                 assert_eq!(peer_a.peer_by_node_id(&id_b).unwrap().init_features, features_b);
2874                 assert_eq!(peer_b.peer_by_node_id(&id_a).unwrap().counterparty_node_id, id_a);
2875                 assert_eq!(peer_b.peer_by_node_id(&id_a).unwrap().socket_address, Some(addr_a));
2876                 assert_eq!(peer_b.peer_by_node_id(&id_a).unwrap().init_features, features_a);
2877                 (fd_a.clone(), fd_b.clone())
2878         }
2879
2880         #[test]
2881         #[cfg(feature = "std")]
2882         fn fuzz_threaded_connections() {
2883                 // Spawn two threads which repeatedly connect two peers together, leading to "got second
2884                 // connection with peer" disconnections and rapid reconnect. This previously found an issue
2885                 // with our internal map consistency, and is a generally good smoke test of disconnection.
2886                 let cfgs = Arc::new(create_peermgr_cfgs(2));
2887                 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
2888                 let peers = Arc::new(create_network(2, unsafe { &*(&*cfgs as *const _) as &'static _ }));
2889
2890                 let start_time = std::time::Instant::now();
2891                 macro_rules! spawn_thread { ($id: expr) => { {
2892                         let peers = Arc::clone(&peers);
2893                         let cfgs = Arc::clone(&cfgs);
2894                         std::thread::spawn(move || {
2895                                 let mut ctr = 0;
2896                                 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2897                                         let id_a = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
2898                                         let mut fd_a = FileDescriptor {
2899                                                 fd: $id  + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2900                                                 disconnect: Arc::new(AtomicBool::new(false)),
2901                                         };
2902                                         let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2903                                         let mut fd_b = FileDescriptor {
2904                                                 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2905                                                 disconnect: Arc::new(AtomicBool::new(false)),
2906                                         };
2907                                         let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2908                                         let initial_data = peers[1].new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2909                                         peers[0].new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2910                                         if peers[0].read_event(&mut fd_a, &initial_data).is_err() { break; }
2911
2912                                         while start_time.elapsed() < std::time::Duration::from_secs(1) {
2913                                                 peers[0].process_events();
2914                                                 if fd_a.disconnect.load(Ordering::Acquire) { break; }
2915                                                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2916                                                 if peers[1].read_event(&mut fd_b, &a_data).is_err() { break; }
2917
2918                                                 peers[1].process_events();
2919                                                 if fd_b.disconnect.load(Ordering::Acquire) { break; }
2920                                                 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2921                                                 if peers[0].read_event(&mut fd_a, &b_data).is_err() { break; }
2922
2923                                                 cfgs[0].chan_handler.pending_events.lock().unwrap()
2924                                                         .push(crate::events::MessageSendEvent::SendShutdown {
2925                                                                 node_id: peers[1].node_signer.get_node_id(Recipient::Node).unwrap(),
2926                                                                 msg: msgs::Shutdown {
2927                                                                         channel_id: ChannelId::new_zero(),
2928                                                                         scriptpubkey: bitcoin::ScriptBuf::new(),
2929                                                                 },
2930                                                         });
2931                                                 cfgs[1].chan_handler.pending_events.lock().unwrap()
2932                                                         .push(crate::events::MessageSendEvent::SendShutdown {
2933                                                                 node_id: peers[0].node_signer.get_node_id(Recipient::Node).unwrap(),
2934                                                                 msg: msgs::Shutdown {
2935                                                                         channel_id: ChannelId::new_zero(),
2936                                                                         scriptpubkey: bitcoin::ScriptBuf::new(),
2937                                                                 },
2938                                                         });
2939
2940                                                 if ctr % 2 == 0 {
2941                                                         peers[0].timer_tick_occurred();
2942                                                         peers[1].timer_tick_occurred();
2943                                                 }
2944                                         }
2945
2946                                         peers[0].socket_disconnected(&fd_a);
2947                                         peers[1].socket_disconnected(&fd_b);
2948                                         ctr += 1;
2949                                         std::thread::sleep(std::time::Duration::from_micros(1));
2950                                 }
2951                         })
2952                 } } }
2953                 let thrd_a = spawn_thread!(1);
2954                 let thrd_b = spawn_thread!(2);
2955
2956                 thrd_a.join().unwrap();
2957                 thrd_b.join().unwrap();
2958         }
2959
2960         #[test]
2961         fn test_feature_incompatible_peers() {
2962                 let cfgs = create_peermgr_cfgs(2);
2963                 let incompatible_cfgs = create_feature_incompatible_peermgr_cfgs(2);
2964
2965                 let peers = create_network(2, &cfgs);
2966                 let incompatible_peers = create_network(2, &incompatible_cfgs);
2967                 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
2968                 for (peer_a, peer_b) in peer_pairs.iter() {
2969                         let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2970                         let mut fd_a = FileDescriptor {
2971                                 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2972                                 disconnect: Arc::new(AtomicBool::new(false)),
2973                         };
2974                         let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2975                         let mut fd_b = FileDescriptor {
2976                                 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2977                                 disconnect: Arc::new(AtomicBool::new(false)),
2978                         };
2979                         let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2980                         let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2981                         peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2982                         assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2983                         peer_a.process_events();
2984
2985                         let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2986                         assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2987
2988                         peer_b.process_events();
2989                         let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2990
2991                         // Should fail because of unknown required features
2992                         assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
2993                 }
2994         }
2995
2996         #[test]
2997         fn test_chain_incompatible_peers() {
2998                 let cfgs = create_peermgr_cfgs(2);
2999                 let incompatible_cfgs = create_chain_incompatible_peermgr_cfgs(2);
3000
3001                 let peers = create_network(2, &cfgs);
3002                 let incompatible_peers = create_network(2, &incompatible_cfgs);
3003                 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
3004                 for (peer_a, peer_b) in peer_pairs.iter() {
3005                         let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
3006                         let mut fd_a = FileDescriptor {
3007                                 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3008                                 disconnect: Arc::new(AtomicBool::new(false)),
3009                         };
3010                         let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
3011                         let mut fd_b = FileDescriptor {
3012                                 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3013                                 disconnect: Arc::new(AtomicBool::new(false)),
3014                         };
3015                         let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
3016                         let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
3017                         peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
3018                         assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
3019                         peer_a.process_events();
3020
3021                         let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3022                         assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
3023
3024                         peer_b.process_events();
3025                         let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3026
3027                         // Should fail because of incompatible chains
3028                         assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
3029                 }
3030         }
3031
3032         #[test]
3033         fn test_disconnect_peer() {
3034                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
3035                 // push a DisconnectPeer event to remove the node flagged by id
3036                 let cfgs = create_peermgr_cfgs(2);
3037                 let peers = create_network(2, &cfgs);
3038                 establish_connection(&peers[0], &peers[1]);
3039                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3040
3041                 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
3042                 cfgs[0].chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
3043                         node_id: their_id,
3044                         action: msgs::ErrorAction::DisconnectPeer { msg: None },
3045                 });
3046
3047                 peers[0].process_events();
3048                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3049         }
3050
3051         #[test]
3052         fn test_send_simple_msg() {
3053                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
3054                 // push a message from one peer to another.
3055                 let cfgs = create_peermgr_cfgs(2);
3056                 let a_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
3057                 let b_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
3058                 let mut peers = create_network(2, &cfgs);
3059                 let (fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
3060                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3061
3062                 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
3063
3064                 let msg = msgs::Shutdown { channel_id: ChannelId::from_bytes([42; 32]), scriptpubkey: bitcoin::ScriptBuf::new() };
3065                 a_chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::SendShutdown {
3066                         node_id: their_id, msg: msg.clone()
3067                 });
3068                 peers[0].message_handler.chan_handler = &a_chan_handler;
3069
3070                 b_chan_handler.expect_receive_msg(wire::Message::Shutdown(msg));
3071                 peers[1].message_handler.chan_handler = &b_chan_handler;
3072
3073                 peers[0].process_events();
3074
3075                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3076                 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
3077         }
3078
3079         #[test]
3080         fn test_non_init_first_msg() {
3081                 // Simple test of the first message received over a connection being something other than
3082                 // Init. This results in an immediate disconnection, which previously included a spurious
3083                 // peer_disconnected event handed to event handlers (which would panic in
3084                 // `TestChannelMessageHandler` here).
3085                 let cfgs = create_peermgr_cfgs(2);
3086                 let peers = create_network(2, &cfgs);
3087
3088                 let mut fd_dup = FileDescriptor {
3089                         fd: 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
3090                         disconnect: Arc::new(AtomicBool::new(false)),
3091                 };
3092                 let addr_dup = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1003};
3093                 let id_a = cfgs[0].node_signer.get_node_id(Recipient::Node).unwrap();
3094                 peers[0].new_inbound_connection(fd_dup.clone(), Some(addr_dup.clone())).unwrap();
3095
3096                 let mut dup_encryptor = PeerChannelEncryptor::new_outbound(id_a, SecretKey::from_slice(&[42; 32]).unwrap());
3097                 let initial_data = dup_encryptor.get_act_one(&peers[1].secp_ctx);
3098                 assert_eq!(peers[0].read_event(&mut fd_dup, &initial_data).unwrap(), false);
3099                 peers[0].process_events();
3100
3101                 let a_data = fd_dup.outbound_data.lock().unwrap().split_off(0);
3102                 let (act_three, _) =
3103                         dup_encryptor.process_act_two(&a_data[..], &&cfgs[1].node_signer).unwrap();
3104                 assert_eq!(peers[0].read_event(&mut fd_dup, &act_three).unwrap(), false);
3105
3106                 let not_init_msg = msgs::Ping { ponglen: 4, byteslen: 0 };
3107                 let msg_bytes = dup_encryptor.encrypt_message(&not_init_msg);
3108                 assert!(peers[0].read_event(&mut fd_dup, &msg_bytes).is_err());
3109         }
3110
3111         #[test]
3112         fn test_disconnect_all_peer() {
3113                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
3114                 // then calls disconnect_all_peers
3115                 let cfgs = create_peermgr_cfgs(2);
3116                 let peers = create_network(2, &cfgs);
3117                 establish_connection(&peers[0], &peers[1]);
3118                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3119
3120                 peers[0].disconnect_all_peers();
3121                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3122         }
3123
3124         #[test]
3125         fn test_timer_tick_occurred() {
3126                 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
3127                 let cfgs = create_peermgr_cfgs(2);
3128                 let peers = create_network(2, &cfgs);
3129                 establish_connection(&peers[0], &peers[1]);
3130                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3131
3132                 // peers[0] awaiting_pong is set to true, but the Peer is still connected
3133                 peers[0].timer_tick_occurred();
3134                 peers[0].process_events();
3135                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3136
3137                 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
3138                 peers[0].timer_tick_occurred();
3139                 peers[0].process_events();
3140                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3141         }
3142
3143         #[test]
3144         fn test_do_attempt_write_data() {
3145                 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
3146                 let cfgs = create_peermgr_cfgs(2);
3147                 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
3148                 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
3149                 let peers = create_network(2, &cfgs);
3150
3151                 // By calling establish_connect, we trigger do_attempt_write_data between
3152                 // the peers. Previously this function would mistakenly enter an infinite loop
3153                 // when there were more channel messages available than could fit into a peer's
3154                 // buffer. This issue would now be detected by this test (because we use custom
3155                 // RoutingMessageHandlers that intentionally return more channel messages
3156                 // than can fit into a peer's buffer).
3157                 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
3158
3159                 // Make each peer to read the messages that the other peer just wrote to them. Note that
3160                 // due to the max-message-before-ping limits this may take a few iterations to complete.
3161                 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
3162                         peers[1].process_events();
3163                         let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3164                         assert!(!a_read_data.is_empty());
3165
3166                         peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
3167                         peers[0].process_events();
3168
3169                         let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3170                         assert!(!b_read_data.is_empty());
3171                         peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
3172
3173                         peers[0].process_events();
3174                         assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
3175                 }
3176
3177                 // Check that each peer has received the expected number of channel updates and channel
3178                 // announcements.
3179                 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
3180                 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
3181                 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
3182                 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
3183         }
3184
3185         #[test]
3186         fn test_handshake_timeout() {
3187                 // Tests that we time out a peer still waiting on handshake completion after a full timer
3188                 // tick.
3189                 let cfgs = create_peermgr_cfgs(2);
3190                 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
3191                 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
3192                 let peers = create_network(2, &cfgs);
3193
3194                 let a_id = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
3195                 let mut fd_a = FileDescriptor {
3196                         fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3197                         disconnect: Arc::new(AtomicBool::new(false)),
3198                 };
3199                 let mut fd_b = FileDescriptor {
3200                         fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3201                         disconnect: Arc::new(AtomicBool::new(false)),
3202                 };
3203                 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
3204                 peers[0].new_inbound_connection(fd_a.clone(), None).unwrap();
3205
3206                 // If we get a single timer tick before completion, that's fine
3207                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3208                 peers[0].timer_tick_occurred();
3209                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3210
3211                 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
3212                 peers[0].process_events();
3213                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3214                 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
3215                 peers[1].process_events();
3216
3217                 // ...but if we get a second timer tick, we should disconnect the peer
3218                 peers[0].timer_tick_occurred();
3219                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3220
3221                 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3222                 assert!(peers[0].read_event(&mut fd_a, &b_data).is_err());
3223         }
3224
3225         #[test]
3226         fn test_filter_addresses(){
3227                 // Tests the filter_addresses function.
3228
3229                 // For (10/8)
3230                 let ip_address = SocketAddress::TcpIpV4{addr: [10, 0, 0, 0], port: 1000};
3231                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3232                 let ip_address = SocketAddress::TcpIpV4{addr: [10, 0, 255, 201], port: 1000};
3233                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3234                 let ip_address = SocketAddress::TcpIpV4{addr: [10, 255, 255, 255], port: 1000};
3235                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3236
3237                 // For (0/8)
3238                 let ip_address = SocketAddress::TcpIpV4{addr: [0, 0, 0, 0], port: 1000};
3239                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3240                 let ip_address = SocketAddress::TcpIpV4{addr: [0, 0, 255, 187], port: 1000};
3241                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3242                 let ip_address = SocketAddress::TcpIpV4{addr: [0, 255, 255, 255], port: 1000};
3243                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3244
3245                 // For (100.64/10)
3246                 let ip_address = SocketAddress::TcpIpV4{addr: [100, 64, 0, 0], port: 1000};
3247                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3248                 let ip_address = SocketAddress::TcpIpV4{addr: [100, 78, 255, 0], port: 1000};
3249                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3250                 let ip_address = SocketAddress::TcpIpV4{addr: [100, 127, 255, 255], port: 1000};
3251                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3252
3253                 // For (127/8)
3254                 let ip_address = SocketAddress::TcpIpV4{addr: [127, 0, 0, 0], port: 1000};
3255                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3256                 let ip_address = SocketAddress::TcpIpV4{addr: [127, 65, 73, 0], port: 1000};
3257                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3258                 let ip_address = SocketAddress::TcpIpV4{addr: [127, 255, 255, 255], port: 1000};
3259                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3260
3261                 // For (169.254/16)
3262                 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 0, 0], port: 1000};
3263                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3264                 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 221, 101], port: 1000};
3265                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3266                 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 255, 255], port: 1000};
3267                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3268
3269                 // For (172.16/12)
3270                 let ip_address = SocketAddress::TcpIpV4{addr: [172, 16, 0, 0], port: 1000};
3271                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3272                 let ip_address = SocketAddress::TcpIpV4{addr: [172, 27, 101, 23], port: 1000};
3273                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3274                 let ip_address = SocketAddress::TcpIpV4{addr: [172, 31, 255, 255], port: 1000};
3275                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3276
3277                 // For (192.168/16)
3278                 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 0, 0], port: 1000};
3279                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3280                 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 205, 159], port: 1000};
3281                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3282                 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 255, 255], port: 1000};
3283                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3284
3285                 // For (192.88.99/24)
3286                 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 0], port: 1000};
3287                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3288                 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 140], port: 1000};
3289                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3290                 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 255], port: 1000};
3291                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3292
3293                 // For other IPv4 addresses
3294                 let ip_address = SocketAddress::TcpIpV4{addr: [188, 255, 99, 0], port: 1000};
3295                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3296                 let ip_address = SocketAddress::TcpIpV4{addr: [123, 8, 129, 14], port: 1000};
3297                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3298                 let ip_address = SocketAddress::TcpIpV4{addr: [2, 88, 9, 255], port: 1000};
3299                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3300
3301                 // For (2000::/3)
3302                 let ip_address = SocketAddress::TcpIpV6{addr: [32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], port: 1000};
3303                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3304                 let ip_address = SocketAddress::TcpIpV6{addr: [45, 34, 209, 190, 0, 123, 55, 34, 0, 0, 3, 27, 201, 0, 0, 0], port: 1000};
3305                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3306                 let ip_address = SocketAddress::TcpIpV6{addr: [63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], port: 1000};
3307                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3308
3309                 // For other IPv6 addresses
3310                 let ip_address = SocketAddress::TcpIpV6{addr: [24, 240, 12, 32, 0, 0, 0, 0, 20, 97, 0, 32, 121, 254, 0, 0], port: 1000};
3311                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3312                 let ip_address = SocketAddress::TcpIpV6{addr: [68, 23, 56, 63, 0, 0, 2, 7, 75, 109, 0, 39, 0, 0, 0, 0], port: 1000};
3313                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3314                 let ip_address = SocketAddress::TcpIpV6{addr: [101, 38, 140, 230, 100, 0, 30, 98, 0, 26, 0, 0, 57, 96, 0, 0], port: 1000};
3315                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3316
3317                 // For (None)
3318                 assert_eq!(filter_addresses(None), None);
3319         }
3320
3321         #[test]
3322         #[cfg(feature = "std")]
3323         fn test_process_events_multithreaded() {
3324                 use std::time::{Duration, Instant};
3325                 // Test that `process_events` getting called on multiple threads doesn't generate too many
3326                 // loop iterations.
3327                 // Each time `process_events` goes around the loop we call
3328                 // `get_and_clear_pending_msg_events`, which we count using the `TestMessageHandler`.
3329                 // Because the loop should go around once more after a call which fails to take the
3330                 // single-threaded lock, if we write zero to the counter before calling `process_events` we
3331                 // should never observe there having been more than 2 loop iterations.
3332                 // Further, because the last thread to exit will call `process_events` before returning, we
3333                 // should always have at least one count at the end.
3334                 let cfg = Arc::new(create_peermgr_cfgs(1));
3335                 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
3336                 let peer = Arc::new(create_network(1, unsafe { &*(&*cfg as *const _) as &'static _ }).pop().unwrap());
3337
3338                 let exit_flag = Arc::new(AtomicBool::new(false));
3339                 macro_rules! spawn_thread { () => { {
3340                         let thread_cfg = Arc::clone(&cfg);
3341                         let thread_peer = Arc::clone(&peer);
3342                         let thread_exit = Arc::clone(&exit_flag);
3343                         std::thread::spawn(move || {
3344                                 while !thread_exit.load(Ordering::Acquire) {
3345                                         thread_cfg[0].chan_handler.message_fetch_counter.store(0, Ordering::Release);
3346                                         thread_peer.process_events();
3347                                         std::thread::sleep(Duration::from_micros(1));
3348                                 }
3349                         })
3350                 } } }
3351
3352                 let thread_a = spawn_thread!();
3353                 let thread_b = spawn_thread!();
3354                 let thread_c = spawn_thread!();
3355
3356                 let start_time = Instant::now();
3357                 while start_time.elapsed() < Duration::from_millis(100) {
3358                         let val = cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire);
3359                         assert!(val <= 2);
3360                         std::thread::yield_now(); // Winblowz seemingly doesn't ever interrupt threads?!
3361                 }
3362
3363                 exit_flag.store(true, Ordering::Release);
3364                 thread_a.join().unwrap();
3365                 thread_b.join().unwrap();
3366                 thread_c.join().unwrap();
3367                 assert!(cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire) >= 1);
3368         }
3369 }