Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/evo/creditpool.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ std::optional<CCreditPoolDiff> GetCreditPoolDiffForBlock(CCreditPoolManager& cpo
}
return creditPoolDiff;
} catch (const EvoDbInconsistencyError& e) {
// Local EvoDB corruption (the node is already aborting): fail with
// Local EvoDB inconsistency (missing or mismatched state): fail with
// M_ERROR so the block is not marked invalid.
state.Error(e.what());
return std::nullopt;
Expand Down
9 changes: 9 additions & 0 deletions src/evo/evodb.h
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,15 @@ class EvoDbInconsistencyError : public std::runtime_error
using std::runtime_error::runtime_error;
};

/** Thrown when block-derived state that EvoDB should hold for a block is missing. Like a mismatch it
* is never evidence about the block, but it does not abort the node: an RPC may ask about a block
* whose state was never stored. */
class EvoDbMissingStateError : public EvoDbInconsistencyError
{
public:
using EvoDbInconsistencyError::EvoDbInconsistencyError;
};

class CEvoDB;

class CEvoDBScopedCommitter
Expand Down
18 changes: 13 additions & 5 deletions src/evo/mnhftx.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ std::optional<CMNHFManager::Signals> CMNHFManager::ProcessBlock(const CBlock& bl
AddToCache(signals, pindex);
return signals;
} catch (const EvoDbInconsistencyError& e) {
// Local EvoDB corruption (the node is already aborting): fail with
// Local EvoDB inconsistency (missing or mismatched state): fail with
// M_ERROR so the block is not marked invalid.
state.Error(e.what());
return std::nullopt;
Expand Down Expand Up @@ -284,12 +284,21 @@ bool CMNHFManager::UndoBlock(const CBlock& block, const CBlockIndex* const pinde

CMNHFManager::Signals CMNHFManager::GetForBlock(const CBlockIndex* pindex)
{
if (pindex == nullptr) return {};
if (auto signals = GetFromCache(pindex)) return *signals;
throw EvoDbMissingStateError(strprintf("MNHF signals unavailable for block %s", pindex->GetBlockHash().ToString()));
Comment on lines +287 to +288

@thepastaclaw thepastaclaw Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Resolved at f02daa75; see the replies below.

🔴 Blocking: Migrate legacy signal state before startup replay

LoadChainstate() runs ReplayBlocks() before calling ForceSignalDBUpdate(). During replay, RollforwardBlock() processes special transactions and versionbits for each block, which calls GetSignalsStage() for the parent. If that parent's v2 state is absent, the new GetForBlock() unconditionally throws EvoDbMissingStateError; GetFromCache() only accepts the legacy mnhf_s entry while MN_RR is inactive. A datadir created by a pre-v2 release can therefore have only legacy state, and an interrupted coins flush after MN_RR activation makes replay fail before the migration can convert the validated history. This is a genuine upgrade/recovery failure even though the required block data is available, and it defeats the stated startup migration path. Migrate the legacy state needed by replay before ReplayBlocks() consumes it, using only script-validated block-index data, and add coverage for an interrupted-flush upgrade from a pre-v2 datadir.

source: gpt-6.1-sol (phase2-reviewer: general)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The ordering is real, but I'm leaving startup as it is. It needs two things together: a datadir last run on v21.x or older (v22.0.0 already stores mnhf_s2), and an interrupted coins flush, which is the only case where ReplayBlocks has blocks to process. An ordinary unclean shutdown reconnects blocks after ForceSignalDBUpdate and is unaffected. When both hold, startup stops with the existing error that asks for -reindex-chainstate, and that recovers the node; nothing is marked invalid or written.

Running the migration before the replay would mean rebuilding from a tip that isn't loaded yet (the replay is what establishes it), so it adds a second startup path for datadirs two major versions old. The PR description now states the exact condition (it previously said v22.0.x, which was wrong).

🤖 Posted autonomously by Claude on behalf of pasta.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still applies (re-reviewed at d427e88c): The latest reply does not change the code path: the two-condition case still reaches ReplayBlocks() before ForceSignalDBUpdate(), while LoadBlockIndex() has already loaded the index and ReplayBlocks() resolves the flushed head from its hashes. The prior answer therefore remains applicable, and this stays disputed for maintainer decision.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f02daa7. You were right that the last flushed tip is known before the replay: ReplayBlocks now rebuilds the signal state for it (src/validation.cpp:5463-5468) inside its EvoDB transaction, before rolling back or forward. On a current datadir the state is already stored and the call does nothing.

No automated test, since it needs a datadir without mnhf_s2 state. Checked by hand on regtest with a throwaway build that never writes mnhf_s2: 1100 blocks, a flush, then a crash mid-flush two blocks later. The previous head fails at startup while rolling forward the first block (MNHF signals unavailable for block ...); this head rebuilds, replays both blocks and restarts cleanly.


🤖 Posted autonomously by Claude on behalf of pasta.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolved (re-reviewed at f02daa75): The new ReplayBlocks path now rebuilds the last flushed tip inside the EvoDB transaction before rollback and roll-forward consume its signal state, so the legacy interrupted-flush ordering failure is addressed for the affected normal chainstate.

}

void CMNHFManager::RebuildSignals(const CBlockIndex* pindex)
{
AssertLockHeld(::cs_main);

std::stack<const CBlockIndex *> to_calculate;

std::optional<CMNHFManager::Signals> signalsTmp;
while (!(signalsTmp = GetFromCache(pindex)).has_value()) {
if (!pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
throw std::runtime_error("failed-getehfforblock-unvalidated");
Comment on lines 298 to +300

@thepastaclaw thepastaclaw Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Withdrawn at f02daa75; see the replies below.

🔴 Blocking: Do not reject assumed-valid snapshot tips during startup signal migration

RebuildSignals now requires every block it rebuilds to pass IsValid(BLOCK_VALID_SCRIPTS). Persisted assumeutxo snapshots deliberately mark blocks below the snapshot base with BLOCK_ASSUMED_VALID, which does not raise the validity mask, and the snapshot payload currently carries no MNHF signal state. On a restart with an active snapshot and no independently validated state in the shared EvoDB/cache, ReplayBlocks() can call this path for the snapshot chainstate and throw at this check. LoadChainstate() invokes replay before ForceSignalDBUpdate(), and the latter also rebuilds from the active snapshot tip, so an interrupted snapshot flush or a cold-start snapshot can fail startup even though the snapshot is an expected supported state. Make the rebuild snapshot-aware by obtaining compatible state without trusting assumed-valid block data, deferring migration until the background chainstate validates the relevant history, or otherwise bypassing these rebuild calls for an unvalidated snapshot chainstate while ensuring the later active-tip path is handled as well.

Raised on code unchanged since the last review, and confirmed by an independent pass: On a restart with an active assumeutxo snapshot whose MNHF state is absent, CompleteChainstateInitialization eventually calls ForceSignalDBUpdate(chainman.ActiveTip()), and ReplayBlocks() can call the same rebuild for an interrupted snapshot flush. RebuildSignals walks back through the snapshot chain to the base/ancestors, which are marked BLOCK_ASSUMED_VALID rather than BLOCK_VALID_SCRIPTS, then throws, causing startup to fail despite the snapshot being a supported state.

source: gpt-6.1-sol (phase2-reviewer: general)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declining this one: it is not a state this PR changes the outcome for.

  • On develop nothing in production creates a snapshot chainstate. There is no loadtxoutset RPC, and ActivateSnapshot() is only called from unit tests.
  • Where such a chainstate does exist with no stored signal state, develop fails at the same place. The old walk went back through the same blocks and threw failed-getehfforblock-read, because a snapshot has no block data at or below its base. This PR only changes which error is reported.
  • The alternative the old code allowed, recomputing signals from blocks that are on disk but not yet validated, is exactly what this PR removes.

Snapshots carry no Dash state yet (see the TODO(assumeutxo, loadtxoutset) note in ActivateSnapshot()). Supplying MNHF signal state for the snapshot base belongs with that payload work in the AssumeUTXO series, not in this fix.


🤖 Posted autonomously by Claude on behalf of pasta.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right that this pull request does not change the startup outcome for an active snapshot: the previous rebuild path already failed when it reached data unavailable below the snapshot base. Since snapshots are not created by production code here and carrying MNHF state is separate AssumeUTXO work, this finding was overstated.

Withdrawing this finding.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Withdrawn (re-reviewed at f02daa75): The current production code has no loadtxoutset path and ActivateSnapshot is only exercised by tests; existing snapshot initialization also lacks the MNHF state or block data needed for this migration. This PR does not introduce a new supported production snapshot failure.

}
to_calculate.push(pindex);
pindex = pindex->pprev;
}
Expand Down Expand Up @@ -317,7 +326,6 @@ CMNHFManager::Signals CMNHFManager::GetForBlock(const CBlockIndex* pindex)

to_calculate.pop();
}
return *signalsTmp;
}

std::optional<CMNHFManager::Signals> CMNHFManager::GetFromCache(const CBlockIndex* const pindex)
Expand Down Expand Up @@ -365,7 +373,7 @@ void CMNHFManager::AddToCache(const Signals& signals, const CBlockIndex* const p
{
assert(pindex != nullptr);
const uint256& blockHash = pindex->GetBlockHash();
if (DeploymentActiveAt(*pindex, m_consensus_params, Consensus::DEPLOYMENT_V20) &&
if (DeploymentActiveAt(*pindex, m_consensus_params, Consensus::DEPLOYMENT_V20) && Assume(m_evoDb.HasActiveTransaction()) &&
!m_evoDb.WriteDerived(std::make_pair(DB_SIGNALS_v2, blockHash), signals)) {
// A mismatch is local EvoDB corruption, not a statement about the
// block. Abort here: some callers (miner, RPC) never pass through a
Expand All @@ -389,7 +397,7 @@ bool CMNHFManager::ForceSignalDBUpdate(const CBlockIndex* tip)

const bool last_legacy = bls::bls_legacy_scheme.load();
bls::bls_legacy_scheme.store(false);
GetSignalsStage(tip);
RebuildSignals(tip);
bls::bls_legacy_scheme.store(last_legacy);

dbTx->Commit();
Expand Down
15 changes: 11 additions & 4 deletions src/evo/mnhftx.h
Original file line number Diff line number Diff line change
Expand Up @@ -128,18 +128,25 @@ class CMNHFManager : public AbstractEHFManager
*/
bool UndoBlock(const CBlock& block, const CBlockIndex* const pindex) EXCLUSIVE_LOCKS_REQUIRED(!cs_cache);

// Implements interface
// Implements interface. Only reads state stored when a block was connected, and throws if
// pindexPrev has none (e.g. it was never connected).
Signals GetSignalsStage(const CBlockIndex* const pindexPrev) override EXCLUSIVE_LOCKS_REQUIRED(!cs_cache);

bool ForceSignalDBUpdate(const CBlockIndex* tip) EXCLUSIVE_LOCKS_REQUIRED(::cs_main, !cs_cache);

/**
* Recompute missing state from block data, walking back from pindex to the first block whose
* state is stored. Throws for a block that did not pass script validation. Only for startup,
* inside an EvoDB transaction: pindex must be a block that was connected.
*/
void RebuildSignals(const CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(::cs_main, !cs_cache);

private:
void AddToCache(const Signals& signals, const CBlockIndex* const pindex) EXCLUSIVE_LOCKS_REQUIRED(!cs_cache);

/**
* This function returns list of signals available on previous block.
* if the signals for previous block is not available in cache it would read blocks from disk
* until state won't be recovered.
* Returns the signals stored for pindex, from the cache or evo db. Throws EvoDbMissingStateError
* if there are none, e.g. because the block was never connected.
* NOTE: that some signals could expired between blocks.
*/
Signals GetForBlock(const CBlockIndex* const pindex) EXCLUSIVE_LOCKS_REQUIRED(!cs_cache);
Expand Down
10 changes: 6 additions & 4 deletions src/evo/specialtxman.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -902,6 +902,8 @@ uint256 CSpecialTxProcessor::GetDeterministicMNListHash(gsl::not_null<const CBlo

void CSpecialTxProcessor::UpdatedMNListTip(gsl::not_null<const CBlockIndex*> pindex) { m_dmnman.UpdatedBlockTip(pindex); }

void CSpecialTxProcessor::RebuildMNHFSignals(const CBlockIndex* pindex) { m_mnhfman->RebuildSignals(pindex); }

void CSpecialTxProcessor::ResetPlatformBans(const CBlock& block, const CBlockIndex& index)
{
AssertLockHeld(::cs_main);
Expand Down Expand Up @@ -1107,8 +1109,8 @@ bool CSpecialTxProcessor::ProcessSpecialTxsInBlock(Chainstate& chainstate, const
LogPrintf("CSpecialTxProcessor::%s -- bls_legacy_scheme=%d\n", __func__, bls::bls_legacy_scheme.load());
}
} catch (const EvoDbInconsistencyError& e) {
// Local EvoDB corruption detected below (the node is already
// aborting): fail with M_ERROR so the block is not marked invalid.
// Local EvoDB inconsistency detected below (missing or mismatched
// state): fail with M_ERROR so the block is not marked invalid.
return state.Error(e.what());
} catch (const std::exception& e) {
LogPrintf("CSpecialTxProcessor::%s -- FAILURE! %s\n", __func__, e.what());
Expand Down Expand Up @@ -1180,8 +1182,8 @@ bool CSpecialTxProcessor::CheckCreditPoolDiffForBlock(const CBlock& block, const
}

} catch (const EvoDbInconsistencyError& e) {
// Local EvoDB corruption detected below (the node is already
// aborting): fail with M_ERROR so the block is not marked invalid.
// Local EvoDB inconsistency detected below (missing or mismatched
// state): fail with M_ERROR so the block is not marked invalid.
return state.Error(e.what());
} catch (const std::exception& e) {
LogPrintf("CSpecialTxProcessor::%s -- FAILURE! %s\n", __func__, e.what());
Expand Down
3 changes: 3 additions & 0 deletions src/evo/specialtxman.h
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@ class CSpecialTxProcessor
/** Passthrough to CDeterministicMNManager::UpdatedBlockTip */
void UpdatedMNListTip(gsl::not_null<const CBlockIndex*> pindex);

/** Passthrough to CMNHFManager::RebuildSignals */
void RebuildMNHFSignals(const CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);

@thepastaclaw thepastaclaw Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Withdrawn at f02daa75; see the replies below.

💬 Nitpick: RebuildMNHFSignals passthrough missing !cs_cache annotation

CMNHFManager::RebuildSignals declares EXCLUSIVE_LOCKS_REQUIRED(::cs_main, !cs_cache) because it calls cache operations internally. The CSpecialTxProcessor::RebuildMNHFSignals passthrough carries only the cs_main requirement, so thread-safety analysis will not reject a future caller that holds cs_cache before entering this function, allowing the documented cache-to-main lock inversion to be reintroduced. Propagate the negative cache-lock requirement through the wrapper.

Suggested change
void RebuildMNHFSignals(const CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
void RebuildMNHFSignals(const CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(::cs_main, !cs_cache);

source: muse-spark-1.3-contributor (phase1-reviewer: general)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declining: cs_cache is a private member of CMNHFManager, so CSpecialTxProcessor cannot name it in an annotation without exposing it. The requirement stays enforced on RebuildSignals() itself, where the passthrough's single call is checked.


🤖 Posted autonomously by Claude on behalf of pasta.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. The wrapper cannot name the manager's private cs_cache without exposing an implementation detail, and the call to RebuildSignals() is still checked against that callee's !cs_cache requirement. The existing annotation is therefore sufficient.

Withdrawing this finding.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Withdrawn (re-reviewed at f02daa75): The wrapper cannot name CMNHFManager's private cs_cache without exposing an implementation detail. The actual RebuildSignals declaration still enforces the !cs_cache requirement at the cache-accessing function.


void ResetPlatformBans(const CBlock& block, const CBlockIndex& index) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
void DiscardDeterministicMNBlock(const uint256& block_hash);

Expand Down
2 changes: 1 addition & 1 deletion src/kernel/chainparams.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ static CBlock FindDevNetGenesisBlock(const CBlock &prevBlock, const std::string&

bool CChainParams::IsValidMNActivation(int nBit, int64_t timePast) const
{
assert(nBit < VERSIONBITS_NUM_BITS);
if (nBit < 0 || nBit >= VERSIONBITS_NUM_BITS) return false;

for (int index = 0; index < Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++index) {
if (consensus.vDeployments[index].bit == nBit) {
Expand Down
4 changes: 4 additions & 0 deletions src/rpc/blockchain.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1727,6 +1727,10 @@ RPCHelpMan getdeploymentinfo()
if (!blockindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
// ConnectBlock skips the genesis block, so it never reaches BLOCK_VALID_SCRIPTS
if (blockindex->pprev && !blockindex->IsValid(BLOCK_VALID_SCRIPTS)) {
throw JSONRPCError(RPC_MISC_ERROR, "MNHF signals unavailable for an invalid or unvalidated block");
}
}

const auto ehf_signals{CHECK_NONFATAL(node.special_tx)->m_mnhfman->GetSignalsStage(blockindex)};
Expand Down
38 changes: 38 additions & 0 deletions src/test/evo_mnhf_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,18 @@
#include <chainparams.h>
#include <consensus/params.h>
#include <consensus/validation.h>
#include <deploymentstatus.h>
#include <evo/evodb.h>
#include <evo/mnhftx.h>
#include <evo/specialtx.h>
#include <evo/specialtxman.h>
#include <llmq/context.h>
#include <primitives/transaction.h>
#include <script/script.h>
#include <uint256.h>
#include <util/string.h>
#include <validation.h>
#include <versionbits.h>

#include <boost/test/unit_test.hpp>
#include <test/util/setup_common.h>
Expand Down Expand Up @@ -66,6 +71,10 @@ BOOST_AUTO_TEST_CASE(verify_mnhf_specialtx_tests)
auto sig = ag_sk.Sign(verHash, use_legacy);
BOOST_CHECK(sig.VerifyInsecure(ag_pk, verHash, use_legacy));

for (const int bit : {-1, VERSIONBITS_NUM_BITS, 255}) {
BOOST_CHECK(!Params().IsValidMNActivation(bit, 0));
}

auto& chainman = Assert(m_node.chainman);
auto& qman = *Assert(m_node.llmq_ctx)->qman;
const CBlockIndex* pindex = WITH_LOCK(::cs_main, return chainman->ActiveChain().Tip());
Expand Down Expand Up @@ -133,4 +142,33 @@ BOOST_FIXTURE_TEST_CASE(mnhf_bit_reuse_reindex_tests, MnhfBitReuseSetup)
BOOST_CHECK(params.IsValidMNActivation(reused_bit, before_window));
}

BOOST_FIXTURE_TEST_CASE(signals_unavailable_for_unconnected_block, TestChainV19Setup)
{
auto& chainman = *Assert(m_node.chainman);
auto& mnhfman = *Assert(m_node.special_tx)->m_mnhfman;

const CBlock connected = CreateBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()), chainman.ActiveChainstate());
const CBlock sibling = CreateBlock({}, CScript() << OP_TRUE, chainman.ActiveChainstate());
BOOST_REQUIRE(chainman.ProcessNewBlock(std::make_shared<const CBlock>(connected), true, nullptr));
BOOST_REQUIRE(chainman.ProcessNewBlock(std::make_shared<const CBlock>(sibling), true, nullptr));

const auto [connected_index, sibling_index] = WITH_LOCK(::cs_main, return std::make_pair(
chainman.m_blockman.LookupBlockIndex(connected.GetHash()), chainman.m_blockman.LookupBlockIndex(sibling.GetHash())));
BOOST_REQUIRE(connected_index && sibling_index);
BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return chainman.ActiveChain().Tip()), connected_index);
BOOST_CHECK(WITH_LOCK(::cs_main, return (sibling_index->nStatus & BLOCK_HAVE_DATA) &&
!sibling_index->IsValid(BLOCK_VALID_SCRIPTS)));
BOOST_REQUIRE(DeploymentActiveAfter(sibling_index, chainman.GetConsensus(), Consensus::DEPLOYMENT_V20));

BOOST_CHECK_NO_THROW(mnhfman.GetSignalsStage(connected_index));
BOOST_CHECK_THROW(mnhfman.GetSignalsStage(sibling_index), EvoDbMissingStateError);

// Connecting the sibling stores its state
BlockValidationState state;
BOOST_REQUIRE(chainman.ActiveChainstate().InvalidateBlock(state, connected_index));
BOOST_REQUIRE(chainman.ActiveChainstate().ActivateBestChain(state));
BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return chainman.ActiveChain().Tip()), sibling_index);
BOOST_CHECK_NO_THROW(mnhfman.GetSignalsStage(sibling_index));
}

BOOST_AUTO_TEST_SUITE_END()
9 changes: 8 additions & 1 deletion src/validation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -938,7 +938,7 @@ bool MemPoolAccept::PreChecks(ATMPArgs& args, Workspace& ws)
return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-already-known");
}
} catch (const EvoDbInconsistencyError& e) {
// Local EvoDB corruption (the node is already aborting): not a statement about the tx
// Local EvoDB inconsistency (missing or mismatched state): not a statement about the tx
return state.Error(e.what());
} catch (const std::exception& e) {
// Reconstruction failed locally (block read, inconsistent pool); the tx is not at
Expand Down Expand Up @@ -5460,6 +5460,13 @@ bool Chainstate::ReplayBlocks()

auto dbTx = m_evoDb.BeginTransaction(EvoDbIdentity());

if (pindexOld) {
// A datadir last run before v22 has no current-format MNHF signal state yet, and
// ForceSignalDBUpdate() only migrates it once the replay is done.
ScopedBLSLegacyScheme bls_scheme_guard{false};
m_special_tx.RebuildMNHFSignals(pindexOld);
}
Comment on lines +5463 to +5468

@thepastaclaw thepastaclaw Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Withdrawn at f02daa75; see the replies below.

🟡 Suggestion: Rebuild in ReplayBlocks can throw instead of returning false

ReplayBlocks() returns bool, and its caller converts false into the established recoverable startup error. The newly added direct RebuildMNHFSignals() call can throw std::runtime_error for an unvalidated tip, failed block read, or failed reconstruction, and can throw EvoDbInconsistencyError from ProcessBlock; none of those exceptions are caught here. This bypasses the function's normal failure contract and can terminate startup through exception propagation rather than returning false, including for missing or pruned block data. Catch the rebuild exceptions, log the failure, and return false (while separately handling the snapshot-specific state problem above).

Suggested change
if (pindexOld) {
// A datadir last run before v22 has no current-format MNHF signal state yet, and
// ForceSignalDBUpdate() only migrates it once the replay is done.
ScopedBLSLegacyScheme bls_scheme_guard{false};
m_special_tx.RebuildMNHFSignals(pindexOld);
}
if (pindexOld) {
// A datadir last run before v22 has no current-format MNHF signal state yet, and
// ForceSignalDBUpdate() only migrates it once the replay is done.
ScopedBLSLegacyScheme bls_scheme_guard{false};
try {
m_special_tx.RebuildMNHFSignals(pindexOld);
} catch (const std::exception& e) {
LogError("ReplayBlocks(DASH): MNHF signal rebuild failed: %s\n", e.what());
return false;
}
}

source: muse-spark-1.3-contributor (phase1-reviewer: general)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declining: the exception already ends in the recoverable startup error. ReplayBlocks() is only reached through LoadChainstate(), which init runs inside catch_exceptions(), and ForceSignalDBUpdate() a few lines later in the same function throws the same way. A second try/catch here would add a path without changing the outcome.


🤖 Posted autonomously by Claude on behalf of pasta.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. Although the direct call does bypass ReplayBlocks()'s local false return, LoadChainstate() invokes it inside catch_exceptions(), which converts the exception into the same recoverable startup failure, and ForceSignalDBUpdate() has the same exception behavior immediately afterward. My suggestion does not materially improve the startup contract here.

Withdrawing this finding.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Withdrawn (re-reviewed at f02daa75): LoadChainstate invokes ReplayBlocks inside the existing catch_exceptions boundary, which catches std::exception and converts it into the established recoverable startup failure. Direct propagation therefore does not create a distinct unhandled startup outcome.


// Rollback along the old branch.
while (pindexOld != pindexFork) {
if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
Expand Down
39 changes: 38 additions & 1 deletion test/functional/interface_rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from test_framework.messages import (
BLOCK_HEADER_SIZE,
COIN,
CMnEhf,
COutPoint,
CTransaction,
CTxIn,
Expand All @@ -27,6 +28,7 @@
assert_equal,
assert_greater_than,
assert_greater_than_or_equal,
assert_raises_rpc_error,
)
from test_framework.wallet import (
MiniWallet,
Expand Down Expand Up @@ -435,6 +437,8 @@ def run_test(self):
previous_bb_hash = self.nodes[0].getblockhash(self.nodes[0].getblockcount() - 1)
deployment_info = self.nodes[0].getdeploymentinfo(previous_bb_hash)
assert_equal(deployment_info, self.test_rest_request(f"/deploymentinfo/{previous_bb_hash}"))
genesis_hash = self.nodes[0].getblockhash(0)
assert_equal(self.nodes[0].getdeploymentinfo(genesis_hash)["height"], 0)

non_existing_blockhash = '42759cde25462784395a337460bde75f58e73d3f08bd31fdc3507cbac856a2c4'
resp = self.test_rest_request(f'/deploymentinfo/{non_existing_blockhash}', ret_type=RetType.OBJ, status=400)
Expand All @@ -451,12 +455,45 @@ def run_test(self):
self.nodes[0].submitheader(self.nodes[1].getblockheader(header_only_hash, False))
resp = self.test_rest_request(f"/deploymentinfo/{header_only_hash}", ret_type=RetType.OBJ, status=500)
assert_equal(resp.getheader('Content-Type'), 'text/plain')
assert_equal(resp.read().decode('utf-8').rstrip(), "failed-getehfforblock-read")
assert_equal(resp.read().decode().rstrip(), "MNHF signals unavailable for an invalid or unvalidated block")
assert_equal(self.nodes[0].getbestblockhash(), tip_before_request)
assert_equal(self.test_rest_request('/deploymentinfo'), self.nodes[0].getdeploymentinfo())
self.log.info("Test deployment info for stored blocks that were never connected")
connected_hash = self.generate(self.nodes[0], 1, sync_fun=self.no_op)[0]
assert_equal(self.nodes[0].submitblock(self.nodes[1].getblock(header_only_hash, 0)), "inconclusive")
assert_equal(self.nodes[0].getblock(header_only_hash)["confirmations"], -1)

def check_unvalidated(block_hash):
assert_raises_rpc_error(-1, "MNHF signals unavailable", self.nodes[0].getdeploymentinfo, block_hash)
self.test_rest_request(f"/deploymentinfo/{block_hash}", ret_type=RetType.OBJ, status=500)
self.nodes[0].gettxoutsetinfo()
assert_equal(self.nodes[0].getbestblockhash(), connected_hash)

check_unvalidated(header_only_hash)

self.log.info("Test deployment info for a stored block rejected for an out-of-range MNHF bit")
signal = CTransaction()
signal.nVersion = 3
signal.nType = 7
signal.vExtraPayload = CMnEhf(version=1, versionBit=200, quorumHash=0, quorumSig=b'\x00' * 96).serialize()
block = create_block(
tmpl=self.nodes[0].getblocktemplate(),
coinbase=create_coinbase(self.nodes[0].getblockcount() + 1, dip4_activated=True, v20_activated=True),
txlist=[signal],
)
block.solve()
assert_equal(self.nodes[0].submitblock(block.serialize().hex()), "bad-mnhf-nbit-out-of-bounds")
assert_equal(self.nodes[0].getblock(block.hash, 0), block.serialize().hex())
check_unvalidated(block.hash)
height = self.nodes[0].getblockcount()
self.restart_node(0)
assert_equal(self.nodes[0].getblockcount(), height)

self.generate(self.nodes[1], 1, sync_fun=self.no_op)
self.connect_nodes(0, 1)
self.sync_all()
assert_equal(self.test_rest_request(f"/deploymentinfo/{header_only_hash}"), self.nodes[0].getdeploymentinfo(header_only_hash))
assert_equal(self.nodes[0].getdeploymentinfo(connected_hash)["hash"], connected_hash)

self.log.info("Test rendering stored ProTx payloads with unsupported versions")
node = self.nodes[0]
Expand Down
Loading