+#[cfg(test)]
+mod tests {
+ use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor};
+ use ln::msgs;
+ use util::events;
+ use util::test_utils;
+ use util::logger::Logger;
+
+ use secp256k1::Secp256k1;
+ use secp256k1::key::{SecretKey, PublicKey};
+
+ use rand::{thread_rng, Rng};
+
+ use std::sync::{Arc};
+
+ #[derive(PartialEq, Eq, Clone, Hash)]
+ struct FileDescriptor {
+ fd: u16,
+ }
+
+ impl SocketDescriptor for FileDescriptor {
+ fn send_data(&mut self, data: &Vec<u8>, write_offset: usize, _resume_read: bool) -> usize {
+ assert!(write_offset < data.len());
+ data.len() - write_offset
+ }
+
+ fn disconnect_socket(&mut self) {}
+ }
+
+ fn create_network(peer_count: usize) -> Vec<PeerManager<FileDescriptor>> {
+ let mut peers = Vec::new();
+ let mut rng = thread_rng();
+ let logger : Arc<Logger> = Arc::new(test_utils::TestLogger::new());
+
+ for _ in 0..peer_count {
+ let chan_handler = test_utils::TestChannelMessageHandler::new();
+ let router = test_utils::TestRoutingMessageHandler::new();
+ let node_id = {
+ let mut key_slice = [0;32];
+ rng.fill_bytes(&mut key_slice);
+ SecretKey::from_slice(&key_slice).unwrap()
+ };
+ let msg_handler = MessageHandler { chan_handler: Arc::new(chan_handler), route_handler: Arc::new(router) };
+ let peer = PeerManager::new(msg_handler, node_id, Arc::clone(&logger));
+ peers.push(peer);
+ }
+
+ peers
+ }
+
+ fn establish_connection(peer_a: &PeerManager<FileDescriptor>, peer_b: &PeerManager<FileDescriptor>) {
+ let secp_ctx = Secp256k1::new();
+ let their_id = PublicKey::from_secret_key(&secp_ctx, &peer_b.our_node_secret);
+ let fd = FileDescriptor { fd: 1};
+ peer_a.new_inbound_connection(fd.clone()).unwrap();
+ peer_a.peers.lock().unwrap().node_id_to_descriptor.insert(their_id, fd.clone());
+ }
+
+ #[test]
+ fn test_disconnect_peer() {
+ // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
+ // push a DisconnectPeer event to remove the node flagged by id
+ let mut peers = create_network(2);
+ establish_connection(&peers[0], &peers[1]);
+ assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
+
+ let secp_ctx = Secp256k1::new();
+ let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
+
+ let chan_handler = test_utils::TestChannelMessageHandler::new();
+ chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
+ node_id: their_id,
+ action: Some(msgs::ErrorAction::DisconnectPeer { msg: None }),
+ });
+ assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
+ peers[0].message_handler.chan_handler = Arc::new(chan_handler);
+
+ peers[0].process_events();
+ assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);