Skip to content

Commit eb6cc05

Browse files
committed
index: Commit DB_MUHASH and DB_BEST_BLOCK to disk together
If these are written to disk at different times, unclean shutdowns can lead to index corruption.
1 parent 48a90c6 commit eb6cc05

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

src/index/coinstatsindex.cpp

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -228,10 +228,9 @@ bool CoinStatsIndex::WriteBlock(const CBlock& block, const CBlockIndex* pindex)
228228
m_muhash.Finalize(out);
229229
value.second.muhash = out;
230230

231-
CDBBatch batch(*m_db);
232-
batch.Write(DBHeightKey(pindex->nHeight), value);
233-
batch.Write(DB_MUHASH, m_muhash);
234-
return m_db->WriteBatch(batch);
231+
// Intentionally do not update DB_MUHASH here so it stays in sync with
232+
// DB_BEST_BLOCK, and the index is not corrupted if there is an unclean shutdown.
233+
return m_db->Write(DBHeightKey(pindex->nHeight), value);
235234
}
236235

237236
static bool CopyHeightIndexToHashIndex(CDBIterator& db_it, CDBBatch& batch,
@@ -388,6 +387,14 @@ bool CoinStatsIndex::Init()
388387
return true;
389388
}
390389

390+
bool CoinStatsIndex::CommitInternal(CDBBatch& batch)
391+
{
392+
// DB_MUHASH should always be committed in a batch together with DB_BEST_BLOCK
393+
// to prevent an inconsistent state of the DB.
394+
batch.Write(DB_MUHASH, m_muhash);
395+
return BaseIndex::CommitInternal(batch);
396+
}
397+
391398
// Reverse a single block as part of a reorg
392399
bool CoinStatsIndex::ReverseBlock(const CBlock& block, const CBlockIndex* pindex)
393400
{
@@ -489,5 +496,5 @@ bool CoinStatsIndex::ReverseBlock(const CBlock& block, const CBlockIndex* pindex
489496
Assert(m_total_unspendables_scripts == read_out.second.total_unspendables_scripts);
490497
Assert(m_total_unspendables_unclaimed_rewards == read_out.second.total_unspendables_unclaimed_rewards);
491498

492-
return m_db->Write(DB_MUHASH, m_muhash);
499+
return true;
493500
}

src/index/coinstatsindex.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ class CoinStatsIndex final : public BaseIndex
3939
protected:
4040
bool Init() override;
4141

42+
bool CommitInternal(CDBBatch& batch) override;
43+
4244
bool WriteBlock(const CBlock& block, const CBlockIndex* pindex) override;
4345

4446
bool Rewind(const CBlockIndex* current_tip, const CBlockIndex* new_tip) override;

0 commit comments

Comments
 (0)