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