1 // This file is Copyright its original authors, visible in version control
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
10 //! Top level peer message handling and socket handling logic lives here.
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.
18 use bitcoin::secp256k1::{self, Secp256k1, SecretKey, PublicKey};
20 use ln::features::InitFeatures;
22 use ln::msgs::{ChannelMessageHandler, LightningError, NetAddress, RoutingMessageHandler};
23 use ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
24 use util::ser::{VecWriter, Writeable, Writer};
25 use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
28 use routing::gossip::{NetworkGraph, P2PGossipSync};
29 use util::atomic_counter::AtomicCounter;
30 use util::events::{MessageSendEvent, MessageSendEventsProvider};
31 use util::logger::Logger;
35 use alloc::collections::LinkedList;
36 use sync::{Arc, Mutex, MutexGuard, FairRwLock};
37 use core::sync::atomic::{AtomicBool, Ordering};
38 use core::{cmp, hash, fmt, mem};
40 use core::convert::Infallible;
41 #[cfg(feature = "std")] use std::error;
43 use bitcoin::hashes::sha256::Hash as Sha256;
44 use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
45 use bitcoin::hashes::{HashEngine, Hash};
47 /// Handler for BOLT1-compliant messages.
48 pub trait CustomMessageHandler: wire::CustomMessageReader {
49 /// Called with the message type that was received and the buffer to be read.
50 /// Can return a `MessageHandlingError` if the message could not be handled.
51 fn handle_custom_message(&self, msg: Self::CustomMessage, sender_node_id: &PublicKey) -> Result<(), LightningError>;
53 /// Gets the list of pending messages which were generated by the custom message
54 /// handler, clearing the list in the process. The first tuple element must
55 /// correspond to the intended recipients node ids. If no connection to one of the
56 /// specified node does not exist, the message is simply not sent to it.
57 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)>;
60 /// A dummy struct which implements `RoutingMessageHandler` without storing any routing information
61 /// or doing any processing. You can provide one of these as the route_handler in a MessageHandler.
62 pub struct IgnoringMessageHandler{}
63 impl MessageSendEventsProvider for IgnoringMessageHandler {
64 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> { Vec::new() }
66 impl RoutingMessageHandler for IgnoringMessageHandler {
67 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
68 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
69 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
70 fn get_next_channel_announcement(&self, _starting_point: u64) ->
71 Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { None }
72 fn get_next_node_announcement(&self, _starting_point: Option<&PublicKey>) -> Option<msgs::NodeAnnouncement> { None }
73 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init) {}
74 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
75 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
76 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) }
77 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) }
79 impl Deref for IgnoringMessageHandler {
80 type Target = IgnoringMessageHandler;
81 fn deref(&self) -> &Self { self }
84 // Implement Type for Infallible, note that it cannot be constructed, and thus you can never call a
85 // method that takes self for it.
86 impl wire::Type for Infallible {
87 fn type_id(&self) -> u16 {
91 impl Writeable for Infallible {
92 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
97 impl wire::CustomMessageReader for IgnoringMessageHandler {
98 type CustomMessage = Infallible;
99 fn read<R: io::Read>(&self, _message_type: u16, _buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
104 impl CustomMessageHandler for IgnoringMessageHandler {
105 fn handle_custom_message(&self, _msg: Infallible, _sender_node_id: &PublicKey) -> Result<(), LightningError> {
106 // Since we always return `None` in the read the handle method should never be called.
110 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
113 /// A dummy struct which implements `ChannelMessageHandler` without having any channels.
114 /// You can provide one of these as the route_handler in a MessageHandler.
115 pub struct ErroringMessageHandler {
116 message_queue: Mutex<Vec<MessageSendEvent>>
118 impl ErroringMessageHandler {
119 /// Constructs a new ErroringMessageHandler
120 pub fn new() -> Self {
121 Self { message_queue: Mutex::new(Vec::new()) }
123 fn push_error(&self, node_id: &PublicKey, channel_id: [u8; 32]) {
124 self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
125 action: msgs::ErrorAction::SendErrorMessage {
126 msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
128 node_id: node_id.clone(),
132 impl MessageSendEventsProvider for ErroringMessageHandler {
133 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
134 let mut res = Vec::new();
135 mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
139 impl ChannelMessageHandler for ErroringMessageHandler {
140 // Any messages which are related to a specific channel generate an error message to let the
141 // peer know we don't care about channels.
142 fn handle_open_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::OpenChannel) {
143 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
145 fn handle_accept_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::AcceptChannel) {
146 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
148 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
149 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
151 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
152 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
154 fn handle_channel_ready(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
155 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
157 fn handle_shutdown(&self, their_node_id: &PublicKey, _their_features: &InitFeatures, msg: &msgs::Shutdown) {
158 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
160 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
161 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
163 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
164 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
166 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
167 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
169 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
170 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
172 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
173 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
175 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
176 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
178 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
179 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
181 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
182 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
184 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
185 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
187 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
188 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
190 // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them.
191 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
192 fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
193 fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {}
194 fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
196 impl Deref for ErroringMessageHandler {
197 type Target = ErroringMessageHandler;
198 fn deref(&self) -> &Self { self }
201 /// Provides references to trait impls which handle different types of messages.
202 pub struct MessageHandler<CM: Deref, RM: Deref> where
203 CM::Target: ChannelMessageHandler,
204 RM::Target: RoutingMessageHandler {
205 /// A message handler which handles messages specific to channels. Usually this is just a
206 /// [`ChannelManager`] object or an [`ErroringMessageHandler`].
208 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
209 pub chan_handler: CM,
210 /// A message handler which handles messages updating our knowledge of the network channel
211 /// graph. Usually this is just a [`P2PGossipSync`] object or an [`IgnoringMessageHandler`].
213 /// [`P2PGossipSync`]: crate::routing::gossip::P2PGossipSync
214 pub route_handler: RM,
217 /// Provides an object which can be used to send data to and which uniquely identifies a connection
218 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
219 /// implement Hash to meet the PeerManager API.
221 /// For efficiency, Clone should be relatively cheap for this type.
223 /// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original
224 /// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it
225 /// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no
226 /// further calls to the [`PeerManager`] related to the original socket occur. This allows you to
227 /// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish
228 /// to simply use another value which is guaranteed to be globally unique instead.
229 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
230 /// Attempts to send some data from the given slice to the peer.
232 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
233 /// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
234 /// called and further write attempts may occur until that time.
236 /// If the returned size is smaller than `data.len()`, a
237 /// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
238 /// written. Additionally, until a `send_data` event completes fully, no further
239 /// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
240 /// prevent denial-of-service issues, you should not read or buffer any data from the socket
243 /// If a [`PeerManager::read_event`] call on this descriptor had previously returned true
244 /// (indicating that read events should be paused to prevent DoS in the send buffer),
245 /// `resume_read` may be set indicating that read events on this descriptor should resume. A
246 /// `resume_read` of false carries no meaning, and should not cause any action.
247 fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
248 /// Disconnect the socket pointed to by this SocketDescriptor.
250 /// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
251 /// call (doing so is a noop).
252 fn disconnect_socket(&mut self);
255 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
256 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
259 pub struct PeerHandleError {
260 /// Used to indicate that we probably can't make any future connections to this peer (e.g.
261 /// because we required features that our peer was missing, or vice versa).
263 /// While LDK's [`ChannelManager`] will not do it automatically, you likely wish to force-close
264 /// any channels with this peer or check for new versions of LDK.
266 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
267 pub no_connection_possible: bool,
269 impl fmt::Debug for PeerHandleError {
270 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
271 formatter.write_str("Peer Sent Invalid Data")
274 impl fmt::Display for PeerHandleError {
275 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
276 formatter.write_str("Peer Sent Invalid Data")
280 #[cfg(feature = "std")]
281 impl error::Error for PeerHandleError {
282 fn description(&self) -> &str {
283 "Peer Sent Invalid Data"
287 enum InitSyncTracker{
289 ChannelsSyncing(u64),
290 NodesSyncing(PublicKey),
293 /// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop
294 /// forwarding gossip messages to peers altogether.
295 const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2;
297 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
298 /// we have fewer than this many messages in the outbound buffer again.
299 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
300 /// refilled as we send bytes.
301 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 10;
302 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
304 const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO;
306 /// If we've sent a ping, and are still awaiting a response, we may need to churn our way through
307 /// the socket receive buffer before receiving the ping.
309 /// On a fairly old Arm64 board, with Linux defaults, this can take as long as 20 seconds, not
310 /// including any network delays, outbound traffic, or the same for messages from other peers.
312 /// Thus, to avoid needlessly disconnecting a peer, we allow a peer to take this many timer ticks
313 /// per connected peer to respond to a ping, as long as they send us at least one message during
314 /// each tick, ensuring we aren't actually just disconnected.
315 /// With a timer tick interval of ten seconds, this translates to about 40 seconds per connected
318 /// When we improve parallelism somewhat we should reduce this to e.g. this many timer ticks per
319 /// two connected peers, assuming most LDK-running systems have at least two cores.
320 const MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER: i8 = 4;
322 /// This is the minimum number of messages we expect a peer to be able to handle within one timer
323 /// tick. Once we have sent this many messages since the last ping, we send a ping right away to
324 /// ensures we don't just fill up our send buffer and leave the peer with too many messages to
325 /// process before the next ping.
327 /// Note that we continue responding to other messages even after we've sent this many messages, so
328 /// it's more of a general guideline used for gossip backfill (and gossip forwarding, times
329 /// [`FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO`]) than a hard limit.
330 const BUFFER_DRAIN_MSGS_PER_TICK: usize = 32;
333 channel_encryptor: PeerChannelEncryptor,
334 their_node_id: Option<PublicKey>,
335 their_features: Option<InitFeatures>,
336 their_net_address: Option<NetAddress>,
338 pending_outbound_buffer: LinkedList<Vec<u8>>,
339 pending_outbound_buffer_first_msg_offset: usize,
340 awaiting_write_event: bool,
342 pending_read_buffer: Vec<u8>,
343 pending_read_buffer_pos: usize,
344 pending_read_is_header: bool,
346 sync_status: InitSyncTracker,
348 msgs_sent_since_pong: usize,
349 awaiting_pong_timer_tick_intervals: i8,
350 received_message_since_timer_tick: bool,
351 sent_gossip_timestamp_filter: bool,
355 /// Returns true if the channel announcements/updates for the given channel should be
356 /// forwarded to this peer.
357 /// If we are sending our routing table to this peer and we have not yet sent channel
358 /// announcements/updates for the given channel_id then we will send it when we get to that
359 /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
360 /// sent the old versions, we should send the update, and so return true here.
361 fn should_forward_channel_announcement(&self, channel_id: u64) -> bool {
362 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
363 !self.sent_gossip_timestamp_filter {
366 match self.sync_status {
367 InitSyncTracker::NoSyncRequested => true,
368 InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
369 InitSyncTracker::NodesSyncing(_) => true,
373 /// Similar to the above, but for node announcements indexed by node_id.
374 fn should_forward_node_announcement(&self, node_id: PublicKey) -> bool {
375 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
376 !self.sent_gossip_timestamp_filter {
379 match self.sync_status {
380 InitSyncTracker::NoSyncRequested => true,
381 InitSyncTracker::ChannelsSyncing(_) => false,
382 InitSyncTracker::NodesSyncing(pk) => pk < node_id,
386 /// Returns whether we should be reading bytes from this peer, based on whether its outbound
387 /// buffer still has space and we don't need to pause reads to get some writes out.
388 fn should_read(&self) -> bool {
389 self.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE
392 /// Determines if we should push additional gossip messages onto a peer's outbound buffer for
393 /// backfilling gossip data to the peer. This is checked every time the peer's buffer may have
395 fn should_buffer_gossip_backfill(&self) -> bool {
396 self.pending_outbound_buffer.is_empty() &&
397 self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
400 /// Returns whether this peer's buffer is full and we should drop gossip messages.
401 fn buffer_full_drop_gossip(&self) -> bool {
402 if self.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP
403 || self.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO {
410 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
411 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
412 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
413 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
414 /// issues such as overly long function definitions.
416 /// (C-not exported) as Arcs don't make sense in bindings
417 pub type SimpleArcPeerManager<SD, M, T, F, C, L> = PeerManager<SD, Arc<SimpleArcChannelManager<M, T, F, L>>, Arc<P2PGossipSync<Arc<NetworkGraph<Arc<L>>>, Arc<C>, Arc<L>>>, Arc<L>, Arc<IgnoringMessageHandler>>;
419 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
420 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
421 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
422 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
423 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
424 /// helps with issues such as long function definitions.
426 /// (C-not exported) as Arcs don't make sense in bindings
427 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>, &'f L, IgnoringMessageHandler>;
429 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
430 /// socket events into messages which it passes on to its [`MessageHandler`].
432 /// Locks are taken internally, so you must never assume that reentrancy from a
433 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
435 /// Calls to [`read_event`] will decode relevant messages and pass them to the
436 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
437 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
438 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
439 /// calls only after previous ones have returned.
441 /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
442 /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
443 /// essentially you should default to using a SimpleRefPeerManager, and use a
444 /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
445 /// you're using lightning-net-tokio.
447 /// [`read_event`]: PeerManager::read_event
448 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> where
449 CM::Target: ChannelMessageHandler,
450 RM::Target: RoutingMessageHandler,
452 CMH::Target: CustomMessageHandler {
453 message_handler: MessageHandler<CM, RM>,
454 /// Connection state for each connected peer - we have an outer read-write lock which is taken
455 /// as read while we're doing processing for a peer and taken write when a peer is being added
458 /// The inner Peer lock is held for sending and receiving bytes, but note that we do *not* hold
459 /// it while we're processing a message. This is fine as [`PeerManager::read_event`] requires
460 /// that there be no parallel calls for a given peer, so mutual exclusion of messages handed to
461 /// the `MessageHandler`s for a given peer is already guaranteed.
462 peers: FairRwLock<HashMap<Descriptor, Mutex<Peer>>>,
463 /// Only add to this set when noise completes.
464 /// Locked *after* peers. When an item is removed, it must be removed with the `peers` write
465 /// lock held. Entries may be added with only the `peers` read lock held (though the
466 /// `Descriptor` value must already exist in `peers`).
467 node_id_to_descriptor: Mutex<HashMap<PublicKey, Descriptor>>,
468 /// We can only have one thread processing events at once, but we don't usually need the full
469 /// `peers` write lock to do so, so instead we block on this empty mutex when entering
470 /// `process_events`.
471 event_processing_lock: Mutex<()>,
472 /// Because event processing is global and always does all available work before returning,
473 /// there is no reason for us to have many event processors waiting on the lock at once.
474 /// Instead, we limit the total blocked event processors to always exactly one by setting this
475 /// when an event process call is waiting.
476 blocked_event_processors: AtomicBool,
477 our_node_secret: SecretKey,
478 ephemeral_key_midstate: Sha256Engine,
479 custom_message_handler: CMH,
481 peer_counter: AtomicCounter,
484 secp_ctx: Secp256k1<secp256k1::SignOnly>
487 enum MessageHandlingError {
488 PeerHandleError(PeerHandleError),
489 LightningError(LightningError),
492 impl From<PeerHandleError> for MessageHandlingError {
493 fn from(error: PeerHandleError) -> Self {
494 MessageHandlingError::PeerHandleError(error)
498 impl From<LightningError> for MessageHandlingError {
499 fn from(error: LightningError) -> Self {
500 MessageHandlingError::LightningError(error)
504 macro_rules! encode_msg {
506 let mut buffer = VecWriter(Vec::new());
507 wire::write($msg, &mut buffer).unwrap();
512 impl<Descriptor: SocketDescriptor, CM: Deref, L: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, L, IgnoringMessageHandler> where
513 CM::Target: ChannelMessageHandler,
515 /// Constructs a new PeerManager with the given ChannelMessageHandler. No routing message
516 /// handler is used and network graph messages are ignored.
518 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
519 /// cryptographically secure random bytes.
521 /// (C-not exported) as we can't export a PeerManager with a dummy route handler
522 pub fn new_channel_only(channel_message_handler: CM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
523 Self::new(MessageHandler {
524 chan_handler: channel_message_handler,
525 route_handler: IgnoringMessageHandler{},
526 }, our_node_secret, ephemeral_random_data, logger, IgnoringMessageHandler{})
530 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, L, IgnoringMessageHandler> where
531 RM::Target: RoutingMessageHandler,
533 /// Constructs a new PeerManager with the given RoutingMessageHandler. No channel message
534 /// handler is used and messages related to channels will be ignored (or generate error
535 /// messages). Note that some other lightning implementations time-out connections after some
536 /// time if no channel is built with the peer.
538 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
539 /// cryptographically secure random bytes.
541 /// (C-not exported) as we can't export a PeerManager with a dummy channel handler
542 pub fn new_routing_only(routing_message_handler: RM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
543 Self::new(MessageHandler {
544 chan_handler: ErroringMessageHandler::new(),
545 route_handler: routing_message_handler,
546 }, our_node_secret, ephemeral_random_data, logger, IgnoringMessageHandler{})
550 /// A simple wrapper that optionally prints " from <pubkey>" for an optional pubkey.
551 /// This works around `format!()` taking a reference to each argument, preventing
552 /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
553 /// due to lifetime errors.
554 struct OptionalFromDebugger<'a>(&'a Option<PublicKey>);
555 impl core::fmt::Display for OptionalFromDebugger<'_> {
556 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
557 if let Some(node_id) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
561 /// A function used to filter out local or private addresses
562 /// https://www.iana.org./assignments/ipv4-address-space/ipv4-address-space.xhtml
563 /// https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml
564 fn filter_addresses(ip_address: Option<NetAddress>) -> Option<NetAddress> {
566 // For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8)
567 Some(NetAddress::IPv4{addr: [10, _, _, _], port: _}) => None,
568 // For IPv4 range 0.0.0.0 - 0.255.255.255 (0/8)
569 Some(NetAddress::IPv4{addr: [0, _, _, _], port: _}) => None,
570 // For IPv4 range 100.64.0.0 - 100.127.255.255 (100.64/10)
571 Some(NetAddress::IPv4{addr: [100, 64..=127, _, _], port: _}) => None,
572 // For IPv4 range 127.0.0.0 - 127.255.255.255 (127/8)
573 Some(NetAddress::IPv4{addr: [127, _, _, _], port: _}) => None,
574 // For IPv4 range 169.254.0.0 - 169.254.255.255 (169.254/16)
575 Some(NetAddress::IPv4{addr: [169, 254, _, _], port: _}) => None,
576 // For IPv4 range 172.16.0.0 - 172.31.255.255 (172.16/12)
577 Some(NetAddress::IPv4{addr: [172, 16..=31, _, _], port: _}) => None,
578 // For IPv4 range 192.168.0.0 - 192.168.255.255 (192.168/16)
579 Some(NetAddress::IPv4{addr: [192, 168, _, _], port: _}) => None,
580 // For IPv4 range 192.88.99.0 - 192.88.99.255 (192.88.99/24)
581 Some(NetAddress::IPv4{addr: [192, 88, 99, _], port: _}) => None,
582 // For IPv6 range 2000:0000:0000:0000:0000:0000:0000:0000 - 3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff (2000::/3)
583 Some(NetAddress::IPv6{addr: [0x20..=0x3F, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _], port: _}) => ip_address,
584 // For remaining addresses
585 Some(NetAddress::IPv6{addr: _, port: _}) => None,
586 Some(..) => ip_address,
591 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> PeerManager<Descriptor, CM, RM, L, CMH> where
592 CM::Target: ChannelMessageHandler,
593 RM::Target: RoutingMessageHandler,
595 CMH::Target: CustomMessageHandler {
596 /// Constructs a new PeerManager with the given message handlers and node_id secret key
597 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
598 /// cryptographically secure random bytes.
599 pub fn new(message_handler: MessageHandler<CM, RM>, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L, custom_message_handler: CMH) -> Self {
600 let mut ephemeral_key_midstate = Sha256::engine();
601 ephemeral_key_midstate.input(ephemeral_random_data);
603 let mut secp_ctx = Secp256k1::signing_only();
604 let ephemeral_hash = Sha256::from_engine(ephemeral_key_midstate.clone()).into_inner();
605 secp_ctx.seeded_randomize(&ephemeral_hash);
609 peers: FairRwLock::new(HashMap::new()),
610 node_id_to_descriptor: Mutex::new(HashMap::new()),
611 event_processing_lock: Mutex::new(()),
612 blocked_event_processors: AtomicBool::new(false),
614 ephemeral_key_midstate,
615 peer_counter: AtomicCounter::new(),
617 custom_message_handler,
622 /// Get the list of node ids for peers which have completed the initial handshake.
624 /// For outbound connections, this will be the same as the their_node_id parameter passed in to
625 /// new_outbound_connection, however entries will only appear once the initial handshake has
626 /// completed and we are sure the remote peer has the private key for the given node_id.
627 pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
628 let peers = self.peers.read().unwrap();
629 peers.values().filter_map(|peer_mutex| {
630 let p = peer_mutex.lock().unwrap();
631 if !p.channel_encryptor.is_ready_for_encryption() || p.their_features.is_none() {
638 fn get_ephemeral_key(&self) -> SecretKey {
639 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
640 let counter = self.peer_counter.get_increment();
641 ephemeral_hash.input(&counter.to_le_bytes());
642 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
645 /// Indicates a new outbound connection has been established to a node with the given node_id
646 /// and an optional remote network address.
648 /// The remote network address adds the option to report a remote IP address back to a connecting
649 /// peer using the init message.
650 /// The user should pass the remote network address of the host they are connected to.
652 /// If an `Err` is returned here you must disconnect the connection immediately.
654 /// Returns a small number of bytes to send to the remote node (currently always 50).
656 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
657 /// [`socket_disconnected()`].
659 /// [`socket_disconnected()`]: PeerManager::socket_disconnected
660 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<Vec<u8>, PeerHandleError> {
661 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
662 let res = peer_encryptor.get_act_one(&self.secp_ctx).to_vec();
663 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
665 let mut peers = self.peers.write().unwrap();
666 if peers.insert(descriptor, Mutex::new(Peer {
667 channel_encryptor: peer_encryptor,
669 their_features: None,
670 their_net_address: remote_network_address,
672 pending_outbound_buffer: LinkedList::new(),
673 pending_outbound_buffer_first_msg_offset: 0,
674 awaiting_write_event: false,
677 pending_read_buffer_pos: 0,
678 pending_read_is_header: false,
680 sync_status: InitSyncTracker::NoSyncRequested,
682 msgs_sent_since_pong: 0,
683 awaiting_pong_timer_tick_intervals: 0,
684 received_message_since_timer_tick: false,
685 sent_gossip_timestamp_filter: false,
687 panic!("PeerManager driver duplicated descriptors!");
692 /// Indicates a new inbound connection has been established to a node with an optional remote
695 /// The remote network address adds the option to report a remote IP address back to a connecting
696 /// peer using the init message.
697 /// The user should pass the remote network address of the host they are connected to.
699 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
700 /// (outbound connector always speaks first). If an `Err` is returned here you must disconnect
701 /// the connection immediately.
703 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
704 /// [`socket_disconnected()`].
706 /// [`socket_disconnected()`]: PeerManager::socket_disconnected
707 pub fn new_inbound_connection(&self, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<(), PeerHandleError> {
708 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret, &self.secp_ctx);
709 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
711 let mut peers = self.peers.write().unwrap();
712 if peers.insert(descriptor, Mutex::new(Peer {
713 channel_encryptor: peer_encryptor,
715 their_features: None,
716 their_net_address: remote_network_address,
718 pending_outbound_buffer: LinkedList::new(),
719 pending_outbound_buffer_first_msg_offset: 0,
720 awaiting_write_event: false,
723 pending_read_buffer_pos: 0,
724 pending_read_is_header: false,
726 sync_status: InitSyncTracker::NoSyncRequested,
728 msgs_sent_since_pong: 0,
729 awaiting_pong_timer_tick_intervals: 0,
730 received_message_since_timer_tick: false,
731 sent_gossip_timestamp_filter: false,
733 panic!("PeerManager driver duplicated descriptors!");
738 fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
739 while !peer.awaiting_write_event {
740 if peer.should_buffer_gossip_backfill() {
741 match peer.sync_status {
742 InitSyncTracker::NoSyncRequested => {},
743 InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
744 if let Some((announce, update_a_option, update_b_option)) =
745 self.message_handler.route_handler.get_next_channel_announcement(c)
747 self.enqueue_message(peer, &announce);
748 if let Some(update_a) = update_a_option {
749 self.enqueue_message(peer, &update_a);
751 if let Some(update_b) = update_b_option {
752 self.enqueue_message(peer, &update_b);
754 peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
756 peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
759 InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
760 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(None) {
761 self.enqueue_message(peer, &msg);
762 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
764 peer.sync_status = InitSyncTracker::NoSyncRequested;
767 InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
768 InitSyncTracker::NodesSyncing(key) => {
769 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(Some(&key)) {
770 self.enqueue_message(peer, &msg);
771 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
773 peer.sync_status = InitSyncTracker::NoSyncRequested;
778 if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
779 self.maybe_send_extra_ping(peer);
782 let next_buff = match peer.pending_outbound_buffer.front() {
787 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
788 let data_sent = descriptor.send_data(pending, peer.should_read());
789 peer.pending_outbound_buffer_first_msg_offset += data_sent;
790 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() {
791 peer.pending_outbound_buffer_first_msg_offset = 0;
792 peer.pending_outbound_buffer.pop_front();
794 peer.awaiting_write_event = true;
799 /// Indicates that there is room to write data to the given socket descriptor.
801 /// May return an Err to indicate that the connection should be closed.
803 /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
804 /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
805 /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
806 /// ready to call `[write_buffer_space_avail`] again if a write call generated here isn't
809 /// [`send_data`]: SocketDescriptor::send_data
810 /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
811 pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
812 let peers = self.peers.read().unwrap();
813 match peers.get(descriptor) {
815 // This is most likely a simple race condition where the user found that the socket
816 // was writeable, then we told the user to `disconnect_socket()`, then they called
817 // this method. Return an error to make sure we get disconnected.
818 return Err(PeerHandleError { no_connection_possible: false });
820 Some(peer_mutex) => {
821 let mut peer = peer_mutex.lock().unwrap();
822 peer.awaiting_write_event = false;
823 self.do_attempt_write_data(descriptor, &mut peer);
829 /// Indicates that data was read from the given socket descriptor.
831 /// May return an Err to indicate that the connection should be closed.
833 /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
834 /// Thus, however, you should call [`process_events`] after any `read_event` to generate
835 /// [`send_data`] calls to handle responses.
837 /// If `Ok(true)` is returned, further read_events should not be triggered until a
838 /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
841 /// [`send_data`]: SocketDescriptor::send_data
842 /// [`process_events`]: PeerManager::process_events
843 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
844 match self.do_read_event(peer_descriptor, data) {
847 log_trace!(self.logger, "Peer sent invalid data or we decided to disconnect due to a protocol error");
848 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
854 /// Append a message to a peer's pending outbound/write buffer
855 fn enqueue_encoded_message(&self, peer: &mut Peer, encoded_message: &Vec<u8>) {
856 peer.msgs_sent_since_pong += 1;
857 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_message[..]));
860 /// Append a message to a peer's pending outbound/write buffer
861 fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
862 let mut buffer = VecWriter(Vec::with_capacity(2048));
863 wire::write(message, &mut buffer).unwrap(); // crash if the write failed
865 if is_gossip_msg(message.type_id()) {
866 log_gossip!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()));
868 log_trace!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()))
870 self.enqueue_encoded_message(peer, &buffer.0);
873 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
874 let mut pause_read = false;
875 let peers = self.peers.read().unwrap();
876 let mut msgs_to_forward = Vec::new();
877 let mut peer_node_id = None;
878 match peers.get(peer_descriptor) {
880 // This is most likely a simple race condition where the user read some bytes
881 // from the socket, then we told the user to `disconnect_socket()`, then they
882 // called this method. Return an error to make sure we get disconnected.
883 return Err(PeerHandleError { no_connection_possible: false });
885 Some(peer_mutex) => {
886 let mut read_pos = 0;
887 while read_pos < data.len() {
888 macro_rules! try_potential_handleerror {
889 ($peer: expr, $thing: expr) => {
894 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
895 //TODO: Try to push msg
896 log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
897 return Err(PeerHandleError{ no_connection_possible: false });
899 msgs::ErrorAction::IgnoreAndLog(level) => {
900 log_given_level!(self.logger, level, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
903 msgs::ErrorAction::IgnoreDuplicateGossip => continue, // Don't even bother logging these
904 msgs::ErrorAction::IgnoreError => {
905 log_debug!(self.logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
908 msgs::ErrorAction::SendErrorMessage { msg } => {
909 log_debug!(self.logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
910 self.enqueue_message($peer, &msg);
913 msgs::ErrorAction::SendWarningMessage { msg, log_level } => {
914 log_given_level!(self.logger, log_level, "Error handling message{}; sending warning message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
915 self.enqueue_message($peer, &msg);
924 let mut peer_lock = peer_mutex.lock().unwrap();
925 let peer = &mut *peer_lock;
926 let mut msg_to_handle = None;
927 if peer_node_id.is_none() {
928 peer_node_id = peer.their_node_id.clone();
931 assert!(peer.pending_read_buffer.len() > 0);
932 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
935 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
936 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]);
937 read_pos += data_to_copy;
938 peer.pending_read_buffer_pos += data_to_copy;
941 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
942 peer.pending_read_buffer_pos = 0;
944 macro_rules! insert_node_id {
946 match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap()) {
947 hash_map::Entry::Occupied(_) => {
948 log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
949 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
950 return Err(PeerHandleError{ no_connection_possible: false })
952 hash_map::Entry::Vacant(entry) => {
953 log_debug!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
954 entry.insert(peer_descriptor.clone())
960 let next_step = peer.channel_encryptor.get_noise_step();
962 NextNoiseStep::ActOne => {
963 let act_two = try_potential_handleerror!(peer, peer.channel_encryptor
964 .process_act_one_with_keys(&peer.pending_read_buffer[..],
965 &self.our_node_secret, self.get_ephemeral_key(), &self.secp_ctx)).to_vec();
966 peer.pending_outbound_buffer.push_back(act_two);
967 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
969 NextNoiseStep::ActTwo => {
970 let (act_three, their_node_id) = try_potential_handleerror!(peer,
971 peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..],
972 &self.our_node_secret, &self.secp_ctx));
973 peer.pending_outbound_buffer.push_back(act_three.to_vec());
974 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
975 peer.pending_read_is_header = true;
977 peer.their_node_id = Some(their_node_id);
979 let features = InitFeatures::known();
980 let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
981 self.enqueue_message(peer, &resp);
982 peer.awaiting_pong_timer_tick_intervals = 0;
984 NextNoiseStep::ActThree => {
985 let their_node_id = try_potential_handleerror!(peer,
986 peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
987 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
988 peer.pending_read_is_header = true;
989 peer.their_node_id = Some(their_node_id);
991 let features = InitFeatures::known();
992 let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
993 self.enqueue_message(peer, &resp);
994 peer.awaiting_pong_timer_tick_intervals = 0;
996 NextNoiseStep::NoiseComplete => {
997 if peer.pending_read_is_header {
998 let msg_len = try_potential_handleerror!(peer,
999 peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
1000 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1001 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
1002 if msg_len < 2 { // Need at least the message type tag
1003 return Err(PeerHandleError{ no_connection_possible: false });
1005 peer.pending_read_is_header = false;
1007 let msg_data = try_potential_handleerror!(peer,
1008 peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
1009 assert!(msg_data.len() >= 2);
1011 // Reset read buffer
1012 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1013 peer.pending_read_buffer.resize(18, 0);
1014 peer.pending_read_is_header = true;
1016 let mut reader = io::Cursor::new(&msg_data[..]);
1017 let message_result = wire::read(&mut reader, &*self.custom_message_handler);
1018 let message = match message_result {
1022 // Note that to avoid recursion we never call
1023 // `do_attempt_write_data` from here, causing
1024 // the messages enqueued here to not actually
1025 // be sent before the peer is disconnected.
1026 (msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
1027 log_gossip!(self.logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
1030 (msgs::DecodeError::UnsupportedCompression, _) => {
1031 log_gossip!(self.logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
1032 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: "Unsupported message compression: zlib".to_owned() });
1035 (_, Some(ty)) if is_gossip_msg(ty) => {
1036 log_gossip!(self.logger, "Got an invalid value while deserializing a gossip message");
1037 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: "Unreadable/bogus gossip message".to_owned() });
1040 (msgs::DecodeError::UnknownRequiredFeature, ty) => {
1041 log_gossip!(self.logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
1042 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: format!("Received an unknown required feature/TLV in message type {:?}", ty) });
1043 return Err(PeerHandleError { no_connection_possible: false });
1045 (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { no_connection_possible: false }),
1046 (msgs::DecodeError::InvalidValue, _) => {
1047 log_debug!(self.logger, "Got an invalid value while deserializing message");
1048 return Err(PeerHandleError { no_connection_possible: false });
1050 (msgs::DecodeError::ShortRead, _) => {
1051 log_debug!(self.logger, "Deserialization failed due to shortness of message");
1052 return Err(PeerHandleError { no_connection_possible: false });
1054 (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { no_connection_possible: false }),
1055 (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { no_connection_possible: false }),
1060 msg_to_handle = Some(message);
1065 pause_read = !peer.should_read();
1067 if let Some(message) = msg_to_handle {
1068 match self.handle_message(&peer_mutex, peer_lock, message) {
1069 Err(handling_error) => match handling_error {
1070 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
1071 MessageHandlingError::LightningError(e) => {
1072 try_potential_handleerror!(&mut peer_mutex.lock().unwrap(), Err(e));
1076 msgs_to_forward.push(msg);
1085 for msg in msgs_to_forward.drain(..) {
1086 self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref());
1092 /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
1093 /// Returns the message back if it needs to be broadcasted to all other peers.
1096 peer_mutex: &Mutex<Peer>,
1097 mut peer_lock: MutexGuard<Peer>,
1098 message: wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>
1099 ) -> Result<Option<wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
1100 let their_node_id = peer_lock.their_node_id.clone().expect("We know the peer's public key by the time we receive messages");
1101 peer_lock.received_message_since_timer_tick = true;
1103 // Need an Init as first message
1104 if let wire::Message::Init(msg) = message {
1105 if msg.features.requires_unknown_bits() {
1106 log_debug!(self.logger, "Peer features required unknown version bits");
1107 return Err(PeerHandleError{ no_connection_possible: true }.into());
1109 if peer_lock.their_features.is_some() {
1110 return Err(PeerHandleError{ no_connection_possible: false }.into());
1113 log_info!(self.logger, "Received peer Init message from {}: {}", log_pubkey!(their_node_id), msg.features);
1115 // For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
1116 if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
1117 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1120 if !msg.features.supports_static_remote_key() {
1121 log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting with no_connection_possible", log_pubkey!(their_node_id));
1122 return Err(PeerHandleError{ no_connection_possible: true }.into());
1125 self.message_handler.route_handler.peer_connected(&their_node_id, &msg);
1127 self.message_handler.chan_handler.peer_connected(&their_node_id, &msg);
1128 peer_lock.their_features = Some(msg.features);
1130 } else if peer_lock.their_features.is_none() {
1131 log_debug!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(their_node_id));
1132 return Err(PeerHandleError{ no_connection_possible: false }.into());
1135 if let wire::Message::GossipTimestampFilter(_msg) = message {
1136 // When supporting gossip messages, start inital gossip sync only after we receive
1137 // a GossipTimestampFilter
1138 if peer_lock.their_features.as_ref().unwrap().supports_gossip_queries() &&
1139 !peer_lock.sent_gossip_timestamp_filter {
1140 peer_lock.sent_gossip_timestamp_filter = true;
1141 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1146 let their_features = peer_lock.their_features.clone();
1147 mem::drop(peer_lock);
1149 if is_gossip_msg(message.type_id()) {
1150 log_gossip!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1152 log_trace!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1155 let mut should_forward = None;
1158 // Setup and Control messages:
1159 wire::Message::Init(_) => {
1162 wire::Message::GossipTimestampFilter(_) => {
1165 wire::Message::Error(msg) => {
1166 let mut data_is_printable = true;
1167 for b in msg.data.bytes() {
1168 if b < 32 || b > 126 {
1169 data_is_printable = false;
1174 if data_is_printable {
1175 log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(their_node_id), msg.data);
1177 log_debug!(self.logger, "Got Err message from {} with non-ASCII error message", log_pubkey!(their_node_id));
1179 self.message_handler.chan_handler.handle_error(&their_node_id, &msg);
1180 if msg.channel_id == [0; 32] {
1181 return Err(PeerHandleError{ no_connection_possible: true }.into());
1184 wire::Message::Warning(msg) => {
1185 let mut data_is_printable = true;
1186 for b in msg.data.bytes() {
1187 if b < 32 || b > 126 {
1188 data_is_printable = false;
1193 if data_is_printable {
1194 log_debug!(self.logger, "Got warning message from {}: {}", log_pubkey!(their_node_id), msg.data);
1196 log_debug!(self.logger, "Got warning message from {} with non-ASCII error message", log_pubkey!(their_node_id));
1200 wire::Message::Ping(msg) => {
1201 if msg.ponglen < 65532 {
1202 let resp = msgs::Pong { byteslen: msg.ponglen };
1203 self.enqueue_message(&mut *peer_mutex.lock().unwrap(), &resp);
1206 wire::Message::Pong(_msg) => {
1207 let mut peer_lock = peer_mutex.lock().unwrap();
1208 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1209 peer_lock.msgs_sent_since_pong = 0;
1212 // Channel messages:
1213 wire::Message::OpenChannel(msg) => {
1214 self.message_handler.chan_handler.handle_open_channel(&their_node_id, their_features.clone().unwrap(), &msg);
1216 wire::Message::AcceptChannel(msg) => {
1217 self.message_handler.chan_handler.handle_accept_channel(&their_node_id, their_features.clone().unwrap(), &msg);
1220 wire::Message::FundingCreated(msg) => {
1221 self.message_handler.chan_handler.handle_funding_created(&their_node_id, &msg);
1223 wire::Message::FundingSigned(msg) => {
1224 self.message_handler.chan_handler.handle_funding_signed(&their_node_id, &msg);
1226 wire::Message::ChannelReady(msg) => {
1227 self.message_handler.chan_handler.handle_channel_ready(&their_node_id, &msg);
1230 wire::Message::Shutdown(msg) => {
1231 self.message_handler.chan_handler.handle_shutdown(&their_node_id, their_features.as_ref().unwrap(), &msg);
1233 wire::Message::ClosingSigned(msg) => {
1234 self.message_handler.chan_handler.handle_closing_signed(&their_node_id, &msg);
1237 // Commitment messages:
1238 wire::Message::UpdateAddHTLC(msg) => {
1239 self.message_handler.chan_handler.handle_update_add_htlc(&their_node_id, &msg);
1241 wire::Message::UpdateFulfillHTLC(msg) => {
1242 self.message_handler.chan_handler.handle_update_fulfill_htlc(&their_node_id, &msg);
1244 wire::Message::UpdateFailHTLC(msg) => {
1245 self.message_handler.chan_handler.handle_update_fail_htlc(&their_node_id, &msg);
1247 wire::Message::UpdateFailMalformedHTLC(msg) => {
1248 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&their_node_id, &msg);
1251 wire::Message::CommitmentSigned(msg) => {
1252 self.message_handler.chan_handler.handle_commitment_signed(&their_node_id, &msg);
1254 wire::Message::RevokeAndACK(msg) => {
1255 self.message_handler.chan_handler.handle_revoke_and_ack(&their_node_id, &msg);
1257 wire::Message::UpdateFee(msg) => {
1258 self.message_handler.chan_handler.handle_update_fee(&their_node_id, &msg);
1260 wire::Message::ChannelReestablish(msg) => {
1261 self.message_handler.chan_handler.handle_channel_reestablish(&their_node_id, &msg);
1264 // Routing messages:
1265 wire::Message::AnnouncementSignatures(msg) => {
1266 self.message_handler.chan_handler.handle_announcement_signatures(&their_node_id, &msg);
1268 wire::Message::ChannelAnnouncement(msg) => {
1269 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1270 .map_err(|e| -> MessageHandlingError { e.into() })? {
1271 should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1274 wire::Message::NodeAnnouncement(msg) => {
1275 if self.message_handler.route_handler.handle_node_announcement(&msg)
1276 .map_err(|e| -> MessageHandlingError { e.into() })? {
1277 should_forward = Some(wire::Message::NodeAnnouncement(msg));
1280 wire::Message::ChannelUpdate(msg) => {
1281 self.message_handler.chan_handler.handle_channel_update(&their_node_id, &msg);
1282 if self.message_handler.route_handler.handle_channel_update(&msg)
1283 .map_err(|e| -> MessageHandlingError { e.into() })? {
1284 should_forward = Some(wire::Message::ChannelUpdate(msg));
1287 wire::Message::QueryShortChannelIds(msg) => {
1288 self.message_handler.route_handler.handle_query_short_channel_ids(&their_node_id, msg)?;
1290 wire::Message::ReplyShortChannelIdsEnd(msg) => {
1291 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&their_node_id, msg)?;
1293 wire::Message::QueryChannelRange(msg) => {
1294 self.message_handler.route_handler.handle_query_channel_range(&their_node_id, msg)?;
1296 wire::Message::ReplyChannelRange(msg) => {
1297 self.message_handler.route_handler.handle_reply_channel_range(&their_node_id, msg)?;
1300 // Unknown messages:
1301 wire::Message::Unknown(type_id) if message.is_even() => {
1302 log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1303 // Fail the channel if message is an even, unknown type as per BOLT #1.
1304 return Err(PeerHandleError{ no_connection_possible: true }.into());
1306 wire::Message::Unknown(type_id) => {
1307 log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", type_id);
1309 wire::Message::Custom(custom) => {
1310 self.custom_message_handler.handle_custom_message(custom, &their_node_id)?;
1316 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>) {
1318 wire::Message::ChannelAnnouncement(ref msg) => {
1319 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1320 let encoded_msg = encode_msg!(msg);
1322 for (_, peer_mutex) in peers.iter() {
1323 let mut peer = peer_mutex.lock().unwrap();
1324 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1325 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1328 if peer.buffer_full_drop_gossip() {
1329 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1332 if peer.their_node_id.as_ref() == Some(&msg.contents.node_id_1) ||
1333 peer.their_node_id.as_ref() == Some(&msg.contents.node_id_2) {
1336 if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1339 self.enqueue_encoded_message(&mut *peer, &encoded_msg);
1342 wire::Message::NodeAnnouncement(ref msg) => {
1343 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1344 let encoded_msg = encode_msg!(msg);
1346 for (_, peer_mutex) in peers.iter() {
1347 let mut peer = peer_mutex.lock().unwrap();
1348 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1349 !peer.should_forward_node_announcement(msg.contents.node_id) {
1352 if peer.buffer_full_drop_gossip() {
1353 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1356 if peer.their_node_id.as_ref() == Some(&msg.contents.node_id) {
1359 if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1362 self.enqueue_encoded_message(&mut *peer, &encoded_msg);
1365 wire::Message::ChannelUpdate(ref msg) => {
1366 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1367 let encoded_msg = encode_msg!(msg);
1369 for (_, peer_mutex) in peers.iter() {
1370 let mut peer = peer_mutex.lock().unwrap();
1371 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1372 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1375 if peer.buffer_full_drop_gossip() {
1376 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1379 if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1382 self.enqueue_encoded_message(&mut *peer, &encoded_msg);
1385 _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1389 /// Checks for any events generated by our handlers and processes them. Includes sending most
1390 /// response messages as well as messages generated by calls to handler functions directly (eg
1391 /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1393 /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1396 /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
1397 /// or one of the other clients provided in our language bindings.
1399 /// Note that if there are any other calls to this function waiting on lock(s) this may return
1400 /// without doing any work. All available events that need handling will be handled before the
1401 /// other calls return.
1403 /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1404 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1405 /// [`send_data`]: SocketDescriptor::send_data
1406 pub fn process_events(&self) {
1407 let mut _single_processor_lock = self.event_processing_lock.try_lock();
1408 if _single_processor_lock.is_err() {
1409 // While we could wake the older sleeper here with a CV and make more even waiting
1410 // times, that would be a lot of overengineering for a simple "reduce total waiter
1412 match self.blocked_event_processors.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) {
1414 debug_assert!(val, "compare_exchange failed spuriously?");
1418 debug_assert!(!val, "compare_exchange succeeded spuriously?");
1419 // We're the only waiter, as the running process_events may have emptied the
1420 // pending events "long" ago and there are new events for us to process, wait until
1421 // its done and process any leftover events before returning.
1422 _single_processor_lock = Ok(self.event_processing_lock.lock().unwrap());
1423 self.blocked_event_processors.store(false, Ordering::Release);
1428 let mut peers_to_disconnect = HashMap::new();
1429 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
1430 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
1433 // TODO: There are some DoS attacks here where you can flood someone's outbound send
1434 // buffer by doing things like announcing channels on another node. We should be willing to
1435 // drop optional-ish messages when send buffers get full!
1437 let peers_lock = self.peers.read().unwrap();
1438 let peers = &*peers_lock;
1439 macro_rules! get_peer_for_forwarding {
1440 ($node_id: expr) => {
1442 if peers_to_disconnect.get($node_id).is_some() {
1443 // If we've "disconnected" this peer, do not send to it.
1446 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().get($node_id).cloned();
1447 match descriptor_opt {
1448 Some(descriptor) => match peers.get(&descriptor) {
1449 Some(peer_mutex) => {
1450 let peer_lock = peer_mutex.lock().unwrap();
1451 if peer_lock.their_features.is_none() {
1457 debug_assert!(false, "Inconsistent peers set state!");
1468 for event in events_generated.drain(..) {
1470 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1471 log_debug!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1472 log_pubkey!(node_id),
1473 log_bytes!(msg.temporary_channel_id));
1474 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1476 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1477 log_debug!(self.logger, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
1478 log_pubkey!(node_id),
1479 log_bytes!(msg.temporary_channel_id));
1480 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1482 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
1483 log_debug!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
1484 log_pubkey!(node_id),
1485 log_bytes!(msg.temporary_channel_id),
1486 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
1487 // TODO: If the peer is gone we should generate a DiscardFunding event
1488 // indicating to the wallet that they should just throw away this funding transaction
1489 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1491 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
1492 log_debug!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
1493 log_pubkey!(node_id),
1494 log_bytes!(msg.channel_id));
1495 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1497 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
1498 log_debug!(self.logger, "Handling SendChannelReady event in peer_handler for node {} for channel {}",
1499 log_pubkey!(node_id),
1500 log_bytes!(msg.channel_id));
1501 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1503 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
1504 log_debug!(self.logger, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
1505 log_pubkey!(node_id),
1506 log_bytes!(msg.channel_id));
1507 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1509 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 } } => {
1510 log_debug!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
1511 log_pubkey!(node_id),
1512 update_add_htlcs.len(),
1513 update_fulfill_htlcs.len(),
1514 update_fail_htlcs.len(),
1515 log_bytes!(commitment_signed.channel_id));
1516 let mut peer = get_peer_for_forwarding!(node_id);
1517 for msg in update_add_htlcs {
1518 self.enqueue_message(&mut *peer, msg);
1520 for msg in update_fulfill_htlcs {
1521 self.enqueue_message(&mut *peer, msg);
1523 for msg in update_fail_htlcs {
1524 self.enqueue_message(&mut *peer, msg);
1526 for msg in update_fail_malformed_htlcs {
1527 self.enqueue_message(&mut *peer, msg);
1529 if let &Some(ref msg) = update_fee {
1530 self.enqueue_message(&mut *peer, msg);
1532 self.enqueue_message(&mut *peer, commitment_signed);
1534 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1535 log_debug!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
1536 log_pubkey!(node_id),
1537 log_bytes!(msg.channel_id));
1538 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1540 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1541 log_debug!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
1542 log_pubkey!(node_id),
1543 log_bytes!(msg.channel_id));
1544 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1546 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1547 log_debug!(self.logger, "Handling Shutdown event in peer_handler for node {} for channel {}",
1548 log_pubkey!(node_id),
1549 log_bytes!(msg.channel_id));
1550 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1552 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
1553 log_debug!(self.logger, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
1554 log_pubkey!(node_id),
1555 log_bytes!(msg.channel_id));
1556 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1558 MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
1559 log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1560 match self.message_handler.route_handler.handle_channel_announcement(&msg) {
1561 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1562 self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
1565 match self.message_handler.route_handler.handle_channel_update(&update_msg) {
1566 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1567 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(update_msg), None),
1571 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
1572 log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler");
1573 match self.message_handler.route_handler.handle_node_announcement(&msg) {
1574 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1575 self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None),
1579 MessageSendEvent::BroadcastChannelUpdate { msg } => {
1580 log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1581 match self.message_handler.route_handler.handle_channel_update(&msg) {
1582 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1583 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
1587 MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
1588 log_trace!(self.logger, "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
1589 log_pubkey!(node_id), msg.contents.short_channel_id);
1590 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1592 MessageSendEvent::HandleError { ref node_id, ref action } => {
1594 msgs::ErrorAction::DisconnectPeer { ref msg } => {
1595 // We do not have the peers write lock, so we just store that we're
1596 // about to disconenct the peer and do it after we finish
1597 // processing most messages.
1598 peers_to_disconnect.insert(*node_id, msg.clone());
1600 msgs::ErrorAction::IgnoreAndLog(level) => {
1601 log_given_level!(self.logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1603 msgs::ErrorAction::IgnoreDuplicateGossip => {},
1604 msgs::ErrorAction::IgnoreError => {
1605 log_debug!(self.logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1607 msgs::ErrorAction::SendErrorMessage { ref msg } => {
1608 log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1609 log_pubkey!(node_id),
1611 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1613 msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
1614 log_given_level!(self.logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
1615 log_pubkey!(node_id),
1617 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1621 MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
1622 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1624 MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
1625 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1627 MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
1628 log_gossip!(self.logger, "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
1629 log_pubkey!(node_id),
1630 msg.short_channel_ids.len(),
1632 msg.number_of_blocks,
1634 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1636 MessageSendEvent::SendGossipTimestampFilter { ref node_id, ref msg } => {
1637 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1642 for (node_id, msg) in self.custom_message_handler.get_and_clear_pending_msg() {
1643 if peers_to_disconnect.get(&node_id).is_some() { continue; }
1644 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), &msg);
1647 for (descriptor, peer_mutex) in peers.iter() {
1648 self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer_mutex.lock().unwrap());
1651 if !peers_to_disconnect.is_empty() {
1652 let mut peers_lock = self.peers.write().unwrap();
1653 let peers = &mut *peers_lock;
1654 for (node_id, msg) in peers_to_disconnect.drain() {
1655 // Note that since we are holding the peers *write* lock we can
1656 // remove from node_id_to_descriptor immediately (as no other
1657 // thread can be holding the peer lock if we have the global write
1660 if let Some(mut descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
1661 if let Some(peer_mutex) = peers.remove(&descriptor) {
1662 if let Some(msg) = msg {
1663 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1664 log_pubkey!(node_id),
1666 let mut peer = peer_mutex.lock().unwrap();
1667 self.enqueue_message(&mut *peer, &msg);
1668 // This isn't guaranteed to work, but if there is enough free
1669 // room in the send buffer, put the error message there...
1670 self.do_attempt_write_data(&mut descriptor, &mut *peer);
1672 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1675 descriptor.disconnect_socket();
1676 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1682 /// Indicates that the given socket descriptor's connection is now closed.
1683 pub fn socket_disconnected(&self, descriptor: &Descriptor) {
1684 self.disconnect_event_internal(descriptor, false);
1687 fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1688 let mut peers = self.peers.write().unwrap();
1689 let peer_option = peers.remove(descriptor);
1692 // This is most likely a simple race condition where the user found that the socket
1693 // was disconnected, then we told the user to `disconnect_socket()`, then they
1694 // called this method. Either way we're disconnected, return.
1696 Some(peer_lock) => {
1697 let peer = peer_lock.lock().unwrap();
1698 if let Some(node_id) = peer.their_node_id {
1699 log_trace!(self.logger,
1700 "Handling disconnection of peer {}, with {}future connection to the peer possible.",
1701 log_pubkey!(node_id), if no_connection_possible { "no " } else { "" });
1702 self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
1703 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1709 /// Disconnect a peer given its node id.
1711 /// Set `no_connection_possible` to true to prevent any further connection with this peer,
1712 /// force-closing any channels we have with it.
1714 /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
1715 /// peer. Thus, be very careful about reentrancy issues.
1717 /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
1718 pub fn disconnect_by_node_id(&self, node_id: PublicKey, no_connection_possible: bool) {
1719 let mut peers_lock = self.peers.write().unwrap();
1720 if let Some(mut descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
1721 log_trace!(self.logger, "Disconnecting peer with id {} due to client request", node_id);
1722 peers_lock.remove(&descriptor);
1723 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1724 descriptor.disconnect_socket();
1728 /// Disconnects all currently-connected peers. This is useful on platforms where there may be
1729 /// an indication that TCP sockets have stalled even if we weren't around to time them out
1730 /// using regular ping/pongs.
1731 pub fn disconnect_all_peers(&self) {
1732 let mut peers_lock = self.peers.write().unwrap();
1733 self.node_id_to_descriptor.lock().unwrap().clear();
1734 let peers = &mut *peers_lock;
1735 for (mut descriptor, peer) in peers.drain() {
1736 if let Some(node_id) = peer.lock().unwrap().their_node_id {
1737 log_trace!(self.logger, "Disconnecting peer with id {} due to client request to disconnect all peers", node_id);
1738 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1740 descriptor.disconnect_socket();
1744 /// This is called when we're blocked on sending additional gossip messages until we receive a
1745 /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
1746 /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
1747 fn maybe_send_extra_ping(&self, peer: &mut Peer) {
1748 if peer.awaiting_pong_timer_tick_intervals == 0 {
1749 peer.awaiting_pong_timer_tick_intervals = -1;
1750 let ping = msgs::Ping {
1754 self.enqueue_message(peer, &ping);
1758 /// Send pings to each peer and disconnect those which did not respond to the last round of
1761 /// This may be called on any timescale you want, however, roughly once every ten seconds is
1762 /// preferred. The call rate determines both how often we send a ping to our peers and how much
1763 /// time they have to respond before we disconnect them.
1765 /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1768 /// [`send_data`]: SocketDescriptor::send_data
1769 pub fn timer_tick_occurred(&self) {
1770 let mut descriptors_needing_disconnect = Vec::new();
1772 let peers_lock = self.peers.read().unwrap();
1774 for (descriptor, peer_mutex) in peers_lock.iter() {
1775 let mut peer = peer_mutex.lock().unwrap();
1776 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_node_id.is_none() {
1777 // The peer needs to complete its handshake before we can exchange messages. We
1778 // give peers one timer tick to complete handshake, reusing
1779 // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
1780 // for handshake completion.
1781 if peer.awaiting_pong_timer_tick_intervals != 0 {
1782 descriptors_needing_disconnect.push(descriptor.clone());
1784 peer.awaiting_pong_timer_tick_intervals = 1;
1789 if peer.awaiting_pong_timer_tick_intervals == -1 {
1790 // Magic value set in `maybe_send_extra_ping`.
1791 peer.awaiting_pong_timer_tick_intervals = 1;
1792 peer.received_message_since_timer_tick = false;
1796 if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
1797 || peer.awaiting_pong_timer_tick_intervals as u64 >
1798 MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64
1800 descriptors_needing_disconnect.push(descriptor.clone());
1803 peer.received_message_since_timer_tick = false;
1805 if peer.awaiting_pong_timer_tick_intervals > 0 {
1806 peer.awaiting_pong_timer_tick_intervals += 1;
1810 peer.awaiting_pong_timer_tick_intervals = 1;
1811 let ping = msgs::Ping {
1815 self.enqueue_message(&mut *peer, &ping);
1816 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer);
1820 if !descriptors_needing_disconnect.is_empty() {
1822 let mut peers_lock = self.peers.write().unwrap();
1823 for descriptor in descriptors_needing_disconnect.iter() {
1824 if let Some(peer) = peers_lock.remove(descriptor) {
1825 if let Some(node_id) = peer.lock().unwrap().their_node_id {
1826 log_trace!(self.logger, "Disconnecting peer with id {} due to ping timeout", node_id);
1827 self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
1828 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1834 for mut descriptor in descriptors_needing_disconnect.drain(..) {
1835 descriptor.disconnect_socket();
1841 fn is_gossip_msg(type_id: u16) -> bool {
1843 msgs::ChannelAnnouncement::TYPE |
1844 msgs::ChannelUpdate::TYPE |
1845 msgs::NodeAnnouncement::TYPE |
1846 msgs::QueryChannelRange::TYPE |
1847 msgs::ReplyChannelRange::TYPE |
1848 msgs::QueryShortChannelIds::TYPE |
1849 msgs::ReplyShortChannelIdsEnd::TYPE => true,
1856 use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses};
1857 use ln::{msgs, wire};
1858 use ln::msgs::NetAddress;
1860 use util::test_utils;
1862 use bitcoin::secp256k1::Secp256k1;
1863 use bitcoin::secp256k1::{SecretKey, PublicKey};
1866 use sync::{Arc, Mutex};
1867 use core::sync::atomic::Ordering;
1870 struct FileDescriptor {
1872 outbound_data: Arc<Mutex<Vec<u8>>>,
1874 impl PartialEq for FileDescriptor {
1875 fn eq(&self, other: &Self) -> bool {
1879 impl Eq for FileDescriptor { }
1880 impl core::hash::Hash for FileDescriptor {
1881 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
1882 self.fd.hash(hasher)
1886 impl SocketDescriptor for FileDescriptor {
1887 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
1888 self.outbound_data.lock().unwrap().extend_from_slice(data);
1892 fn disconnect_socket(&mut self) {}
1895 struct PeerManagerCfg {
1896 chan_handler: test_utils::TestChannelMessageHandler,
1897 routing_handler: test_utils::TestRoutingMessageHandler,
1898 logger: test_utils::TestLogger,
1901 fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
1902 let mut cfgs = Vec::new();
1903 for _ in 0..peer_count {
1906 chan_handler: test_utils::TestChannelMessageHandler::new(),
1907 logger: test_utils::TestLogger::new(),
1908 routing_handler: test_utils::TestRoutingMessageHandler::new(),
1916 fn create_network<'a>(peer_count: usize, cfgs: &'a Vec<PeerManagerCfg>) -> Vec<PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler>> {
1917 let mut peers = Vec::new();
1918 for i in 0..peer_count {
1919 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
1920 let ephemeral_bytes = [i as u8; 32];
1921 let msg_handler = MessageHandler { chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler };
1922 let peer = PeerManager::new(msg_handler, node_secret, &ephemeral_bytes, &cfgs[i].logger, IgnoringMessageHandler {});
1929 fn establish_connection<'a>(peer_a: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler>, peer_b: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler>) -> (FileDescriptor, FileDescriptor) {
1930 let secp_ctx = Secp256k1::new();
1931 let a_id = PublicKey::from_secret_key(&secp_ctx, &peer_a.our_node_secret);
1932 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1933 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1934 let initial_data = peer_b.new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
1935 peer_a.new_inbound_connection(fd_a.clone(), None).unwrap();
1936 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
1937 peer_a.process_events();
1939 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
1940 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
1942 peer_b.process_events();
1943 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
1944 assert_eq!(peer_a.read_event(&mut fd_a, &b_data).unwrap(), false);
1946 peer_a.process_events();
1947 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
1948 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
1950 (fd_a.clone(), fd_b.clone())
1954 fn test_disconnect_peer() {
1955 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
1956 // push a DisconnectPeer event to remove the node flagged by id
1957 let cfgs = create_peermgr_cfgs(2);
1958 let chan_handler = test_utils::TestChannelMessageHandler::new();
1959 let mut peers = create_network(2, &cfgs);
1960 establish_connection(&peers[0], &peers[1]);
1961 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
1963 let secp_ctx = Secp256k1::new();
1964 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
1966 chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
1968 action: msgs::ErrorAction::DisconnectPeer { msg: None },
1970 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
1971 peers[0].message_handler.chan_handler = &chan_handler;
1973 peers[0].process_events();
1974 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
1978 fn test_send_simple_msg() {
1979 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
1980 // push a message from one peer to another.
1981 let cfgs = create_peermgr_cfgs(2);
1982 let a_chan_handler = test_utils::TestChannelMessageHandler::new();
1983 let b_chan_handler = test_utils::TestChannelMessageHandler::new();
1984 let mut peers = create_network(2, &cfgs);
1985 let (fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
1986 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
1988 let secp_ctx = Secp256k1::new();
1989 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
1991 let msg = msgs::Shutdown { channel_id: [42; 32], scriptpubkey: bitcoin::Script::new() };
1992 a_chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::SendShutdown {
1993 node_id: their_id, msg: msg.clone()
1995 peers[0].message_handler.chan_handler = &a_chan_handler;
1997 b_chan_handler.expect_receive_msg(wire::Message::Shutdown(msg));
1998 peers[1].message_handler.chan_handler = &b_chan_handler;
2000 peers[0].process_events();
2002 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2003 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2007 fn test_disconnect_all_peer() {
2008 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2009 // then calls disconnect_all_peers
2010 let cfgs = create_peermgr_cfgs(2);
2011 let peers = create_network(2, &cfgs);
2012 establish_connection(&peers[0], &peers[1]);
2013 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2015 peers[0].disconnect_all_peers();
2016 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2020 fn test_timer_tick_occurred() {
2021 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
2022 let cfgs = create_peermgr_cfgs(2);
2023 let peers = create_network(2, &cfgs);
2024 establish_connection(&peers[0], &peers[1]);
2025 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2027 // peers[0] awaiting_pong is set to true, but the Peer is still connected
2028 peers[0].timer_tick_occurred();
2029 peers[0].process_events();
2030 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2032 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
2033 peers[0].timer_tick_occurred();
2034 peers[0].process_events();
2035 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2039 fn test_do_attempt_write_data() {
2040 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
2041 let cfgs = create_peermgr_cfgs(2);
2042 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2043 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2044 let peers = create_network(2, &cfgs);
2046 // By calling establish_connect, we trigger do_attempt_write_data between
2047 // the peers. Previously this function would mistakenly enter an infinite loop
2048 // when there were more channel messages available than could fit into a peer's
2049 // buffer. This issue would now be detected by this test (because we use custom
2050 // RoutingMessageHandlers that intentionally return more channel messages
2051 // than can fit into a peer's buffer).
2052 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2054 // Make each peer to read the messages that the other peer just wrote to them. Note that
2055 // due to the max-message-before-ping limits this may take a few iterations to complete.
2056 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
2057 peers[1].process_events();
2058 let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2059 assert!(!a_read_data.is_empty());
2061 peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
2062 peers[0].process_events();
2064 let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2065 assert!(!b_read_data.is_empty());
2066 peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
2068 peers[0].process_events();
2069 assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
2072 // Check that each peer has received the expected number of channel updates and channel
2074 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2075 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2076 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2077 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2081 fn test_handshake_timeout() {
2082 // Tests that we time out a peer still waiting on handshake completion after a full timer
2084 let cfgs = create_peermgr_cfgs(2);
2085 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2086 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2087 let peers = create_network(2, &cfgs);
2089 let secp_ctx = Secp256k1::new();
2090 let a_id = PublicKey::from_secret_key(&secp_ctx, &peers[0].our_node_secret);
2091 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2092 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2093 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
2094 peers[0].new_inbound_connection(fd_a.clone(), None).unwrap();
2096 // If we get a single timer tick before completion, that's fine
2097 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2098 peers[0].timer_tick_occurred();
2099 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2101 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
2102 peers[0].process_events();
2103 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2104 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2105 peers[1].process_events();
2107 // ...but if we get a second timer tick, we should disconnect the peer
2108 peers[0].timer_tick_occurred();
2109 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2111 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2112 assert!(peers[0].read_event(&mut fd_a, &b_data).is_err());
2116 fn test_filter_addresses(){
2117 // Tests the filter_addresses function.
2120 let ip_address = NetAddress::IPv4{addr: [10, 0, 0, 0], port: 1000};
2121 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2122 let ip_address = NetAddress::IPv4{addr: [10, 0, 255, 201], port: 1000};
2123 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2124 let ip_address = NetAddress::IPv4{addr: [10, 255, 255, 255], port: 1000};
2125 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2128 let ip_address = NetAddress::IPv4{addr: [0, 0, 0, 0], port: 1000};
2129 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2130 let ip_address = NetAddress::IPv4{addr: [0, 0, 255, 187], port: 1000};
2131 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2132 let ip_address = NetAddress::IPv4{addr: [0, 255, 255, 255], port: 1000};
2133 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2136 let ip_address = NetAddress::IPv4{addr: [100, 64, 0, 0], port: 1000};
2137 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2138 let ip_address = NetAddress::IPv4{addr: [100, 78, 255, 0], port: 1000};
2139 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2140 let ip_address = NetAddress::IPv4{addr: [100, 127, 255, 255], port: 1000};
2141 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2144 let ip_address = NetAddress::IPv4{addr: [127, 0, 0, 0], port: 1000};
2145 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2146 let ip_address = NetAddress::IPv4{addr: [127, 65, 73, 0], port: 1000};
2147 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2148 let ip_address = NetAddress::IPv4{addr: [127, 255, 255, 255], port: 1000};
2149 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2152 let ip_address = NetAddress::IPv4{addr: [169, 254, 0, 0], port: 1000};
2153 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2154 let ip_address = NetAddress::IPv4{addr: [169, 254, 221, 101], port: 1000};
2155 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2156 let ip_address = NetAddress::IPv4{addr: [169, 254, 255, 255], port: 1000};
2157 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2160 let ip_address = NetAddress::IPv4{addr: [172, 16, 0, 0], port: 1000};
2161 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2162 let ip_address = NetAddress::IPv4{addr: [172, 27, 101, 23], port: 1000};
2163 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2164 let ip_address = NetAddress::IPv4{addr: [172, 31, 255, 255], port: 1000};
2165 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2168 let ip_address = NetAddress::IPv4{addr: [192, 168, 0, 0], port: 1000};
2169 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2170 let ip_address = NetAddress::IPv4{addr: [192, 168, 205, 159], port: 1000};
2171 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2172 let ip_address = NetAddress::IPv4{addr: [192, 168, 255, 255], port: 1000};
2173 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2175 // For (192.88.99/24)
2176 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 0], port: 1000};
2177 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2178 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 140], port: 1000};
2179 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2180 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 255], port: 1000};
2181 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2183 // For other IPv4 addresses
2184 let ip_address = NetAddress::IPv4{addr: [188, 255, 99, 0], port: 1000};
2185 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2186 let ip_address = NetAddress::IPv4{addr: [123, 8, 129, 14], port: 1000};
2187 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2188 let ip_address = NetAddress::IPv4{addr: [2, 88, 9, 255], port: 1000};
2189 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2192 let ip_address = NetAddress::IPv6{addr: [32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], port: 1000};
2193 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2194 let ip_address = NetAddress::IPv6{addr: [45, 34, 209, 190, 0, 123, 55, 34, 0, 0, 3, 27, 201, 0, 0, 0], port: 1000};
2195 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2196 let ip_address = NetAddress::IPv6{addr: [63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], port: 1000};
2197 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2199 // For other IPv6 addresses
2200 let ip_address = NetAddress::IPv6{addr: [24, 240, 12, 32, 0, 0, 0, 0, 20, 97, 0, 32, 121, 254, 0, 0], port: 1000};
2201 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2202 let ip_address = NetAddress::IPv6{addr: [68, 23, 56, 63, 0, 0, 2, 7, 75, 109, 0, 39, 0, 0, 0, 0], port: 1000};
2203 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2204 let ip_address = NetAddress::IPv6{addr: [101, 38, 140, 230, 100, 0, 30, 98, 0, 26, 0, 0, 57, 96, 0, 0], port: 1000};
2205 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2208 assert_eq!(filter_addresses(None), None);