diff --git a/src/net_processing.cpp b/src/net_processing.cpp index 17e078615b0..c01f93c21ae 100644 --- a/src/net_processing.cpp +++ b/src/net_processing.cpp @@ -1986,6 +1986,12 @@ util::Expected PeerManagerImpl::FetchBlock(NodeId peer_id, co { if (m_chainman.m_blockman.LoadingBlocks()) return util::Unexpected{"Loading blocks ..."}; + // The lock must be taken here before fetching Peer so another thread does + // not delete the CNodeState from under the current thread, causing an + // assertion failure in BlockRequested. This lock can be replaced with a + // net-specific lock when more of CNodeState is moved into Peer. + LOCK(cs_main); + // Ensure this peer exists and hasn't been disconnected PeerRef peer = GetPeerRef(peer_id); if (peer == nullptr) return util::Unexpected{"Peer does not exist"}; @@ -1993,8 +1999,6 @@ util::Expected PeerManagerImpl::FetchBlock(NodeId peer_id, co // Ignore pre-segwit peers if (!CanServeWitnesses(*peer)) return util::Unexpected{"Pre-SegWit peer"}; - LOCK(cs_main); - // Forget about all prior requests RemoveBlockRequest(block_index.GetBlockHash(), std::nullopt);