Merge bitcoin/bitcoin#29843: policy: Allow non-standard scripts with -acceptnonstdtxn=1 (test nets only)
What changed, and why it matters
This change loosens transaction acceptance rules only on Bitcoin test networks when a special command-line option (-acceptnonstdtxn=1) is used. It lets developers test unusual or experimental scripts in the mempool, while still enforcing all consensus rules that protect real money. Main network behavior is unchanged, and the option is not available there.
No urgent action needed. This is an intentional testnet-only policy relaxation with defensive compile-time and runtime checks. Operators running test networks with -acceptnonstdtxn=1 should understand that their mempool will accept non-standard but consensus-valid transactions. Reviewers should verify that the new CONSENSUS_SCRIPT_VERIFY_FLAGS set and GetAllConsensusScriptFlags remain complete as future soft forks add flags.
Security signals we found
Relaxes mempool policy checks under an explicit opt-in testnet-only flag
Adds static_assert ensuring standard flags remain a superset of consensus flags
Adds runtime Assume checks tying block script flags to tracked consensus flags
Introduces explicit CheckInputScriptsFor enum to separate consensus vs standardness failure reporting
Changes error classification from NOT_STANDARD to TX_NOT_STANDARD/TX_CONSENSUS based on caller context
Evidence from the diff
The commit refactors CheckInputScripts to distinguish block validation from mempool validation and changes PolicyScriptChecks so that when -acceptnonstdtxn=1 is set on test networks, only potential consensus script flags are enforced instead of the full standard policy flags. It adds compile-time and runtime checks to ensure consensus flags are a subset of standard flags and that all possible block consensus flags are tracked in a new m_all_consensus_script_flags member. Tests are updated to verify both standard and non-standard rejection paths.
Changed components
src/validation.cppsrc/validation.hmempool acceptance (PolicyScriptChecks)block validation (ConnectBlock)test/functional/p2p_invalid_tx.pytest/functional/p2p_segwit.pysrc/test/txvalidationcache_tests.cppsrc/test/versionbits_tests.cppInspect captured patch +217 / −55
### doc/release-notes-29843.md
@@ -0,0 +1,10 @@
+Updated settings
+----------------
+
+- On test networks, the `-acceptnonstdtxn` option now also allows
+ transactions with non-standard scripts (that fail on
+ `mempool-script-verify-flag-failed` checks) to be relayed and
+ mined. Script flags that the node enforces at the consensus level (or
+ may eventually enforce after a soft fork activates) are still applied,
+ meaning that transactions that could become consensus-invalid are
+ still rejected from the mempool. (#29843)
### src/test/txvalidationcache_tests.cpp
@@ -20,12 +20,6 @@ struct Dersig100Setup : public TestChain100Setup {
: TestChain100Setup{ChainType::REGTEST, {.extra_args = {"-testactivationheight=dersig@102"}}} {}
};
-bool CheckInputScripts(const CTransaction& tx, TxValidationState& state,
- const CCoinsViewCache& inputs, script_verify_flags flags, bool cacheSigStore,
- bool cacheFullScriptStore, PrecomputedTransactionData& txdata,
- ValidationCache& validation_cache,
- std::vector<CScriptCheck>* pvChecks) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
-
BOOST_AUTO_TEST_SUITE(txvalidationcache_tests)
BOOST_FIXTURE_TEST_CASE(tx_mempool_block_doublespend, Dersig100Setup)
@@ -140,7 +134,7 @@ static void ValidateCheckInputsForAllFlags(const CTransaction &tx, script_verify
// WITNESS requires P2SH
test_flags |= SCRIPT_VERIFY_P2SH;
}
- bool ret = CheckInputScripts(tx, state, &active_coins_tip, test_flags, true, add_to_cache, txdata, validation_cache, nullptr);
+ bool ret = CheckInputScripts(tx, state, &active_coins_tip, test_flags, CheckInputScriptsFor::Mempool, true, add_to_cache, txdata, validation_cache, nullptr);
// CheckInputScripts should succeed iff test_flags doesn't intersect with
// failing_flags
bool expected_return_value = !(test_flags & failing_flags);
@@ -150,13 +144,13 @@ static void ValidateCheckInputsForAllFlags(const CTransaction &tx, script_verify
if (ret && add_to_cache) {
// Check that we get a cache hit if the tx was valid
std::vector<CScriptCheck> scriptchecks;
- BOOST_CHECK(CheckInputScripts(tx, state, &active_coins_tip, test_flags, true, add_to_cache, txdata, validation_cache, &scriptchecks));
+ BOOST_CHECK(CheckInputScripts(tx, state, &active_coins_tip, test_flags, CheckInputScriptsFor::Mempool, true, add_to_cache, txdata, validation_cache, &scriptchecks));
BOOST_CHECK(scriptchecks.empty());
} else {
// Check that we get script executions to check, if the transaction
// was invalid, or we didn't add to cache.
std::vector<CScriptCheck> scriptchecks;
- BOOST_CHECK(CheckInputScripts(tx, state, &active_coins_tip, test_flags, true, add_to_cache, txdata, validation_cache, &scriptchecks));
+ BOOST_CHECK(CheckInputScripts(tx, state, &active_coins_tip, test_flags, CheckInputScriptsFor::Mempool, true, add_to_cache, txdata, validation_cache, &scriptchecks));
BOOST_CHECK_EQUAL(scriptchecks.size(), tx.vin.size());
}
}
@@ -211,13 +205,13 @@ BOOST_FIXTURE_TEST_CASE(checkinputs_test, Dersig100Setup)
TxValidationState state;
PrecomputedTransactionData ptd_spend_tx;
- BOOST_CHECK(!CheckInputScripts(CTransaction(spend_tx), state, &m_node.chainman->ActiveChainstate().CoinsTip(), SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_DERSIG, true, true, ptd_spend_tx, m_node.chainman->m_validation_cache, nullptr));
+ BOOST_CHECK(!CheckInputScripts(CTransaction(spend_tx), state, &m_node.chainman->ActiveChainstate().CoinsTip(), SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_DERSIG, CheckInputScriptsFor::Mempool, true, true, ptd_spend_tx, m_node.chainman->m_validation_cache, nullptr));
// If we call again asking for scriptchecks (as happens in
// ConnectBlock), we should add a script check object for this -- we're
// not caching invalidity (if that changes, delete this test case).
std::vector<CScriptCheck> scriptchecks;
- BOOST_CHECK(CheckInputScripts(CTransaction(spend_tx), state, &m_node.chainman->ActiveChainstate().CoinsTip(), SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_DERSIG, true, true, ptd_spend_tx, m_node.chainman->m_validation_cache, &scriptchecks));
+ BOOST_CHECK(CheckInputScripts(CTransaction(spend_tx), state, &m_node.chainman->ActiveChainstate().CoinsTip(), SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_DERSIG, CheckInputScriptsFor::Mempool, true, true, ptd_spend_tx, m_node.chainman->m_validation_cache, &scriptchecks));
BOOST_CHECK_EQUAL(scriptchecks.size(), 1U);
// Test that CheckInputScripts returns true iff DERSIG-enforcing flags are
@@ -270,7 +264,7 @@ BOOST_FIXTURE_TEST_CASE(checkinputs_test, Dersig100Setup)
invalid_with_cltv_tx.vin[0].scriptSig = CScript() << vchSig << 100;
TxValidationState state;
PrecomputedTransactionData txdata;
- BOOST_CHECK(CheckInputScripts(CTransaction(invalid_with_cltv_tx), state, m_node.chainman->ActiveChainstate().CoinsTip(), SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY, true, true, txdata, m_node.chainman->m_validation_cache, nullptr));
+ BOOST_CHECK(CheckInputScripts(CTransaction(invalid_with_cltv_tx), state, m_node.chainman->ActiveChainstate().CoinsTip(), SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY, CheckInputScriptsFor::Mempool, true, true, txdata, m_node.chainman->m_validation_cache, nullptr));
}
// TEST CHECKSEQUENCEVERIFY
@@ -293,7 +287,7 @@ BOOST_FIXTURE_TEST_CASE(checkinputs_test, Dersig100Setup)
invalid_with_csv_tx.vin[0].scriptSig = CScript() << vchSig << 100;
TxValidationState state;
PrecomputedTransactionData txdata;
- BOOST_CHECK(CheckInputScripts(CTransaction(invalid_with_csv_tx), state, &m_node.chainman->ActiveChainstate().CoinsTip(), SCRIPT_VERIFY_CHECKSEQUENCEVERIFY, true, true, txdata, m_node.chainman->m_validation_cache, nullptr));
+ BOOST_CHECK(CheckInputScripts(CTransaction(invalid_with_csv_tx), state, &m_node.chainman->ActiveChainstate().CoinsTip(), SCRIPT_VERIFY_CHECKSEQUENCEVERIFY, CheckInputScriptsFor::Mempool, true, true, txdata, m_node.chainman->m_validation_cache, nullptr));
}
// TODO: add tests for remaining script flags
@@ -374,12 +368,12 @@ BOOST_FIXTURE_TEST_CASE(checkinputs_test, Dersig100Setup)
TxValidationState state;
PrecomputedTransactionData txdata;
// This transaction is now invalid under segwit, because of the second input.
- BOOST_CHECK(!CheckInputScripts(CTransaction(tx), state, &m_node.chainman->ActiveChainstate().CoinsTip(), SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, true, true, txdata, m_node.chainman->m_validation_cache, nullptr));
+ BOOST_CHECK(!CheckInputScripts(CTransaction(tx), state, &m_node.chainman->ActiveChainstate().CoinsTip(), SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, CheckInputScriptsFor::Mempool, true, true, txdata, m_node.chainman->m_validation_cache, nullptr));
std::vector<CScriptCheck> scriptchecks;
// Make sure this transaction was not cached (ie because the first
// input was valid)
- BOOST_CHECK(CheckInputScripts(CTransaction(tx), state, &m_node.chainman->ActiveChainstate().CoinsTip(), SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, true, true, txdata, m_node.chainman->m_validation_cache, &scriptchecks));
+ BOOST_CHECK(CheckInputScripts(CTransaction(tx), state, &m_node.chainman->ActiveChainstate().CoinsTip(), SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, CheckInputScriptsFor::Mempool, true, true, txdata, m_node.chainman->m_validation_cache, &scriptchecks));
// Should get 2 script checks back -- caching is on a whole-transaction basis.
BOOST_CHECK_EQUAL(scriptchecks.size(), 2U);
}
### src/test/versionbits_tests.cpp
@@ -10,6 +10,7 @@
#include <test/util/setup_common.h>
#include <test/util/versionbits.h>
#include <util/chaintype.h>
+#include <validation.h>
#include <versionbits.h>
#include <versionbits_impl.h>
@@ -440,6 +441,28 @@ void check_computeblockversion(VersionBitsCache& versionbitscache, const Consens
}
}; // struct BlockVersionTest
+BOOST_FIXTURE_TEST_CASE(blockscriptflags, RegTestingSetup)
+{
+ // RegTest should have all possible flags enabled by default
+ // If this check fails, then either remove the flag from
+ // CONSENSUS_SCRIPT_VERIFY_FLAGS, so that it's never a consensus
+ // flag for any chain, or ensure the deployment is enabled by
+ // default for RegTest.
+ auto regtest{CreateChainParams(*m_node.args, ChainType::REGTEST)};
+ BOOST_CHECK_EQUAL(ChainstateManager::GetAllConsensusScriptFlags(regtest->GetConsensus()).as_int(), CONSENSUS_SCRIPT_VERIFY_FLAGS.as_int());
+
+ // Check stored value is consistent
+ ChainstateManager& chainman = *m_node.chainman;
+ BOOST_CHECK_EQUAL(chainman.m_all_consensus_script_flags.as_int(), CONSENSUS_SCRIPT_VERIFY_FLAGS.as_int());
+
+ // Every other chain should have a subset (though this should already have been checked at compile-time)
+ for (const auto& chain_type : {ChainType::MAIN, ChainType::TESTNET, ChainType::TESTNET4, ChainType::SIGNET}) {
+ auto params{CreateChainParams(*m_node.args, chain_type)};
+ script_verify_flags possible_flags{ChainstateManager::GetAllConsensusScriptFlags(params->GetConsensus())};
+ BOOST_CHECK_EQUAL((possible_flags & CONSENSUS_SCRIPT_VERIFY_FLAGS).as_int(), possible_flags.as_int());
+ }
+}
+
BOOST_FIXTURE_TEST_CASE(versionbits_computeblockversion, BlockVersionTest)
{
VersionBitsCache vbcache;
### src/validation.cpp
@@ -146,13 +146,6 @@ const CBlockIndex* Chainstate::FindForkInGlobalIndex(const CBlockLocator& locato
return m_chain.Genesis();
}
-bool CheckInputScripts(const CTransaction& tx, TxValidationState& state,
- const CCoinsViewCache& inputs, script_verify_flags flags, bool cacheSigStore,
- bool cacheFullScriptStore, PrecomputedTransactionData& txdata,
- ValidationCache& validation_cache,
- std::vector<CScriptCheck>* pvChecks = nullptr)
- EXCLUSIVE_LOCKS_REQUIRED(cs_main);
-
bool CheckFinalTxAtTip(const CBlockIndex& active_chain_tip, const CTransaction& tx)
{
AssertLockHeld(cs_main);
@@ -436,7 +429,7 @@ static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, TxValidationS
}
// Call CheckInputScripts() to cache signature and script validity against current tip consensus rules.
- return CheckInputScripts(tx, state, view, flags, /* cacheSigStore= */ true, /* cacheFullScriptStore= */ true, txdata, validation_cache);
+ return CheckInputScripts(tx, state, view, flags, CheckInputScriptsFor::Mempool, /* cacheSigStore= */ true, /* cacheFullScriptStore= */ true, txdata, validation_cache);
}
namespace {
@@ -1133,11 +1126,11 @@ bool MemPoolAccept::PolicyScriptChecks(Workspace& ws)
const CTransaction& tx = *ws.m_ptx;
TxValidationState& state = ws.m_state;
- constexpr script_verify_flags scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
+ const script_verify_flags scriptVerifyFlags = (m_pool.m_opts.require_standard ? STANDARD_SCRIPT_VERIFY_FLAGS : m_active_chainstate.m_chainman.m_all_consensus_script_flags);
// Check input scripts and signatures.
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
- if (!CheckInputScripts(tx, state, m_view, scriptVerifyFlags, true, false, ws.m_precomputed_txdata, GetValidationCache())) {
+ if (!CheckInputScripts(tx, state, m_view, scriptVerifyFlags, CheckInputScriptsFor::Mempool, true, false, ws.m_precomputed_txdata, GetValidationCache())) {
// Detect a failure due to a missing witness so that p2p code can handle rejection caching appropriately.
if (!tx.HasWitness() && SpendsNonAnchorWitnessProg(tx, m_view)) {
state.Invalid(TxValidationResult::TX_WITNESS_STRIPPED,
@@ -1173,9 +1166,10 @@ bool MemPoolAccept::ConsensusScriptChecks(Workspace& ws)
// invalid blocks (using TestBlockValidity), however allowing such
// transactions into the mempool can be exploited as a DoS attack.
script_verify_flags currentBlockScriptVerifyFlags{GetBlockScriptFlags(*m_active_chainstate.m_chain.Tip(), m_active_chainstate.m_chainman)};
+
if (!CheckInputsFromMempoolAndCache(tx, state, m_view, m_pool, currentBlockScriptVerifyFlags,
ws.m_precomputed_txdata, m_active_chainstate.CoinsTip(), GetValidationCache())) {
- LogError("BUG! PLEASE REPORT THIS! CheckInputScripts failed against latest-block but not STANDARD flags %s, %s", hash.ToString(), state.ToString());
+ LogError("BUG! PLEASE REPORT THIS! CheckInputScripts failed against latest-block but not mempool flags %s, %s", hash.ToString(), state.ToString());
return Assume(false);
}
@@ -2051,14 +2045,10 @@ ValidationCache::ValidationCache(const size_t script_execution_cache_bytes, cons
* Setting cacheSigStore/cacheFullScriptStore to false will remove elements from the corresponding cache
* which are matched. This is useful for checking blocks where we will likely never need the cache
* entry again.
- *
- * Note that we may set state.reason to NOT_STANDARD for extra soft-fork flags in flags, block-checking
- * callers should probably reset it to CONSENSUS in such cases.
- *
- * Non-static (and redeclared) in src/test/txvalidationcache_tests.cpp
*/
bool CheckInputScripts(const CTransaction& tx, TxValidationState& state,
- const CCoinsViewCache& inputs, script_verify_flags flags, bool cacheSigStore,
+ const CCoinsViewCache& inputs, script_verify_flags flags, CheckInputScriptsFor check_for,
+ bool cacheSigStore,
bool cacheFullScriptStore, PrecomputedTransactionData& txdata,
ValidationCache& validation_cache,
std::vector<CScriptCheck>* pvChecks)
@@ -2115,11 +2105,13 @@ bool CheckInputScripts(const CTransaction& tx, TxValidationState& state,
// non-standard DER encodings or non-null dummy
// arguments) or due to new consensus rules introduced in
// soft forks.
- if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
+ switch (check_for) {
+ case CheckInputScriptsFor::Mempool:
return state.Invalid(TxValidationResult::TX_NOT_STANDARD, strprintf("mempool-script-verify-flag-failed (%s)", ScriptErrorString(result->first)), result->second);
- } else {
+ case CheckInputScriptsFor::Block:
return state.Invalid(TxValidationResult::TX_CONSENSUS, strprintf("block-script-verify-flag-failed (%s)", ScriptErrorString(result->first)), result->second);
}
+ assert(false); // unreachable
}
}
@@ -2246,6 +2238,82 @@ DisconnectResult Chainstate::DisconnectBlock(const CBlock& block, const CBlockIn
return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
}
+namespace {
+/* If STANDARD_SCRIPT_VERIFY_FLAGS doesn't cover a consensus flag,
+ * MemPoolAccept::PolicyScriptChecks may accept txs that violate the
+ * corresponding consensus rule, which would cause us to create invalid
+ * block templates.
+ */
+static_assert((CONSENSUS_SCRIPT_VERIFY_FLAGS & STANDARD_SCRIPT_VERIFY_FLAGS) == CONSENSUS_SCRIPT_VERIFY_FLAGS, "standard flags must be a superset of consensus flags");
+
+/* Check that there's no inconsistency with the policy/policy.h value */
+static_assert(CONSENSUS_SCRIPT_VERIFY_FLAGS == MANDATORY_SCRIPT_VERIFY_FLAGS);
+
+/** Helper class for building up script_verify_flags values for consensus
+ * checks (particularly GetBlockScriptFlags() and
+ * GetAllConsensusScriptFlags()). Designed so that flags can
+ * only be added with constant expressions, and will trigger a
+ * compile-time error on any attempt to include flags other than
+ * CONSENSUS_SCRIPT_VERIFY_FLAGS. This approach avoids enforcing any
+ * particular structure on the consensus logic that enables flags,
+ * keeping flexibility for future soft forks.
+ */
+class ConsensusScriptVerifyFlags
+{
+public:
+ using value_type = script_verify_flags::value_type;
+
+ consteval ConsensusScriptVerifyFlags(script_verify_flags flags)
+ {
+ if ((flags & CONSENSUS_SCRIPT_VERIFY_FLAGS) != flags) throw;
+ m_value = flags.as_int();
+ }
+
+ consteval ConsensusScriptVerifyFlags(script_verify_flag_name flag) : ConsensusScriptVerifyFlags{script_verify_flags{flag}} { }
+
+ /* Merging two sets of consensus script verify flags is fine */
+ ConsensusScriptVerifyFlags& operator|=(const ConsensusScriptVerifyFlags& flags)
+ {
+ m_value |= flags.m_value;
+ return *this;
+ }
+
+ /* Allow masking with generic script_verify_flags, since that
+ * cannot add non-consensus flags */
+ ConsensusScriptVerifyFlags& operator&=(const script_verify_flags& flags)
+ {
+ m_value &= flags.as_int();
+ return *this;
+ }
+
+ operator script_verify_flags() const
+ {
+ return script_verify_flags::from_int(m_value);
+ }
+
+private:
+ value_type m_value{0};
+};
+
+template<script_verify_flag_name VFN>
+ConsensusScriptVerifyFlags add_pending_flag(const Consensus::Params& params, auto dep)
+{
+ if (DeploymentEnabled(params, dep)) return VFN;
+ return SCRIPT_VERIFY_NONE;
+}
+} // namespace
+
+script_verify_flags ChainstateManager::GetAllConsensusScriptFlags(const Consensus::Params& params)
+{
+ ConsensusScriptVerifyFlags flags{SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_TAPROOT};
+ flags |= add_pending_flag<SCRIPT_VERIFY_DERSIG>(params, Consensus::DEPLOYMENT_DERSIG);
+ flags |= add_pending_flag<SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY>(params, Consensus::DEPLOYMENT_CLTV);
+ flags |= add_pending_flag<SCRIPT_VERIFY_CHECKSEQUENCEVERIFY>(params, Consensus::DEPLOYMENT_CSV);
+ flags |= add_pending_flag<SCRIPT_VERIFY_NULLDUMMY>(params, Consensus::DEPLOYMENT_SEGWIT);
+
+ return flags;
+}
+
script_verify_flags GetBlockScriptFlags(const CBlockIndex& block_index, const ChainstateManager& chainman)
{
const Consensus::Params& consensusparams = chainman.GetConsensus();
@@ -2258,10 +2326,12 @@ script_verify_flags GetBlockScriptFlags(const CBlockIndex& block_index, const Ch
// mainnet.
// For simplicity, always leave P2SH+WITNESS+TAPROOT on except for the two
// violating blocks.
- script_verify_flags flags{SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_TAPROOT};
+ ConsensusScriptVerifyFlags flags{SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_TAPROOT};
const auto it{consensusparams.script_flag_exceptions.find(*Assert(block_index.phashBlock))};
if (it != consensusparams.script_flag_exceptions.end()) {
- flags = it->second;
+ // only trimming flags, not trying to enable new ones
+ flags &= it->second;
+ Assume(flags == it->second);
}
// Enforce the DERSIG (BIP66) rule
@@ -2284,6 +2354,10 @@ script_verify_flags GetBlockScriptFlags(const CBlockIndex& block_index, const Ch
flags |= SCRIPT_VERIFY_NULLDUMMY;
}
+ // Note: flags returned from this function must also be included in
+ // GetAllConsensusScriptFlags() above.
+ Assume((chainman.m_all_consensus_script_flags & flags) == flags);
+
return flags;
}
@@ -2578,10 +2652,10 @@ bool Chainstate::ConnectBlock(const CBlock& block, BlockValidationState& state,
// they need to be added to control which runs them asynchronously. Otherwise, CheckInputScripts runs the checks before returning.
if (control) {
std::vector<CScriptCheck> vChecks;
- tx_ok = CheckInputScripts(tx, tx_state, view, flags, fCacheResults, fCacheResults, txsdata[i], m_chainman.m_validation_cache, &vChecks);
+ tx_ok = CheckInputScripts(tx, tx_state, view, flags, CheckInputScriptsFor::Block, fCacheResults, fCacheResults, txsdata[i], m_chainman.m_validation_cache, &vChecks);
if (tx_ok) control->Add(std::move(vChecks));
} else {
- tx_ok = CheckInputScripts(tx, tx_state, view, flags, fCacheResults, fCacheResults, txsdata[i], m_chainman.m_validation_cache);
+ tx_ok = CheckInputScripts(tx, tx_state, view, flags, CheckInputScriptsFor::Block, fCacheResults, fCacheResults, txsdata[i], m_chainman.m_validation_cache);
}
if (!tx_ok) {
// Any transaction validation failure in ConnectBlock is a block consensus failure
@@ -6154,6 +6228,7 @@ ChainstateManager::ChainstateManager(const util::SignalInterrupt& interrupt, Opt
m_interrupt{interrupt},
m_options{Flatten(std::move(options))},
m_blockman{interrupt, std::move(blockman_options)},
+ m_all_consensus_script_flags{GetAllConsensusScriptFlags(m_options.chainparams.GetConsensus())},
m_validation_cache{m_options.script_execution_cache_bytes, m_options.signature_cache_bytes}
{
}
### src/validation.h
@@ -1047,6 +1047,12 @@ class ChainstateManager
//! chainstate to avoid duplicating block metadata.
node::BlockManager m_blockman;
+ /** Determine the potential consensus script flags for blocks in a chain */
+ static script_verify_flags GetAllConsensusScriptFlags(const Consensus::Params& params);
+
+ /** Store the potential consensus script flags for this manager's selected params */
+ const script_verify_flags m_all_consensus_script_flags;
+
ValidationCache m_validation_cache;
/**
@@ -1421,7 +1427,43 @@ bool IsBIP30Repeat(const CBlockIndex& block_index);
/** Identifies blocks which coinbase output was subsequently overwritten in the UTXO set (see BIP30) */
bool IsBIP30Unspendable(const uint256& block_hash, int block_height);
+/** Set of script verify flags that may be enforced at the consensus level
+ * (for some combination of chain params and chain state)
+ */
+inline constexpr script_verify_flags CONSENSUS_SCRIPT_VERIFY_FLAGS{
+ SCRIPT_VERIFY_NONE
+ | SCRIPT_VERIFY_P2SH
+ | SCRIPT_VERIFY_WITNESS
+ | SCRIPT_VERIFY_TAPROOT
+ | SCRIPT_VERIFY_DERSIG
+ | SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY
+ | SCRIPT_VERIFY_CHECKSEQUENCEVERIFY
+ | SCRIPT_VERIFY_NULLDUMMY
+};
+
// Returns the script flags which should be checked for a given block
+// (a subset of CONSENSUS_SCRIPT_VERIFY_FLAGS)
script_verify_flags GetBlockScriptFlags(const CBlockIndex& block_index, const ChainstateManager& chainman);
+/** The context CheckInputScripts is called in, which decides how a
+ * script failure is reported: as a consensus failure for blocks,
+ * or as a standardness failure for the mempool. The flags alone can't
+ * determine this, as the mempool may check with consensus flags only
+ * (-acceptnonstdtxn).
+ */
+enum class CheckInputScriptsFor {
+ Block,
+ Mempool,
+};
+
+bool CheckInputScripts(const CTransaction& tx, TxValidationState& state,
+ const CCoinsViewCache& inputs,
+ script_verify_flags flags,
+ CheckInputScriptsFor check_for,
+ bool cacheSigStore,
+ bool cacheFullScriptStore, PrecomputedTransactionData& txdata,
+ ValidationCache& validation_cache,
+ std::vector<CScriptCheck>* pvChecks = nullptr)
+ EXCLUSIVE_LOCKS_REQUIRED(cs_main);
+
#endif // BITCOIN_VALIDATION_H
### test/functional/data/invalid_txs.py
@@ -73,6 +73,9 @@ class BadTxTemplate:
# The expected error code given by bitcoind upon submission of the tx.
reject_reason: Optional[str] = ""
+ # The expected error code with -acceptnonstdtxn=0 if different.
+ std_reject_reason: Optional[str] = None
+
# Only specified if it differs from mempool acceptance error.
block_reject_reason = ""
@@ -131,6 +134,7 @@ def get_tx(self):
# but doesn't spend a segwit output
class ExtraWitness(BadTxTemplate):
reject_reason = "tx-size-small"
+ std_reject_reason = "scriptpubkey"
block_reject_reason = "block-script-verify-flag-failed (Witness provided for non-witness script)"
def get_tx(self):
@@ -227,6 +231,7 @@ def get_tx(self):
class InvalidOPIFConstruction(BadTxTemplate):
reject_reason = "mempool-script-verify-flag-failed (Invalid OP_IF construction)"
+ std_reject_reason = "scriptsig-not-pushonly"
def get_tx(self):
return create_tx_with_script(
@@ -236,6 +241,7 @@ def get_tx(self):
class TooManySigopsPerBlock(BadTxTemplate):
reject_reason = "bad-txns-too-many-sigops"
+ std_reject_reason = "scriptpubkey"
block_reject_reason = "bad-blk-sigops, out-of-bounds SigOpCount"
def get_tx(self):
@@ -248,6 +254,7 @@ def get_tx(self):
class TooManySigopsPerTransaction(BadTxTemplate):
reject_reason = "bad-txns-too-many-sigops"
+ std_reject_reason = "scriptpubkey"
valid_in_block = True
def get_tx(self):
@@ -270,13 +277,15 @@ def get_tx(self):
return type('DisabledOpcode_' + str(opcode), (BadTxTemplate,), {
'reject_reason': "disabled opcode",
+ 'std_reject_reason': "scriptsig-not-pushonly",
'get_tx': get_tx,
'valid_in_block' : False
})
class NonStandardAndInvalid(BadTxTemplate):
"""A non-standard transaction which is also consensus-invalid should return the first error."""
- reject_reason = "mempool-script-verify-flag-failed (Using OP_CODESEPARATOR in non-witness script)"
+ reject_reason = "mempool-script-verify-flag-failed (OP_RETURN was encountered)"
+ std_reject_reason = "scriptsig-not-pushonly"
block_reject_reason = "block-script-verify-flag-failed (OP_RETURN was encountered)"
valid_in_block = False
### test/functional/p2p_invalid_tx.py
@@ -23,10 +23,11 @@
class InvalidTxRequestTest(BitcoinTestFramework):
def set_test_params(self):
- self.num_nodes = 1
- self.extra_args = [[
- "-acceptnonstdtxn=1",
- ]]
+ self.num_nodes = 2
+ self.extra_args = [
+ ["-acceptnonstdtxn=1"],
+ ["-acceptnonstdtxn=0"], # default
+ ]
self.setup_clean_chain = True
def bootstrap_p2p(self, *, num_connections=1):
@@ -46,9 +47,13 @@ def reconnect_p2p(self, **kwargs):
def run_test(self):
node = self.nodes[0] # convenience reference to the node
+ std_node = self.nodes[1] # convenience reference to the node
self.bootstrap_p2p() # Add one p2p connection to the node
+ # Add a p2p connection for the std node
+ std_node.add_p2p_connection(P2PDataStore())
+
best_block = self.nodes[0].getbestblockhash()
tip = int(best_block, 16)
best_block_time = self.nodes[0].getblock(best_block)['time']
@@ -75,6 +80,11 @@ def run_test(self):
[tx], node, success=False,
reject_reason=template.reject_reason,
)
+ std_reject = template.std_reject_reason or template.reject_reason
+ std_node.p2ps[0].send_txs_and_test(
+ [tx], std_node, success=False,
+ reject_reason=std_reject,
+ )
# Make two p2p connections to provide the node with orphans
# * p2ps[0] will send valid orphan txs (one with low fee)
@@ -116,7 +126,7 @@ def run_test(self):
node.p2ps[1].send_txs_and_test([tx_orphan_2_invalid], node, success=False)
assert_equal(0, node.getmempoolinfo()['size']) # Mempool should be empty
- assert_equal(2, len(node.getpeerinfo())) # p2ps[1] is still connected
+ assert_equal(3, len(node.getpeerinfo())) # std node and both p2ps still connected
self.log.info('Send the withhold tx ... ')
with node.assert_debug_log(expected_msgs=["bad-txns-in-belowout"]):
### test/functional/p2p_segwit.py
@@ -1394,14 +1394,13 @@ def test_segwit_versions(self):
# Now the node will no longer ask for getdata of this transaction when advertised by same txid
self.std_node.announce_tx_and_wait_for_getdata(tx3, success=False)
- # Spending a higher version witness output is not allowed by policy,
- # even with the node that accepts non-standard txs.
- test_transaction_acceptance(self.nodes[0], self.test_node, tx3, with_witness=True, accepted=False, reason="reserved for soft-fork upgrades")
+ # Spending a higher version witness output is allowed on the node with -acceptnonstdtxn
+ test_transaction_acceptance(self.nodes[0], self.test_node, tx3, with_witness=True, accepted=True)
- # Building a block with the transaction must be valid, however.
+ # Building a block with the transaction must be valid, however, even without -acceptnonstdtxn.
block = self.build_next_block()
self.update_witness_block_with_transactions(block, [tx2, tx3])
- test_witness_block(self.nodes[0], self.test_node, block, accepted=True)
+ test_witness_block(self.nodes[1], self.std_node, block, accepted=True)
self.sync_blocks()
# Add utxo to our list
@@ -1480,11 +1479,11 @@ def test_uncompressed_pubkey(self):
sign_input_segwitv0(tx2, 0, script, tx.vout[0].nValue, key)
# Should fail policy test.
- test_transaction_acceptance(self.nodes[0], self.test_node, tx2, True, False, 'mempool-script-verify-flag-failed (Using non-compressed keys in segwit)')
+ test_transaction_acceptance(self.nodes[1], self.std_node, tx2, True, False, 'mempool-script-verify-flag-failed (Using non-compressed keys in segwit)')
# But passes consensus.
block = self.build_next_block()
self.update_witness_block_with_transactions(block, [tx2])
- test_witness_block(self.nodes[0], self.test_node, block, accepted=True)
+ test_witness_block(self.nodes[1], self.std_node, block, accepted=True)
# Test 2: P2WSH
# Try to spend the P2WSH output created in last test.
@@ -1499,11 +1498,11 @@ def test_uncompressed_pubkey(self):
sign_p2pk_witness_input(witness_script, tx3, 0, SIGHASH_ALL, tx2.vout[0].nValue, key)
# Should fail policy test.
- test_transaction_acceptance(self.nodes[0], self.test_node, tx3, True, False, 'mempool-script-verify-flag-failed (Using non-compressed keys in segwit)')
+ test_transaction_acceptance(self.nodes[1], self.std_node, tx3, True, False, 'mempool-script-verify-flag-failed (Using non-compressed keys in segwit)')
# But passes consensus.
block = self.build_next_block()
self.update_witness_block_with_transactions(block, [tx3])
- test_witness_block(self.nodes[0], self.test_node, block, accepted=True)
+ test_witness_block(self.nodes[1], self.std_node, block, accepted=True)
# Test 3: P2SH(P2WSH)
# Try to spend the P2SH output created in the last test.
@@ -1516,10 +1515,10 @@ def test_uncompressed_pubkey(self):
sign_p2pk_witness_input(witness_script, tx4, 0, SIGHASH_ALL, tx3.vout[0].nValue, key)
# Should fail policy test.
- test_transaction_acceptance(self.nodes[0], self.test_node, tx4, True, False, 'mempool-script-verify-flag-failed (Using non-compressed keys in segwit)')
+ test_transaction_acceptance(self.nodes[1], self.std_node, tx4, True, False, 'mempool-script-verify-flag-failed (Using non-compressed keys in segwit)')
block = self.build_next_block()
self.update_witness_block_with_transactions(block, [tx4])
- test_witness_block(self.nodes[0], self.test_node, block, accepted=True)
+ test_witness_block(self.nodes[1], self.std_node, block, accepted=True)
# Test 4: Uncompressed pubkeys should still be valid in non-segwit
# transactions.Why this scored 22/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.