Skip to content

Commit 0e2e7d1

Browse files
committed
Merge bitcoin/bitcoin#29867: index: race fix, lock cs_main while 'm_synced' is subject to change
65951e0 index: race fix, lock cs_main while 'm_synced' is subject to change (Ryan Ofsky) Pull request description: Fixes #29831 and #29863. Thanks to Marko for the detailed description of the issue. The race occurs because a block could be connected and its event signaled in-between reading the 'next block' and setting `m_synced` during the index initial synchronization. This is because `cs_main` is not locked through the process of determining the final index sync state. To address the issue, the `m_synced` flag set has been moved under `cs_main` guard. ACKs for top commit: fjahr: Code review ACK 65951e0 achow101: ACK 65951e0 ryanofsky: Code review ACK 65951e0 Tree-SHA512: 77286e22de164a27939d2681b7baa6552eb75e99c541d3b9631f4340d7dd01742667c86899b6987fd2d97799d959e0a913a7749b2b69d9e50505128cd3ae0e69
2 parents 2066295 + 65951e0 commit 0e2e7d1

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

src/index/base.cpp

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -160,12 +160,24 @@ void BaseIndex::Sync()
160160
}
161161

162162
const CBlockIndex* pindex_next = WITH_LOCK(cs_main, return NextSyncBlock(pindex, m_chainstate->m_chain));
163+
// If pindex_next is null, it means pindex is the chain tip, so
164+
// commit data indexed so far.
163165
if (!pindex_next) {
164166
SetBestBlockIndex(pindex);
165167
// No need to handle errors in Commit. See rationale above.
166168
Commit();
167-
m_synced = true;
168-
break;
169+
170+
// If pindex is still the chain tip after committing, exit the
171+
// sync loop. It is important for cs_main to be locked while
172+
// setting m_synced = true, otherwise a new block could be
173+
// attached while m_synced is still false, and it would not be
174+
// indexed.
175+
LOCK(::cs_main);
176+
pindex_next = NextSyncBlock(pindex, m_chainstate->m_chain);
177+
if (!pindex_next) {
178+
m_synced = true;
179+
break;
180+
}
169181
}
170182
if (pindex_next->pprev != pindex && !Rewind(pindex, pindex_next->pprev)) {
171183
FatalErrorf("%s: Failed to rewind index %s to a previous chain tip", __func__, GetName());

0 commit comments

Comments
 (0)