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