1258026e17ec123f9e28b9047dbf65b225a8f3db
[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 ln::features::InitFeatures;
21 use ln::msgs;
22 use ln::msgs::{ChannelMessageHandler, LightningError, NetAddress, OnionMessageHandler, RoutingMessageHandler};
23 use ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
24 use util::ser::{VecWriter, Writeable, Writer};
25 use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
26 use ln::wire;
27 use ln::wire::Encode;
28 use routing::gossip::{NetworkGraph, P2PGossipSync};
29 use util::atomic_counter::AtomicCounter;
30 use util::events::{MessageSendEvent, MessageSendEventsProvider, OnionMessageProvider};
31 use util::logger::Logger;
32
33 use prelude::*;
34 use io;
35 use alloc::collections::LinkedList;
36 use sync::{Arc, Mutex, MutexGuard, FairRwLock};
37 use core::sync::atomic::{AtomicBool, Ordering};
38 use core::{cmp, hash, fmt, mem};
39 use core::ops::Deref;
40 use core::convert::Infallible;
41 #[cfg(feature = "std")] use std::error;
42
43 use bitcoin::hashes::sha256::Hash as Sha256;
44 use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
45 use bitcoin::hashes::{HashEngine, Hash};
46
47 /// Handler for BOLT1-compliant messages.
48 pub trait CustomMessageHandler: wire::CustomMessageReader {
49         /// Called with the message type that was received and the buffer to be read.
50         /// Can return a `MessageHandlingError` if the message could not be handled.
51         fn handle_custom_message(&self, msg: Self::CustomMessage, sender_node_id: &PublicKey) -> Result<(), LightningError>;
52
53         /// Gets the list of pending messages which were generated by the custom message
54         /// handler, clearing the list in the process. The first tuple element must
55         /// correspond to the intended recipients node ids. If no connection to one of the
56         /// specified node does not exist, the message is simply not sent to it.
57         fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)>;
58 }
59
60 /// A dummy struct which implements `RoutingMessageHandler` without storing any routing information
61 /// or doing any processing. You can provide one of these as the route_handler in a MessageHandler.
62 pub struct IgnoringMessageHandler{}
63 impl MessageSendEventsProvider for IgnoringMessageHandler {
64         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> { Vec::new() }
65 }
66 impl RoutingMessageHandler for IgnoringMessageHandler {
67         fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
68         fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
69         fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
70         fn get_next_channel_announcement(&self, _starting_point: u64) ->
71                 Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { None }
72         fn get_next_node_announcement(&self, _starting_point: Option<&PublicKey>) -> Option<msgs::NodeAnnouncement> { None }
73         fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init) {}
74         fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
75         fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
76         fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) }
77         fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) }
78 }
79 impl OnionMessageProvider for IgnoringMessageHandler {
80         fn next_onion_message_for_peer(&self, _peer_node_id: PublicKey) -> Option<msgs::OnionMessage> { None }
81 }
82 impl OnionMessageHandler for IgnoringMessageHandler {
83         fn handle_onion_message(&self, _their_node_id: &PublicKey, _msg: &msgs::OnionMessage) {}
84 }
85 impl Deref for IgnoringMessageHandler {
86         type Target = IgnoringMessageHandler;
87         fn deref(&self) -> &Self { self }
88 }
89
90 // Implement Type for Infallible, note that it cannot be constructed, and thus you can never call a
91 // method that takes self for it.
92 impl wire::Type for Infallible {
93         fn type_id(&self) -> u16 {
94                 unreachable!();
95         }
96 }
97 impl Writeable for Infallible {
98         fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
99                 unreachable!();
100         }
101 }
102
103 impl wire::CustomMessageReader for IgnoringMessageHandler {
104         type CustomMessage = Infallible;
105         fn read<R: io::Read>(&self, _message_type: u16, _buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
106                 Ok(None)
107         }
108 }
109
110 impl CustomMessageHandler for IgnoringMessageHandler {
111         fn handle_custom_message(&self, _msg: Infallible, _sender_node_id: &PublicKey) -> Result<(), LightningError> {
112                 // Since we always return `None` in the read the handle method should never be called.
113                 unreachable!();
114         }
115
116         fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
117 }
118
119 /// A dummy struct which implements `ChannelMessageHandler` without having any channels.
120 /// You can provide one of these as the route_handler in a MessageHandler.
121 pub struct ErroringMessageHandler {
122         message_queue: Mutex<Vec<MessageSendEvent>>
123 }
124 impl ErroringMessageHandler {
125         /// Constructs a new ErroringMessageHandler
126         pub fn new() -> Self {
127                 Self { message_queue: Mutex::new(Vec::new()) }
128         }
129         fn push_error(&self, node_id: &PublicKey, channel_id: [u8; 32]) {
130                 self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
131                         action: msgs::ErrorAction::SendErrorMessage {
132                                 msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
133                         },
134                         node_id: node_id.clone(),
135                 });
136         }
137 }
138 impl MessageSendEventsProvider for ErroringMessageHandler {
139         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
140                 let mut res = Vec::new();
141                 mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
142                 res
143         }
144 }
145 impl ChannelMessageHandler for ErroringMessageHandler {
146         // Any messages which are related to a specific channel generate an error message to let the
147         // peer know we don't care about channels.
148         fn handle_open_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::OpenChannel) {
149                 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
150         }
151         fn handle_accept_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::AcceptChannel) {
152                 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
153         }
154         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
155                 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
156         }
157         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
158                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
159         }
160         fn handle_channel_ready(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
161                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
162         }
163         fn handle_shutdown(&self, their_node_id: &PublicKey, _their_features: &InitFeatures, msg: &msgs::Shutdown) {
164                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
165         }
166         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
167                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
168         }
169         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
170                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
171         }
172         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
173                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
174         }
175         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
176                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
177         }
178         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
179                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
180         }
181         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
182                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
183         }
184         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
185                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
186         }
187         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
188                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
189         }
190         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
191                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
192         }
193         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
194                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
195         }
196         // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them.
197         fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
198         fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
199         fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {}
200         fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
201 }
202 impl Deref for ErroringMessageHandler {
203         type Target = ErroringMessageHandler;
204         fn deref(&self) -> &Self { self }
205 }
206
207 /// Provides references to trait impls which handle different types of messages.
208 pub struct MessageHandler<CM: Deref, RM: Deref, OM: Deref> where
209                 CM::Target: ChannelMessageHandler,
210                 RM::Target: RoutingMessageHandler,
211                 OM::Target: OnionMessageHandler,
212 {
213         /// A message handler which handles messages specific to channels. Usually this is just a
214         /// [`ChannelManager`] object or an [`ErroringMessageHandler`].
215         ///
216         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
217         pub chan_handler: CM,
218         /// A message handler which handles messages updating our knowledge of the network channel
219         /// graph. Usually this is just a [`P2PGossipSync`] object or an [`IgnoringMessageHandler`].
220         ///
221         /// [`P2PGossipSync`]: crate::routing::gossip::P2PGossipSync
222         pub route_handler: RM,
223
224         /// A message handler which handles onion messages. For now, this can only be an
225         /// [`IgnoringMessageHandler`].
226         pub onion_message_handler: OM,
227 }
228
229 /// Provides an object which can be used to send data to and which uniquely identifies a connection
230 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
231 /// implement Hash to meet the PeerManager API.
232 ///
233 /// For efficiency, Clone should be relatively cheap for this type.
234 ///
235 /// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original
236 /// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it
237 /// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no
238 /// further calls to the [`PeerManager`] related to the original socket occur. This allows you to
239 /// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish
240 /// to simply use another value which is guaranteed to be globally unique instead.
241 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
242         /// Attempts to send some data from the given slice to the peer.
243         ///
244         /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
245         /// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
246         /// called and further write attempts may occur until that time.
247         ///
248         /// If the returned size is smaller than `data.len()`, a
249         /// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
250         /// written. Additionally, until a `send_data` event completes fully, no further
251         /// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
252         /// prevent denial-of-service issues, you should not read or buffer any data from the socket
253         /// until then.
254         ///
255         /// If a [`PeerManager::read_event`] call on this descriptor had previously returned true
256         /// (indicating that read events should be paused to prevent DoS in the send buffer),
257         /// `resume_read` may be set indicating that read events on this descriptor should resume. A
258         /// `resume_read` of false carries no meaning, and should not cause any action.
259         fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
260         /// Disconnect the socket pointed to by this SocketDescriptor.
261         ///
262         /// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
263         /// call (doing so is a noop).
264         fn disconnect_socket(&mut self);
265 }
266
267 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
268 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
269 /// descriptor.
270 #[derive(Clone)]
271 pub struct PeerHandleError {
272         /// Used to indicate that we probably can't make any future connections to this peer (e.g.
273         /// because we required features that our peer was missing, or vice versa).
274         ///
275         /// While LDK's [`ChannelManager`] will not do it automatically, you likely wish to force-close
276         /// any channels with this peer or check for new versions of LDK.
277         ///
278         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
279         pub no_connection_possible: bool,
280 }
281 impl fmt::Debug for PeerHandleError {
282         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
283                 formatter.write_str("Peer Sent Invalid Data")
284         }
285 }
286 impl fmt::Display for PeerHandleError {
287         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
288                 formatter.write_str("Peer Sent Invalid Data")
289         }
290 }
291
292 #[cfg(feature = "std")]
293 impl error::Error for PeerHandleError {
294         fn description(&self) -> &str {
295                 "Peer Sent Invalid Data"
296         }
297 }
298
299 enum InitSyncTracker{
300         NoSyncRequested,
301         ChannelsSyncing(u64),
302         NodesSyncing(PublicKey),
303 }
304
305 /// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop
306 /// forwarding gossip messages to peers altogether.
307 const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2;
308
309 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
310 /// we have fewer than this many messages in the outbound buffer again.
311 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
312 /// refilled as we send bytes.
313 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 12;
314 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
315 /// the peer.
316 const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO;
317
318 /// If we've sent a ping, and are still awaiting a response, we may need to churn our way through
319 /// the socket receive buffer before receiving the ping.
320 ///
321 /// On a fairly old Arm64 board, with Linux defaults, this can take as long as 20 seconds, not
322 /// including any network delays, outbound traffic, or the same for messages from other peers.
323 ///
324 /// Thus, to avoid needlessly disconnecting a peer, we allow a peer to take this many timer ticks
325 /// per connected peer to respond to a ping, as long as they send us at least one message during
326 /// each tick, ensuring we aren't actually just disconnected.
327 /// With a timer tick interval of ten seconds, this translates to about 40 seconds per connected
328 /// peer.
329 ///
330 /// When we improve parallelism somewhat we should reduce this to e.g. this many timer ticks per
331 /// two connected peers, assuming most LDK-running systems have at least two cores.
332 const MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER: i8 = 4;
333
334 /// This is the minimum number of messages we expect a peer to be able to handle within one timer
335 /// tick. Once we have sent this many messages since the last ping, we send a ping right away to
336 /// ensures we don't just fill up our send buffer and leave the peer with too many messages to
337 /// process before the next ping.
338 ///
339 /// Note that we continue responding to other messages even after we've sent this many messages, so
340 /// it's more of a general guideline used for gossip backfill (and gossip forwarding, times
341 /// [`FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO`]) than a hard limit.
342 const BUFFER_DRAIN_MSGS_PER_TICK: usize = 32;
343
344 struct Peer {
345         channel_encryptor: PeerChannelEncryptor,
346         their_node_id: Option<PublicKey>,
347         their_features: Option<InitFeatures>,
348         their_net_address: Option<NetAddress>,
349
350         pending_outbound_buffer: LinkedList<Vec<u8>>,
351         pending_outbound_buffer_first_msg_offset: usize,
352         // Queue gossip broadcasts separately from `pending_outbound_buffer` so we can easily prioritize
353         // channel messages over them.
354         gossip_broadcast_buffer: LinkedList<Vec<u8>>,
355         awaiting_write_event: bool,
356
357         pending_read_buffer: Vec<u8>,
358         pending_read_buffer_pos: usize,
359         pending_read_is_header: bool,
360
361         sync_status: InitSyncTracker,
362
363         msgs_sent_since_pong: usize,
364         awaiting_pong_timer_tick_intervals: i8,
365         received_message_since_timer_tick: bool,
366         sent_gossip_timestamp_filter: bool,
367 }
368
369 impl Peer {
370         /// Returns true if the channel announcements/updates for the given channel should be
371         /// forwarded to this peer.
372         /// If we are sending our routing table to this peer and we have not yet sent channel
373         /// announcements/updates for the given channel_id then we will send it when we get to that
374         /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
375         /// sent the old versions, we should send the update, and so return true here.
376         fn should_forward_channel_announcement(&self, channel_id: u64) -> bool {
377                 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
378                         !self.sent_gossip_timestamp_filter {
379                                 return false;
380                         }
381                 match self.sync_status {
382                         InitSyncTracker::NoSyncRequested => true,
383                         InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
384                         InitSyncTracker::NodesSyncing(_) => true,
385                 }
386         }
387
388         /// Similar to the above, but for node announcements indexed by node_id.
389         fn should_forward_node_announcement(&self, node_id: PublicKey) -> bool {
390                 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
391                         !self.sent_gossip_timestamp_filter {
392                                 return false;
393                         }
394                 match self.sync_status {
395                         InitSyncTracker::NoSyncRequested => true,
396                         InitSyncTracker::ChannelsSyncing(_) => false,
397                         InitSyncTracker::NodesSyncing(pk) => pk < node_id,
398                 }
399         }
400
401         /// Returns whether we should be reading bytes from this peer, based on whether its outbound
402         /// buffer still has space and we don't need to pause reads to get some writes out.
403         fn should_read(&self) -> bool {
404                 self.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE
405         }
406
407         /// Determines if we should push additional gossip background sync (aka "backfill") onto a peer's
408         /// outbound buffer. This is checked every time the peer's buffer may have been drained.
409         fn should_buffer_gossip_backfill(&self) -> bool {
410                 self.pending_outbound_buffer.is_empty() && self.gossip_broadcast_buffer.is_empty()
411                         && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
412         }
413
414         /// Determines if we should push an onion message onto a peer's outbound buffer. This is checked
415         /// every time the peer's buffer may have been drained.
416         fn should_buffer_onion_message(&self) -> bool {
417                 self.pending_outbound_buffer.is_empty()
418                         && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
419         }
420
421         /// Determines if we should push additional gossip broadcast messages onto a peer's outbound
422         /// buffer. This is checked every time the peer's buffer may have been drained.
423         fn should_buffer_gossip_broadcast(&self) -> bool {
424                 self.pending_outbound_buffer.is_empty()
425                         && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
426         }
427
428         /// Returns whether this peer's outbound buffers are full and we should drop gossip broadcasts.
429         fn buffer_full_drop_gossip_broadcast(&self) -> bool {
430                 let total_outbound_buffered =
431                         self.gossip_broadcast_buffer.len() + self.pending_outbound_buffer.len();
432
433                 total_outbound_buffered > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP ||
434                         self.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
435         }
436 }
437
438 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
439 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
440 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
441 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
442 /// issues such as overly long function definitions.
443 ///
444 /// (C-not exported) as Arcs don't make sense in bindings
445 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>>>, IgnoringMessageHandler, Arc<L>, Arc<IgnoringMessageHandler>>;
446
447 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
448 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
449 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
450 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
451 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
452 /// helps with issues such as long function definitions.
453 ///
454 /// (C-not exported) as Arcs don't make sense in bindings
455 pub type SimpleRefPeerManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, SD, M, T, F, C, L> = PeerManager<SD, SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L>, &'e P2PGossipSync<&'g NetworkGraph<&'f L>, &'h C, &'f L>, IgnoringMessageHandler, &'f L, IgnoringMessageHandler>;
456
457 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
458 /// socket events into messages which it passes on to its [`MessageHandler`].
459 ///
460 /// Locks are taken internally, so you must never assume that reentrancy from a
461 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
462 ///
463 /// Calls to [`read_event`] will decode relevant messages and pass them to the
464 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
465 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
466 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
467 /// calls only after previous ones have returned.
468 ///
469 /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
470 /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
471 /// essentially you should default to using a SimpleRefPeerManager, and use a
472 /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
473 /// you're using lightning-net-tokio.
474 ///
475 /// [`read_event`]: PeerManager::read_event
476 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref> where
477                 CM::Target: ChannelMessageHandler,
478                 RM::Target: RoutingMessageHandler,
479                 OM::Target: OnionMessageHandler,
480                 L::Target: Logger,
481                 CMH::Target: CustomMessageHandler {
482         message_handler: MessageHandler<CM, RM, OM>,
483         /// Connection state for each connected peer - we have an outer read-write lock which is taken
484         /// as read while we're doing processing for a peer and taken write when a peer is being added
485         /// or removed.
486         ///
487         /// The inner Peer lock is held for sending and receiving bytes, but note that we do *not* hold
488         /// it while we're processing a message. This is fine as [`PeerManager::read_event`] requires
489         /// that there be no parallel calls for a given peer, so mutual exclusion of messages handed to
490         /// the `MessageHandler`s for a given peer is already guaranteed.
491         peers: FairRwLock<HashMap<Descriptor, Mutex<Peer>>>,
492         /// Only add to this set when noise completes.
493         /// Locked *after* peers. When an item is removed, it must be removed with the `peers` write
494         /// lock held. Entries may be added with only the `peers` read lock held (though the
495         /// `Descriptor` value must already exist in `peers`).
496         node_id_to_descriptor: Mutex<HashMap<PublicKey, Descriptor>>,
497         /// We can only have one thread processing events at once, but we don't usually need the full
498         /// `peers` write lock to do so, so instead we block on this empty mutex when entering
499         /// `process_events`.
500         event_processing_lock: Mutex<()>,
501         /// Because event processing is global and always does all available work before returning,
502         /// there is no reason for us to have many event processors waiting on the lock at once.
503         /// Instead, we limit the total blocked event processors to always exactly one by setting this
504         /// when an event process call is waiting.
505         blocked_event_processors: AtomicBool,
506         our_node_secret: SecretKey,
507         ephemeral_key_midstate: Sha256Engine,
508         custom_message_handler: CMH,
509
510         peer_counter: AtomicCounter,
511
512         logger: L,
513         secp_ctx: Secp256k1<secp256k1::SignOnly>
514 }
515
516 enum MessageHandlingError {
517         PeerHandleError(PeerHandleError),
518         LightningError(LightningError),
519 }
520
521 impl From<PeerHandleError> for MessageHandlingError {
522         fn from(error: PeerHandleError) -> Self {
523                 MessageHandlingError::PeerHandleError(error)
524         }
525 }
526
527 impl From<LightningError> for MessageHandlingError {
528         fn from(error: LightningError) -> Self {
529                 MessageHandlingError::LightningError(error)
530         }
531 }
532
533 macro_rules! encode_msg {
534         ($msg: expr) => {{
535                 let mut buffer = VecWriter(Vec::new());
536                 wire::write($msg, &mut buffer).unwrap();
537                 buffer.0
538         }}
539 }
540
541 impl<Descriptor: SocketDescriptor, CM: Deref, OM: Deref, L: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, OM, L, IgnoringMessageHandler> where
542                 CM::Target: ChannelMessageHandler,
543                 OM::Target: OnionMessageHandler,
544                 L::Target: Logger {
545         /// Constructs a new `PeerManager` with the given `ChannelMessageHandler` and
546         /// `OnionMessageHandler`. No routing message handler is used and network graph messages are
547         /// ignored.
548         ///
549         /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
550         /// cryptographically secure random bytes.
551         ///
552         /// (C-not exported) as we can't export a PeerManager with a dummy route handler
553         pub fn new_channel_only(channel_message_handler: CM, onion_message_handler: OM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
554                 Self::new(MessageHandler {
555                         chan_handler: channel_message_handler,
556                         route_handler: IgnoringMessageHandler{},
557                         onion_message_handler,
558                 }, our_node_secret, ephemeral_random_data, logger, IgnoringMessageHandler{})
559         }
560 }
561
562 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, IgnoringMessageHandler, L, IgnoringMessageHandler> where
563                 RM::Target: RoutingMessageHandler,
564                 L::Target: Logger {
565         /// Constructs a new `PeerManager` with the given `RoutingMessageHandler`. No channel message
566         /// handler or onion message handler is used and onion and channel messages will be ignored (or
567         /// generate error messages). Note that some other lightning implementations time-out connections
568         /// after some time if no channel is built with the peer.
569         ///
570         /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
571         /// cryptographically secure random bytes.
572         ///
573         /// (C-not exported) as we can't export a PeerManager with a dummy channel handler
574         pub fn new_routing_only(routing_message_handler: RM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
575                 Self::new(MessageHandler {
576                         chan_handler: ErroringMessageHandler::new(),
577                         route_handler: routing_message_handler,
578                         onion_message_handler: IgnoringMessageHandler{},
579                 }, our_node_secret, ephemeral_random_data, logger, IgnoringMessageHandler{})
580         }
581 }
582
583 /// A simple wrapper that optionally prints " from <pubkey>" for an optional pubkey.
584 /// This works around `format!()` taking a reference to each argument, preventing
585 /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
586 /// due to lifetime errors.
587 struct OptionalFromDebugger<'a>(&'a Option<PublicKey>);
588 impl core::fmt::Display for OptionalFromDebugger<'_> {
589         fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
590                 if let Some(node_id) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
591         }
592 }
593
594 /// A function used to filter out local or private addresses
595 /// https://www.iana.org./assignments/ipv4-address-space/ipv4-address-space.xhtml
596 /// https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml
597 fn filter_addresses(ip_address: Option<NetAddress>) -> Option<NetAddress> {
598         match ip_address{
599                 // For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8)
600                 Some(NetAddress::IPv4{addr: [10, _, _, _], port: _}) => None,
601                 // For IPv4 range 0.0.0.0 - 0.255.255.255 (0/8)
602                 Some(NetAddress::IPv4{addr: [0, _, _, _], port: _}) => None,
603                 // For IPv4 range 100.64.0.0 - 100.127.255.255 (100.64/10)
604                 Some(NetAddress::IPv4{addr: [100, 64..=127, _, _], port: _}) => None,
605                 // For IPv4 range       127.0.0.0 - 127.255.255.255 (127/8)
606                 Some(NetAddress::IPv4{addr: [127, _, _, _], port: _}) => None,
607                 // For IPv4 range       169.254.0.0 - 169.254.255.255 (169.254/16)
608                 Some(NetAddress::IPv4{addr: [169, 254, _, _], port: _}) => None,
609                 // For IPv4 range 172.16.0.0 - 172.31.255.255 (172.16/12)
610                 Some(NetAddress::IPv4{addr: [172, 16..=31, _, _], port: _}) => None,
611                 // For IPv4 range 192.168.0.0 - 192.168.255.255 (192.168/16)
612                 Some(NetAddress::IPv4{addr: [192, 168, _, _], port: _}) => None,
613                 // For IPv4 range 192.88.99.0 - 192.88.99.255  (192.88.99/24)
614                 Some(NetAddress::IPv4{addr: [192, 88, 99, _], port: _}) => None,
615                 // For IPv6 range 2000:0000:0000:0000:0000:0000:0000:0000 - 3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff (2000::/3)
616                 Some(NetAddress::IPv6{addr: [0x20..=0x3F, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _], port: _}) => ip_address,
617                 // For remaining addresses
618                 Some(NetAddress::IPv6{addr: _, port: _}) => None,
619                 Some(..) => ip_address,
620                 None => None,
621         }
622 }
623
624 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref> PeerManager<Descriptor, CM, RM, OM, L, CMH> where
625                 CM::Target: ChannelMessageHandler,
626                 RM::Target: RoutingMessageHandler,
627                 OM::Target: OnionMessageHandler,
628                 L::Target: Logger,
629                 CMH::Target: CustomMessageHandler {
630         /// Constructs a new PeerManager with the given message handlers and node_id secret key
631         /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
632         /// cryptographically secure random bytes.
633         pub fn new(message_handler: MessageHandler<CM, RM, OM>, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L, custom_message_handler: CMH) -> Self {
634                 let mut ephemeral_key_midstate = Sha256::engine();
635                 ephemeral_key_midstate.input(ephemeral_random_data);
636
637                 let mut secp_ctx = Secp256k1::signing_only();
638                 let ephemeral_hash = Sha256::from_engine(ephemeral_key_midstate.clone()).into_inner();
639                 secp_ctx.seeded_randomize(&ephemeral_hash);
640
641                 PeerManager {
642                         message_handler,
643                         peers: FairRwLock::new(HashMap::new()),
644                         node_id_to_descriptor: Mutex::new(HashMap::new()),
645                         event_processing_lock: Mutex::new(()),
646                         blocked_event_processors: AtomicBool::new(false),
647                         our_node_secret,
648                         ephemeral_key_midstate,
649                         peer_counter: AtomicCounter::new(),
650                         logger,
651                         custom_message_handler,
652                         secp_ctx,
653                 }
654         }
655
656         /// Get the list of node ids for peers which have completed the initial handshake.
657         ///
658         /// For outbound connections, this will be the same as the their_node_id parameter passed in to
659         /// new_outbound_connection, however entries will only appear once the initial handshake has
660         /// completed and we are sure the remote peer has the private key for the given node_id.
661         pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
662                 let peers = self.peers.read().unwrap();
663                 peers.values().filter_map(|peer_mutex| {
664                         let p = peer_mutex.lock().unwrap();
665                         if !p.channel_encryptor.is_ready_for_encryption() || p.their_features.is_none() {
666                                 return None;
667                         }
668                         p.their_node_id
669                 }).collect()
670         }
671
672         fn get_ephemeral_key(&self) -> SecretKey {
673                 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
674                 let counter = self.peer_counter.get_increment();
675                 ephemeral_hash.input(&counter.to_le_bytes());
676                 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
677         }
678
679         /// Indicates a new outbound connection has been established to a node with the given node_id
680         /// and an optional remote network address.
681         ///
682         /// The remote network address adds the option to report a remote IP address back to a connecting
683         /// peer using the init message.
684         /// The user should pass the remote network address of the host they are connected to.
685         ///
686         /// If an `Err` is returned here you must disconnect the connection immediately.
687         ///
688         /// Returns a small number of bytes to send to the remote node (currently always 50).
689         ///
690         /// Panics if descriptor is duplicative with some other descriptor which has not yet been
691         /// [`socket_disconnected()`].
692         ///
693         /// [`socket_disconnected()`]: PeerManager::socket_disconnected
694         pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<Vec<u8>, PeerHandleError> {
695                 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
696                 let res = peer_encryptor.get_act_one(&self.secp_ctx).to_vec();
697                 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
698
699                 let mut peers = self.peers.write().unwrap();
700                 if peers.insert(descriptor, Mutex::new(Peer {
701                         channel_encryptor: peer_encryptor,
702                         their_node_id: None,
703                         their_features: None,
704                         their_net_address: remote_network_address,
705
706                         pending_outbound_buffer: LinkedList::new(),
707                         pending_outbound_buffer_first_msg_offset: 0,
708                         gossip_broadcast_buffer: LinkedList::new(),
709                         awaiting_write_event: false,
710
711                         pending_read_buffer,
712                         pending_read_buffer_pos: 0,
713                         pending_read_is_header: false,
714
715                         sync_status: InitSyncTracker::NoSyncRequested,
716
717                         msgs_sent_since_pong: 0,
718                         awaiting_pong_timer_tick_intervals: 0,
719                         received_message_since_timer_tick: false,
720                         sent_gossip_timestamp_filter: false,
721                 })).is_some() {
722                         panic!("PeerManager driver duplicated descriptors!");
723                 };
724                 Ok(res)
725         }
726
727         /// Indicates a new inbound connection has been established to a node with an optional remote
728         /// network address.
729         ///
730         /// The remote network address adds the option to report a remote IP address back to a connecting
731         /// peer using the init message.
732         /// The user should pass the remote network address of the host they are connected to.
733         ///
734         /// May refuse the connection by returning an Err, but will never write bytes to the remote end
735         /// (outbound connector always speaks first). If an `Err` is returned here you must disconnect
736         /// the connection immediately.
737         ///
738         /// Panics if descriptor is duplicative with some other descriptor which has not yet been
739         /// [`socket_disconnected()`].
740         ///
741         /// [`socket_disconnected()`]: PeerManager::socket_disconnected
742         pub fn new_inbound_connection(&self, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<(), PeerHandleError> {
743                 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret, &self.secp_ctx);
744                 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
745
746                 let mut peers = self.peers.write().unwrap();
747                 if peers.insert(descriptor, Mutex::new(Peer {
748                         channel_encryptor: peer_encryptor,
749                         their_node_id: None,
750                         their_features: None,
751                         their_net_address: remote_network_address,
752
753                         pending_outbound_buffer: LinkedList::new(),
754                         pending_outbound_buffer_first_msg_offset: 0,
755                         gossip_broadcast_buffer: LinkedList::new(),
756                         awaiting_write_event: false,
757
758                         pending_read_buffer,
759                         pending_read_buffer_pos: 0,
760                         pending_read_is_header: false,
761
762                         sync_status: InitSyncTracker::NoSyncRequested,
763
764                         msgs_sent_since_pong: 0,
765                         awaiting_pong_timer_tick_intervals: 0,
766                         received_message_since_timer_tick: false,
767                         sent_gossip_timestamp_filter: false,
768                 })).is_some() {
769                         panic!("PeerManager driver duplicated descriptors!");
770                 };
771                 Ok(())
772         }
773
774         fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
775                 while !peer.awaiting_write_event {
776                         if peer.should_buffer_onion_message() {
777                                 if let Some(peer_node_id) = peer.their_node_id {
778                                         if let Some(next_onion_message) =
779                                                 self.message_handler.onion_message_handler.next_onion_message_for_peer(peer_node_id) {
780                                                         self.enqueue_message(peer, &next_onion_message);
781                                         }
782                                 }
783                         }
784                         if peer.should_buffer_gossip_broadcast() {
785                                 if let Some(msg) = peer.gossip_broadcast_buffer.pop_front() {
786                                         peer.pending_outbound_buffer.push_back(msg);
787                                 }
788                         }
789                         if peer.should_buffer_gossip_backfill() {
790                                 match peer.sync_status {
791                                         InitSyncTracker::NoSyncRequested => {},
792                                         InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
793                                                 if let Some((announce, update_a_option, update_b_option)) =
794                                                         self.message_handler.route_handler.get_next_channel_announcement(c)
795                                                 {
796                                                         self.enqueue_message(peer, &announce);
797                                                         if let Some(update_a) = update_a_option {
798                                                                 self.enqueue_message(peer, &update_a);
799                                                         }
800                                                         if let Some(update_b) = update_b_option {
801                                                                 self.enqueue_message(peer, &update_b);
802                                                         }
803                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
804                                                 } else {
805                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
806                                                 }
807                                         },
808                                         InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
809                                                 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(None) {
810                                                         self.enqueue_message(peer, &msg);
811                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
812                                                 } else {
813                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
814                                                 }
815                                         },
816                                         InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
817                                         InitSyncTracker::NodesSyncing(key) => {
818                                                 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(Some(&key)) {
819                                                         self.enqueue_message(peer, &msg);
820                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
821                                                 } else {
822                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
823                                                 }
824                                         },
825                                 }
826                         }
827                         if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
828                                 self.maybe_send_extra_ping(peer);
829                         }
830
831                         let next_buff = match peer.pending_outbound_buffer.front() {
832                                 None => return,
833                                 Some(buff) => buff,
834                         };
835
836                         let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
837                         let data_sent = descriptor.send_data(pending, peer.should_read());
838                         peer.pending_outbound_buffer_first_msg_offset += data_sent;
839                         if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() {
840                                 peer.pending_outbound_buffer_first_msg_offset = 0;
841                                 peer.pending_outbound_buffer.pop_front();
842                         } else {
843                                 peer.awaiting_write_event = true;
844                         }
845                 }
846         }
847
848         /// Indicates that there is room to write data to the given socket descriptor.
849         ///
850         /// May return an Err to indicate that the connection should be closed.
851         ///
852         /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
853         /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
854         /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
855         /// ready to call `[write_buffer_space_avail`] again if a write call generated here isn't
856         /// sufficient!
857         ///
858         /// [`send_data`]: SocketDescriptor::send_data
859         /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
860         pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
861                 let peers = self.peers.read().unwrap();
862                 match peers.get(descriptor) {
863                         None => {
864                                 // This is most likely a simple race condition where the user found that the socket
865                                 // was writeable, then we told the user to `disconnect_socket()`, then they called
866                                 // this method. Return an error to make sure we get disconnected.
867                                 return Err(PeerHandleError { no_connection_possible: false });
868                         },
869                         Some(peer_mutex) => {
870                                 let mut peer = peer_mutex.lock().unwrap();
871                                 peer.awaiting_write_event = false;
872                                 self.do_attempt_write_data(descriptor, &mut peer);
873                         }
874                 };
875                 Ok(())
876         }
877
878         /// Indicates that data was read from the given socket descriptor.
879         ///
880         /// May return an Err to indicate that the connection should be closed.
881         ///
882         /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
883         /// Thus, however, you should call [`process_events`] after any `read_event` to generate
884         /// [`send_data`] calls to handle responses.
885         ///
886         /// If `Ok(true)` is returned, further read_events should not be triggered until a
887         /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
888         /// send buffer).
889         ///
890         /// [`send_data`]: SocketDescriptor::send_data
891         /// [`process_events`]: PeerManager::process_events
892         pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
893                 match self.do_read_event(peer_descriptor, data) {
894                         Ok(res) => Ok(res),
895                         Err(e) => {
896                                 log_trace!(self.logger, "Peer sent invalid data or we decided to disconnect due to a protocol error");
897                                 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
898                                 Err(e)
899                         }
900                 }
901         }
902
903         /// Append a message to a peer's pending outbound/write buffer
904         fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
905                 let mut buffer = VecWriter(Vec::with_capacity(2048));
906                 wire::write(message, &mut buffer).unwrap(); // crash if the write failed
907
908                 if is_gossip_msg(message.type_id()) {
909                         log_gossip!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()));
910                 } else {
911                         log_trace!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()))
912                 }
913                 peer.msgs_sent_since_pong += 1;
914                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&buffer.0[..]));
915         }
916
917         /// Append a message to a peer's pending outbound/write gossip broadcast buffer
918         fn enqueue_encoded_gossip_broadcast(&self, peer: &mut Peer, encoded_message: &Vec<u8>) {
919                 peer.msgs_sent_since_pong += 1;
920                 peer.gossip_broadcast_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_message[..]));
921         }
922
923         fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
924                 let mut pause_read = false;
925                 let peers = self.peers.read().unwrap();
926                 let mut msgs_to_forward = Vec::new();
927                 let mut peer_node_id = None;
928                 match peers.get(peer_descriptor) {
929                         None => {
930                                 // This is most likely a simple race condition where the user read some bytes
931                                 // from the socket, then we told the user to `disconnect_socket()`, then they
932                                 // called this method. Return an error to make sure we get disconnected.
933                                 return Err(PeerHandleError { no_connection_possible: false });
934                         },
935                         Some(peer_mutex) => {
936                                 let mut read_pos = 0;
937                                 while read_pos < data.len() {
938                                         macro_rules! try_potential_handleerror {
939                                                 ($peer: expr, $thing: expr) => {
940                                                         match $thing {
941                                                                 Ok(x) => x,
942                                                                 Err(e) => {
943                                                                         match e.action {
944                                                                                 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
945                                                                                         //TODO: Try to push msg
946                                                                                         log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
947                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
948                                                                                 },
949                                                                                 msgs::ErrorAction::IgnoreAndLog(level) => {
950                                                                                         log_given_level!(self.logger, level, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
951                                                                                         continue
952                                                                                 },
953                                                                                 msgs::ErrorAction::IgnoreDuplicateGossip => continue, // Don't even bother logging these
954                                                                                 msgs::ErrorAction::IgnoreError => {
955                                                                                         log_debug!(self.logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
956                                                                                         continue;
957                                                                                 },
958                                                                                 msgs::ErrorAction::SendErrorMessage { msg } => {
959                                                                                         log_debug!(self.logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
960                                                                                         self.enqueue_message($peer, &msg);
961                                                                                         continue;
962                                                                                 },
963                                                                                 msgs::ErrorAction::SendWarningMessage { msg, log_level } => {
964                                                                                         log_given_level!(self.logger, log_level, "Error handling message{}; sending warning message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
965                                                                                         self.enqueue_message($peer, &msg);
966                                                                                         continue;
967                                                                                 },
968                                                                         }
969                                                                 }
970                                                         }
971                                                 }
972                                         }
973
974                                         let mut peer_lock = peer_mutex.lock().unwrap();
975                                         let peer = &mut *peer_lock;
976                                         let mut msg_to_handle = None;
977                                         if peer_node_id.is_none() {
978                                                 peer_node_id = peer.their_node_id.clone();
979                                         }
980
981                                         assert!(peer.pending_read_buffer.len() > 0);
982                                         assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
983
984                                         {
985                                                 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
986                                                 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]);
987                                                 read_pos += data_to_copy;
988                                                 peer.pending_read_buffer_pos += data_to_copy;
989                                         }
990
991                                         if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
992                                                 peer.pending_read_buffer_pos = 0;
993
994                                                 macro_rules! insert_node_id {
995                                                         () => {
996                                                                 match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap()) {
997                                                                         hash_map::Entry::Occupied(_) => {
998                                                                                 log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
999                                                                                 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
1000                                                                                 return Err(PeerHandleError{ no_connection_possible: false })
1001                                                                         },
1002                                                                         hash_map::Entry::Vacant(entry) => {
1003                                                                                 log_debug!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
1004                                                                                 entry.insert(peer_descriptor.clone())
1005                                                                         },
1006                                                                 };
1007                                                         }
1008                                                 }
1009
1010                                                 let next_step = peer.channel_encryptor.get_noise_step();
1011                                                 match next_step {
1012                                                         NextNoiseStep::ActOne => {
1013                                                                 let act_two = try_potential_handleerror!(peer, peer.channel_encryptor
1014                                                                         .process_act_one_with_keys(&peer.pending_read_buffer[..],
1015                                                                                 &self.our_node_secret, self.get_ephemeral_key(), &self.secp_ctx)).to_vec();
1016                                                                 peer.pending_outbound_buffer.push_back(act_two);
1017                                                                 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
1018                                                         },
1019                                                         NextNoiseStep::ActTwo => {
1020                                                                 let (act_three, their_node_id) = try_potential_handleerror!(peer,
1021                                                                         peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..],
1022                                                                                 &self.our_node_secret, &self.secp_ctx));
1023                                                                 peer.pending_outbound_buffer.push_back(act_three.to_vec());
1024                                                                 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1025                                                                 peer.pending_read_is_header = true;
1026
1027                                                                 peer.their_node_id = Some(their_node_id);
1028                                                                 insert_node_id!();
1029                                                                 let features = InitFeatures::known();
1030                                                                 let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
1031                                                                 self.enqueue_message(peer, &resp);
1032                                                                 peer.awaiting_pong_timer_tick_intervals = 0;
1033                                                         },
1034                                                         NextNoiseStep::ActThree => {
1035                                                                 let their_node_id = try_potential_handleerror!(peer,
1036                                                                         peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
1037                                                                 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1038                                                                 peer.pending_read_is_header = true;
1039                                                                 peer.their_node_id = Some(their_node_id);
1040                                                                 insert_node_id!();
1041                                                                 let features = InitFeatures::known();
1042                                                                 let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
1043                                                                 self.enqueue_message(peer, &resp);
1044                                                                 peer.awaiting_pong_timer_tick_intervals = 0;
1045                                                         },
1046                                                         NextNoiseStep::NoiseComplete => {
1047                                                                 if peer.pending_read_is_header {
1048                                                                         let msg_len = try_potential_handleerror!(peer,
1049                                                                                 peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
1050                                                                         if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1051                                                                         peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
1052                                                                         if msg_len < 2 { // Need at least the message type tag
1053                                                                                 return Err(PeerHandleError{ no_connection_possible: false });
1054                                                                         }
1055                                                                         peer.pending_read_is_header = false;
1056                                                                 } else {
1057                                                                         let msg_data = try_potential_handleerror!(peer,
1058                                                                                 peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
1059                                                                         assert!(msg_data.len() >= 2);
1060
1061                                                                         // Reset read buffer
1062                                                                         if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1063                                                                         peer.pending_read_buffer.resize(18, 0);
1064                                                                         peer.pending_read_is_header = true;
1065
1066                                                                         let mut reader = io::Cursor::new(&msg_data[..]);
1067                                                                         let message_result = wire::read(&mut reader, &*self.custom_message_handler);
1068                                                                         let message = match message_result {
1069                                                                                 Ok(x) => x,
1070                                                                                 Err(e) => {
1071                                                                                         match e {
1072                                                                                                 // Note that to avoid recursion we never call
1073                                                                                                 // `do_attempt_write_data` from here, causing
1074                                                                                                 // the messages enqueued here to not actually
1075                                                                                                 // be sent before the peer is disconnected.
1076                                                                                                 (msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
1077                                                                                                         log_gossip!(self.logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
1078                                                                                                         continue;
1079                                                                                                 }
1080                                                                                                 (msgs::DecodeError::UnsupportedCompression, _) => {
1081                                                                                                         log_gossip!(self.logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
1082                                                                                                         self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: "Unsupported message compression: zlib".to_owned() });
1083                                                                                                         continue;
1084                                                                                                 }
1085                                                                                                 (_, Some(ty)) if is_gossip_msg(ty) => {
1086                                                                                                         log_gossip!(self.logger, "Got an invalid value while deserializing a gossip message");
1087                                                                                                         self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: "Unreadable/bogus gossip message".to_owned() });
1088                                                                                                         continue;
1089                                                                                                 }
1090                                                                                                 (msgs::DecodeError::UnknownRequiredFeature, ty) => {
1091                                                                                                         log_gossip!(self.logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
1092                                                                                                         self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: format!("Received an unknown required feature/TLV in message type {:?}", ty) });
1093                                                                                                         return Err(PeerHandleError { no_connection_possible: false });
1094                                                                                                 }
1095                                                                                                 (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { no_connection_possible: false }),
1096                                                                                                 (msgs::DecodeError::InvalidValue, _) => {
1097                                                                                                         log_debug!(self.logger, "Got an invalid value while deserializing message");
1098                                                                                                         return Err(PeerHandleError { no_connection_possible: false });
1099                                                                                                 }
1100                                                                                                 (msgs::DecodeError::ShortRead, _) => {
1101                                                                                                         log_debug!(self.logger, "Deserialization failed due to shortness of message");
1102                                                                                                         return Err(PeerHandleError { no_connection_possible: false });
1103                                                                                                 }
1104                                                                                                 (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { no_connection_possible: false }),
1105                                                                                                 (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { no_connection_possible: false }),
1106                                                                                         }
1107                                                                                 }
1108                                                                         };
1109
1110                                                                         msg_to_handle = Some(message);
1111                                                                 }
1112                                                         }
1113                                                 }
1114                                         }
1115                                         pause_read = !peer.should_read();
1116
1117                                         if let Some(message) = msg_to_handle {
1118                                                 match self.handle_message(&peer_mutex, peer_lock, message) {
1119                                                         Err(handling_error) => match handling_error {
1120                                                                 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
1121                                                                 MessageHandlingError::LightningError(e) => {
1122                                                                         try_potential_handleerror!(&mut peer_mutex.lock().unwrap(), Err(e));
1123                                                                 },
1124                                                         },
1125                                                         Ok(Some(msg)) => {
1126                                                                 msgs_to_forward.push(msg);
1127                                                         },
1128                                                         Ok(None) => {},
1129                                                 }
1130                                         }
1131                                 }
1132                         }
1133                 }
1134
1135                 for msg in msgs_to_forward.drain(..) {
1136                         self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref());
1137                 }
1138
1139                 Ok(pause_read)
1140         }
1141
1142         /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
1143         /// Returns the message back if it needs to be broadcasted to all other peers.
1144         fn handle_message(
1145                 &self,
1146                 peer_mutex: &Mutex<Peer>,
1147                 mut peer_lock: MutexGuard<Peer>,
1148                 message: wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>
1149         ) -> Result<Option<wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
1150                 let their_node_id = peer_lock.their_node_id.clone().expect("We know the peer's public key by the time we receive messages");
1151                 peer_lock.received_message_since_timer_tick = true;
1152
1153                 // Need an Init as first message
1154                 if let wire::Message::Init(msg) = message {
1155                         if msg.features.requires_unknown_bits() {
1156                                 log_debug!(self.logger, "Peer features required unknown version bits");
1157                                 return Err(PeerHandleError{ no_connection_possible: true }.into());
1158                         }
1159                         if peer_lock.their_features.is_some() {
1160                                 return Err(PeerHandleError{ no_connection_possible: false }.into());
1161                         }
1162
1163                         log_info!(self.logger, "Received peer Init message from {}: {}", log_pubkey!(their_node_id), msg.features);
1164
1165                         // For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
1166                         if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
1167                                 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1168                         }
1169
1170                         if !msg.features.supports_static_remote_key() {
1171                                 log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting with no_connection_possible", log_pubkey!(their_node_id));
1172                                 return Err(PeerHandleError{ no_connection_possible: true }.into());
1173                         }
1174
1175                         self.message_handler.route_handler.peer_connected(&their_node_id, &msg);
1176
1177                         self.message_handler.chan_handler.peer_connected(&their_node_id, &msg);
1178                         peer_lock.their_features = Some(msg.features);
1179                         return Ok(None);
1180                 } else if peer_lock.their_features.is_none() {
1181                         log_debug!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(their_node_id));
1182                         return Err(PeerHandleError{ no_connection_possible: false }.into());
1183                 }
1184
1185                 if let wire::Message::GossipTimestampFilter(_msg) = message {
1186                         // When supporting gossip messages, start inital gossip sync only after we receive
1187                         // a GossipTimestampFilter
1188                         if peer_lock.their_features.as_ref().unwrap().supports_gossip_queries() &&
1189                                 !peer_lock.sent_gossip_timestamp_filter {
1190                                 peer_lock.sent_gossip_timestamp_filter = true;
1191                                 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1192                         }
1193                         return Ok(None);
1194                 }
1195
1196                 let their_features = peer_lock.their_features.clone();
1197                 mem::drop(peer_lock);
1198
1199                 if is_gossip_msg(message.type_id()) {
1200                         log_gossip!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1201                 } else {
1202                         log_trace!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1203                 }
1204
1205                 let mut should_forward = None;
1206
1207                 match message {
1208                         // Setup and Control messages:
1209                         wire::Message::Init(_) => {
1210                                 // Handled above
1211                         },
1212                         wire::Message::GossipTimestampFilter(_) => {
1213                                 // Handled above
1214                         },
1215                         wire::Message::Error(msg) => {
1216                                 let mut data_is_printable = true;
1217                                 for b in msg.data.bytes() {
1218                                         if b < 32 || b > 126 {
1219                                                 data_is_printable = false;
1220                                                 break;
1221                                         }
1222                                 }
1223
1224                                 if data_is_printable {
1225                                         log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(their_node_id), msg.data);
1226                                 } else {
1227                                         log_debug!(self.logger, "Got Err message from {} with non-ASCII error message", log_pubkey!(their_node_id));
1228                                 }
1229                                 self.message_handler.chan_handler.handle_error(&their_node_id, &msg);
1230                                 if msg.channel_id == [0; 32] {
1231                                         return Err(PeerHandleError{ no_connection_possible: true }.into());
1232                                 }
1233                         },
1234                         wire::Message::Warning(msg) => {
1235                                 let mut data_is_printable = true;
1236                                 for b in msg.data.bytes() {
1237                                         if b < 32 || b > 126 {
1238                                                 data_is_printable = false;
1239                                                 break;
1240                                         }
1241                                 }
1242
1243                                 if data_is_printable {
1244                                         log_debug!(self.logger, "Got warning message from {}: {}", log_pubkey!(their_node_id), msg.data);
1245                                 } else {
1246                                         log_debug!(self.logger, "Got warning message from {} with non-ASCII error message", log_pubkey!(their_node_id));
1247                                 }
1248                         },
1249
1250                         wire::Message::Ping(msg) => {
1251                                 if msg.ponglen < 65532 {
1252                                         let resp = msgs::Pong { byteslen: msg.ponglen };
1253                                         self.enqueue_message(&mut *peer_mutex.lock().unwrap(), &resp);
1254                                 }
1255                         },
1256                         wire::Message::Pong(_msg) => {
1257                                 let mut peer_lock = peer_mutex.lock().unwrap();
1258                                 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1259                                 peer_lock.msgs_sent_since_pong = 0;
1260                         },
1261
1262                         // Channel messages:
1263                         wire::Message::OpenChannel(msg) => {
1264                                 self.message_handler.chan_handler.handle_open_channel(&their_node_id, their_features.clone().unwrap(), &msg);
1265                         },
1266                         wire::Message::AcceptChannel(msg) => {
1267                                 self.message_handler.chan_handler.handle_accept_channel(&their_node_id, their_features.clone().unwrap(), &msg);
1268                         },
1269
1270                         wire::Message::FundingCreated(msg) => {
1271                                 self.message_handler.chan_handler.handle_funding_created(&their_node_id, &msg);
1272                         },
1273                         wire::Message::FundingSigned(msg) => {
1274                                 self.message_handler.chan_handler.handle_funding_signed(&their_node_id, &msg);
1275                         },
1276                         wire::Message::ChannelReady(msg) => {
1277                                 self.message_handler.chan_handler.handle_channel_ready(&their_node_id, &msg);
1278                         },
1279
1280                         wire::Message::Shutdown(msg) => {
1281                                 self.message_handler.chan_handler.handle_shutdown(&their_node_id, their_features.as_ref().unwrap(), &msg);
1282                         },
1283                         wire::Message::ClosingSigned(msg) => {
1284                                 self.message_handler.chan_handler.handle_closing_signed(&their_node_id, &msg);
1285                         },
1286
1287                         // Commitment messages:
1288                         wire::Message::UpdateAddHTLC(msg) => {
1289                                 self.message_handler.chan_handler.handle_update_add_htlc(&their_node_id, &msg);
1290                         },
1291                         wire::Message::UpdateFulfillHTLC(msg) => {
1292                                 self.message_handler.chan_handler.handle_update_fulfill_htlc(&their_node_id, &msg);
1293                         },
1294                         wire::Message::UpdateFailHTLC(msg) => {
1295                                 self.message_handler.chan_handler.handle_update_fail_htlc(&their_node_id, &msg);
1296                         },
1297                         wire::Message::UpdateFailMalformedHTLC(msg) => {
1298                                 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&their_node_id, &msg);
1299                         },
1300
1301                         wire::Message::CommitmentSigned(msg) => {
1302                                 self.message_handler.chan_handler.handle_commitment_signed(&their_node_id, &msg);
1303                         },
1304                         wire::Message::RevokeAndACK(msg) => {
1305                                 self.message_handler.chan_handler.handle_revoke_and_ack(&their_node_id, &msg);
1306                         },
1307                         wire::Message::UpdateFee(msg) => {
1308                                 self.message_handler.chan_handler.handle_update_fee(&their_node_id, &msg);
1309                         },
1310                         wire::Message::ChannelReestablish(msg) => {
1311                                 self.message_handler.chan_handler.handle_channel_reestablish(&their_node_id, &msg);
1312                         },
1313
1314                         // Routing messages:
1315                         wire::Message::AnnouncementSignatures(msg) => {
1316                                 self.message_handler.chan_handler.handle_announcement_signatures(&their_node_id, &msg);
1317                         },
1318                         wire::Message::ChannelAnnouncement(msg) => {
1319                                 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1320                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1321                                         should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1322                                 }
1323                         },
1324                         wire::Message::NodeAnnouncement(msg) => {
1325                                 if self.message_handler.route_handler.handle_node_announcement(&msg)
1326                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1327                                         should_forward = Some(wire::Message::NodeAnnouncement(msg));
1328                                 }
1329                         },
1330                         wire::Message::ChannelUpdate(msg) => {
1331                                 self.message_handler.chan_handler.handle_channel_update(&their_node_id, &msg);
1332                                 if self.message_handler.route_handler.handle_channel_update(&msg)
1333                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1334                                         should_forward = Some(wire::Message::ChannelUpdate(msg));
1335                                 }
1336                         },
1337                         wire::Message::QueryShortChannelIds(msg) => {
1338                                 self.message_handler.route_handler.handle_query_short_channel_ids(&their_node_id, msg)?;
1339                         },
1340                         wire::Message::ReplyShortChannelIdsEnd(msg) => {
1341                                 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&their_node_id, msg)?;
1342                         },
1343                         wire::Message::QueryChannelRange(msg) => {
1344                                 self.message_handler.route_handler.handle_query_channel_range(&their_node_id, msg)?;
1345                         },
1346                         wire::Message::ReplyChannelRange(msg) => {
1347                                 self.message_handler.route_handler.handle_reply_channel_range(&their_node_id, msg)?;
1348                         },
1349
1350                         // Onion message:
1351                         wire::Message::OnionMessage(msg) => {
1352                                 self.message_handler.onion_message_handler.handle_onion_message(&their_node_id, &msg);
1353                         },
1354
1355                         // Unknown messages:
1356                         wire::Message::Unknown(type_id) if message.is_even() => {
1357                                 log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1358                                 // Fail the channel if message is an even, unknown type as per BOLT #1.
1359                                 return Err(PeerHandleError{ no_connection_possible: true }.into());
1360                         },
1361                         wire::Message::Unknown(type_id) => {
1362                                 log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", type_id);
1363                         },
1364                         wire::Message::Custom(custom) => {
1365                                 self.custom_message_handler.handle_custom_message(custom, &their_node_id)?;
1366                         },
1367                 };
1368                 Ok(should_forward)
1369         }
1370
1371         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>) {
1372                 match msg {
1373                         wire::Message::ChannelAnnouncement(ref msg) => {
1374                                 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1375                                 let encoded_msg = encode_msg!(msg);
1376
1377                                 for (_, peer_mutex) in peers.iter() {
1378                                         let mut peer = peer_mutex.lock().unwrap();
1379                                         if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1380                                                         !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1381                                                 continue
1382                                         }
1383                                         if peer.buffer_full_drop_gossip_broadcast() {
1384                                                 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1385                                                 continue;
1386                                         }
1387                                         if peer.their_node_id.as_ref() == Some(&msg.contents.node_id_1) ||
1388                                            peer.their_node_id.as_ref() == Some(&msg.contents.node_id_2) {
1389                                                 continue;
1390                                         }
1391                                         if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1392                                                 continue;
1393                                         }
1394                                         self.enqueue_encoded_gossip_broadcast(&mut *peer, &encoded_msg);
1395                                 }
1396                         },
1397                         wire::Message::NodeAnnouncement(ref msg) => {
1398                                 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1399                                 let encoded_msg = encode_msg!(msg);
1400
1401                                 for (_, peer_mutex) in peers.iter() {
1402                                         let mut peer = peer_mutex.lock().unwrap();
1403                                         if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1404                                                         !peer.should_forward_node_announcement(msg.contents.node_id) {
1405                                                 continue
1406                                         }
1407                                         if peer.buffer_full_drop_gossip_broadcast() {
1408                                                 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1409                                                 continue;
1410                                         }
1411                                         if peer.their_node_id.as_ref() == Some(&msg.contents.node_id) {
1412                                                 continue;
1413                                         }
1414                                         if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1415                                                 continue;
1416                                         }
1417                                         self.enqueue_encoded_gossip_broadcast(&mut *peer, &encoded_msg);
1418                                 }
1419                         },
1420                         wire::Message::ChannelUpdate(ref msg) => {
1421                                 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1422                                 let encoded_msg = encode_msg!(msg);
1423
1424                                 for (_, peer_mutex) in peers.iter() {
1425                                         let mut peer = peer_mutex.lock().unwrap();
1426                                         if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1427                                                         !peer.should_forward_channel_announcement(msg.contents.short_channel_id)  {
1428                                                 continue
1429                                         }
1430                                         if peer.buffer_full_drop_gossip_broadcast() {
1431                                                 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1432                                                 continue;
1433                                         }
1434                                         if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1435                                                 continue;
1436                                         }
1437                                         self.enqueue_encoded_gossip_broadcast(&mut *peer, &encoded_msg);
1438                                 }
1439                         },
1440                         _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1441                 }
1442         }
1443
1444         /// Checks for any events generated by our handlers and processes them. Includes sending most
1445         /// response messages as well as messages generated by calls to handler functions directly (eg
1446         /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1447         ///
1448         /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1449         /// issues!
1450         ///
1451         /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
1452         /// or one of the other clients provided in our language bindings.
1453         ///
1454         /// Note that if there are any other calls to this function waiting on lock(s) this may return
1455         /// without doing any work. All available events that need handling will be handled before the
1456         /// other calls return.
1457         ///
1458         /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1459         /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1460         /// [`send_data`]: SocketDescriptor::send_data
1461         pub fn process_events(&self) {
1462                 let mut _single_processor_lock = self.event_processing_lock.try_lock();
1463                 if _single_processor_lock.is_err() {
1464                         // While we could wake the older sleeper here with a CV and make more even waiting
1465                         // times, that would be a lot of overengineering for a simple "reduce total waiter
1466                         // count" goal.
1467                         match self.blocked_event_processors.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) {
1468                                 Err(val) => {
1469                                         debug_assert!(val, "compare_exchange failed spuriously?");
1470                                         return;
1471                                 },
1472                                 Ok(val) => {
1473                                         debug_assert!(!val, "compare_exchange succeeded spuriously?");
1474                                         // We're the only waiter, as the running process_events may have emptied the
1475                                         // pending events "long" ago and there are new events for us to process, wait until
1476                                         // its done and process any leftover events before returning.
1477                                         _single_processor_lock = Ok(self.event_processing_lock.lock().unwrap());
1478                                         self.blocked_event_processors.store(false, Ordering::Release);
1479                                 }
1480                         }
1481                 }
1482
1483                 let mut peers_to_disconnect = HashMap::new();
1484                 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
1485                 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
1486
1487                 {
1488                         // TODO: There are some DoS attacks here where you can flood someone's outbound send
1489                         // buffer by doing things like announcing channels on another node. We should be willing to
1490                         // drop optional-ish messages when send buffers get full!
1491
1492                         let peers_lock = self.peers.read().unwrap();
1493                         let peers = &*peers_lock;
1494                         macro_rules! get_peer_for_forwarding {
1495                                 ($node_id: expr) => {
1496                                         {
1497                                                 if peers_to_disconnect.get($node_id).is_some() {
1498                                                         // If we've "disconnected" this peer, do not send to it.
1499                                                         continue;
1500                                                 }
1501                                                 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().get($node_id).cloned();
1502                                                 match descriptor_opt {
1503                                                         Some(descriptor) => match peers.get(&descriptor) {
1504                                                                 Some(peer_mutex) => {
1505                                                                         let peer_lock = peer_mutex.lock().unwrap();
1506                                                                         if peer_lock.their_features.is_none() {
1507                                                                                 continue;
1508                                                                         }
1509                                                                         peer_lock
1510                                                                 },
1511                                                                 None => {
1512                                                                         debug_assert!(false, "Inconsistent peers set state!");
1513                                                                         continue;
1514                                                                 }
1515                                                         },
1516                                                         None => {
1517                                                                 continue;
1518                                                         },
1519                                                 }
1520                                         }
1521                                 }
1522                         }
1523                         for event in events_generated.drain(..) {
1524                                 match event {
1525                                         MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1526                                                 log_debug!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1527                                                                 log_pubkey!(node_id),
1528                                                                 log_bytes!(msg.temporary_channel_id));
1529                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1530                                         },
1531                                         MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1532                                                 log_debug!(self.logger, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
1533                                                                 log_pubkey!(node_id),
1534                                                                 log_bytes!(msg.temporary_channel_id));
1535                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1536                                         },
1537                                         MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
1538                                                 log_debug!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
1539                                                                 log_pubkey!(node_id),
1540                                                                 log_bytes!(msg.temporary_channel_id),
1541                                                                 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
1542                                                 // TODO: If the peer is gone we should generate a DiscardFunding event
1543                                                 // indicating to the wallet that they should just throw away this funding transaction
1544                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1545                                         },
1546                                         MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
1547                                                 log_debug!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
1548                                                                 log_pubkey!(node_id),
1549                                                                 log_bytes!(msg.channel_id));
1550                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1551                                         },
1552                                         MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
1553                                                 log_debug!(self.logger, "Handling SendChannelReady event in peer_handler for node {} for channel {}",
1554                                                                 log_pubkey!(node_id),
1555                                                                 log_bytes!(msg.channel_id));
1556                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1557                                         },
1558                                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
1559                                                 log_debug!(self.logger, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
1560                                                                 log_pubkey!(node_id),
1561                                                                 log_bytes!(msg.channel_id));
1562                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1563                                         },
1564                                         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 } } => {
1565                                                 log_debug!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
1566                                                                 log_pubkey!(node_id),
1567                                                                 update_add_htlcs.len(),
1568                                                                 update_fulfill_htlcs.len(),
1569                                                                 update_fail_htlcs.len(),
1570                                                                 log_bytes!(commitment_signed.channel_id));
1571                                                 let mut peer = get_peer_for_forwarding!(node_id);
1572                                                 for msg in update_add_htlcs {
1573                                                         self.enqueue_message(&mut *peer, msg);
1574                                                 }
1575                                                 for msg in update_fulfill_htlcs {
1576                                                         self.enqueue_message(&mut *peer, msg);
1577                                                 }
1578                                                 for msg in update_fail_htlcs {
1579                                                         self.enqueue_message(&mut *peer, msg);
1580                                                 }
1581                                                 for msg in update_fail_malformed_htlcs {
1582                                                         self.enqueue_message(&mut *peer, msg);
1583                                                 }
1584                                                 if let &Some(ref msg) = update_fee {
1585                                                         self.enqueue_message(&mut *peer, msg);
1586                                                 }
1587                                                 self.enqueue_message(&mut *peer, commitment_signed);
1588                                         },
1589                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1590                                                 log_debug!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
1591                                                                 log_pubkey!(node_id),
1592                                                                 log_bytes!(msg.channel_id));
1593                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1594                                         },
1595                                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1596                                                 log_debug!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
1597                                                                 log_pubkey!(node_id),
1598                                                                 log_bytes!(msg.channel_id));
1599                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1600                                         },
1601                                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1602                                                 log_debug!(self.logger, "Handling Shutdown event in peer_handler for node {} for channel {}",
1603                                                                 log_pubkey!(node_id),
1604                                                                 log_bytes!(msg.channel_id));
1605                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1606                                         },
1607                                         MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
1608                                                 log_debug!(self.logger, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
1609                                                                 log_pubkey!(node_id),
1610                                                                 log_bytes!(msg.channel_id));
1611                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1612                                         },
1613                                         MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
1614                                                 log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1615                                                 match self.message_handler.route_handler.handle_channel_announcement(&msg) {
1616                                                         Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1617                                                                 self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
1618                                                         _ => {},
1619                                                 }
1620                                                 match self.message_handler.route_handler.handle_channel_update(&update_msg) {
1621                                                         Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1622                                                                 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(update_msg), None),
1623                                                         _ => {},
1624                                                 }
1625                                         },
1626                                         MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
1627                                                 log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler");
1628                                                 match self.message_handler.route_handler.handle_node_announcement(&msg) {
1629                                                         Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1630                                                                 self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None),
1631                                                         _ => {},
1632                                                 }
1633                                         },
1634                                         MessageSendEvent::BroadcastChannelUpdate { msg } => {
1635                                                 log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1636                                                 match self.message_handler.route_handler.handle_channel_update(&msg) {
1637                                                         Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1638                                                                 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
1639                                                         _ => {},
1640                                                 }
1641                                         },
1642                                         MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
1643                                                 log_trace!(self.logger, "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
1644                                                                 log_pubkey!(node_id), msg.contents.short_channel_id);
1645                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1646                                         },
1647                                         MessageSendEvent::HandleError { ref node_id, ref action } => {
1648                                                 match *action {
1649                                                         msgs::ErrorAction::DisconnectPeer { ref msg } => {
1650                                                                 // We do not have the peers write lock, so we just store that we're
1651                                                                 // about to disconenct the peer and do it after we finish
1652                                                                 // processing most messages.
1653                                                                 peers_to_disconnect.insert(*node_id, msg.clone());
1654                                                         },
1655                                                         msgs::ErrorAction::IgnoreAndLog(level) => {
1656                                                                 log_given_level!(self.logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1657                                                         },
1658                                                         msgs::ErrorAction::IgnoreDuplicateGossip => {},
1659                                                         msgs::ErrorAction::IgnoreError => {
1660                                                                 log_debug!(self.logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1661                                                         },
1662                                                         msgs::ErrorAction::SendErrorMessage { ref msg } => {
1663                                                                 log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1664                                                                                 log_pubkey!(node_id),
1665                                                                                 msg.data);
1666                                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1667                                                         },
1668                                                         msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
1669                                                                 log_given_level!(self.logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
1670                                                                                 log_pubkey!(node_id),
1671                                                                                 msg.data);
1672                                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1673                                                         },
1674                                                 }
1675                                         },
1676                                         MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
1677                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1678                                         },
1679                                         MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
1680                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1681                                         }
1682                                         MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
1683                                                 log_gossip!(self.logger, "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
1684                                                         log_pubkey!(node_id),
1685                                                         msg.short_channel_ids.len(),
1686                                                         msg.first_blocknum,
1687                                                         msg.number_of_blocks,
1688                                                         msg.sync_complete);
1689                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1690                                         }
1691                                         MessageSendEvent::SendGossipTimestampFilter { ref node_id, ref msg } => {
1692                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1693                                         }
1694                                 }
1695                         }
1696
1697                         for (node_id, msg) in self.custom_message_handler.get_and_clear_pending_msg() {
1698                                 if peers_to_disconnect.get(&node_id).is_some() { continue; }
1699                                 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), &msg);
1700                         }
1701
1702                         for (descriptor, peer_mutex) in peers.iter() {
1703                                 self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer_mutex.lock().unwrap());
1704                         }
1705                 }
1706                 if !peers_to_disconnect.is_empty() {
1707                         let mut peers_lock = self.peers.write().unwrap();
1708                         let peers = &mut *peers_lock;
1709                         for (node_id, msg) in peers_to_disconnect.drain() {
1710                                 // Note that since we are holding the peers *write* lock we can
1711                                 // remove from node_id_to_descriptor immediately (as no other
1712                                 // thread can be holding the peer lock if we have the global write
1713                                 // lock).
1714
1715                                 if let Some(mut descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
1716                                         if let Some(peer_mutex) = peers.remove(&descriptor) {
1717                                                 if let Some(msg) = msg {
1718                                                         log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1719                                                                         log_pubkey!(node_id),
1720                                                                         msg.data);
1721                                                         let mut peer = peer_mutex.lock().unwrap();
1722                                                         self.enqueue_message(&mut *peer, &msg);
1723                                                         // This isn't guaranteed to work, but if there is enough free
1724                                                         // room in the send buffer, put the error message there...
1725                                                         self.do_attempt_write_data(&mut descriptor, &mut *peer);
1726                                                 } else {
1727                                                         log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1728                                                 }
1729                                         }
1730                                         descriptor.disconnect_socket();
1731                                         self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1732                                 }
1733                         }
1734                 }
1735         }
1736
1737         /// Indicates that the given socket descriptor's connection is now closed.
1738         pub fn socket_disconnected(&self, descriptor: &Descriptor) {
1739                 self.disconnect_event_internal(descriptor, false);
1740         }
1741
1742         fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1743                 let mut peers = self.peers.write().unwrap();
1744                 let peer_option = peers.remove(descriptor);
1745                 match peer_option {
1746                         None => {
1747                                 // This is most likely a simple race condition where the user found that the socket
1748                                 // was disconnected, then we told the user to `disconnect_socket()`, then they
1749                                 // called this method. Either way we're disconnected, return.
1750                         },
1751                         Some(peer_lock) => {
1752                                 let peer = peer_lock.lock().unwrap();
1753                                 if let Some(node_id) = peer.their_node_id {
1754                                         log_trace!(self.logger,
1755                                                 "Handling disconnection of peer {}, with {}future connection to the peer possible.",
1756                                                 log_pubkey!(node_id), if no_connection_possible { "no " } else { "" });
1757                                         self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
1758                                         self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1759                                 }
1760                         }
1761                 };
1762         }
1763
1764         /// Disconnect a peer given its node id.
1765         ///
1766         /// Set `no_connection_possible` to true to prevent any further connection with this peer,
1767         /// force-closing any channels we have with it.
1768         ///
1769         /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
1770         /// peer. Thus, be very careful about reentrancy issues.
1771         ///
1772         /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
1773         pub fn disconnect_by_node_id(&self, node_id: PublicKey, no_connection_possible: bool) {
1774                 let mut peers_lock = self.peers.write().unwrap();
1775                 if let Some(mut descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
1776                         log_trace!(self.logger, "Disconnecting peer with id {} due to client request", node_id);
1777                         peers_lock.remove(&descriptor);
1778                         self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1779                         descriptor.disconnect_socket();
1780                 }
1781         }
1782
1783         /// Disconnects all currently-connected peers. This is useful on platforms where there may be
1784         /// an indication that TCP sockets have stalled even if we weren't around to time them out
1785         /// using regular ping/pongs.
1786         pub fn disconnect_all_peers(&self) {
1787                 let mut peers_lock = self.peers.write().unwrap();
1788                 self.node_id_to_descriptor.lock().unwrap().clear();
1789                 let peers = &mut *peers_lock;
1790                 for (mut descriptor, peer) in peers.drain() {
1791                         if let Some(node_id) = peer.lock().unwrap().their_node_id {
1792                                 log_trace!(self.logger, "Disconnecting peer with id {} due to client request to disconnect all peers", node_id);
1793                                 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1794                         }
1795                         descriptor.disconnect_socket();
1796                 }
1797         }
1798
1799         /// This is called when we're blocked on sending additional gossip messages until we receive a
1800         /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
1801         /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
1802         fn maybe_send_extra_ping(&self, peer: &mut Peer) {
1803                 if peer.awaiting_pong_timer_tick_intervals == 0 {
1804                         peer.awaiting_pong_timer_tick_intervals = -1;
1805                         let ping = msgs::Ping {
1806                                 ponglen: 0,
1807                                 byteslen: 64,
1808                         };
1809                         self.enqueue_message(peer, &ping);
1810                 }
1811         }
1812
1813         /// Send pings to each peer and disconnect those which did not respond to the last round of
1814         /// pings.
1815         ///
1816         /// This may be called on any timescale you want, however, roughly once every ten seconds is
1817         /// preferred. The call rate determines both how often we send a ping to our peers and how much
1818         /// time they have to respond before we disconnect them.
1819         ///
1820         /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1821         /// issues!
1822         ///
1823         /// [`send_data`]: SocketDescriptor::send_data
1824         pub fn timer_tick_occurred(&self) {
1825                 let mut descriptors_needing_disconnect = Vec::new();
1826                 {
1827                         let peers_lock = self.peers.read().unwrap();
1828
1829                         for (descriptor, peer_mutex) in peers_lock.iter() {
1830                                 let mut peer = peer_mutex.lock().unwrap();
1831                                 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_node_id.is_none() {
1832                                         // The peer needs to complete its handshake before we can exchange messages. We
1833                                         // give peers one timer tick to complete handshake, reusing
1834                                         // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
1835                                         // for handshake completion.
1836                                         if peer.awaiting_pong_timer_tick_intervals != 0 {
1837                                                 descriptors_needing_disconnect.push(descriptor.clone());
1838                                         } else {
1839                                                 peer.awaiting_pong_timer_tick_intervals = 1;
1840                                         }
1841                                         continue;
1842                                 }
1843
1844                                 if peer.awaiting_pong_timer_tick_intervals == -1 {
1845                                         // Magic value set in `maybe_send_extra_ping`.
1846                                         peer.awaiting_pong_timer_tick_intervals = 1;
1847                                         peer.received_message_since_timer_tick = false;
1848                                         continue;
1849                                 }
1850
1851                                 if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
1852                                         || peer.awaiting_pong_timer_tick_intervals as u64 >
1853                                                 MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64
1854                                 {
1855                                         descriptors_needing_disconnect.push(descriptor.clone());
1856                                         continue;
1857                                 }
1858                                 peer.received_message_since_timer_tick = false;
1859
1860                                 if peer.awaiting_pong_timer_tick_intervals > 0 {
1861                                         peer.awaiting_pong_timer_tick_intervals += 1;
1862                                         continue;
1863                                 }
1864
1865                                 peer.awaiting_pong_timer_tick_intervals = 1;
1866                                 let ping = msgs::Ping {
1867                                         ponglen: 0,
1868                                         byteslen: 64,
1869                                 };
1870                                 self.enqueue_message(&mut *peer, &ping);
1871                                 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer);
1872                         }
1873                 }
1874
1875                 if !descriptors_needing_disconnect.is_empty() {
1876                         {
1877                                 let mut peers_lock = self.peers.write().unwrap();
1878                                 for descriptor in descriptors_needing_disconnect.iter() {
1879                                         if let Some(peer) = peers_lock.remove(descriptor) {
1880                                                 if let Some(node_id) = peer.lock().unwrap().their_node_id {
1881                                                         log_trace!(self.logger, "Disconnecting peer with id {} due to ping timeout", node_id);
1882                                                         self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
1883                                                         self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1884                                                 }
1885                                         }
1886                                 }
1887                         }
1888
1889                         for mut descriptor in descriptors_needing_disconnect.drain(..) {
1890                                 descriptor.disconnect_socket();
1891                         }
1892                 }
1893         }
1894 }
1895
1896 fn is_gossip_msg(type_id: u16) -> bool {
1897         match type_id {
1898                 msgs::ChannelAnnouncement::TYPE |
1899                 msgs::ChannelUpdate::TYPE |
1900                 msgs::NodeAnnouncement::TYPE |
1901                 msgs::QueryChannelRange::TYPE |
1902                 msgs::ReplyChannelRange::TYPE |
1903                 msgs::QueryShortChannelIds::TYPE |
1904                 msgs::ReplyShortChannelIdsEnd::TYPE => true,
1905                 _ => false
1906         }
1907 }
1908
1909 #[cfg(test)]
1910 mod tests {
1911         use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses};
1912         use ln::{msgs, wire};
1913         use ln::msgs::NetAddress;
1914         use util::events;
1915         use util::test_utils;
1916
1917         use bitcoin::secp256k1::Secp256k1;
1918         use bitcoin::secp256k1::{SecretKey, PublicKey};
1919
1920         use prelude::*;
1921         use sync::{Arc, Mutex};
1922         use core::sync::atomic::Ordering;
1923
1924         #[derive(Clone)]
1925         struct FileDescriptor {
1926                 fd: u16,
1927                 outbound_data: Arc<Mutex<Vec<u8>>>,
1928         }
1929         impl PartialEq for FileDescriptor {
1930                 fn eq(&self, other: &Self) -> bool {
1931                         self.fd == other.fd
1932                 }
1933         }
1934         impl Eq for FileDescriptor { }
1935         impl core::hash::Hash for FileDescriptor {
1936                 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
1937                         self.fd.hash(hasher)
1938                 }
1939         }
1940
1941         impl SocketDescriptor for FileDescriptor {
1942                 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
1943                         self.outbound_data.lock().unwrap().extend_from_slice(data);
1944                         data.len()
1945                 }
1946
1947                 fn disconnect_socket(&mut self) {}
1948         }
1949
1950         struct PeerManagerCfg {
1951                 chan_handler: test_utils::TestChannelMessageHandler,
1952                 routing_handler: test_utils::TestRoutingMessageHandler,
1953                 logger: test_utils::TestLogger,
1954         }
1955
1956         fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
1957                 let mut cfgs = Vec::new();
1958                 for _ in 0..peer_count {
1959                         cfgs.push(
1960                                 PeerManagerCfg{
1961                                         chan_handler: test_utils::TestChannelMessageHandler::new(),
1962                                         logger: test_utils::TestLogger::new(),
1963                                         routing_handler: test_utils::TestRoutingMessageHandler::new(),
1964                                 }
1965                         );
1966                 }
1967
1968                 cfgs
1969         }
1970
1971         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, IgnoringMessageHandler>> {
1972                 let mut peers = Vec::new();
1973                 for i in 0..peer_count {
1974                         let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
1975                         let ephemeral_bytes = [i as u8; 32];
1976                         let msg_handler = MessageHandler { chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler, onion_message_handler: IgnoringMessageHandler {} };
1977                         let peer = PeerManager::new(msg_handler, node_secret, &ephemeral_bytes, &cfgs[i].logger, IgnoringMessageHandler {});
1978                         peers.push(peer);
1979                 }
1980
1981                 peers
1982         }
1983
1984         fn establish_connection<'a>(peer_a: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, IgnoringMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler>, peer_b: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, IgnoringMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler>) -> (FileDescriptor, FileDescriptor) {
1985                 let secp_ctx = Secp256k1::new();
1986                 let a_id = PublicKey::from_secret_key(&secp_ctx, &peer_a.our_node_secret);
1987                 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1988                 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1989                 let initial_data = peer_b.new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
1990                 peer_a.new_inbound_connection(fd_a.clone(), None).unwrap();
1991                 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
1992                 peer_a.process_events();
1993
1994                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
1995                 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
1996
1997                 peer_b.process_events();
1998                 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
1999                 assert_eq!(peer_a.read_event(&mut fd_a, &b_data).unwrap(), false);
2000
2001                 peer_a.process_events();
2002                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2003                 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2004
2005                 (fd_a.clone(), fd_b.clone())
2006         }
2007
2008         #[test]
2009         fn test_disconnect_peer() {
2010                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2011                 // push a DisconnectPeer event to remove the node flagged by id
2012                 let cfgs = create_peermgr_cfgs(2);
2013                 let chan_handler = test_utils::TestChannelMessageHandler::new();
2014                 let mut peers = create_network(2, &cfgs);
2015                 establish_connection(&peers[0], &peers[1]);
2016                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2017
2018                 let secp_ctx = Secp256k1::new();
2019                 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
2020
2021                 chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
2022                         node_id: their_id,
2023                         action: msgs::ErrorAction::DisconnectPeer { msg: None },
2024                 });
2025                 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
2026                 peers[0].message_handler.chan_handler = &chan_handler;
2027
2028                 peers[0].process_events();
2029                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2030         }
2031
2032         #[test]
2033         fn test_send_simple_msg() {
2034                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2035                 // push a message from one peer to another.
2036                 let cfgs = create_peermgr_cfgs(2);
2037                 let a_chan_handler = test_utils::TestChannelMessageHandler::new();
2038                 let b_chan_handler = test_utils::TestChannelMessageHandler::new();
2039                 let mut peers = create_network(2, &cfgs);
2040                 let (fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2041                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2042
2043                 let secp_ctx = Secp256k1::new();
2044                 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
2045
2046                 let msg = msgs::Shutdown { channel_id: [42; 32], scriptpubkey: bitcoin::Script::new() };
2047                 a_chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::SendShutdown {
2048                         node_id: their_id, msg: msg.clone()
2049                 });
2050                 peers[0].message_handler.chan_handler = &a_chan_handler;
2051
2052                 b_chan_handler.expect_receive_msg(wire::Message::Shutdown(msg));
2053                 peers[1].message_handler.chan_handler = &b_chan_handler;
2054
2055                 peers[0].process_events();
2056
2057                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2058                 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2059         }
2060
2061         #[test]
2062         fn test_disconnect_all_peer() {
2063                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2064                 // then calls disconnect_all_peers
2065                 let cfgs = create_peermgr_cfgs(2);
2066                 let peers = create_network(2, &cfgs);
2067                 establish_connection(&peers[0], &peers[1]);
2068                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2069
2070                 peers[0].disconnect_all_peers();
2071                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2072         }
2073
2074         #[test]
2075         fn test_timer_tick_occurred() {
2076                 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
2077                 let cfgs = create_peermgr_cfgs(2);
2078                 let peers = create_network(2, &cfgs);
2079                 establish_connection(&peers[0], &peers[1]);
2080                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2081
2082                 // peers[0] awaiting_pong is set to true, but the Peer is still connected
2083                 peers[0].timer_tick_occurred();
2084                 peers[0].process_events();
2085                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2086
2087                 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
2088                 peers[0].timer_tick_occurred();
2089                 peers[0].process_events();
2090                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2091         }
2092
2093         #[test]
2094         fn test_do_attempt_write_data() {
2095                 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
2096                 let cfgs = create_peermgr_cfgs(2);
2097                 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2098                 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2099                 let peers = create_network(2, &cfgs);
2100
2101                 // By calling establish_connect, we trigger do_attempt_write_data between
2102                 // the peers. Previously this function would mistakenly enter an infinite loop
2103                 // when there were more channel messages available than could fit into a peer's
2104                 // buffer. This issue would now be detected by this test (because we use custom
2105                 // RoutingMessageHandlers that intentionally return more channel messages
2106                 // than can fit into a peer's buffer).
2107                 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2108
2109                 // Make each peer to read the messages that the other peer just wrote to them. Note that
2110                 // due to the max-message-before-ping limits this may take a few iterations to complete.
2111                 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
2112                         peers[1].process_events();
2113                         let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2114                         assert!(!a_read_data.is_empty());
2115
2116                         peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
2117                         peers[0].process_events();
2118
2119                         let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2120                         assert!(!b_read_data.is_empty());
2121                         peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
2122
2123                         peers[0].process_events();
2124                         assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
2125                 }
2126
2127                 // Check that each peer has received the expected number of channel updates and channel
2128                 // announcements.
2129                 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2130                 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2131                 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2132                 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2133         }
2134
2135         #[test]
2136         fn test_handshake_timeout() {
2137                 // Tests that we time out a peer still waiting on handshake completion after a full timer
2138                 // tick.
2139                 let cfgs = create_peermgr_cfgs(2);
2140                 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2141                 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2142                 let peers = create_network(2, &cfgs);
2143
2144                 let secp_ctx = Secp256k1::new();
2145                 let a_id = PublicKey::from_secret_key(&secp_ctx, &peers[0].our_node_secret);
2146                 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2147                 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2148                 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
2149                 peers[0].new_inbound_connection(fd_a.clone(), None).unwrap();
2150
2151                 // If we get a single timer tick before completion, that's fine
2152                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2153                 peers[0].timer_tick_occurred();
2154                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2155
2156                 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
2157                 peers[0].process_events();
2158                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2159                 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2160                 peers[1].process_events();
2161
2162                 // ...but if we get a second timer tick, we should disconnect the peer
2163                 peers[0].timer_tick_occurred();
2164                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2165
2166                 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2167                 assert!(peers[0].read_event(&mut fd_a, &b_data).is_err());
2168         }
2169
2170         #[test]
2171         fn test_filter_addresses(){
2172                 // Tests the filter_addresses function.
2173
2174                 // For (10/8)
2175                 let ip_address = NetAddress::IPv4{addr: [10, 0, 0, 0], port: 1000};
2176                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2177                 let ip_address = NetAddress::IPv4{addr: [10, 0, 255, 201], port: 1000};
2178                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2179                 let ip_address = NetAddress::IPv4{addr: [10, 255, 255, 255], port: 1000};
2180                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2181
2182                 // For (0/8)
2183                 let ip_address = NetAddress::IPv4{addr: [0, 0, 0, 0], port: 1000};
2184                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2185                 let ip_address = NetAddress::IPv4{addr: [0, 0, 255, 187], port: 1000};
2186                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2187                 let ip_address = NetAddress::IPv4{addr: [0, 255, 255, 255], port: 1000};
2188                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2189
2190                 // For (100.64/10)
2191                 let ip_address = NetAddress::IPv4{addr: [100, 64, 0, 0], port: 1000};
2192                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2193                 let ip_address = NetAddress::IPv4{addr: [100, 78, 255, 0], port: 1000};
2194                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2195                 let ip_address = NetAddress::IPv4{addr: [100, 127, 255, 255], port: 1000};
2196                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2197
2198                 // For (127/8)
2199                 let ip_address = NetAddress::IPv4{addr: [127, 0, 0, 0], port: 1000};
2200                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2201                 let ip_address = NetAddress::IPv4{addr: [127, 65, 73, 0], port: 1000};
2202                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2203                 let ip_address = NetAddress::IPv4{addr: [127, 255, 255, 255], port: 1000};
2204                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2205
2206                 // For (169.254/16)
2207                 let ip_address = NetAddress::IPv4{addr: [169, 254, 0, 0], port: 1000};
2208                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2209                 let ip_address = NetAddress::IPv4{addr: [169, 254, 221, 101], port: 1000};
2210                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2211                 let ip_address = NetAddress::IPv4{addr: [169, 254, 255, 255], port: 1000};
2212                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2213
2214                 // For (172.16/12)
2215                 let ip_address = NetAddress::IPv4{addr: [172, 16, 0, 0], port: 1000};
2216                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2217                 let ip_address = NetAddress::IPv4{addr: [172, 27, 101, 23], port: 1000};
2218                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2219                 let ip_address = NetAddress::IPv4{addr: [172, 31, 255, 255], port: 1000};
2220                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2221
2222                 // For (192.168/16)
2223                 let ip_address = NetAddress::IPv4{addr: [192, 168, 0, 0], port: 1000};
2224                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2225                 let ip_address = NetAddress::IPv4{addr: [192, 168, 205, 159], port: 1000};
2226                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2227                 let ip_address = NetAddress::IPv4{addr: [192, 168, 255, 255], port: 1000};
2228                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2229
2230                 // For (192.88.99/24)
2231                 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 0], port: 1000};
2232                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2233                 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 140], port: 1000};
2234                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2235                 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 255], port: 1000};
2236                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2237
2238                 // For other IPv4 addresses
2239                 let ip_address = NetAddress::IPv4{addr: [188, 255, 99, 0], port: 1000};
2240                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2241                 let ip_address = NetAddress::IPv4{addr: [123, 8, 129, 14], port: 1000};
2242                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2243                 let ip_address = NetAddress::IPv4{addr: [2, 88, 9, 255], port: 1000};
2244                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2245
2246                 // For (2000::/3)
2247                 let ip_address = NetAddress::IPv6{addr: [32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], port: 1000};
2248                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2249                 let ip_address = NetAddress::IPv6{addr: [45, 34, 209, 190, 0, 123, 55, 34, 0, 0, 3, 27, 201, 0, 0, 0], port: 1000};
2250                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2251                 let ip_address = NetAddress::IPv6{addr: [63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], port: 1000};
2252                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2253
2254                 // For other IPv6 addresses
2255                 let ip_address = NetAddress::IPv6{addr: [24, 240, 12, 32, 0, 0, 0, 0, 20, 97, 0, 32, 121, 254, 0, 0], port: 1000};
2256                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2257                 let ip_address = NetAddress::IPv6{addr: [68, 23, 56, 63, 0, 0, 2, 7, 75, 109, 0, 39, 0, 0, 0, 0], port: 1000};
2258                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2259                 let ip_address = NetAddress::IPv6{addr: [101, 38, 140, 230, 100, 0, 30, 98, 0, 26, 0, 0, 57, 96, 0, 0], port: 1000};
2260                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2261
2262                 // For (None)
2263                 assert_eq!(filter_addresses(None), None);
2264         }
2265 }