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