Skip to content

Commit 359680b

Browse files
committed
net: move cs_main up in FetchBlock to fix rpc assert crash
1. FetchBlock runs in a http worker thread. It acquires a PeerRef, locks cs_main, then may later call BlockRequested which asserts that CNodeState exists for the peer. 2. FinalizeNode may run in either the bitcoind or b-net threads. It locks cs_main, fetches a PeerRef from RemovePeer, fetches a CNodeState, and later removes it from m_node_states. Because of the lock placement in FetchBlock, the http worker thread in 1) can acquire a valid PeerRef and block while the b-net thread in 2) is cleaning up the peer in FinalizeNode. When the worker thread later acquires cs_main, it may crash in BlockRequested since no CNodeState exists. Fix this by acquiring the lock earlier in FetchBlock. The lock can be replaced with a net-specific lock when the remaining CNodeState fields are moved to Peer.
1 parent bcbf5ba commit 359680b

1 file changed

Lines changed: 6 additions & 2 deletions

File tree

‎src/net_processing.cpp‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1977,15 +1977,19 @@ util::Expected<void, std::string> PeerManagerImpl::FetchBlock(NodeId peer_id, co
19771977
{
19781978
if (m_chainman.m_blockman.LoadingBlocks()) return util::Unexpected{"Loading blocks ..."};
19791979

1980+
// The lock must be taken here before fetching Peer so another thread does
1981+
// not delete the CNodeState from under the current thread, causing an
1982+
// assertion failure in BlockRequested. This lock can be replaced with a
1983+
// net-specific lock when more of CNodeState is moved into Peer.
1984+
LOCK(cs_main);
1985+
19801986
// Ensure this peer exists and hasn't been disconnected
19811987
PeerRef peer = GetPeerRef(peer_id);
19821988
if (peer == nullptr) return util::Unexpected{"Peer does not exist"};
19831989

19841990
// Ignore pre-segwit peers
19851991
if (!CanServeWitnesses(*peer)) return util::Unexpected{"Pre-SegWit peer"};
19861992

1987-
LOCK(cs_main);
1988-
19891993
// Forget about all prior requests
19901994
RemoveBlockRequest(block_index.GetBlockHash(), std::nullopt);
19911995

0 commit comments

Comments
 (0)