From: Chiru <48340051+ch1ru@users.noreply.github.com> Date: Tue, 1 Nov 2022 17:29:33 +0000 (+0000) Subject: Add `disconnectpeer` subcommand X-Git-Url: http://git.bitcoin.ninja/?a=commitdiff_plain;h=d868dd44678e49dcc5f1ac6b3b9f34bed70d81ac;p=ldk-sample Add `disconnectpeer` subcommand Disconnect peer with `disconnectpeer `. Checks all channels are closed before disconnecting. --- 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,