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