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