From d868dd44678e49dcc5f1ac6b3b9f34bed70d81ac Mon Sep 17 00:00:00 2001 From: Chiru <48340051+ch1ru@users.noreply.github.com> Date: Tue, 1 Nov 2022 17:29:33 +0000 Subject: [PATCH] Add `disconnectpeer` subcommand Disconnect peer with `disconnectpeer `. Checks all channels are closed before disconnecting. --- src/cli.rs | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/src/cli.rs b/src/cli.rs index 99a4378..64ee04d 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -357,6 +357,32 @@ pub(crate) async fn poll_for_user_input( println!("SUCCESS: connected to peer {}", pubkey); } } + "disconnectpeer" => { + let peer_pubkey = words.next(); + if peer_pubkey.is_none() { + println!("ERROR: disconnectpeer requires peer public key: `disconnectpeer `"); + continue; + } + + let peer_pubkey = + match bitcoin::secp256k1::PublicKey::from_str(peer_pubkey.unwrap()) { + Ok(pubkey) => pubkey, + Err(e) => { + println!("ERROR: {}", e.to_string()); + continue; + } + }; + + if do_disconnect_peer( + peer_pubkey, + peer_manager.clone(), + channel_manager.clone(), + ) + .is_ok() + { + println!("SUCCESS: disconnected from peer {}", peer_pubkey); + } + } "listchannels" => list_channels(&channel_manager, &network_graph), "listpayments" => { list_payments(inbound_payments.clone(), outbound_payments.clone()) @@ -530,6 +556,7 @@ fn help() { println!(" listchannels"); println!("\n Peers:"); println!(" connectpeer pubkey@host:port"); + println!(" disconnectpeer "); println!(" listpeers"); println!("\n Payments:"); println!(" sendpayment "); @@ -688,6 +715,29 @@ pub(crate) async fn do_connect_peer( } } +fn do_disconnect_peer( + pubkey: bitcoin::secp256k1::PublicKey, peer_manager: Arc, + channel_manager: Arc, +) -> Result<(), ()> { + //check for open channels with peer + for channel in channel_manager.list_channels() { + if channel.counterparty.node_id == pubkey { + println!("Error: Node has an active channel with this peer, close any channels first"); + return Err(()); + } + } + + //check the pubkey matches a valid connected peer + let peers = peer_manager.get_peer_node_ids(); + if !peers.contains(&pubkey) { + println!("Error: Could not find peer {}", pubkey); + return Err(()); + } + + peer_manager.disconnect_by_node_id(pubkey, false); + Ok(()) +} + fn open_channel( peer_pubkey: PublicKey, channel_amt_sat: u64, announced_channel: bool, channel_manager: Arc, -- 2.39.5