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