From c65fa5ce5926f5e575acf03fbce4809d0d8f3a8f Mon Sep 17 00:00:00 2001 From: Jeff Bencin Date: Thu, 9 May 2024 10:44:44 -0400 Subject: [PATCH] fix: Skip `PeerNetwork::bind()` if re-using object --- stackslib/src/net/p2p.rs | 18 ++++++++++++++++++ testnet/stacks-node/src/nakamoto_node/peer.rs | 9 +++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/stackslib/src/net/p2p.rs b/stackslib/src/net/p2p.rs index 4e358128f..26f85d69e 100644 --- a/stackslib/src/net/p2p.rs +++ b/stackslib/src/net/p2p.rs @@ -646,6 +646,24 @@ impl PeerNetwork { Ok(()) } + /// Call `bind()` only if not already bound + /// Returns: + /// - `Ok(true)` if `bind()` call was successful + /// - `Ok(false)` if `bind()` call was skipped + /// - `Err()` if `bind()`` failed + #[cfg_attr(test, mutants::skip)] + pub fn try_bind( + &mut self, + my_addr: &SocketAddr, + http_addr: &SocketAddr, + ) -> Result { + if self.network.is_some() { + // Already bound + return Ok(false); + } + self.bind(my_addr, http_addr).map(|()| true) + } + /// Get bound neighbor key. This is how this PeerNetwork appears to other nodes. pub fn bound_neighbor_key(&self) -> &NeighborKey { &self.bind_nk diff --git a/testnet/stacks-node/src/nakamoto_node/peer.rs b/testnet/stacks-node/src/nakamoto_node/peer.rs index eeb6789d3..dc060e06b 100644 --- a/testnet/stacks-node/src/nakamoto_node/peer.rs +++ b/testnet/stacks-node/src/nakamoto_node/peer.rs @@ -182,8 +182,13 @@ impl PeerThread { .parse() .unwrap_or_else(|_| panic!("Failed to parse socket: {}", &config.node.rpc_bind)); - net.bind(&p2p_sock, &rpc_sock) - .expect("BUG: PeerNetwork could not bind or is already bound"); + let did_bind = net + .try_bind(&p2p_sock, &rpc_sock) + .expect("BUG: PeerNetwork could not bind"); + + if !did_bind { + info!("`PeerNetwork::bind()` skipped, already bound"); + } let poll_timeout = cmp::min(5000, config.miner.first_attempt_time_ms / 2);