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