1 //! Top level peer message handling and socket handling logic lives here.
3 //! Instead of actually servicing sockets ourselves we require that you implement the
4 //! SocketDescriptor interface and use that to receive actions which you should perform on the
5 //! socket, and call into PeerManager with bytes read from the socket. The PeerManager will then
6 //! call into the provided message handlers (probably a ChannelManager and Router) with messages
7 //! they should handle, and encoding/sending response messages.
9 use secp256k1::key::{SecretKey,PublicKey};
11 use ln::features::InitFeatures;
13 use ln::msgs::ChannelMessageHandler;
14 use ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
15 use util::ser::VecWriter;
16 use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
20 use util::events::{MessageSendEvent, MessageSendEventsProvider};
21 use util::logger::Logger;
23 use std::collections::{HashMap,hash_map,HashSet,LinkedList};
24 use std::sync::{Arc, Mutex};
25 use std::sync::atomic::{AtomicUsize, Ordering};
26 use std::{cmp,error,hash,fmt};
29 use bitcoin_hashes::sha256::Hash as Sha256;
30 use bitcoin_hashes::sha256::HashEngine as Sha256Engine;
31 use bitcoin_hashes::{HashEngine, Hash};
33 /// Provides references to trait impls which handle different types of messages.
34 pub struct MessageHandler<CM: Deref> where CM::Target: msgs::ChannelMessageHandler {
35 /// A message handler which handles messages specific to channels. Usually this is just a
36 /// ChannelManager object.
38 /// A message handler which handles messages updating our knowledge of the network channel
39 /// graph. Usually this is just a Router object.
40 pub route_handler: Arc<msgs::RoutingMessageHandler>,
43 /// Provides an object which can be used to send data to and which uniquely identifies a connection
44 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
45 /// implement Hash to meet the PeerManager API.
47 /// For efficiency, Clone should be relatively cheap for this type.
49 /// You probably want to just extend an int and put a file descriptor in a struct and implement
50 /// send_data. Note that if you are using a higher-level net library that may call close() itself,
51 /// be careful to ensure you don't have races whereby you might register a new connection with an
52 /// fd which is the same as a previous one which has yet to be removed via
53 /// PeerManager::socket_disconnected().
54 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
55 /// Attempts to send some data from the given slice to the peer.
57 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
58 /// Note that in the disconnected case, socket_disconnected must still fire and further write
59 /// attempts may occur until that time.
61 /// If the returned size is smaller than data.len(), a write_available event must
62 /// trigger the next time more data can be written. Additionally, until the a send_data event
63 /// completes fully, no further read_events should trigger on the same peer!
65 /// If a read_event on this descriptor had previously returned true (indicating that read
66 /// events should be paused to prevent DoS in the send buffer), resume_read may be set
67 /// indicating that read events on this descriptor should resume. A resume_read of false does
68 /// *not* imply that further read events should be paused.
69 fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
70 /// Disconnect the socket pointed to by this SocketDescriptor. Once this function returns, no
71 /// more calls to write_buffer_space_avail, read_event or socket_disconnected may be made with
72 /// this descriptor. No socket_disconnected call should be generated as a result of this call,
73 /// though races may occur whereby disconnect_socket is called after a call to
74 /// socket_disconnected but prior to socket_disconnected returning.
75 fn disconnect_socket(&mut self);
78 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
79 /// generate no further read_event/write_buffer_space_avail calls for the descriptor, only
80 /// triggering a single socket_disconnected call (unless it was provided in response to a
81 /// new_*_connection event, in which case no such socket_disconnected() must be called and the
82 /// socket silently disconencted).
83 pub struct PeerHandleError {
84 /// Used to indicate that we probably can't make any future connections to this peer, implying
85 /// we should go ahead and force-close any channels we have with it.
86 no_connection_possible: bool,
88 impl fmt::Debug for PeerHandleError {
89 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
90 formatter.write_str("Peer Sent Invalid Data")
93 impl fmt::Display for PeerHandleError {
94 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
95 formatter.write_str("Peer Sent Invalid Data")
98 impl error::Error for PeerHandleError {
99 fn description(&self) -> &str {
100 "Peer Sent Invalid Data"
104 enum InitSyncTracker{
106 ChannelsSyncing(u64),
107 NodesSyncing(PublicKey),
111 channel_encryptor: PeerChannelEncryptor,
113 their_node_id: Option<PublicKey>,
114 their_features: Option<InitFeatures>,
116 pending_outbound_buffer: LinkedList<Vec<u8>>,
117 pending_outbound_buffer_first_msg_offset: usize,
118 awaiting_write_event: bool,
120 pending_read_buffer: Vec<u8>,
121 pending_read_buffer_pos: usize,
122 pending_read_is_header: bool,
124 sync_status: InitSyncTracker,
130 /// Returns true if the channel announcements/updates for the given channel should be
131 /// forwarded to this peer.
132 /// If we are sending our routing table to this peer and we have not yet sent channel
133 /// announcements/updates for the given channel_id then we will send it when we get to that
134 /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
135 /// sent the old versions, we should send the update, and so return true here.
136 fn should_forward_channel(&self, channel_id: u64)->bool{
137 match self.sync_status {
138 InitSyncTracker::NoSyncRequested => true,
139 InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
140 InitSyncTracker::NodesSyncing(_) => true,
145 struct PeerHolder<Descriptor: SocketDescriptor> {
146 peers: HashMap<Descriptor, Peer>,
147 /// Added to by do_read_event for cases where we pushed a message onto the send buffer but
148 /// didn't call do_attempt_write_data to avoid reentrancy. Cleared in process_events()
149 peers_needing_send: HashSet<Descriptor>,
150 /// Only add to this set when noise completes:
151 node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
154 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
155 fn _check_usize_is_32_or_64() {
156 // See below, less than 32 bit pointers may be unsafe here!
157 unsafe { mem::transmute::<*const usize, [u8; 4]>(panic!()); }
160 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
161 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
162 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
163 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
164 /// issues such as overly long function definitions.
165 pub type SimpleArcPeerManager<SD, M, T, F> = Arc<PeerManager<SD, SimpleArcChannelManager<M, T, F>>>;
167 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
168 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
169 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
170 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
171 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
172 /// helps with issues such as long function definitions.
173 pub type SimpleRefPeerManager<'a, 'b, 'c, 'd, SD, M, T, F> = PeerManager<SD, SimpleRefChannelManager<'a, 'b, 'c, 'd, M, T, F>>;
175 /// A PeerManager manages a set of peers, described by their SocketDescriptor and marshalls socket
176 /// events into messages which it passes on to its MessageHandlers.
178 /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
179 /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
180 /// essentially you should default to using a SimpleRefPeerManager, and use a
181 /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
182 /// you're using lightning-net-tokio.
183 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref> where CM::Target: msgs::ChannelMessageHandler {
184 message_handler: MessageHandler<CM>,
185 peers: Mutex<PeerHolder<Descriptor>>,
186 our_node_secret: SecretKey,
187 ephemeral_key_midstate: Sha256Engine,
189 // Usize needs to be at least 32 bits to avoid overflowing both low and high. If usize is 64
190 // bits we will never realistically count into high:
191 peer_counter_low: AtomicUsize,
192 peer_counter_high: AtomicUsize,
197 macro_rules! encode_msg {
199 let mut buffer = VecWriter(Vec::new());
200 wire::write($msg, &mut buffer).unwrap();
205 /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds.
206 /// PeerIds may repeat, but only after socket_disconnected() has been called.
207 impl<Descriptor: SocketDescriptor, CM: Deref> PeerManager<Descriptor, CM> where CM::Target: msgs::ChannelMessageHandler {
208 /// Constructs a new PeerManager with the given message handlers and node_id secret key
209 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
210 /// cryptographically secure random bytes.
211 pub fn new(message_handler: MessageHandler<CM>, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: Arc<Logger>) -> PeerManager<Descriptor, CM> {
212 let mut ephemeral_key_midstate = Sha256::engine();
213 ephemeral_key_midstate.input(ephemeral_random_data);
216 message_handler: message_handler,
217 peers: Mutex::new(PeerHolder {
218 peers: HashMap::new(),
219 peers_needing_send: HashSet::new(),
220 node_id_to_descriptor: HashMap::new()
222 our_node_secret: our_node_secret,
223 ephemeral_key_midstate,
224 peer_counter_low: AtomicUsize::new(0),
225 peer_counter_high: AtomicUsize::new(0),
230 /// Get the list of node ids for peers which have completed the initial handshake.
232 /// For outbound connections, this will be the same as the their_node_id parameter passed in to
233 /// new_outbound_connection, however entries will only appear once the initial handshake has
234 /// completed and we are sure the remote peer has the private key for the given node_id.
235 pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
236 let peers = self.peers.lock().unwrap();
237 peers.peers.values().filter_map(|p| {
238 if !p.channel_encryptor.is_ready_for_encryption() || p.their_features.is_none() {
245 fn get_ephemeral_key(&self) -> SecretKey {
246 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
247 let low = self.peer_counter_low.fetch_add(1, Ordering::AcqRel);
248 let high = if low == 0 {
249 self.peer_counter_high.fetch_add(1, Ordering::AcqRel)
251 self.peer_counter_high.load(Ordering::Acquire)
253 ephemeral_hash.input(&byte_utils::le64_to_array(low as u64));
254 ephemeral_hash.input(&byte_utils::le64_to_array(high as u64));
255 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
258 /// Indicates a new outbound connection has been established to a node with the given node_id.
259 /// Note that if an Err is returned here you MUST NOT call socket_disconnected for the new
260 /// descriptor but must disconnect the connection immediately.
262 /// Returns a small number of bytes to send to the remote node (currently always 50).
264 /// Panics if descriptor is duplicative with some other descriptor which has not yet had a
265 /// socket_disconnected().
266 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
267 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
268 let res = peer_encryptor.get_act_one().to_vec();
269 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
271 let mut peers = self.peers.lock().unwrap();
272 if peers.peers.insert(descriptor, Peer {
273 channel_encryptor: peer_encryptor,
276 their_features: None,
278 pending_outbound_buffer: LinkedList::new(),
279 pending_outbound_buffer_first_msg_offset: 0,
280 awaiting_write_event: false,
282 pending_read_buffer: pending_read_buffer,
283 pending_read_buffer_pos: 0,
284 pending_read_is_header: false,
286 sync_status: InitSyncTracker::NoSyncRequested,
288 awaiting_pong: false,
290 panic!("PeerManager driver duplicated descriptors!");
295 /// Indicates a new inbound connection has been established.
297 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
298 /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
299 /// call socket_disconnected for the new descriptor but must disconnect the connection
302 /// Panics if descriptor is duplicative with some other descriptor which has not yet had
303 /// socket_disconnected called.
304 pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
305 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
306 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
308 let mut peers = self.peers.lock().unwrap();
309 if peers.peers.insert(descriptor, Peer {
310 channel_encryptor: peer_encryptor,
313 their_features: None,
315 pending_outbound_buffer: LinkedList::new(),
316 pending_outbound_buffer_first_msg_offset: 0,
317 awaiting_write_event: false,
319 pending_read_buffer: pending_read_buffer,
320 pending_read_buffer_pos: 0,
321 pending_read_is_header: false,
323 sync_status: InitSyncTracker::NoSyncRequested,
325 awaiting_pong: false,
327 panic!("PeerManager driver duplicated descriptors!");
332 fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
333 macro_rules! encode_and_send_msg {
336 log_trace!(self, "Encoding and sending sync update message of type {} to {}", $msg.type_id(), log_pubkey!(peer.their_node_id.unwrap()));
337 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!($msg)[..]));
341 const MSG_BUFF_SIZE: usize = 10;
342 while !peer.awaiting_write_event {
343 if peer.pending_outbound_buffer.len() < MSG_BUFF_SIZE {
344 match peer.sync_status {
345 InitSyncTracker::NoSyncRequested => {},
346 InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
347 let steps = ((MSG_BUFF_SIZE - peer.pending_outbound_buffer.len() + 2) / 3) as u8;
348 let all_messages = self.message_handler.route_handler.get_next_channel_announcements(0, steps);
349 for &(ref announce, ref update_a, ref update_b) in all_messages.iter() {
350 encode_and_send_msg!(announce);
351 encode_and_send_msg!(update_a);
352 encode_and_send_msg!(update_b);
353 peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
355 if all_messages.is_empty() || all_messages.len() != steps as usize {
356 peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
359 InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
360 let steps = (MSG_BUFF_SIZE - peer.pending_outbound_buffer.len()) as u8;
361 let all_messages = self.message_handler.route_handler.get_next_node_announcements(None, steps);
362 for msg in all_messages.iter() {
363 encode_and_send_msg!(msg);
364 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
366 if all_messages.is_empty() || all_messages.len() != steps as usize {
367 peer.sync_status = InitSyncTracker::NoSyncRequested;
370 InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
371 InitSyncTracker::NodesSyncing(key) => {
372 let steps = (MSG_BUFF_SIZE - peer.pending_outbound_buffer.len()) as u8;
373 let all_messages = self.message_handler.route_handler.get_next_node_announcements(Some(&key), steps);
374 for msg in all_messages.iter() {
375 encode_and_send_msg!(msg);
376 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
378 if all_messages.is_empty() || all_messages.len() != steps as usize {
379 peer.sync_status = InitSyncTracker::NoSyncRequested;
386 let next_buff = match peer.pending_outbound_buffer.front() {
391 let should_be_reading = peer.pending_outbound_buffer.len() < MSG_BUFF_SIZE;
392 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
393 let data_sent = descriptor.send_data(pending, should_be_reading);
394 peer.pending_outbound_buffer_first_msg_offset += data_sent;
395 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
397 peer.pending_outbound_buffer_first_msg_offset = 0;
398 peer.pending_outbound_buffer.pop_front();
400 peer.awaiting_write_event = true;
405 /// Indicates that there is room to write data to the given socket descriptor.
407 /// May return an Err to indicate that the connection should be closed.
409 /// Will most likely call send_data on the descriptor passed in (or the descriptor handed into
410 /// new_*\_connection) before returning. Thus, be very careful with reentrancy issues! The
411 /// invariants around calling write_buffer_space_avail in case a write did not fully complete
412 /// must still hold - be ready to call write_buffer_space_avail again if a write call generated
413 /// here isn't sufficient! Panics if the descriptor was not previously registered in a
414 /// new_\*_connection event.
415 pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
416 let mut peers = self.peers.lock().unwrap();
417 match peers.peers.get_mut(descriptor) {
418 None => panic!("Descriptor for write_event is not already known to PeerManager"),
420 peer.awaiting_write_event = false;
421 self.do_attempt_write_data(descriptor, peer);
427 /// Indicates that data was read from the given socket descriptor.
429 /// May return an Err to indicate that the connection should be closed.
431 /// Will *not* call back into send_data on any descriptors to avoid reentrancy complexity.
432 /// Thus, however, you almost certainly want to call process_events() after any read_event to
433 /// generate send_data calls to handle responses.
435 /// If Ok(true) is returned, further read_events should not be triggered until a send_data call
436 /// on this file descriptor has resume_read set (preventing DoS issues in the send buffer).
438 /// Panics if the descriptor was not previously registered in a new_*_connection event.
439 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
440 match self.do_read_event(peer_descriptor, data) {
443 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
449 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
451 let mut peers_lock = self.peers.lock().unwrap();
452 let peers = &mut *peers_lock;
453 let pause_read = match peers.peers.get_mut(peer_descriptor) {
454 None => panic!("Descriptor for read_event is not already known to PeerManager"),
456 assert!(peer.pending_read_buffer.len() > 0);
457 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
459 let mut read_pos = 0;
460 while read_pos < data.len() {
462 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
463 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]);
464 read_pos += data_to_copy;
465 peer.pending_read_buffer_pos += data_to_copy;
468 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
469 peer.pending_read_buffer_pos = 0;
471 macro_rules! encode_and_send_msg {
474 log_trace!(self, "Encoding and sending message of type {} to {}", $msg.type_id(), log_pubkey!(peer.their_node_id.unwrap()));
475 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(&$msg)[..]));
476 peers.peers_needing_send.insert(peer_descriptor.clone());
481 macro_rules! try_potential_handleerror {
487 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
488 //TODO: Try to push msg
489 log_trace!(self, "Got Err handling message, disconnecting peer because {}", e.err);
490 return Err(PeerHandleError{ no_connection_possible: false });
492 msgs::ErrorAction::IgnoreError => {
493 log_trace!(self, "Got Err handling message, ignoring because {}", e.err);
496 msgs::ErrorAction::SendErrorMessage { msg } => {
497 log_trace!(self, "Got Err handling message, sending Error message because {}", e.err);
498 encode_and_send_msg!(msg);
507 macro_rules! insert_node_id {
509 match peers.node_id_to_descriptor.entry(peer.their_node_id.unwrap()) {
510 hash_map::Entry::Occupied(_) => {
511 log_trace!(self, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
512 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
513 return Err(PeerHandleError{ no_connection_possible: false })
515 hash_map::Entry::Vacant(entry) => {
516 log_trace!(self, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
517 entry.insert(peer_descriptor.clone())
523 let next_step = peer.channel_encryptor.get_noise_step();
525 NextNoiseStep::ActOne => {
526 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();
527 peer.pending_outbound_buffer.push_back(act_two);
528 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
530 NextNoiseStep::ActTwo => {
531 let (act_three, their_node_id) = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret));
532 peer.pending_outbound_buffer.push_back(act_three.to_vec());
533 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
534 peer.pending_read_is_header = true;
536 peer.their_node_id = Some(their_node_id);
538 let mut features = InitFeatures::supported();
539 if self.message_handler.route_handler.should_request_full_sync(&peer.their_node_id.unwrap()) {
540 features.set_initial_routing_sync();
543 let resp = msgs::Init { features };
544 encode_and_send_msg!(resp);
546 NextNoiseStep::ActThree => {
547 let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
548 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
549 peer.pending_read_is_header = true;
550 peer.their_node_id = Some(their_node_id);
553 NextNoiseStep::NoiseComplete => {
554 if peer.pending_read_is_header {
555 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
556 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
557 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
558 if msg_len < 2 { // Need at least the message type tag
559 return Err(PeerHandleError{ no_connection_possible: false });
561 peer.pending_read_is_header = false;
563 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
564 assert!(msg_data.len() >= 2);
567 peer.pending_read_buffer = [0; 18].to_vec();
568 peer.pending_read_is_header = true;
570 let mut reader = ::std::io::Cursor::new(&msg_data[..]);
571 let message_result = wire::read(&mut reader);
572 let message = match message_result {
576 msgs::DecodeError::UnknownVersion => return Err(PeerHandleError { no_connection_possible: false }),
577 msgs::DecodeError::UnknownRequiredFeature => {
578 log_debug!(self, "Got a channel/node announcement with an known required feature flag, you may want to update!");
581 msgs::DecodeError::InvalidValue => {
582 log_debug!(self, "Got an invalid value while deserializing message");
583 return Err(PeerHandleError { no_connection_possible: false });
585 msgs::DecodeError::ShortRead => {
586 log_debug!(self, "Deserialization failed due to shortness of message");
587 return Err(PeerHandleError { no_connection_possible: false });
589 msgs::DecodeError::BadLengthDescriptor => return Err(PeerHandleError { no_connection_possible: false }),
590 msgs::DecodeError::Io(_) => return Err(PeerHandleError { no_connection_possible: false }),
595 log_trace!(self, "Received message of type {} from {}", message.type_id(), log_pubkey!(peer.their_node_id.unwrap()));
597 // Need an Init as first message
598 if let wire::Message::Init(_) = message {
599 } else if peer.their_features.is_none() {
600 log_trace!(self, "Peer {} sent non-Init first message", log_pubkey!(peer.their_node_id.unwrap()));
601 return Err(PeerHandleError{ no_connection_possible: false });
605 // Setup and Control messages:
606 wire::Message::Init(msg) => {
607 if msg.features.requires_unknown_bits() {
608 log_info!(self, "Peer global features required unknown version bits");
609 return Err(PeerHandleError{ no_connection_possible: true });
611 if msg.features.requires_unknown_bits() {
612 log_info!(self, "Peer local features required unknown version bits");
613 return Err(PeerHandleError{ no_connection_possible: true });
615 if peer.their_features.is_some() {
616 return Err(PeerHandleError{ no_connection_possible: false });
619 log_info!(self, "Received peer Init message: data_loss_protect: {}, initial_routing_sync: {}, upfront_shutdown_script: {}, unkown local flags: {}, unknown global flags: {}",
620 if msg.features.supports_data_loss_protect() { "supported" } else { "not supported"},
621 if msg.features.initial_routing_sync() { "requested" } else { "not requested" },
622 if msg.features.supports_upfront_shutdown_script() { "supported" } else { "not supported"},
623 if msg.features.supports_unknown_bits() { "present" } else { "none" },
624 if msg.features.supports_unknown_bits() { "present" } else { "none" });
626 if msg.features.initial_routing_sync() {
627 peer.sync_status = InitSyncTracker::ChannelsSyncing(0);
628 peers.peers_needing_send.insert(peer_descriptor.clone());
632 let mut features = InitFeatures::supported();
633 if self.message_handler.route_handler.should_request_full_sync(&peer.their_node_id.unwrap()) {
634 features.set_initial_routing_sync();
637 let resp = msgs::Init { features };
638 encode_and_send_msg!(resp);
641 self.message_handler.chan_handler.peer_connected(&peer.their_node_id.unwrap(), &msg);
642 peer.their_features = Some(msg.features);
644 wire::Message::Error(msg) => {
645 let mut data_is_printable = true;
646 for b in msg.data.bytes() {
647 if b < 32 || b > 126 {
648 data_is_printable = false;
653 if data_is_printable {
654 log_debug!(self, "Got Err message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data);
656 log_debug!(self, "Got Err message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap()));
658 self.message_handler.chan_handler.handle_error(&peer.their_node_id.unwrap(), &msg);
659 if msg.channel_id == [0; 32] {
660 return Err(PeerHandleError{ no_connection_possible: true });
664 wire::Message::Ping(msg) => {
665 if msg.ponglen < 65532 {
666 let resp = msgs::Pong { byteslen: msg.ponglen };
667 encode_and_send_msg!(resp);
670 wire::Message::Pong(_msg) => {
671 peer.awaiting_pong = false;
675 wire::Message::OpenChannel(msg) => {
676 self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
678 wire::Message::AcceptChannel(msg) => {
679 self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
682 wire::Message::FundingCreated(msg) => {
683 self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg);
685 wire::Message::FundingSigned(msg) => {
686 self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg);
688 wire::Message::FundingLocked(msg) => {
689 self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg);
692 wire::Message::Shutdown(msg) => {
693 self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg);
695 wire::Message::ClosingSigned(msg) => {
696 self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg);
699 // Commitment messages:
700 wire::Message::UpdateAddHTLC(msg) => {
701 self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg);
703 wire::Message::UpdateFulfillHTLC(msg) => {
704 self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg);
706 wire::Message::UpdateFailHTLC(msg) => {
707 self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg);
709 wire::Message::UpdateFailMalformedHTLC(msg) => {
710 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg);
713 wire::Message::CommitmentSigned(msg) => {
714 self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg);
716 wire::Message::RevokeAndACK(msg) => {
717 self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg);
719 wire::Message::UpdateFee(msg) => {
720 self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg);
722 wire::Message::ChannelReestablish(msg) => {
723 self.message_handler.chan_handler.handle_channel_reestablish(&peer.their_node_id.unwrap(), &msg);
727 wire::Message::AnnouncementSignatures(msg) => {
728 self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg);
730 wire::Message::ChannelAnnouncement(msg) => {
731 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_announcement(&msg));
734 // TODO: forward msg along to all our other peers!
737 wire::Message::NodeAnnouncement(msg) => {
738 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_node_announcement(&msg));
741 // TODO: forward msg along to all our other peers!
744 wire::Message::ChannelUpdate(msg) => {
745 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_update(&msg));
748 // TODO: forward msg along to all our other peers!
753 wire::Message::Unknown(msg_type) if msg_type.is_even() => {
754 log_debug!(self, "Received unknown even message of type {}, disconnecting peer!", msg_type);
755 // Fail the channel if message is an even, unknown type as per BOLT #1.
756 return Err(PeerHandleError{ no_connection_possible: true });
758 wire::Message::Unknown(msg_type) => {
759 log_trace!(self, "Received unknown odd message of type {}, ignoring", msg_type);
768 self.do_attempt_write_data(peer_descriptor, peer);
770 peer.pending_outbound_buffer.len() > 10 // pause_read
780 /// Checks for any events generated by our handlers and processes them. Includes sending most
781 /// response messages as well as messages generated by calls to handler functions directly (eg
782 /// functions like ChannelManager::process_pending_htlc_forward or send_payment).
783 pub fn process_events(&self) {
785 // TODO: There are some DoS attacks here where you can flood someone's outbound send
786 // buffer by doing things like announcing channels on another node. We should be willing to
787 // drop optional-ish messages when send buffers get full!
789 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
790 let mut peers_lock = self.peers.lock().unwrap();
791 let peers = &mut *peers_lock;
792 for event in events_generated.drain(..) {
793 macro_rules! get_peer_for_forwarding {
794 ($node_id: expr, $handle_no_such_peer: block) => {
796 let descriptor = match peers.node_id_to_descriptor.get($node_id) {
797 Some(descriptor) => descriptor.clone(),
799 $handle_no_such_peer;
803 match peers.peers.get_mut(&descriptor) {
805 if peer.their_features.is_none() {
806 $handle_no_such_peer;
811 None => panic!("Inconsistent peers set state!"),
817 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
818 log_trace!(self, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
819 log_pubkey!(node_id),
820 log_bytes!(msg.temporary_channel_id));
821 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
822 //TODO: Drop the pending channel? (or just let it timeout, but that sucks)
824 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
825 self.do_attempt_write_data(&mut descriptor, peer);
827 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
828 log_trace!(self, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
829 log_pubkey!(node_id),
830 log_bytes!(msg.temporary_channel_id));
831 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
832 //TODO: Drop the pending channel? (or just let it timeout, but that sucks)
834 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
835 self.do_attempt_write_data(&mut descriptor, peer);
837 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
838 log_trace!(self, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
839 log_pubkey!(node_id),
840 log_bytes!(msg.temporary_channel_id),
841 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
842 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
843 //TODO: generate a DiscardFunding event indicating to the wallet that
844 //they should just throw away this funding transaction
846 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
847 self.do_attempt_write_data(&mut descriptor, peer);
849 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
850 log_trace!(self, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
851 log_pubkey!(node_id),
852 log_bytes!(msg.channel_id));
853 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
854 //TODO: generate a DiscardFunding event indicating to the wallet that
855 //they should just throw away this funding transaction
857 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
858 self.do_attempt_write_data(&mut descriptor, peer);
860 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
861 log_trace!(self, "Handling SendFundingLocked event in peer_handler for node {} for channel {}",
862 log_pubkey!(node_id),
863 log_bytes!(msg.channel_id));
864 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
865 //TODO: Do whatever we're gonna do for handling dropped messages
867 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
868 self.do_attempt_write_data(&mut descriptor, peer);
870 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
871 log_trace!(self, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
872 log_pubkey!(node_id),
873 log_bytes!(msg.channel_id));
874 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
875 //TODO: generate a DiscardFunding event indicating to the wallet that
876 //they should just throw away this funding transaction
878 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
879 self.do_attempt_write_data(&mut descriptor, peer);
881 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 } } => {
882 log_trace!(self, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
883 log_pubkey!(node_id),
884 update_add_htlcs.len(),
885 update_fulfill_htlcs.len(),
886 update_fail_htlcs.len(),
887 log_bytes!(commitment_signed.channel_id));
888 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
889 //TODO: Do whatever we're gonna do for handling dropped messages
891 for msg in update_add_htlcs {
892 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
894 for msg in update_fulfill_htlcs {
895 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
897 for msg in update_fail_htlcs {
898 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
900 for msg in update_fail_malformed_htlcs {
901 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
903 if let &Some(ref msg) = update_fee {
904 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
906 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_signed)));
907 self.do_attempt_write_data(&mut descriptor, peer);
909 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
910 log_trace!(self, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
911 log_pubkey!(node_id),
912 log_bytes!(msg.channel_id));
913 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
914 //TODO: Do whatever we're gonna do for handling dropped messages
916 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
917 self.do_attempt_write_data(&mut descriptor, peer);
919 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
920 log_trace!(self, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
921 log_pubkey!(node_id),
922 log_bytes!(msg.channel_id));
923 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
924 //TODO: Do whatever we're gonna do for handling dropped messages
926 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
927 self.do_attempt_write_data(&mut descriptor, peer);
929 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
930 log_trace!(self, "Handling Shutdown event in peer_handler for node {} for channel {}",
931 log_pubkey!(node_id),
932 log_bytes!(msg.channel_id));
933 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
934 //TODO: Do whatever we're gonna do for handling dropped messages
936 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
937 self.do_attempt_write_data(&mut descriptor, peer);
939 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
940 log_trace!(self, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
941 log_pubkey!(node_id),
942 log_bytes!(msg.channel_id));
943 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
944 //TODO: Do whatever we're gonna do for handling dropped messages
946 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
947 self.do_attempt_write_data(&mut descriptor, peer);
949 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
950 log_trace!(self, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
951 if self.message_handler.route_handler.handle_channel_announcement(msg).is_ok() && self.message_handler.route_handler.handle_channel_update(update_msg).is_ok() {
952 let encoded_msg = encode_msg!(msg);
953 let encoded_update_msg = encode_msg!(update_msg);
955 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
956 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
957 !peer.should_forward_channel(msg.contents.short_channel_id) {
960 match peer.their_node_id {
962 Some(their_node_id) => {
963 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
968 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
969 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..]));
970 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
974 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
975 log_trace!(self, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
976 if self.message_handler.route_handler.handle_channel_update(msg).is_ok() {
977 let encoded_msg = encode_msg!(msg);
979 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
980 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
981 !peer.should_forward_channel(msg.contents.short_channel_id) {
984 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
985 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
989 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
990 self.message_handler.route_handler.handle_htlc_fail_channel_update(update);
992 MessageSendEvent::HandleError { ref node_id, ref action } => {
994 msgs::ErrorAction::DisconnectPeer { ref msg } => {
995 if let Some(mut descriptor) = peers.node_id_to_descriptor.remove(node_id) {
996 peers.peers_needing_send.remove(&descriptor);
997 if let Some(mut peer) = peers.peers.remove(&descriptor) {
998 if let Some(ref msg) = *msg {
999 log_trace!(self, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1000 log_pubkey!(node_id),
1002 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1003 // This isn't guaranteed to work, but if there is enough free
1004 // room in the send buffer, put the error message there...
1005 self.do_attempt_write_data(&mut descriptor, &mut peer);
1007 log_trace!(self, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1010 descriptor.disconnect_socket();
1011 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1014 msgs::ErrorAction::IgnoreError => {},
1015 msgs::ErrorAction::SendErrorMessage { ref msg } => {
1016 log_trace!(self, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1017 log_pubkey!(node_id),
1019 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
1020 //TODO: Do whatever we're gonna do for handling dropped messages
1022 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1023 self.do_attempt_write_data(&mut descriptor, peer);
1030 for mut descriptor in peers.peers_needing_send.drain() {
1031 match peers.peers.get_mut(&descriptor) {
1032 Some(peer) => self.do_attempt_write_data(&mut descriptor, peer),
1033 None => panic!("Inconsistent peers set state!"),
1039 /// Indicates that the given socket descriptor's connection is now closed.
1041 /// This must only be called if the socket has been disconnected by the peer or your own
1042 /// decision to disconnect it and must NOT be called in any case where other parts of this
1043 /// library (eg PeerHandleError, explicit disconnect_socket calls) instruct you to disconnect
1046 /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
1047 pub fn socket_disconnected(&self, descriptor: &Descriptor) {
1048 self.disconnect_event_internal(descriptor, false);
1051 fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1052 let mut peers = self.peers.lock().unwrap();
1053 peers.peers_needing_send.remove(descriptor);
1054 let peer_option = peers.peers.remove(descriptor);
1056 None => panic!("Descriptor for disconnect_event is not already known to PeerManager"),
1058 match peer.their_node_id {
1060 peers.node_id_to_descriptor.remove(&node_id);
1061 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1069 /// This function should be called roughly once every 30 seconds.
1070 /// It will send pings to each peer and disconnect those which did not respond to the last round of pings.
1072 /// Will most likely call send_data on all of the registered descriptors, thus, be very careful with reentrancy issues!
1073 pub fn timer_tick_occured(&self) {
1074 let mut peers_lock = self.peers.lock().unwrap();
1076 let peers = &mut *peers_lock;
1077 let peers_needing_send = &mut peers.peers_needing_send;
1078 let node_id_to_descriptor = &mut peers.node_id_to_descriptor;
1079 let peers = &mut peers.peers;
1080 let mut descriptors_needing_disconnect = Vec::new();
1082 peers.retain(|descriptor, peer| {
1083 if peer.awaiting_pong {
1084 peers_needing_send.remove(descriptor);
1085 descriptors_needing_disconnect.push(descriptor.clone());
1086 match peer.their_node_id {
1088 log_trace!(self, "Disconnecting peer with id {} due to ping timeout", node_id);
1089 node_id_to_descriptor.remove(&node_id);
1090 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1093 // This can't actually happen as we should have hit
1094 // is_ready_for_encryption() previously on this same peer.
1101 if !peer.channel_encryptor.is_ready_for_encryption() {
1102 // The peer needs to complete its handshake before we can exchange messages
1106 let ping = msgs::Ping {
1110 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(&ping)));
1112 let mut descriptor_clone = descriptor.clone();
1113 self.do_attempt_write_data(&mut descriptor_clone, peer);
1115 peer.awaiting_pong = true;
1119 for mut descriptor in descriptors_needing_disconnect.drain(..) {
1120 descriptor.disconnect_socket();
1128 use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor};
1131 use util::test_utils;
1132 use util::logger::Logger;
1134 use secp256k1::Secp256k1;
1135 use secp256k1::key::{SecretKey, PublicKey};
1137 use rand::{thread_rng, Rng};
1140 use std::sync::{Arc, Mutex};
1143 struct FileDescriptor {
1145 outbound_data: Arc<Mutex<Vec<u8>>>,
1147 impl PartialEq for FileDescriptor {
1148 fn eq(&self, other: &Self) -> bool {
1152 impl Eq for FileDescriptor { }
1153 impl std::hash::Hash for FileDescriptor {
1154 fn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {
1155 self.fd.hash(hasher)
1159 impl SocketDescriptor for FileDescriptor {
1160 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
1161 self.outbound_data.lock().unwrap().extend_from_slice(data);
1165 fn disconnect_socket(&mut self) {}
1168 fn create_chan_handlers(peer_count: usize) -> Vec<test_utils::TestChannelMessageHandler> {
1169 let mut chan_handlers = Vec::new();
1170 for _ in 0..peer_count {
1171 let chan_handler = test_utils::TestChannelMessageHandler::new();
1172 chan_handlers.push(chan_handler);
1178 fn create_network<'a>(peer_count: usize, chan_handlers: &'a Vec<test_utils::TestChannelMessageHandler>) -> Vec<PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler>> {
1179 let mut peers = Vec::new();
1180 let mut rng = thread_rng();
1181 let logger : Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1182 let mut ephemeral_bytes = [0; 32];
1183 rng.fill_bytes(&mut ephemeral_bytes);
1185 for i in 0..peer_count {
1186 let router = test_utils::TestRoutingMessageHandler::new();
1188 let mut key_slice = [0;32];
1189 rng.fill_bytes(&mut key_slice);
1190 SecretKey::from_slice(&key_slice).unwrap()
1192 let msg_handler = MessageHandler { chan_handler: &chan_handlers[i], route_handler: Arc::new(router) };
1193 let peer = PeerManager::new(msg_handler, node_id, &ephemeral_bytes, Arc::clone(&logger));
1200 fn establish_connection<'a>(peer_a: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler>, peer_b: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler>) {
1201 let secp_ctx = Secp256k1::new();
1202 let a_id = PublicKey::from_secret_key(&secp_ctx, &peer_a.our_node_secret);
1203 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1204 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1205 let initial_data = peer_b.new_outbound_connection(a_id, fd_b.clone()).unwrap();
1206 peer_a.new_inbound_connection(fd_a.clone()).unwrap();
1207 assert_eq!(peer_a.read_event(&mut fd_a, initial_data).unwrap(), false);
1208 assert_eq!(peer_b.read_event(&mut fd_b, fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1209 assert_eq!(peer_a.read_event(&mut fd_a, fd_b.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1213 fn test_disconnect_peer() {
1214 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
1215 // push a DisconnectPeer event to remove the node flagged by id
1216 let chan_handlers = create_chan_handlers(2);
1217 let chan_handler = test_utils::TestChannelMessageHandler::new();
1218 let mut peers = create_network(2, &chan_handlers);
1219 establish_connection(&peers[0], &peers[1]);
1220 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1222 let secp_ctx = Secp256k1::new();
1223 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
1225 chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
1227 action: msgs::ErrorAction::DisconnectPeer { msg: None },
1229 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
1230 peers[0].message_handler.chan_handler = &chan_handler;
1232 peers[0].process_events();
1233 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
1236 fn test_timer_tick_occured(){
1237 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
1238 let chan_handlers = create_chan_handlers(2);
1239 let peers = create_network(2, &chan_handlers);
1240 establish_connection(&peers[0], &peers[1]);
1241 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1243 // peers[0] awaiting_pong is set to true, but the Peer is still connected
1244 peers[0].timer_tick_occured();
1245 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1247 // Since timer_tick_occured() is called again when awaiting_pong is true, all Peers are disconnected
1248 peers[0].timer_tick_occured();
1249 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);