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 NetGraphmsgHandler) with messages
16 //! they should handle, and encoding/sending response messages.
18 use bitcoin::secp256k1::key::{SecretKey,PublicKey};
20 use ln::features::InitFeatures;
22 use ln::msgs::{ChannelMessageHandler, LightningError, RoutingMessageHandler};
23 use ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
24 use util::ser::{VecWriter, Writeable};
25 use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
29 use util::events::{MessageSendEvent, MessageSendEventsProvider};
30 use util::logger::Logger;
31 use routing::network_graph::NetGraphMsgHandler;
34 use alloc::collections::LinkedList;
35 use alloc::fmt::Debug;
36 use std::sync::{Arc, Mutex};
37 use core::sync::atomic::{AtomicUsize, Ordering};
38 use core::{cmp, hash, fmt, mem};
42 use bitcoin::hashes::sha256::Hash as Sha256;
43 use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
44 use bitcoin::hashes::{HashEngine, Hash};
46 /// A dummy struct which implements `RoutingMessageHandler` without storing any routing information
47 /// or doing any processing. You can provide one of these as the route_handler in a MessageHandler.
48 pub struct IgnoringMessageHandler{}
49 impl MessageSendEventsProvider for IgnoringMessageHandler {
50 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> { Vec::new() }
52 impl RoutingMessageHandler for IgnoringMessageHandler {
53 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
54 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
55 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
56 fn handle_htlc_fail_channel_update(&self, _update: &msgs::HTLCFailChannelUpdate) {}
57 fn get_next_channel_announcements(&self, _starting_point: u64, _batch_amount: u8) ->
58 Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { Vec::new() }
59 fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> { Vec::new() }
60 fn sync_routing_table(&self, _their_node_id: &PublicKey, _init: &msgs::Init) {}
61 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
62 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
63 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) }
64 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) }
66 impl Deref for IgnoringMessageHandler {
67 type Target = IgnoringMessageHandler;
68 fn deref(&self) -> &Self { self }
71 /// A dummy implementation of `UnknownMessageHandler` that does nothing.
72 pub struct IgnoringUnknownMessageHandler{}
73 impl MessageSendEventsProvider for IgnoringUnknownMessageHandler {
74 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
79 /// Define a dummy type to satisfy the constraint of UnknownMessageHandle `Message`
80 /// associated type for implementing it for IgnoringUnknownMessageHandler.
82 impl Encode for DummyType {
85 impl Writeable for DummyType {
86 fn write<W: ::util::ser::Writer>(&self, _writer: &mut W) -> Result<(), ::std::io::Error> {
91 impl UnknownMessageHandler for IgnoringUnknownMessageHandler {
92 type MessageEnum = ();
93 type Message = DummyType;
94 fn read<R: ::std::io::Read>(&self, _message_type: u16, _buffer: &mut R) -> Result<Option<Self::MessageEnum>, msgs::DecodeError> {
98 fn handle_unknown_message(&self, _msg: Self::MessageEnum) -> Result<(), MessageHandlingError> {
99 // Since we always return `None` in the read the handle method should never be called.
103 fn get_and_clear_pending_msgs(&self) -> Vec<(&PublicKey, Self::Message)> {
107 impl Deref for IgnoringUnknownMessageHandler {
108 type Target = IgnoringUnknownMessageHandler;
109 fn deref(&self) -> &Self { self }
112 /// A dummy struct which implements `ChannelMessageHandler` without having any channels.
113 /// You can provide one of these as the route_handler in a MessageHandler.
114 pub struct ErroringMessageHandler {
115 message_queue: Mutex<Vec<MessageSendEvent>>
117 impl ErroringMessageHandler {
118 /// Constructs a new ErroringMessageHandler
119 pub fn new() -> Self {
120 Self { message_queue: Mutex::new(Vec::new()) }
122 fn push_error(&self, node_id: &PublicKey, channel_id: [u8; 32]) {
123 self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
124 action: msgs::ErrorAction::SendErrorMessage {
125 msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
127 node_id: node_id.clone(),
131 impl MessageSendEventsProvider for ErroringMessageHandler {
132 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
133 let mut res = Vec::new();
134 mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
138 impl ChannelMessageHandler for ErroringMessageHandler {
139 // Any messages which are related to a specific channel generate an error message to let the
140 // peer know we don't care about channels.
141 fn handle_open_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::OpenChannel) {
142 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
144 fn handle_accept_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::AcceptChannel) {
145 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
147 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
148 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
150 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
151 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
153 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) {
154 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
156 fn handle_shutdown(&self, their_node_id: &PublicKey, _their_features: &InitFeatures, msg: &msgs::Shutdown) {
157 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
159 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
160 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
162 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
163 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
165 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
166 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
168 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
169 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
171 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
172 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
174 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
175 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
177 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
178 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
180 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
181 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
183 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
184 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
186 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
187 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
189 // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them.
190 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
191 fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
192 fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {}
193 fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
195 impl Deref for ErroringMessageHandler {
196 type Target = ErroringMessageHandler;
197 fn deref(&self) -> &Self { self }
200 /// Provides references to trait impls which handle different types of messages.
201 pub struct MessageHandler<CM: Deref, RM: Deref> where
202 CM::Target: ChannelMessageHandler,
203 RM::Target: RoutingMessageHandler {
204 /// A message handler which handles messages specific to channels. Usually this is just a
205 /// [`ChannelManager`] object or an [`ErroringMessageHandler`].
207 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
208 pub chan_handler: CM,
209 /// A message handler which handles messages updating our knowledge of the network channel
210 /// graph. Usually this is just a [`NetGraphMsgHandler`] object or an
211 /// [`IgnoringMessageHandler`].
213 /// [`NetGraphMsgHandler`]: crate::routing::network_graph::NetGraphMsgHandler
214 pub route_handler: RM,
217 /// Handler for messages external to the LN protocol.
218 pub trait UnknownMessageHandler where Self::Message : Encode + Writeable + Debug {
219 /// A type that represents a message that can be sent over the wire
221 /// A type that represents an enumeration of messages that can be handled by the handler.
224 fn read<R: ::std::io::Read>(&self, msg_type: u16, buffer: &mut R) -> Result<Option<Self::MessageEnum>, msgs::DecodeError>;
225 /// Called with the message type that was received and the buffer to be read. If the handler
226 /// could handle the message, should return `Ok(Some(wire::Message::HandledUnknownMessage(msg_type)))`,
227 /// otherwise Ok(None). Can also return a `DecodingError` if the buffer contained unexpected data
228 /// for the given message type.
229 fn handle_unknown_message(&self, msg: Self::MessageEnum) -> Result<(), MessageHandlingError>;
230 /// Get messages to be sent to specified peers.
231 fn get_and_clear_pending_msgs(&self) -> Vec<(&PublicKey, Self::Message)>;
234 /// Provides an object which can be used to send data to and which uniquely identifies a connection
235 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
236 /// implement Hash to meet the PeerManager API.
238 /// For efficiency, Clone should be relatively cheap for this type.
240 /// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original
241 /// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it
242 /// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no
243 /// further calls to the [`PeerManager`] related to the original socket occur. This allows you to
244 /// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish
245 /// to simply use another value which is guaranteed to be globally unique instead.
246 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
247 /// Attempts to send some data from the given slice to the peer.
249 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
250 /// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
251 /// called and further write attempts may occur until that time.
253 /// If the returned size is smaller than `data.len()`, a
254 /// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
255 /// written. Additionally, until a `send_data` event completes fully, no further
256 /// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
257 /// prevent denial-of-service issues, you should not read or buffer any data from the socket
260 /// If a [`PeerManager::read_event`] call on this descriptor had previously returned true
261 /// (indicating that read events should be paused to prevent DoS in the send buffer),
262 /// `resume_read` may be set indicating that read events on this descriptor should resume. A
263 /// `resume_read` of false carries no meaning, and should not cause any action.
264 fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
265 /// Disconnect the socket pointed to by this SocketDescriptor.
267 /// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
268 /// call (doing so is a noop).
269 fn disconnect_socket(&mut self);
272 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
273 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
276 pub struct PeerHandleError {
277 /// Used to indicate that we probably can't make any future connections to this peer, implying
278 /// we should go ahead and force-close any channels we have with it.
279 pub no_connection_possible: bool,
281 impl fmt::Debug for PeerHandleError {
282 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
283 formatter.write_str("Peer Sent Invalid Data")
286 impl fmt::Display for PeerHandleError {
287 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
288 formatter.write_str("Peer Sent Invalid Data")
291 impl error::Error for PeerHandleError {
292 fn description(&self) -> &str {
293 "Peer Sent Invalid Data"
297 enum InitSyncTracker{
299 ChannelsSyncing(u64),
300 NodesSyncing(PublicKey),
303 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
304 /// we have fewer than this many messages in the outbound buffer again.
305 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
306 /// refilled as we send bytes.
307 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 10;
308 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
310 const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = 20;
313 channel_encryptor: PeerChannelEncryptor,
314 their_node_id: Option<PublicKey>,
315 their_features: Option<InitFeatures>,
317 pending_outbound_buffer: LinkedList<Vec<u8>>,
318 pending_outbound_buffer_first_msg_offset: usize,
319 awaiting_write_event: bool,
321 pending_read_buffer: Vec<u8>,
322 pending_read_buffer_pos: usize,
323 pending_read_is_header: bool,
325 sync_status: InitSyncTracker,
331 /// Returns true if the channel announcements/updates for the given channel should be
332 /// forwarded to this peer.
333 /// If we are sending our routing table to this peer and we have not yet sent channel
334 /// announcements/updates for the given channel_id then we will send it when we get to that
335 /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
336 /// sent the old versions, we should send the update, and so return true here.
337 fn should_forward_channel_announcement(&self, channel_id: u64)->bool{
338 match self.sync_status {
339 InitSyncTracker::NoSyncRequested => true,
340 InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
341 InitSyncTracker::NodesSyncing(_) => true,
345 /// Similar to the above, but for node announcements indexed by node_id.
346 fn should_forward_node_announcement(&self, node_id: PublicKey) -> bool {
347 match self.sync_status {
348 InitSyncTracker::NoSyncRequested => true,
349 InitSyncTracker::ChannelsSyncing(_) => false,
350 InitSyncTracker::NodesSyncing(pk) => pk < node_id,
355 struct PeerHolder<Descriptor: SocketDescriptor> {
356 peers: HashMap<Descriptor, Peer>,
357 /// Only add to this set when noise completes:
358 node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
361 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
362 fn _check_usize_is_32_or_64() {
363 // See below, less than 32 bit pointers may be unsafe here!
364 unsafe { mem::transmute::<*const usize, [u8; 4]>(panic!()); }
367 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
368 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
369 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
370 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
371 /// issues such as overly long function definitions.
372 pub type SimpleArcPeerManager<SD, M, T, F, C, L, UMH> = PeerManager<SD, Arc<SimpleArcChannelManager<M, T, F, L>>, Arc<NetGraphMsgHandler<Arc<C>, Arc<L>>>, Arc<L>, UMH>;
374 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
375 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
376 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
377 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
378 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
379 /// helps with issues such as long function definitions.
380 pub type SimpleRefPeerManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, SD, M, T, F, C, L, UMH> = PeerManager<SD, SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L>, &'e NetGraphMsgHandler<&'g C, &'f L>, &'f L, UMH>;
382 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
383 /// socket events into messages which it passes on to its [`MessageHandler`].
385 /// Locks are taken internally, so you must never assume that reentrancy from a
386 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
388 /// Calls to [`read_event`] will decode relevant messages and pass them to the
389 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
390 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
391 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
392 /// calls only after previous ones have returned.
394 /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
395 /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
396 /// essentially you should default to using a SimpleRefPeerManager, and use a
397 /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
398 /// you're using lightning-net-tokio.
400 /// [`read_event`]: PeerManager::read_event
401 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, UMH: Deref> where
402 CM::Target: ChannelMessageHandler,
403 RM::Target: RoutingMessageHandler,
405 UMH::Target: UnknownMessageHandler {
406 message_handler: MessageHandler<CM, RM>,
407 peers: Mutex<PeerHolder<Descriptor>>,
408 our_node_secret: SecretKey,
409 ephemeral_key_midstate: Sha256Engine,
410 unknown_message_handler: UMH,
412 // Usize needs to be at least 32 bits to avoid overflowing both low and high. If usize is 64
413 // bits we will never realistically count into high:
414 peer_counter_low: AtomicUsize,
415 peer_counter_high: AtomicUsize,
420 /// An error indicating a failure to handle a received message.
421 pub enum MessageHandlingError {
422 /// An error related to communication with a peer.
423 PeerHandleError(PeerHandleError),
424 /// An error related to the LN protocol.
425 LightningError(LightningError),
428 impl From<PeerHandleError> for MessageHandlingError {
429 fn from(error: PeerHandleError) -> Self {
430 MessageHandlingError::PeerHandleError(error)
434 impl From<LightningError> for MessageHandlingError {
435 fn from(error: LightningError) -> Self {
436 MessageHandlingError::LightningError(error)
440 macro_rules! encode_msg {
442 let mut buffer = VecWriter(Vec::new());
443 wire::write($msg, &mut buffer).unwrap();
448 impl<Descriptor: SocketDescriptor, CM: Deref, L: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, L, IgnoringUnknownMessageHandler> where
449 CM::Target: ChannelMessageHandler,
451 /// Constructs a new PeerManager with the given ChannelMessageHandler. No routing message
452 /// handler is used and network graph messages are ignored.
454 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
455 /// cryptographically secure random bytes.
457 /// (C-not exported) as we can't export a PeerManager with a dummy route handler
458 pub fn new_channel_only(channel_message_handler: CM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
459 Self::new(MessageHandler {
460 chan_handler: channel_message_handler,
461 route_handler: IgnoringMessageHandler{},
462 }, our_node_secret, ephemeral_random_data, logger, IgnoringUnknownMessageHandler{})
466 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, L, IgnoringUnknownMessageHandler> where
467 RM::Target: RoutingMessageHandler,
469 /// Constructs a new PeerManager with the given RoutingMessageHandler. No channel message
470 /// handler is used and messages related to channels will be ignored (or generate error
471 /// messages). Note that some other lightning implementations time-out connections after some
472 /// time if no channel is built with the peer.
474 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
475 /// cryptographically secure random bytes.
477 /// (C-not exported) as we can't export a PeerManager with a dummy channel handler
478 pub fn new_routing_only(routing_message_handler: RM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
479 Self::new(MessageHandler {
480 chan_handler: ErroringMessageHandler::new(),
481 route_handler: routing_message_handler,
482 }, our_node_secret, ephemeral_random_data, logger, IgnoringUnknownMessageHandler{})
486 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, UMH: Deref> PeerManager<Descriptor, CM, RM, L, UMH> where
487 CM::Target: ChannelMessageHandler,
488 RM::Target: RoutingMessageHandler,
490 UMH::Target: UnknownMessageHandler {
491 /// Constructs a new PeerManager with the given message handlers and node_id secret key
492 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
493 /// cryptographically secure random bytes.
494 pub fn new(message_handler: MessageHandler<CM, RM>, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L, unknown_message_handler: UMH) -> Self {
495 let mut ephemeral_key_midstate = Sha256::engine();
496 ephemeral_key_midstate.input(ephemeral_random_data);
500 peers: Mutex::new(PeerHolder {
501 peers: HashMap::new(),
502 node_id_to_descriptor: HashMap::new()
505 ephemeral_key_midstate,
506 peer_counter_low: AtomicUsize::new(0),
507 peer_counter_high: AtomicUsize::new(0),
509 unknown_message_handler,
513 /// Get the list of node ids for peers which have completed the initial handshake.
515 /// For outbound connections, this will be the same as the their_node_id parameter passed in to
516 /// new_outbound_connection, however entries will only appear once the initial handshake has
517 /// completed and we are sure the remote peer has the private key for the given node_id.
518 pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
519 let peers = self.peers.lock().unwrap();
520 peers.peers.values().filter_map(|p| {
521 if !p.channel_encryptor.is_ready_for_encryption() || p.their_features.is_none() {
528 fn get_ephemeral_key(&self) -> SecretKey {
529 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
530 let low = self.peer_counter_low.fetch_add(1, Ordering::AcqRel);
531 let high = if low == 0 {
532 self.peer_counter_high.fetch_add(1, Ordering::AcqRel)
534 self.peer_counter_high.load(Ordering::Acquire)
536 ephemeral_hash.input(&byte_utils::le64_to_array(low as u64));
537 ephemeral_hash.input(&byte_utils::le64_to_array(high as u64));
538 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
541 /// Indicates a new outbound connection has been established to a node with the given node_id.
542 /// Note that if an Err is returned here you MUST NOT call socket_disconnected for the new
543 /// descriptor but must disconnect the connection immediately.
545 /// Returns a small number of bytes to send to the remote node (currently always 50).
547 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
548 /// [`socket_disconnected()`].
550 /// [`socket_disconnected()`]: PeerManager::socket_disconnected
551 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
552 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
553 let res = peer_encryptor.get_act_one().to_vec();
554 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
556 let mut peers = self.peers.lock().unwrap();
557 if peers.peers.insert(descriptor, Peer {
558 channel_encryptor: peer_encryptor,
560 their_features: None,
562 pending_outbound_buffer: LinkedList::new(),
563 pending_outbound_buffer_first_msg_offset: 0,
564 awaiting_write_event: false,
567 pending_read_buffer_pos: 0,
568 pending_read_is_header: false,
570 sync_status: InitSyncTracker::NoSyncRequested,
572 awaiting_pong: false,
574 panic!("PeerManager driver duplicated descriptors!");
579 /// Indicates a new inbound connection has been established.
581 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
582 /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
583 /// call socket_disconnected for the new descriptor but must disconnect the connection
586 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
587 /// [`socket_disconnected()`].
589 /// [`socket_disconnected()`]: PeerManager::socket_disconnected
590 pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
591 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
592 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
594 let mut peers = self.peers.lock().unwrap();
595 if peers.peers.insert(descriptor, Peer {
596 channel_encryptor: peer_encryptor,
598 their_features: None,
600 pending_outbound_buffer: LinkedList::new(),
601 pending_outbound_buffer_first_msg_offset: 0,
602 awaiting_write_event: false,
605 pending_read_buffer_pos: 0,
606 pending_read_is_header: false,
608 sync_status: InitSyncTracker::NoSyncRequested,
610 awaiting_pong: false,
612 panic!("PeerManager driver duplicated descriptors!");
617 fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
618 while !peer.awaiting_write_event {
619 if peer.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE {
620 match peer.sync_status {
621 InitSyncTracker::NoSyncRequested => {},
622 InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
623 let steps = ((OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len() + 2) / 3) as u8;
624 let all_messages = self.message_handler.route_handler.get_next_channel_announcements(c, steps);
625 for &(ref announce, ref update_a_option, ref update_b_option) in all_messages.iter() {
626 self.enqueue_message(peer, announce);
627 if let &Some(ref update_a) = update_a_option {
628 self.enqueue_message(peer, update_a);
630 if let &Some(ref update_b) = update_b_option {
631 self.enqueue_message(peer, update_b);
633 peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
635 if all_messages.is_empty() || all_messages.len() != steps as usize {
636 peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
639 InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
640 let steps = (OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len()) as u8;
641 let all_messages = self.message_handler.route_handler.get_next_node_announcements(None, steps);
642 for msg in all_messages.iter() {
643 self.enqueue_message(peer, msg);
644 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
646 if all_messages.is_empty() || all_messages.len() != steps as usize {
647 peer.sync_status = InitSyncTracker::NoSyncRequested;
650 InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
651 InitSyncTracker::NodesSyncing(key) => {
652 let steps = (OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len()) as u8;
653 let all_messages = self.message_handler.route_handler.get_next_node_announcements(Some(&key), steps);
654 for msg in all_messages.iter() {
655 self.enqueue_message(peer, msg);
656 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
658 if all_messages.is_empty() || all_messages.len() != steps as usize {
659 peer.sync_status = InitSyncTracker::NoSyncRequested;
666 let next_buff = match peer.pending_outbound_buffer.front() {
671 let should_be_reading = peer.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE;
672 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
673 let data_sent = descriptor.send_data(pending, should_be_reading);
674 peer.pending_outbound_buffer_first_msg_offset += data_sent;
675 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
677 peer.pending_outbound_buffer_first_msg_offset = 0;
678 peer.pending_outbound_buffer.pop_front();
680 peer.awaiting_write_event = true;
685 /// Indicates that there is room to write data to the given socket descriptor.
687 /// May return an Err to indicate that the connection should be closed.
689 /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
690 /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
691 /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
692 /// ready to call `[write_buffer_space_avail`] again if a write call generated here isn't
695 /// [`send_data`]: SocketDescriptor::send_data
696 /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
697 pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
698 let mut peers = self.peers.lock().unwrap();
699 match peers.peers.get_mut(descriptor) {
701 // This is most likely a simple race condition where the user found that the socket
702 // was writeable, then we told the user to `disconnect_socket()`, then they called
703 // this method. Return an error to make sure we get disconnected.
704 return Err(PeerHandleError { no_connection_possible: false });
707 peer.awaiting_write_event = false;
708 self.do_attempt_write_data(descriptor, peer);
714 /// Indicates that data was read from the given socket descriptor.
716 /// May return an Err to indicate that the connection should be closed.
718 /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
719 /// Thus, however, you should call [`process_events`] after any `read_event` to generate
720 /// [`send_data`] calls to handle responses.
722 /// If `Ok(true)` is returned, further read_events should not be triggered until a
723 /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
726 /// [`send_data`]: SocketDescriptor::send_data
727 /// [`process_events`]: PeerManager::process_events
728 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
729 match self.do_read_event(peer_descriptor, data) {
732 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
738 /// Append a message to a peer's pending outbound/write buffer, and update the map of peers needing sends accordingly.
739 fn enqueue_message<M: Encode + Writeable + Debug>(&self, peer: &mut Peer, message: &M) {
740 let mut buffer = VecWriter(Vec::new());
741 wire::write(message, &mut buffer).unwrap(); // crash if the write failed
742 let encoded_message = buffer.0;
744 log_trace!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()));
745 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_message[..]));
748 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
750 let mut peers_lock = self.peers.lock().unwrap();
751 let peers = &mut *peers_lock;
752 let mut msgs_to_forward = Vec::new();
753 let mut peer_node_id = None;
754 let pause_read = match peers.peers.get_mut(peer_descriptor) {
756 // This is most likely a simple race condition where the user read some bytes
757 // from the socket, then we told the user to `disconnect_socket()`, then they
758 // called this method. Return an error to make sure we get disconnected.
759 return Err(PeerHandleError { no_connection_possible: false });
762 assert!(peer.pending_read_buffer.len() > 0);
763 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
765 let mut read_pos = 0;
766 while read_pos < data.len() {
768 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
769 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]);
770 read_pos += data_to_copy;
771 peer.pending_read_buffer_pos += data_to_copy;
774 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
775 peer.pending_read_buffer_pos = 0;
777 macro_rules! try_potential_handleerror {
783 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
784 //TODO: Try to push msg
785 log_debug!(self.logger, "Error handling message; disconnecting peer with: {}", e.err);
786 return Err(PeerHandleError{ no_connection_possible: false });
788 msgs::ErrorAction::IgnoreAndLog(level) => {
789 log_given_level!(self.logger, level, "Error handling message; ignoring: {}", e.err);
792 msgs::ErrorAction::IgnoreError => {
793 log_debug!(self.logger, "Error handling message; ignoring: {}", e.err);
796 msgs::ErrorAction::SendErrorMessage { msg } => {
797 log_debug!(self.logger, "Error handling message; sending error message with: {}", e.err);
798 self.enqueue_message(peer, &msg);
807 macro_rules! insert_node_id {
809 match peers.node_id_to_descriptor.entry(peer.their_node_id.unwrap()) {
810 hash_map::Entry::Occupied(_) => {
811 log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
812 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
813 return Err(PeerHandleError{ no_connection_possible: false })
815 hash_map::Entry::Vacant(entry) => {
816 log_debug!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
817 entry.insert(peer_descriptor.clone())
823 let next_step = peer.channel_encryptor.get_noise_step();
825 NextNoiseStep::ActOne => {
826 let act_two = try_potential_handleerror!(peer.channel_encryptor.process_act_one_with_keys(&peer.pending_read_buffer[..], &self.our_node_secret, self.get_ephemeral_key())).to_vec();
827 peer.pending_outbound_buffer.push_back(act_two);
828 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
830 NextNoiseStep::ActTwo => {
831 let (act_three, their_node_id) = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret));
832 peer.pending_outbound_buffer.push_back(act_three.to_vec());
833 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
834 peer.pending_read_is_header = true;
836 peer.their_node_id = Some(their_node_id);
838 let features = InitFeatures::known();
839 let resp = msgs::Init { features };
840 self.enqueue_message(peer, &resp);
842 NextNoiseStep::ActThree => {
843 let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
844 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
845 peer.pending_read_is_header = true;
846 peer.their_node_id = Some(their_node_id);
848 let features = InitFeatures::known();
849 let resp = msgs::Init { features };
850 self.enqueue_message(peer, &resp);
852 NextNoiseStep::NoiseComplete => {
853 if peer.pending_read_is_header {
854 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
855 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
856 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
857 if msg_len < 2 { // Need at least the message type tag
858 return Err(PeerHandleError{ no_connection_possible: false });
860 peer.pending_read_is_header = false;
862 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
863 assert!(msg_data.len() >= 2);
866 peer.pending_read_buffer = [0; 18].to_vec();
867 peer.pending_read_is_header = true;
869 let mut message_result = wire::read(&mut ::std::io::Cursor::new(&msg_data[..]));
871 // Need an Init as first message
872 if let Ok(wire::Message::Init(_)) = message_result {
873 } else if peer.their_features.is_none() {
874 log_debug!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(peer.their_node_id.unwrap()));
875 return Err(PeerHandleError{ no_connection_possible: false }.into());
878 let mut message_err = Ok(());
879 let mut handle_err = Ok(());
880 match message_result {
881 Ok(wire::Message::Unknown(msg_type)) => {
882 let mut type_bytes = [0; 2];
883 let mut reader = ::std::io::Cursor::new(&msg_data[..]);
884 reader.read_exact(&mut type_bytes).expect("How did we read these to begin with?");
885 match self.unknown_message_handler.read(*msg_type, &mut reader) {
887 handle_err = self.unknown_message_handler.handle_unknown_message(msg);
890 if *msg_type % 2 == 0 {
891 return Err(PeerHandleError { no_connection_possible: true });
894 Err(e) => { message_err = Err(e); },
898 match self.handle_message(peer, msg) {
899 Ok(Some(forward_msg)) => {
900 peer_node_id = Some(peer.their_node_id.expect("After noise is complete, their_node_id is always set"));
901 msgs_to_forward.push(forward_msg);
904 Err(e) => { handle_err = Err(e); },
907 Err(e) => { message_err = Err(e); },
913 msgs::DecodeError::UnknownVersion => return Err(PeerHandleError { no_connection_possible: false }),
914 msgs::DecodeError::UnknownRequiredFeature => {
915 log_trace!(self.logger, "Got a channel/node announcement with an known required feature flag, you may want to update!");
918 msgs::DecodeError::InvalidValue => {
919 log_debug!(self.logger, "Got an invalid value while deserializing message");
920 return Err(PeerHandleError { no_connection_possible: false });
922 msgs::DecodeError::ShortRead => {
923 log_debug!(self.logger, "Deserialization failed due to shortness of message");
924 return Err(PeerHandleError { no_connection_possible: false });
926 msgs::DecodeError::BadLengthDescriptor => return Err(PeerHandleError { no_connection_possible: false }),
927 msgs::DecodeError::Io(_) => return Err(PeerHandleError { no_connection_possible: false }),
928 msgs::DecodeError::UnsupportedCompression => {
929 log_trace!(self.logger, "We don't support zlib-compressed message fields, ignoring message");
939 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
940 MessageHandlingError::LightningError(e) => {
941 try_potential_handleerror!(Err(e));
951 peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_READ_PAUSE // pause_read
955 for msg in msgs_to_forward.drain(..) {
956 self.forward_broadcast_msg(peers, &msg, peer_node_id.as_ref());
965 /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
966 /// Returns the message back if it needs to be broadcasted to all other peers.
967 fn handle_message(&self, peer: &mut Peer, message: wire::Message) -> Result<Option<wire::Message>, MessageHandlingError> {
968 log_trace!(self.logger, "Received message {:?} from {}", message, log_pubkey!(peer.their_node_id.unwrap()));
970 let mut should_forward = None;
973 // Setup and Control messages:
974 wire::Message::Init(msg) => {
975 if msg.features.requires_unknown_bits() {
976 log_debug!(self.logger, "Peer features required unknown version bits");
977 return Err(PeerHandleError{ no_connection_possible: true }.into());
979 if peer.their_features.is_some() {
980 return Err(PeerHandleError{ no_connection_possible: false }.into());
984 self.logger, "Received peer Init message: data_loss_protect: {}, initial_routing_sync: {}, upfront_shutdown_script: {}, gossip_queries: {}, static_remote_key: {}, unknown flags (local and global): {}",
985 if msg.features.supports_data_loss_protect() { "supported" } else { "not supported"},
986 if msg.features.initial_routing_sync() { "requested" } else { "not requested" },
987 if msg.features.supports_upfront_shutdown_script() { "supported" } else { "not supported"},
988 if msg.features.supports_gossip_queries() { "supported" } else { "not supported" },
989 if msg.features.supports_static_remote_key() { "supported" } else { "not supported"},
990 if msg.features.supports_unknown_bits() { "present" } else { "none" }
993 if msg.features.initial_routing_sync() {
994 peer.sync_status = InitSyncTracker::ChannelsSyncing(0);
996 if !msg.features.supports_static_remote_key() {
997 log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting with no_connection_possible", log_pubkey!(peer.their_node_id.unwrap()));
998 return Err(PeerHandleError{ no_connection_possible: true }.into());
1001 self.message_handler.route_handler.sync_routing_table(&peer.their_node_id.unwrap(), &msg);
1003 self.message_handler.chan_handler.peer_connected(&peer.their_node_id.unwrap(), &msg);
1004 peer.their_features = Some(msg.features);
1006 wire::Message::Error(msg) => {
1007 let mut data_is_printable = true;
1008 for b in msg.data.bytes() {
1009 if b < 32 || b > 126 {
1010 data_is_printable = false;
1015 if data_is_printable {
1016 log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data);
1018 log_debug!(self.logger, "Got Err message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap()));
1020 self.message_handler.chan_handler.handle_error(&peer.their_node_id.unwrap(), &msg);
1021 if msg.channel_id == [0; 32] {
1022 return Err(PeerHandleError{ no_connection_possible: true }.into());
1026 wire::Message::Ping(msg) => {
1027 if msg.ponglen < 65532 {
1028 let resp = msgs::Pong { byteslen: msg.ponglen };
1029 self.enqueue_message(peer, &resp);
1032 wire::Message::Pong(_msg) => {
1033 peer.awaiting_pong = false;
1036 // Channel messages:
1037 wire::Message::OpenChannel(msg) => {
1038 self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
1040 wire::Message::AcceptChannel(msg) => {
1041 self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
1044 wire::Message::FundingCreated(msg) => {
1045 self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg);
1047 wire::Message::FundingSigned(msg) => {
1048 self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg);
1050 wire::Message::FundingLocked(msg) => {
1051 self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg);
1054 wire::Message::Shutdown(msg) => {
1055 self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), peer.their_features.as_ref().unwrap(), &msg);
1057 wire::Message::ClosingSigned(msg) => {
1058 self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg);
1061 // Commitment messages:
1062 wire::Message::UpdateAddHTLC(msg) => {
1063 self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg);
1065 wire::Message::UpdateFulfillHTLC(msg) => {
1066 self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg);
1068 wire::Message::UpdateFailHTLC(msg) => {
1069 self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg);
1071 wire::Message::UpdateFailMalformedHTLC(msg) => {
1072 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg);
1075 wire::Message::CommitmentSigned(msg) => {
1076 self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg);
1078 wire::Message::RevokeAndACK(msg) => {
1079 self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg);
1081 wire::Message::UpdateFee(msg) => {
1082 self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg);
1084 wire::Message::ChannelReestablish(msg) => {
1085 self.message_handler.chan_handler.handle_channel_reestablish(&peer.their_node_id.unwrap(), &msg);
1088 // Routing messages:
1089 wire::Message::AnnouncementSignatures(msg) => {
1090 self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg);
1092 wire::Message::ChannelAnnouncement(msg) => {
1093 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1094 .map_err(|e| -> MessageHandlingError { e.into() })? {
1095 should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1098 wire::Message::NodeAnnouncement(msg) => {
1099 if self.message_handler.route_handler.handle_node_announcement(&msg)
1100 .map_err(|e| -> MessageHandlingError { e.into() })? {
1101 should_forward = Some(wire::Message::NodeAnnouncement(msg));
1104 wire::Message::ChannelUpdate(msg) => {
1105 self.message_handler.chan_handler.handle_channel_update(&peer.their_node_id.unwrap(), &msg);
1106 if self.message_handler.route_handler.handle_channel_update(&msg)
1107 .map_err(|e| -> MessageHandlingError { e.into() })? {
1108 should_forward = Some(wire::Message::ChannelUpdate(msg));
1111 wire::Message::QueryShortChannelIds(msg) => {
1112 self.message_handler.route_handler.handle_query_short_channel_ids(&peer.their_node_id.unwrap(), msg)?;
1114 wire::Message::ReplyShortChannelIdsEnd(msg) => {
1115 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&peer.their_node_id.unwrap(), msg)?;
1117 wire::Message::QueryChannelRange(msg) => {
1118 self.message_handler.route_handler.handle_query_channel_range(&peer.their_node_id.unwrap(), msg)?;
1120 wire::Message::ReplyChannelRange(msg) => {
1121 self.message_handler.route_handler.handle_reply_channel_range(&peer.their_node_id.unwrap(), msg)?;
1123 wire::Message::GossipTimestampFilter(_msg) => {
1124 // TODO: handle message
1127 // Unknown messages:
1128 wire::Message::Unknown(_msg) => {
1129 // Handled in `do_read_event`.
1135 fn forward_broadcast_msg(&self, peers: &mut PeerHolder<Descriptor>, msg: &wire::Message, except_node: Option<&PublicKey>) {
1137 wire::Message::ChannelAnnouncement(ref msg) => {
1138 log_trace!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1139 let encoded_msg = encode_msg!(msg);
1141 for (_, peer) in peers.peers.iter_mut() {
1142 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1143 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1146 if peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP {
1147 log_trace!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1150 if peer.their_node_id.as_ref() == Some(&msg.contents.node_id_1) ||
1151 peer.their_node_id.as_ref() == Some(&msg.contents.node_id_2) {
1154 if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1157 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
1160 wire::Message::NodeAnnouncement(ref msg) => {
1161 log_trace!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1162 let encoded_msg = encode_msg!(msg);
1164 for (_, peer) in peers.peers.iter_mut() {
1165 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1166 !peer.should_forward_node_announcement(msg.contents.node_id) {
1169 if peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP {
1170 log_trace!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1173 if peer.their_node_id.as_ref() == Some(&msg.contents.node_id) {
1176 if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1179 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
1182 wire::Message::ChannelUpdate(ref msg) => {
1183 log_trace!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1184 let encoded_msg = encode_msg!(msg);
1186 for (_, peer) in peers.peers.iter_mut() {
1187 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1188 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1191 if peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP {
1192 log_trace!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1195 if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1198 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
1201 _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1205 /// Checks for any events generated by our handlers and processes them. Includes sending most
1206 /// response messages as well as messages generated by calls to handler functions directly (eg
1207 /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1209 /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1212 /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1213 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1214 /// [`send_data`]: SocketDescriptor::send_data
1215 pub fn process_events(&self) {
1217 // TODO: There are some DoS attacks here where you can flood someone's outbound send
1218 // buffer by doing things like announcing channels on another node. We should be willing to
1219 // drop optional-ish messages when send buffers get full!
1221 let mut peers_lock = self.peers.lock().unwrap();
1222 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
1223 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
1224 let peers = &mut *peers_lock;
1226 macro_rules! get_peer_for_forwarding {
1227 ($node_id: expr) => {
1229 match peers.node_id_to_descriptor.get($node_id) {
1230 Some(descriptor) => match peers.peers.get_mut(&descriptor) {
1232 if peer.their_features.is_none() {
1237 None => panic!("Inconsistent peers set state!"),
1247 for event in events_generated.drain(..) {
1249 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1250 log_debug!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1251 log_pubkey!(node_id),
1252 log_bytes!(msg.temporary_channel_id));
1253 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1255 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1256 log_debug!(self.logger, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
1257 log_pubkey!(node_id),
1258 log_bytes!(msg.temporary_channel_id));
1259 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1261 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
1262 log_debug!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
1263 log_pubkey!(node_id),
1264 log_bytes!(msg.temporary_channel_id),
1265 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
1266 // TODO: If the peer is gone we should generate a DiscardFunding event
1267 // indicating to the wallet that they should just throw away this funding transaction
1268 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1270 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
1271 log_debug!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
1272 log_pubkey!(node_id),
1273 log_bytes!(msg.channel_id));
1274 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1276 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
1277 log_debug!(self.logger, "Handling SendFundingLocked event in peer_handler for node {} for channel {}",
1278 log_pubkey!(node_id),
1279 log_bytes!(msg.channel_id));
1280 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1282 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
1283 log_debug!(self.logger, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
1284 log_pubkey!(node_id),
1285 log_bytes!(msg.channel_id));
1286 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1288 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 } } => {
1289 log_debug!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
1290 log_pubkey!(node_id),
1291 update_add_htlcs.len(),
1292 update_fulfill_htlcs.len(),
1293 update_fail_htlcs.len(),
1294 log_bytes!(commitment_signed.channel_id));
1295 let peer = get_peer_for_forwarding!(node_id);
1296 for msg in update_add_htlcs {
1297 self.enqueue_message(peer, msg);
1299 for msg in update_fulfill_htlcs {
1300 self.enqueue_message(peer, msg);
1302 for msg in update_fail_htlcs {
1303 self.enqueue_message(peer, msg);
1305 for msg in update_fail_malformed_htlcs {
1306 self.enqueue_message(peer, msg);
1308 if let &Some(ref msg) = update_fee {
1309 self.enqueue_message(peer, msg);
1311 self.enqueue_message(peer, commitment_signed);
1313 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1314 log_debug!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
1315 log_pubkey!(node_id),
1316 log_bytes!(msg.channel_id));
1317 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1319 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1320 log_debug!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
1321 log_pubkey!(node_id),
1322 log_bytes!(msg.channel_id));
1323 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1325 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1326 log_debug!(self.logger, "Handling Shutdown event in peer_handler for node {} for channel {}",
1327 log_pubkey!(node_id),
1328 log_bytes!(msg.channel_id));
1329 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1331 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
1332 log_debug!(self.logger, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
1333 log_pubkey!(node_id),
1334 log_bytes!(msg.channel_id));
1335 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1337 MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
1338 log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1339 if self.message_handler.route_handler.handle_channel_announcement(&msg).is_ok() && self.message_handler.route_handler.handle_channel_update(&update_msg).is_ok() {
1340 self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None);
1341 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(update_msg), None);
1344 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
1345 log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler");
1346 if self.message_handler.route_handler.handle_node_announcement(&msg).is_ok() {
1347 self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None);
1350 MessageSendEvent::BroadcastChannelUpdate { msg } => {
1351 log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1352 if self.message_handler.route_handler.handle_channel_update(&msg).is_ok() {
1353 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None);
1356 MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
1357 log_trace!(self.logger, "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
1358 log_pubkey!(node_id), msg.contents.short_channel_id);
1359 let peer = get_peer_for_forwarding!(node_id);
1360 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1362 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
1363 self.message_handler.route_handler.handle_htlc_fail_channel_update(update);
1365 MessageSendEvent::HandleError { ref node_id, ref action } => {
1367 msgs::ErrorAction::DisconnectPeer { ref msg } => {
1368 if let Some(mut descriptor) = peers.node_id_to_descriptor.remove(node_id) {
1369 if let Some(mut peer) = peers.peers.remove(&descriptor) {
1370 if let Some(ref msg) = *msg {
1371 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1372 log_pubkey!(node_id),
1374 self.enqueue_message(&mut peer, msg);
1375 // This isn't guaranteed to work, but if there is enough free
1376 // room in the send buffer, put the error message there...
1377 self.do_attempt_write_data(&mut descriptor, &mut peer);
1379 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1382 descriptor.disconnect_socket();
1383 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1386 msgs::ErrorAction::IgnoreAndLog(level) => {
1387 log_given_level!(self.logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1389 msgs::ErrorAction::IgnoreError => {
1390 log_debug!(self.logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1392 msgs::ErrorAction::SendErrorMessage { ref msg } => {
1393 log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1394 log_pubkey!(node_id),
1396 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1400 MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
1401 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1403 MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
1404 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1406 MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
1407 log_trace!(self.logger, "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
1408 log_pubkey!(node_id),
1409 msg.short_channel_ids.len(),
1411 msg.number_of_blocks,
1413 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1418 for (node_id, message) in self.unknown_message_handler.get_and_clear_pending_msgs() {
1419 self.enqueue_message(get_peer_for_forwarding!(node_id), &message);
1422 for (descriptor, peer) in peers.peers.iter_mut() {
1423 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
1428 /// Indicates that the given socket descriptor's connection is now closed.
1429 pub fn socket_disconnected(&self, descriptor: &Descriptor) {
1430 self.disconnect_event_internal(descriptor, false);
1433 fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1434 let mut peers = self.peers.lock().unwrap();
1435 let peer_option = peers.peers.remove(descriptor);
1438 // This is most likely a simple race condition where the user found that the socket
1439 // was disconnected, then we told the user to `disconnect_socket()`, then they
1440 // called this method. Either way we're disconnected, return.
1443 match peer.their_node_id {
1445 peers.node_id_to_descriptor.remove(&node_id);
1446 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1454 /// Disconnect a peer given its node id.
1456 /// Set `no_connection_possible` to true to prevent any further connection with this peer,
1457 /// force-closing any channels we have with it.
1459 /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
1460 /// peer. Thus, be very careful about reentrancy issues.
1462 /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
1463 pub fn disconnect_by_node_id(&self, node_id: PublicKey, no_connection_possible: bool) {
1464 let mut peers_lock = self.peers.lock().unwrap();
1465 if let Some(mut descriptor) = peers_lock.node_id_to_descriptor.remove(&node_id) {
1466 log_trace!(self.logger, "Disconnecting peer with id {} due to client request", node_id);
1467 peers_lock.peers.remove(&descriptor);
1468 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1469 descriptor.disconnect_socket();
1473 /// This function should be called roughly once every 30 seconds.
1474 /// It will send pings to each peer and disconnect those which did not respond to the last
1477 /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1480 /// [`send_data`]: SocketDescriptor::send_data
1481 pub fn timer_tick_occurred(&self) {
1482 let mut peers_lock = self.peers.lock().unwrap();
1484 let peers = &mut *peers_lock;
1485 let node_id_to_descriptor = &mut peers.node_id_to_descriptor;
1486 let peers = &mut peers.peers;
1487 let mut descriptors_needing_disconnect = Vec::new();
1489 peers.retain(|descriptor, peer| {
1490 if peer.awaiting_pong {
1491 descriptors_needing_disconnect.push(descriptor.clone());
1492 match peer.their_node_id {
1494 log_trace!(self.logger, "Disconnecting peer with id {} due to ping timeout", node_id);
1495 node_id_to_descriptor.remove(&node_id);
1496 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1499 // This can't actually happen as we should have hit
1500 // is_ready_for_encryption() previously on this same peer.
1507 if !peer.channel_encryptor.is_ready_for_encryption() {
1508 // The peer needs to complete its handshake before we can exchange messages
1512 let ping = msgs::Ping {
1516 self.enqueue_message(peer, &ping);
1518 let mut descriptor_clone = descriptor.clone();
1519 self.do_attempt_write_data(&mut descriptor_clone, peer);
1521 peer.awaiting_pong = true;
1525 for mut descriptor in descriptors_needing_disconnect.drain(..) {
1526 descriptor.disconnect_socket();
1534 use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringUnknownMessageHandler};
1537 use util::test_utils;
1539 use bitcoin::secp256k1::Secp256k1;
1540 use bitcoin::secp256k1::key::{SecretKey, PublicKey};
1543 use std::sync::{Arc, Mutex};
1544 use core::sync::atomic::Ordering;
1547 struct FileDescriptor {
1549 outbound_data: Arc<Mutex<Vec<u8>>>,
1551 impl PartialEq for FileDescriptor {
1552 fn eq(&self, other: &Self) -> bool {
1556 impl Eq for FileDescriptor { }
1557 impl core::hash::Hash for FileDescriptor {
1558 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
1559 self.fd.hash(hasher)
1563 impl SocketDescriptor for FileDescriptor {
1564 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
1565 self.outbound_data.lock().unwrap().extend_from_slice(data);
1569 fn disconnect_socket(&mut self) {}
1572 struct PeerManagerCfg {
1573 chan_handler: test_utils::TestChannelMessageHandler,
1574 routing_handler: test_utils::TestRoutingMessageHandler,
1575 logger: test_utils::TestLogger,
1578 fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
1579 let mut cfgs = Vec::new();
1580 for _ in 0..peer_count {
1583 chan_handler: test_utils::TestChannelMessageHandler::new(),
1584 logger: test_utils::TestLogger::new(),
1585 routing_handler: test_utils::TestRoutingMessageHandler::new(),
1593 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, IgnoringUnknownMessageHandler>> {
1594 let mut peers = Vec::new();
1595 for i in 0..peer_count {
1596 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
1597 let ephemeral_bytes = [i as u8; 32];
1598 let msg_handler = MessageHandler { chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler };
1599 let peer = PeerManager::new(msg_handler, node_secret, &ephemeral_bytes, &cfgs[i].logger, IgnoringUnknownMessageHandler {});
1606 fn establish_connection<'a>(peer_a: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, &'a test_utils::TestLogger, IgnoringUnknownMessageHandler>, peer_b: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, &'a test_utils::TestLogger, IgnoringUnknownMessageHandler>) -> (FileDescriptor, FileDescriptor) {
1607 let secp_ctx = Secp256k1::new();
1608 let a_id = PublicKey::from_secret_key(&secp_ctx, &peer_a.our_node_secret);
1609 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1610 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1611 let initial_data = peer_b.new_outbound_connection(a_id, fd_b.clone()).unwrap();
1612 peer_a.new_inbound_connection(fd_a.clone()).unwrap();
1613 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
1614 peer_a.process_events();
1615 assert_eq!(peer_b.read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1616 peer_b.process_events();
1617 assert_eq!(peer_a.read_event(&mut fd_a, &fd_b.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1618 (fd_a.clone(), fd_b.clone())
1622 fn test_disconnect_peer() {
1623 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
1624 // push a DisconnectPeer event to remove the node flagged by id
1625 let cfgs = create_peermgr_cfgs(2);
1626 let chan_handler = test_utils::TestChannelMessageHandler::new();
1627 let mut peers = create_network(2, &cfgs);
1628 establish_connection(&peers[0], &peers[1]);
1629 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1631 let secp_ctx = Secp256k1::new();
1632 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
1634 chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
1636 action: msgs::ErrorAction::DisconnectPeer { msg: None },
1638 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
1639 peers[0].message_handler.chan_handler = &chan_handler;
1641 peers[0].process_events();
1642 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
1646 fn test_timer_tick_occurred() {
1647 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
1648 let cfgs = create_peermgr_cfgs(2);
1649 let peers = create_network(2, &cfgs);
1650 establish_connection(&peers[0], &peers[1]);
1651 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1653 // peers[0] awaiting_pong is set to true, but the Peer is still connected
1654 peers[0].timer_tick_occurred();
1655 peers[0].process_events();
1656 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1658 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
1659 peers[0].timer_tick_occurred();
1660 peers[0].process_events();
1661 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
1665 fn test_do_attempt_write_data() {
1666 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
1667 let cfgs = create_peermgr_cfgs(2);
1668 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
1669 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
1670 let peers = create_network(2, &cfgs);
1672 // By calling establish_connect, we trigger do_attempt_write_data between
1673 // the peers. Previously this function would mistakenly enter an infinite loop
1674 // when there were more channel messages available than could fit into a peer's
1675 // buffer. This issue would now be detected by this test (because we use custom
1676 // RoutingMessageHandlers that intentionally return more channel messages
1677 // than can fit into a peer's buffer).
1678 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
1680 // Make each peer to read the messages that the other peer just wrote to them.
1681 peers[0].process_events();
1682 peers[1].read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap();
1683 peers[1].process_events();
1684 peers[0].read_event(&mut fd_a, &fd_b.outbound_data.lock().unwrap().split_off(0)).unwrap();
1686 // Check that each peer has received the expected number of channel updates and channel
1688 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 100);
1689 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 50);
1690 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 100);
1691 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 50);