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