Skip to content

Commit d831e71

Browse files
committed
[validation] RewindBlockIndex no longer needed
Instead of rewinding blocks, we request that the user restarts with -reindex
1 parent 92cf3a2 commit d831e71

File tree

4 files changed

+43
-165
lines changed

4 files changed

+43
-165
lines changed

src/init.cpp

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1698,29 +1698,17 @@ bool AppInitMain(const util::Ref& context, NodeContext& node, interfaces::BlockA
16981698
break;
16991699
}
17001700

1701-
bool failed_rewind{false};
1702-
// Can't hold cs_main while calling RewindBlockIndex, so retrieve the relevant
1703-
// chainstates beforehand.
1704-
for (CChainState* chainstate : WITH_LOCK(::cs_main, return chainman.GetAll())) {
1705-
if (!fReset) {
1706-
// Note that RewindBlockIndex MUST run even if we're about to -reindex-chainstate.
1707-
// It both disconnects blocks based on the chainstate, and drops block data in
1708-
// BlockIndex() based on lack of available witness data.
1709-
uiInterface.InitMessage(_("Rewinding blocks...").translated);
1710-
if (!chainstate->RewindBlockIndex(chainparams)) {
1711-
strLoadError = _(
1712-
"Unable to rewind the database to a pre-fork state. "
1713-
"You will need to redownload the blockchain");
1714-
failed_rewind = true;
1715-
break; // out of the per-chainstate loop
1716-
}
1701+
if (!fReset) {
1702+
LOCK(cs_main);
1703+
auto chainstates{chainman.GetAll()};
1704+
if (std::any_of(chainstates.begin(), chainstates.end(),
1705+
[&chainparams](const CChainState* cs) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return cs->NeedsRedownload(chainparams); })) {
1706+
strLoadError = strprintf(_("Witness data for blocks after height %d requires validation. Please restart with -reindex."),
1707+
chainparams.GetConsensus().SegwitHeight);
1708+
break;
17171709
}
17181710
}
17191711

1720-
if (failed_rewind) {
1721-
break; // out of the chainstate activation do-while
1722-
}
1723-
17241712
bool failed_verification = false;
17251713

17261714
try {

src/validation.cpp

Lines changed: 10 additions & 130 deletions
Original file line numberDiff line numberDiff line change
@@ -4431,143 +4431,23 @@ bool CChainState::ReplayBlocks(const CChainParams& params)
44314431
return true;
44324432
}
44334433

4434-
//! Helper for CChainState::RewindBlockIndex
4435-
void CChainState::EraseBlockData(CBlockIndex* index)
4434+
bool CChainState::NeedsRedownload(const CChainParams& params) const
44364435
{
44374436
AssertLockHeld(cs_main);
4438-
assert(!m_chain.Contains(index)); // Make sure this block isn't active
4439-
4440-
// Reduce validity
4441-
index->nStatus = std::min<unsigned int>(index->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (index->nStatus & ~BLOCK_VALID_MASK);
4442-
// Remove have-data flags.
4443-
index->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
4444-
// Remove storage location.
4445-
index->nFile = 0;
4446-
index->nDataPos = 0;
4447-
index->nUndoPos = 0;
4448-
// Remove various other things
4449-
index->nTx = 0;
4450-
index->nChainTx = 0;
4451-
index->nSequenceId = 0;
4452-
// Make sure it gets written.
4453-
setDirtyBlockIndex.insert(index);
4454-
// Update indexes
4455-
setBlockIndexCandidates.erase(index);
4456-
auto ret = m_blockman.m_blocks_unlinked.equal_range(index->pprev);
4457-
while (ret.first != ret.second) {
4458-
if (ret.first->second == index) {
4459-
m_blockman.m_blocks_unlinked.erase(ret.first++);
4460-
} else {
4461-
++ret.first;
4462-
}
4463-
}
4464-
// Mark parent as eligible for main chain again
4465-
if (index->pprev && index->pprev->IsValid(BLOCK_VALID_TRANSACTIONS) && index->pprev->HaveTxsDownloaded()) {
4466-
setBlockIndexCandidates.insert(index->pprev);
4467-
}
4468-
}
4469-
4470-
bool CChainState::RewindBlockIndex(const CChainParams& params)
4471-
{
4472-
// Note that during -reindex-chainstate we are called with an empty m_chain!
44734437

4474-
// First erase all post-segwit blocks without witness not in the main chain,
4475-
// as this can we done without costly DisconnectTip calls. Active
4476-
// blocks will be dealt with below (releasing cs_main in between).
4477-
{
4478-
LOCK(cs_main);
4479-
for (const auto& entry : m_blockman.m_block_index) {
4480-
if (IsWitnessEnabled(entry.second->pprev, params.GetConsensus()) && !(entry.second->nStatus & BLOCK_OPT_WITNESS) && !m_chain.Contains(entry.second)) {
4481-
EraseBlockData(entry.second);
4482-
}
4483-
}
4484-
}
4438+
// At and above params.SegwitHeight, segwit consensus rules must be validated
4439+
CBlockIndex* block{m_chain.Tip()};
4440+
const int segwit_height{params.GetConsensus().SegwitHeight};
44854441

4486-
// Find what height we need to reorganize to.
4487-
CBlockIndex *tip;
4488-
int nHeight = 1;
4489-
{
4490-
LOCK(cs_main);
4491-
while (nHeight <= m_chain.Height()) {
4492-
// Although SCRIPT_VERIFY_WITNESS is now generally enforced on all
4493-
// blocks in ConnectBlock, we don't need to go back and
4494-
// re-download/re-verify blocks from before segwit actually activated.
4495-
if (IsWitnessEnabled(m_chain[nHeight - 1], params.GetConsensus()) && !(m_chain[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
4496-
break;
4497-
}
4498-
nHeight++;
4499-
}
4500-
4501-
tip = m_chain.Tip();
4502-
}
4503-
// nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
4504-
4505-
BlockValidationState state;
4506-
// Loop until the tip is below nHeight, or we reach a pruned block.
4507-
while (!ShutdownRequested()) {
4508-
{
4509-
LOCK(cs_main);
4510-
LOCK(m_mempool.cs);
4511-
// Make sure nothing changed from under us (this won't happen because RewindBlockIndex runs before importing/network are active)
4512-
assert(tip == m_chain.Tip());
4513-
if (tip == nullptr || tip->nHeight < nHeight) break;
4514-
if (fPruneMode && !(tip->nStatus & BLOCK_HAVE_DATA)) {
4515-
// If pruning, don't try rewinding past the HAVE_DATA point;
4516-
// since older blocks can't be served anyway, there's
4517-
// no need to walk further, and trying to DisconnectTip()
4518-
// will fail (and require a needless reindex/redownload
4519-
// of the blockchain).
4520-
break;
4521-
}
4522-
4523-
// Disconnect block
4524-
if (!DisconnectTip(state, params, nullptr)) {
4525-
return error("RewindBlockIndex: unable to disconnect block at height %i (%s)", tip->nHeight, state.ToString());
4526-
}
4527-
4528-
// Reduce validity flag and have-data flags.
4529-
// We do this after actual disconnecting, otherwise we'll end up writing the lack of data
4530-
// to disk before writing the chainstate, resulting in a failure to continue if interrupted.
4531-
// Note: If we encounter an insufficiently validated block that
4532-
// is on m_chain, it must be because we are a pruning node, and
4533-
// this block or some successor doesn't HAVE_DATA, so we were unable to
4534-
// rewind all the way. Blocks remaining on m_chain at this point
4535-
// must not have their validity reduced.
4536-
EraseBlockData(tip);
4537-
4538-
tip = tip->pprev;
4539-
}
4540-
// Make sure the queue of validation callbacks doesn't grow unboundedly.
4541-
LimitValidationInterfaceQueue();
4542-
4543-
// Occasionally flush state to disk.
4544-
if (!FlushStateToDisk(params, state, FlushStateMode::PERIODIC)) {
4545-
LogPrintf("RewindBlockIndex: unable to flush state to disk (%s)\n", state.ToString());
4546-
return false;
4547-
}
4548-
}
4549-
4550-
{
4551-
LOCK(cs_main);
4552-
if (m_chain.Tip() != nullptr) {
4553-
// We can't prune block index candidates based on our tip if we have
4554-
// no tip due to m_chain being empty!
4555-
PruneBlockIndexCandidates();
4556-
4557-
CheckBlockIndex(params.GetConsensus());
4558-
4559-
// FlushStateToDisk can possibly read ::ChainActive(). Be conservative
4560-
// and skip it here, we're about to -reindex-chainstate anyway, so
4561-
// it'll get called a bunch real soon.
4562-
BlockValidationState state;
4563-
if (!FlushStateToDisk(params, state, FlushStateMode::ALWAYS)) {
4564-
LogPrintf("RewindBlockIndex: unable to flush state to disk (%s)\n", state.ToString());
4565-
return false;
4566-
}
4442+
while (block != nullptr && block->nHeight >= segwit_height) {
4443+
if (!(block->nStatus & BLOCK_OPT_WITNESS)) {
4444+
// block is insufficiently validated for a segwit client
4445+
return true;
45674446
}
4447+
block = block->pprev;
45684448
}
45694449

4570-
return true;
4450+
return false;
45714451
}
45724452

45734453
void CChainState::UnloadBlockIndex() {

src/validation.h

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -722,7 +722,9 @@ class CChainState
722722

723723
/** Replay blocks that aren't fully applied to the database. */
724724
bool ReplayBlocks(const CChainParams& params);
725-
bool RewindBlockIndex(const CChainParams& params) LOCKS_EXCLUDED(cs_main);
725+
726+
/** Whether the chain state needs to be redownloaded due to lack of witness data */
727+
[[nodiscard]] bool NeedsRedownload(const CChainParams& params) const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
726728
/** Ensures we have a genesis block in the block tree, possibly writing one to disk. */
727729
bool LoadGenesisBlock(const CChainParams& chainparams);
728730

@@ -769,9 +771,6 @@ class CChainState
769771

770772
bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
771773

772-
//! Mark a block as not having block data
773-
void EraseBlockData(CBlockIndex* index) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
774-
775774
void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
776775
void InvalidChainFound(CBlockIndex* pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
777776

test/functional/p2p_segwit.py

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1956,22 +1956,33 @@ def test_non_standard_witness(self):
19561956
def test_upgrade_after_activation(self):
19571957
"""Test the behavior of starting up a segwit-aware node after the softfork has activated."""
19581958

1959-
self.restart_node(2, extra_args=["-segwitheight={}".format(SEGWIT_HEIGHT)])
1959+
# All nodes are caught up and node 2 is a pre-segwit node that will soon upgrade.
1960+
for n in range(2):
1961+
assert_equal(self.nodes[n].getblockcount(), self.nodes[2].getblockcount())
1962+
assert softfork_active(self.nodes[n], "segwit")
1963+
assert SEGWIT_HEIGHT < self.nodes[2].getblockcount()
1964+
assert 'segwit' not in self.nodes[2].getblockchaininfo()['softforks']
1965+
1966+
# Restarting node 2 should result in a shutdown because the blockchain consists of
1967+
# insufficiently validated blocks per segwit consensus rules.
1968+
self.stop_node(2)
1969+
with self.nodes[2].assert_debug_log(expected_msgs=[
1970+
f"Witness data for blocks after height {SEGWIT_HEIGHT} requires validation. Please restart with -reindex."], timeout=10):
1971+
self.nodes[2].start([f"-segwitheight={SEGWIT_HEIGHT}"])
1972+
1973+
# As directed, the user restarts the node with -reindex
1974+
self.start_node(2, extra_args=["-reindex", f"-segwitheight={SEGWIT_HEIGHT}"])
1975+
1976+
# With the segwit consensus rules, the node is able to validate only up to SEGWIT_HEIGHT - 1
1977+
assert_equal(self.nodes[2].getblockcount(), SEGWIT_HEIGHT - 1)
19601978
self.connect_nodes(0, 2)
19611979

19621980
# We reconnect more than 100 blocks, give it plenty of time
1981+
# sync_blocks() also verifies the best block hash is the same for all nodes
19631982
self.sync_blocks(timeout=240)
19641983

1965-
# Make sure that this peer thinks segwit has activated.
1966-
assert softfork_active(self.nodes[2], 'segwit')
1967-
1968-
# Make sure this peer's blocks match those of node0.
1969-
height = self.nodes[2].getblockcount()
1970-
while height >= 0:
1971-
block_hash = self.nodes[2].getblockhash(height)
1972-
assert_equal(block_hash, self.nodes[0].getblockhash(height))
1973-
assert_equal(self.nodes[0].getblock(block_hash), self.nodes[2].getblock(block_hash))
1974-
height -= 1
1984+
# The upgraded node should now have segwit activated
1985+
assert softfork_active(self.nodes[2], "segwit")
19751986

19761987
@subtest # type: ignore
19771988
def test_witness_sigops(self):

0 commit comments

Comments
 (0)