From 0ee6f6326a77fac20adff9d4ab3a801d214f3583 Mon Sep 17 00:00:00 2001 From: Antoine Poinsot Date: Thu, 30 Apr 2026 17:11:12 -0400 Subject: [PATCH 01/20] chainparams: add versionbits deployment for BIP 54 --- src/consensus/params.h | 1 + src/deploymentinfo.cpp | 4 +++ src/kernel/chainparams.cpp | 28 ++++++++++++++++++++ src/rpc/blockchain.cpp | 1 + test/functional/mining_basic.py | 2 +- test/functional/rpc_blockchain.py | 13 +++++++++ test/functional/test_framework/blocktools.py | 2 +- 7 files changed, 49 insertions(+), 2 deletions(-) diff --git a/src/consensus/params.h b/src/consensus/params.h index 7f56729455a8..e33bce3e95e9 100644 --- a/src/consensus/params.h +++ b/src/consensus/params.h @@ -36,6 +36,7 @@ constexpr bool ValidDeployment(BuriedDeployment dep) { return dep <= DEPLOYMENT_ enum DeploymentPos : uint16_t { DEPLOYMENT_TESTDUMMY, + DEPLOYMENT_CONSENSUSCLEANUP, // Deployment of BIP 54 // NOTE: Also add new deployments to VersionBitsDeploymentInfo in deploymentinfo.cpp // Removing an entry may require bumping MinBIP9WarningHeight. MAX_VERSION_BITS_DEPLOYMENTS diff --git a/src/deploymentinfo.cpp b/src/deploymentinfo.cpp index 551982b23ae7..69076a3040b2 100644 --- a/src/deploymentinfo.cpp +++ b/src/deploymentinfo.cpp @@ -13,6 +13,10 @@ const std::array Versi .name = "testdummy", .gbt_optional_rule = true, }, + VBDeploymentInfo{ + .name = "consensuscleanup", + .gbt_optional_rule = false, + }, }; std::string DeploymentName(Consensus::BuriedDeployment dep) diff --git a/src/kernel/chainparams.cpp b/src/kernel/chainparams.cpp index 352434dae51c..5fe6f94743e2 100644 --- a/src/kernel/chainparams.cpp +++ b/src/kernel/chainparams.cpp @@ -136,6 +136,11 @@ class CMainParams : public CChainParams { consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].threshold = 1815; // 90% consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].period = 2016; + // Deployment of the Consensus Cleanup (BIP 54) + consensus.vDeployments[Consensus::DEPLOYMENT_CONSENSUSCLEANUP].bit = 3; + consensus.vDeployments[Consensus::DEPLOYMENT_CONSENSUSCLEANUP].nStartTime = Consensus::BIP9Deployment::NEVER_ACTIVE; + consensus.vDeployments[Consensus::DEPLOYMENT_CONSENSUSCLEANUP].nTimeout = Consensus::BIP9Deployment::NO_TIMEOUT; + ApplyDeploymentOptions(opts.dep_opts); consensus.nMinimumChainWork = uint256{"0000000000000000000000000000000000000001128750f82f4c366153a3a030"}; @@ -260,6 +265,11 @@ class CTestNetParams : public CChainParams { consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].threshold = 1512; // 75% consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].period = 2016; + // Deployment of the Consensus Cleanup (BIP 54) + consensus.vDeployments[Consensus::DEPLOYMENT_CONSENSUSCLEANUP].bit = 3; + consensus.vDeployments[Consensus::DEPLOYMENT_CONSENSUSCLEANUP].nStartTime = Consensus::BIP9Deployment::NEVER_ACTIVE; + consensus.vDeployments[Consensus::DEPLOYMENT_CONSENSUSCLEANUP].nTimeout = Consensus::BIP9Deployment::NO_TIMEOUT; + ApplyDeploymentOptions(opts.dep_opts); consensus.nMinimumChainWork = uint256{"0000000000000000000000000000000000000000000017dde1c649f3708d14b6"}; @@ -362,6 +372,11 @@ class CTestNet4Params : public CChainParams { consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].threshold = 1512; // 75% consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].period = 2016; + // Deployment of the Consensus Cleanup (BIP 54) + consensus.vDeployments[Consensus::DEPLOYMENT_CONSENSUSCLEANUP].bit = 3; + consensus.vDeployments[Consensus::DEPLOYMENT_CONSENSUSCLEANUP].nStartTime = Consensus::BIP9Deployment::NEVER_ACTIVE; + consensus.vDeployments[Consensus::DEPLOYMENT_CONSENSUSCLEANUP].nTimeout = Consensus::BIP9Deployment::NO_TIMEOUT; + ApplyDeploymentOptions(opts.dep_opts); consensus.nMinimumChainWork = uint256{"0000000000000000000000000000000000000000000009a0fe15d0177d086304"}; @@ -507,6 +522,11 @@ class SigNetParams : public CChainParams { consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].threshold = 1815; // 90% consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].period = 2016; + // Deployment of the Consensus Cleanup (BIP 54) + consensus.vDeployments[Consensus::DEPLOYMENT_CONSENSUSCLEANUP].bit = 3; + consensus.vDeployments[Consensus::DEPLOYMENT_CONSENSUSCLEANUP].nStartTime = Consensus::BIP9Deployment::NEVER_ACTIVE; + consensus.vDeployments[Consensus::DEPLOYMENT_CONSENSUSCLEANUP].nTimeout = Consensus::BIP9Deployment::NO_TIMEOUT; + ApplyDeploymentOptions(options.dep_opts); // message start is defined as the first 4 bytes of the sha256d of the block script @@ -591,6 +611,14 @@ class CRegTestParams : public CChainParams consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].threshold = 108; // 75% consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].period = 144; // Faster than normal for regtest (144 instead of 2016) + // Deployment of the Consensus Cleanup (BIP 54) + consensus.vDeployments[Consensus::DEPLOYMENT_CONSENSUSCLEANUP].bit = 3; + consensus.vDeployments[Consensus::DEPLOYMENT_CONSENSUSCLEANUP].nStartTime = Consensus::BIP9Deployment::ALWAYS_ACTIVE; + consensus.vDeployments[Consensus::DEPLOYMENT_CONSENSUSCLEANUP].nTimeout = Consensus::BIP9Deployment::NO_TIMEOUT; + consensus.vDeployments[Consensus::DEPLOYMENT_CONSENSUSCLEANUP].min_activation_height = 0; // No activation delay + consensus.vDeployments[Consensus::DEPLOYMENT_CONSENSUSCLEANUP].threshold = 108; // 75% + consensus.vDeployments[Consensus::DEPLOYMENT_CONSENSUSCLEANUP].period = 144; + consensus.nMinimumChainWork = uint256{}; consensus.defaultAssumeValid = uint256{}; diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index f3e1330b4494..cc9214a4da88 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -1508,6 +1508,7 @@ UniValue DeploymentInfo(const CBlockIndex* blockindex, const ChainstateManager& SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_CSV); SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_SEGWIT); SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_TESTDUMMY); + SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_CONSENSUSCLEANUP); return softforks; } } // anon namespace diff --git a/test/functional/mining_basic.py b/test/functional/mining_basic.py index 7060a3cba62b..d89b385f4e82 100755 --- a/test/functional/mining_basic.py +++ b/test/functional/mining_basic.py @@ -449,7 +449,7 @@ def run_test(self): assert_raises_rpc_error(-8, "getblocktemplate must be called with the segwit rule set", node.getblocktemplate, {}) self.log.info("getblocktemplate: result should set the right rules") - assert_equal(['csv', '!segwit', 'taproot'], self.nodes[0].getblocktemplate(NORMAL_GBT_REQUEST_PARAMS)['rules']) + assert_equal(['csv', '!segwit', 'taproot', '!consensuscleanup'], self.nodes[0].getblocktemplate(NORMAL_GBT_REQUEST_PARAMS)['rules']) self.log.info("submitblock: Test block decode failure") assert_raises_rpc_error(-22, "Block decode failed", node.submitblock, block.serialize()[:-15].hex()) diff --git a/test/functional/rpc_blockchain.py b/test/functional/rpc_blockchain.py index d731907fd8ca..fb8a722fb342 100755 --- a/test/functional/rpc_blockchain.py +++ b/test/functional/rpc_blockchain.py @@ -244,6 +244,19 @@ def check_signalling_deploymentinfo_result(self, gdi_result, height, blockhash, }, 'active': False }, + 'consensuscleanup': { + 'type': 'bip9', + 'bip9': { + 'start_time': -1, + 'timeout': 9223372036854775807, + 'min_activation_height': 0, + 'status': 'active', + 'status_next': 'active', + 'since': 0, + }, + 'height': 0, + 'active': True + } } }) diff --git a/test/functional/test_framework/blocktools.py b/test/functional/test_framework/blocktools.py index 529f07cd3c7f..5e410f2f222c 100644 --- a/test/functional/test_framework/blocktools.py +++ b/test/functional/test_framework/blocktools.py @@ -65,7 +65,7 @@ NULL_OUTPOINT = COutPoint(0, 0xffffffff) -NORMAL_GBT_REQUEST_PARAMS = {"rules": ["segwit"]} +NORMAL_GBT_REQUEST_PARAMS = {"rules": ["segwit", "consensuscleanup"]} VERSIONBITS_LAST_OLD_BLOCK_VERSION = 4 MIN_BLOCKS_TO_KEEP = 288 From a16b14a77526eeba92ff205d45eb007708ad05b1 Mon Sep 17 00:00:00 2001 From: Antoine Poinsot Date: Tue, 20 Jan 2026 16:38:25 -0500 Subject: [PATCH 02/20] scripted-diff: rename BIP54-sigops constants to MAX_TX_BIP54_SIGOPS BIP54 counts sigops differently from existing sigops-based checks. Since we are overloading the sigops term, make clear the constant refers to BIP54-sigops, not other kinds of pre-existing sigops. Also update the functional test framework's constant that has "standardness" in its name, since we are about to make it consensus critical (func test scripted-diff courtesy of Anthony Towns). -BEGIN VERIFY SCRIPT- sed -i 's/MAX_TX_LEGACY_SIGOPS/MAX_TX_BIP54_SIGOPS/g' $(git grep -l MAX_TX_LEGACY_SIGOPS src/) sed -i 's/MAX_STD_LEGACY_SIGOPS/MAX_TX_BIP54_SIGOPS/g' $(git grep -l MAX_STD_LEGACY_SIGOPS) sed -i 's/signature operations in validating a transaction./signature operations in a single transaction, per BIP54./' test/functional/test_framework/script_util.py -END VERIFY SCRIPT- Co-Authored-by: Anthony Towns --- src/policy/policy.cpp | 2 +- src/policy/policy.h | 2 +- src/test/transaction_tests.cpp | 10 +++++----- test/functional/mempool_sigoplimit.py | 4 ++-- test/functional/test_framework/script_util.py | 4 ++-- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/policy/policy.cpp b/src/policy/policy.cpp index 83ceb63cbcd7..a386a0481126 100644 --- a/src/policy/policy.cpp +++ b/src/policy/policy.cpp @@ -185,7 +185,7 @@ static bool CheckSigopsBIP54(const CTransaction& tx, const CCoinsViewCache& inpu sigops += txin.scriptSig.GetSigOpCount(/*fAccurate=*/true); sigops += prev_txo.scriptPubKey.GetSigOpCount(txin.scriptSig); - if (sigops > MAX_TX_LEGACY_SIGOPS) { + if (sigops > MAX_TX_BIP54_SIGOPS) { return false; } } diff --git a/src/policy/policy.h b/src/policy/policy.h index 13bcf4cef750..861441d7fd79 100644 --- a/src/policy/policy.h +++ b/src/policy/policy.h @@ -43,7 +43,7 @@ static constexpr unsigned int MAX_P2SH_SIGOPS{15}; /** The maximum number of sigops we're willing to relay/mine in a single tx */ static constexpr unsigned int MAX_STANDARD_TX_SIGOPS_COST{MAX_BLOCK_SIGOPS_COST/5}; /** The maximum number of potentially executed legacy signature operations in a single standard tx */ -static constexpr unsigned int MAX_TX_LEGACY_SIGOPS{2'500}; +static constexpr unsigned int MAX_TX_BIP54_SIGOPS{2'500}; /** Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or replacement **/ static constexpr unsigned int DEFAULT_INCREMENTAL_RELAY_FEE{100}; /** Default for -bytespersigop */ diff --git a/src/test/transaction_tests.cpp b/src/test/transaction_tests.cpp index a5b123ed4659..6829ff11dbd8 100644 --- a/src/test/transaction_tests.cpp +++ b/src/test/transaction_tests.cpp @@ -1033,7 +1033,7 @@ BOOST_AUTO_TEST_CASE(max_standard_legacy_sigops) // Create a transaction fanning out as many such P2SH outputs as is standard to spend in a // single transaction, and a transaction spending them. CMutableTransaction tx_create, tx_max_sigops; - const unsigned p2sh_inputs_count{MAX_TX_LEGACY_SIGOPS / MAX_P2SH_SIGOPS}; + const unsigned p2sh_inputs_count{MAX_TX_BIP54_SIGOPS / MAX_P2SH_SIGOPS}; tx_create.vout.reserve(p2sh_inputs_count); for (unsigned i{0}; i < p2sh_inputs_count; ++i) { tx_create.vout.emplace_back(424242 + i, max_sigops_p2sh); @@ -1045,7 +1045,7 @@ BOOST_AUTO_TEST_CASE(max_standard_legacy_sigops) } // p2sh_inputs_count is truncated to 166 (from 166.6666..) - BOOST_CHECK_LT(p2sh_inputs_count * MAX_P2SH_SIGOPS, MAX_TX_LEGACY_SIGOPS); + BOOST_CHECK_LT(p2sh_inputs_count * MAX_P2SH_SIGOPS, MAX_TX_BIP54_SIGOPS); AddCoins(coins, CTransaction(tx_create), 0, false); // 2490 sigops is below the limit. @@ -1060,7 +1060,7 @@ BOOST_AUTO_TEST_CASE(max_standard_legacy_sigops) } tx_max_sigops.vin.emplace_back(prev_txid, p2sh_inputs_count, CScript() << ToByteVector(max_sigops_redeem_script)); AddCoins(coins, CTransaction(tx_create), 0, false); - BOOST_CHECK_GT((p2sh_inputs_count + 1) * MAX_P2SH_SIGOPS, MAX_TX_LEGACY_SIGOPS); + BOOST_CHECK_GT((p2sh_inputs_count + 1) * MAX_P2SH_SIGOPS, MAX_TX_BIP54_SIGOPS); auto legacy_sigops_count = GetP2SHSigOpCount(CTransaction(tx_max_sigops), coins); BOOST_CHECK_EQUAL(legacy_sigops_count, 2505); std::string reject_reason("bad-txns-nonstandard-inputs"); @@ -1089,7 +1089,7 @@ BOOST_AUTO_TEST_CASE(max_standard_legacy_sigops) AddCoins(coins, CTransaction(tx_create_p2pk), 0, false); // The transaction now contains exactly 2500 sigops, the check should pass. - BOOST_CHECK_EQUAL(p2sh_inputs_count * MAX_P2SH_SIGOPS + p2pk_inputs_count * 1, MAX_TX_LEGACY_SIGOPS); + BOOST_CHECK_EQUAL(p2sh_inputs_count * MAX_P2SH_SIGOPS + p2pk_inputs_count * 1, MAX_TX_BIP54_SIGOPS); BOOST_CHECK(::ValidateInputsStandardness(CTransaction(tx_max_sigops), coins).IsValid()); // Now, add some Segwit inputs. We add one for each defined Segwit output type. The limit @@ -1118,7 +1118,7 @@ BOOST_AUTO_TEST_CASE(max_standard_legacy_sigops) } AddCoins(coins, CTransaction(tx_create_p2pk), 0, false); auto legacy_sigop_count_p2pk = p2sh_inputs_count * MAX_P2SH_SIGOPS + p2pk_inputs_count * 1; - BOOST_CHECK_GT(legacy_sigop_count_p2pk, MAX_TX_LEGACY_SIGOPS); + BOOST_CHECK_GT(legacy_sigop_count_p2pk, MAX_TX_BIP54_SIGOPS); { auto validation_state = ValidateInputsStandardness(CTransaction(tx_max_sigops), coins); BOOST_CHECK(validation_state.IsInvalid()); diff --git a/test/functional/mempool_sigoplimit.py b/test/functional/mempool_sigoplimit.py index 823d70549ee1..5b129c146265 100755 --- a/test/functional/mempool_sigoplimit.py +++ b/test/functional/mempool_sigoplimit.py @@ -33,7 +33,7 @@ keys_to_multisig_script, script_to_p2wsh_script, script_to_p2sh_script, - MAX_STD_LEGACY_SIGOPS, + MAX_TX_BIP54_SIGOPS, MAX_STD_P2SH_SIGOPS, ) from test_framework.test_framework import BitcoinTestFramework @@ -198,7 +198,7 @@ def test_legacy_sigops_stdness(self): # Create enough outputs to reach the sigops limit when spending them all at once. outpoints = [] - for _ in range(int(MAX_STD_LEGACY_SIGOPS / MAX_STD_P2SH_SIGOPS) + 1): + for _ in range(int(MAX_TX_BIP54_SIGOPS / MAX_STD_P2SH_SIGOPS) + 1): res = self.wallet.send_to(from_node=self.nodes[0], scriptPubKey=packed_p2sh_script, amount=1_000) txid = int.from_bytes(bytes.fromhex(res["txid"]), byteorder="big") outpoints.append(COutPoint(txid, res["sent_vout"])) diff --git a/test/functional/test_framework/script_util.py b/test/functional/test_framework/script_util.py index 02be353854be..3bbb5d7e5aff 100755 --- a/test/functional/test_framework/script_util.py +++ b/test/functional/test_framework/script_util.py @@ -41,8 +41,8 @@ assert_equal, ) -# Maximum number of potentially executed legacy signature operations in validating a transaction. -MAX_STD_LEGACY_SIGOPS = 2_500 +# Maximum number of potentially executed legacy signature operations in a single transaction, per BIP54. +MAX_TX_BIP54_SIGOPS = 2_500 # Maximum number of sigops per standard P2SH redeemScript. MAX_STD_P2SH_SIGOPS = 15 From e2d02a248943aaa3bcb62136db895cbd8c3a3f19 Mon Sep 17 00:00:00 2001 From: Antoine Poinsot Date: Thu, 4 Sep 2025 16:14:42 -0400 Subject: [PATCH 03/20] moveonly: move CheckSigopsBIP54 from policy to consensus Move the function that checks whether a transaction respects the BIP54 sigops rule to the consensus folder (along with the accompanying constant), as it will be made consensus-critical in the next commit. Can be reviewed with git's --color-moved option. --- src/CMakeLists.txt | 2 +- src/consensus/consensus.h | 3 +++ src/consensus/tx_verify.cpp | 26 ++++++++++++++++++++++++++ src/consensus/tx_verify.h | 5 +++++ src/policy/policy.cpp | 32 ++------------------------------ src/policy/policy.h | 2 -- 6 files changed, 37 insertions(+), 33 deletions(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 2b6840bbc390..7040a48f664d 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -115,6 +115,7 @@ add_library(bitcoin_common STATIC EXCLUDE_FROM_ALL common/system.cpp common/url.cpp compressor.cpp + consensus/tx_verify.cpp core_io.cpp deploymentinfo.cpp external_signer.cpp @@ -188,7 +189,6 @@ add_library(bitcoin_node STATIC EXCLUDE_FROM_ALL bip324.cpp blockencodings.cpp blockfilter.cpp - consensus/tx_verify.cpp dbwrapper.cpp deploymentstatus.cpp flatfile.cpp diff --git a/src/consensus/consensus.h b/src/consensus/consensus.h index 71b5fe2468d9..ae230ce47b28 100644 --- a/src/consensus/consensus.h +++ b/src/consensus/consensus.h @@ -34,4 +34,7 @@ static constexpr unsigned int LOCKTIME_VERIFY_SEQUENCE = (1 << 0); */ static constexpr int64_t MAX_TIMEWARP = 600; +/** The maximum number of potentially executed legacy signature operations in a single tx */ +static constexpr unsigned int MAX_TX_BIP54_SIGOPS{2'500}; + #endif // BITCOIN_CONSENSUS_CONSENSUS_H diff --git a/src/consensus/tx_verify.cpp b/src/consensus/tx_verify.cpp index 4efed70fd411..2247591f3889 100644 --- a/src/consensus/tx_verify.cpp +++ b/src/consensus/tx_verify.cpp @@ -161,6 +161,32 @@ int64_t GetTransactionSigOpCost(const CTransaction& tx, const CCoinsViewCache& i return nSigOps; } +bool Consensus::CheckSigopsBIP54(const CTransaction& tx, const CCoinsViewCache& inputs) +{ + Assert(!tx.IsCoinBase()); + + unsigned int sigops{0}; + for (const auto& txin: tx.vin) { + const auto& prev_txo{inputs.AccessCoin(txin.prevout).out}; + + // Unlike the existing block wide sigop limit which counts sigops present in the block + // itself (including the scriptPubKey which is not executed until spending later), BIP54 + // counts sigops in the block where they are potentially executed (only). + // This means sigops in the spent scriptPubKey count toward the limit. + // `fAccurate` means correctly accounting sigops for CHECKMULTISIGs(VERIFY) with 16 pubkeys + // or fewer. This method of accounting was introduced by BIP16, and BIP54 reuses it. + // The GetSigOpCount call on the previous scriptPubKey counts both bare and P2SH sigops. + sigops += txin.scriptSig.GetSigOpCount(/*fAccurate=*/true); + sigops += prev_txo.scriptPubKey.GetSigOpCount(txin.scriptSig); + + if (sigops > MAX_TX_BIP54_SIGOPS) { + return false; + } + } + + return true; +} + bool Consensus::CheckTxInputs(const CTransaction& tx, TxValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, CAmount& txfee) { // are the actual inputs available? diff --git a/src/consensus/tx_verify.h b/src/consensus/tx_verify.h index ed44d435c1b9..d964a9de54fe 100644 --- a/src/consensus/tx_verify.h +++ b/src/consensus/tx_verify.h @@ -19,6 +19,11 @@ class TxValidationState; /** Transaction validation functions */ namespace Consensus { +/** + * Check the total number of non-witness sigops across the whole transaction, as per BIP54. + */ +bool CheckSigopsBIP54(const CTransaction& tx, const CCoinsViewCache& inputs); + /** * Check whether all inputs of this transaction are valid (no double spends and amounts) * This does not modify the UTXO set. This does not check scripts and sigs. diff --git a/src/policy/policy.cpp b/src/policy/policy.cpp index a386a0481126..3ec0a8d7204e 100644 --- a/src/policy/policy.cpp +++ b/src/policy/policy.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -164,35 +165,6 @@ bool IsStandardTx(const CTransaction& tx, const std::optional& max_dat return true; } -/** - * Check the total number of non-witness sigops across the whole transaction, as per BIP54. - */ -static bool CheckSigopsBIP54(const CTransaction& tx, const CCoinsViewCache& inputs) -{ - Assert(!tx.IsCoinBase()); - - unsigned int sigops{0}; - for (const auto& txin: tx.vin) { - const auto& prev_txo{inputs.AccessCoin(txin.prevout).out}; - - // Unlike the existing block wide sigop limit which counts sigops present in the block - // itself (including the scriptPubKey which is not executed until spending later), BIP54 - // counts sigops in the block where they are potentially executed (only). - // This means sigops in the spent scriptPubKey count toward the limit. - // `fAccurate` means correctly accounting sigops for CHECKMULTISIGs(VERIFY) with 16 pubkeys - // or fewer. This method of accounting was introduced by BIP16, and BIP54 reuses it. - // The GetSigOpCount call on the previous scriptPubKey counts both bare and P2SH sigops. - sigops += txin.scriptSig.GetSigOpCount(/*fAccurate=*/true); - sigops += prev_txo.scriptPubKey.GetSigOpCount(txin.scriptSig); - - if (sigops > MAX_TX_BIP54_SIGOPS) { - return false; - } - } - - return true; -} - /** * Check transaction inputs. * @@ -218,7 +190,7 @@ TxValidationState ValidateInputsStandardness(const CTransaction& tx, const CCoin return state; // Coinbases don't use vin normally } - if (!CheckSigopsBIP54(tx, mapInputs)) { + if (!Consensus::CheckSigopsBIP54(tx, mapInputs)) { state.Invalid(TxValidationResult::TX_INPUTS_NOT_STANDARD, "bad-txns-nonstandard-inputs", "non-witness sigops exceed bip54 limit"); return state; } diff --git a/src/policy/policy.h b/src/policy/policy.h index 861441d7fd79..a2158122b79c 100644 --- a/src/policy/policy.h +++ b/src/policy/policy.h @@ -42,8 +42,6 @@ static constexpr unsigned int MIN_STANDARD_TX_NONWITNESS_SIZE{65}; static constexpr unsigned int MAX_P2SH_SIGOPS{15}; /** The maximum number of sigops we're willing to relay/mine in a single tx */ static constexpr unsigned int MAX_STANDARD_TX_SIGOPS_COST{MAX_BLOCK_SIGOPS_COST/5}; -/** The maximum number of potentially executed legacy signature operations in a single standard tx */ -static constexpr unsigned int MAX_TX_BIP54_SIGOPS{2'500}; /** Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or replacement **/ static constexpr unsigned int DEFAULT_INCREMENTAL_RELAY_FEE{100}; /** Default for -bytespersigop */ From c1945dda121aef1b43897b8adca8acb738b8c4ad Mon Sep 17 00:00:00 2001 From: Antoine Poinsot Date: Tue, 14 Oct 2025 16:20:07 -0400 Subject: [PATCH 04/20] validation: make BIP54 sigops check consensus-critical When BIP54 is active, enforce that block transactions do not violate the BIP54 limit on the number of legacy sigops present in Scripts that get executed during block validation. --- src/consensus/tx_verify.cpp | 6 +++- src/consensus/tx_verify.h | 3 +- src/policy/policy.cpp | 7 ----- src/test/fuzz/coins_view.cpp | 7 ++++- src/test/transaction_tests.cpp | 40 ++++++++++++++------------- src/txmempool.cpp | 2 +- src/validation.cpp | 5 ++-- test/functional/mempool_sigoplimit.py | 13 ++++----- 8 files changed, 44 insertions(+), 39 deletions(-) diff --git a/src/consensus/tx_verify.cpp b/src/consensus/tx_verify.cpp index 2247591f3889..0c0ab2393c29 100644 --- a/src/consensus/tx_verify.cpp +++ b/src/consensus/tx_verify.cpp @@ -187,7 +187,7 @@ bool Consensus::CheckSigopsBIP54(const CTransaction& tx, const CCoinsViewCache& return true; } -bool Consensus::CheckTxInputs(const CTransaction& tx, TxValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, CAmount& txfee) +bool Consensus::CheckTxInputs(const CTransaction& tx, TxValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, CAmount& txfee, bool enforce_bip54) { // are the actual inputs available? if (!inputs.HaveInputs(tx)) { @@ -195,6 +195,10 @@ bool Consensus::CheckTxInputs(const CTransaction& tx, TxValidationState& state, strprintf("%s: inputs missing/spent", __func__)); } + if (enforce_bip54 && !Consensus::CheckSigopsBIP54(tx, inputs)) { + return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-legacy-sigops", "too many legacy sigops (BIP54)"); + } + CAmount nValueIn = 0; for (unsigned int i = 0; i < tx.vin.size(); ++i) { const COutPoint &prevout = tx.vin[i].prevout; diff --git a/src/consensus/tx_verify.h b/src/consensus/tx_verify.h index d964a9de54fe..6657373fc5a2 100644 --- a/src/consensus/tx_verify.h +++ b/src/consensus/tx_verify.h @@ -28,9 +28,10 @@ bool CheckSigopsBIP54(const CTransaction& tx, const CCoinsViewCache& inputs); * Check whether all inputs of this transaction are valid (no double spends and amounts) * This does not modify the UTXO set. This does not check scripts and sigs. * @param[out] txfee Set to the transaction fee if successful. + * @param[in] enforce_bip54 Whether to perform the BIP54 sigops check. * Preconditions: tx.IsCoinBase() is false. */ -[[nodiscard]] bool CheckTxInputs(const CTransaction& tx, TxValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, CAmount& txfee); +[[nodiscard]] bool CheckTxInputs(const CTransaction& tx, TxValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, CAmount& txfee, bool enforce_bip54); } // namespace Consensus /** Auxiliary functions for transaction validation (ideally should not be exposed) */ diff --git a/src/policy/policy.cpp b/src/policy/policy.cpp index 3ec0a8d7204e..d3739f43db27 100644 --- a/src/policy/policy.cpp +++ b/src/policy/policy.cpp @@ -180,8 +180,6 @@ bool IsStandardTx(const CTransaction& tx, const std::optional& max_dat * as potential new upgrade hooks. * * Note that only the non-witness portion of the transaction is checked here. - * - * We also check the total number of non-witness sigops across the whole transaction, as per BIP54. */ TxValidationState ValidateInputsStandardness(const CTransaction& tx, const CCoinsViewCache& mapInputs) { @@ -190,11 +188,6 @@ TxValidationState ValidateInputsStandardness(const CTransaction& tx, const CCoin return state; // Coinbases don't use vin normally } - if (!Consensus::CheckSigopsBIP54(tx, mapInputs)) { - state.Invalid(TxValidationResult::TX_INPUTS_NOT_STANDARD, "bad-txns-nonstandard-inputs", "non-witness sigops exceed bip54 limit"); - return state; - } - for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxOut& prev = mapInputs.AccessCoin(tx.vin[i].prevout).out; diff --git a/src/test/fuzz/coins_view.cpp b/src/test/fuzz/coins_view.cpp index 6f5dbd624149..02e1a988adaa 100644 --- a/src/test/fuzz/coins_view.cpp +++ b/src/test/fuzz/coins_view.cpp @@ -335,7 +335,12 @@ void TestCoinsView(FuzzedDataProvider& fuzzed_data_provider, CCoinsViewCache& co // It is not allowed to call CheckTxInputs if CheckTransaction failed return; } - if (Consensus::CheckTxInputs(transaction, state, coins_view_cache, fuzzed_data_provider.ConsumeIntegralInRange(0, std::numeric_limits::max()), tx_fee_out)) { + if (transaction.IsCoinBase()) { + // It is not allowed to call CheckTxInputs on a coinbase transaction. + return; + } + const bool enforce_bip54{fuzzed_data_provider.ConsumeBool()}; + if (Consensus::CheckTxInputs(transaction, state, coins_view_cache, fuzzed_data_provider.ConsumeIntegralInRange(0, std::numeric_limits::max()), tx_fee_out, enforce_bip54)) { assert(MoneyRange(tx_fee_out)); } }, diff --git a/src/test/transaction_tests.cpp b/src/test/transaction_tests.cpp index 6829ff11dbd8..7dc0580e3a4d 100644 --- a/src/test/transaction_tests.cpp +++ b/src/test/transaction_tests.cpp @@ -1020,6 +1020,9 @@ BOOST_AUTO_TEST_CASE(test_IsStandard) BOOST_AUTO_TEST_CASE(max_standard_legacy_sigops) { + TxValidationState state; + const int dummy_height{0}; + CAmount dummy_fee; CCoinsViewCache coins{&CoinsViewEmpty::Get()}; CKey key; key.MakeNewKey(true); @@ -1050,7 +1053,8 @@ BOOST_AUTO_TEST_CASE(max_standard_legacy_sigops) // 2490 sigops is below the limit. BOOST_CHECK_EQUAL(GetP2SHSigOpCount(CTransaction(tx_max_sigops), coins), 2490); - BOOST_CHECK(::ValidateInputsStandardness(CTransaction(tx_max_sigops), coins).IsValid()); + BOOST_CHECK(Consensus::CheckTxInputs(CTransaction(tx_max_sigops), state, coins, dummy_height, dummy_fee, /*enforce_bip54=*/true)); + BOOST_CHECK(state.IsValid()); // Adding one more input will bump this to 2505, hitting the limit. tx_create.vout.emplace_back(424242, max_sigops_p2sh); @@ -1063,15 +1067,13 @@ BOOST_AUTO_TEST_CASE(max_standard_legacy_sigops) BOOST_CHECK_GT((p2sh_inputs_count + 1) * MAX_P2SH_SIGOPS, MAX_TX_BIP54_SIGOPS); auto legacy_sigops_count = GetP2SHSigOpCount(CTransaction(tx_max_sigops), coins); BOOST_CHECK_EQUAL(legacy_sigops_count, 2505); - std::string reject_reason("bad-txns-nonstandard-inputs"); - std::string sigop_limit_reject_debug_message("non-witness sigops exceed bip54 limit"); - { - auto validation_state = ValidateInputsStandardness(CTransaction(tx_max_sigops), coins); - BOOST_CHECK(validation_state.IsInvalid()); - BOOST_CHECK_EQUAL(validation_state.GetRejectReason(), reject_reason); - BOOST_CHECK_EQUAL(validation_state.GetDebugMessage(), sigop_limit_reject_debug_message); - } - + BOOST_CHECK(!Consensus::CheckTxInputs(CTransaction(tx_max_sigops), state, coins, dummy_height, dummy_fee, /*enforce_bip54=*/true)); + BOOST_CHECK(state.IsInvalid()); + std::string reject_reason("bad-txns-legacy-sigops"); + std::string sigop_limit_reject_debug_message("too many legacy sigops (BIP54)"); + BOOST_CHECK_EQUAL(state.GetRejectReason(), reject_reason); + BOOST_CHECK_EQUAL(state.GetDebugMessage(), sigop_limit_reject_debug_message); + state = TxValidationState{}; // Now, check the limit can be reached with regular P2PK outputs too. Use a separate // preparation transaction, to demonstrate spending coins from a single tx is irrelevant. @@ -1090,7 +1092,8 @@ BOOST_AUTO_TEST_CASE(max_standard_legacy_sigops) // The transaction now contains exactly 2500 sigops, the check should pass. BOOST_CHECK_EQUAL(p2sh_inputs_count * MAX_P2SH_SIGOPS + p2pk_inputs_count * 1, MAX_TX_BIP54_SIGOPS); - BOOST_CHECK(::ValidateInputsStandardness(CTransaction(tx_max_sigops), coins).IsValid()); + BOOST_CHECK(Consensus::CheckTxInputs(CTransaction(tx_max_sigops), state, coins, dummy_height, dummy_fee, /*enforce_bip54=*/true)); + BOOST_CHECK(state.IsValid()); // Now, add some Segwit inputs. We add one for each defined Segwit output type. The limit // is exclusively on non-witness sigops and therefore those should not be counted. @@ -1106,7 +1109,8 @@ BOOST_AUTO_TEST_CASE(max_standard_legacy_sigops) // The transaction now still contains exactly 2500 sigops, the check should pass. AddCoins(coins, CTransaction(tx_create_segwit), 0, false); - BOOST_REQUIRE(::ValidateInputsStandardness(CTransaction(tx_max_sigops), coins).IsValid()); + BOOST_CHECK(Consensus::CheckTxInputs(CTransaction(tx_max_sigops), state, coins, dummy_height, dummy_fee, /*enforce_bip54=*/true)); + BOOST_CHECK(state.IsValid()); // Add one more P2PK input. We'll reach the limit. tx_create_p2pk.vout.emplace_back(212121, p2pk_script); @@ -1119,12 +1123,10 @@ BOOST_AUTO_TEST_CASE(max_standard_legacy_sigops) AddCoins(coins, CTransaction(tx_create_p2pk), 0, false); auto legacy_sigop_count_p2pk = p2sh_inputs_count * MAX_P2SH_SIGOPS + p2pk_inputs_count * 1; BOOST_CHECK_GT(legacy_sigop_count_p2pk, MAX_TX_BIP54_SIGOPS); - { - auto validation_state = ValidateInputsStandardness(CTransaction(tx_max_sigops), coins); - BOOST_CHECK(validation_state.IsInvalid()); - BOOST_CHECK_EQUAL(validation_state.GetRejectReason(), reject_reason); - BOOST_CHECK_EQUAL(validation_state.GetDebugMessage(), sigop_limit_reject_debug_message); - } + BOOST_CHECK(!Consensus::CheckTxInputs(CTransaction(tx_max_sigops), state, coins, dummy_height, dummy_fee, /*enforce_bip54=*/true)); + BOOST_CHECK(state.IsInvalid()); + BOOST_CHECK_EQUAL(state.GetRejectReason(), reject_reason); + BOOST_CHECK_EQUAL(state.GetDebugMessage(), sigop_limit_reject_debug_message); } BOOST_AUTO_TEST_CASE(checktxinputs_invalid_transactions_test) @@ -1141,7 +1143,7 @@ BOOST_AUTO_TEST_CASE(checktxinputs_invalid_transactions_test) TxValidationState state; CAmount txfee{0}; - BOOST_CHECK(!Consensus::CheckTxInputs(CTransaction{mtx}, state, inputs, spend_height, txfee)); + BOOST_CHECK(!Consensus::CheckTxInputs(CTransaction{mtx}, state, inputs, spend_height, txfee, /*enforce_bip54=*/true)); BOOST_CHECK(state.IsInvalid()); BOOST_CHECK_EQUAL(state.GetResult(), expected_result); BOOST_CHECK_EQUAL(state.GetRejectReason(), expected_reason); diff --git a/src/txmempool.cpp b/src/txmempool.cpp index 86cbc1adc43d..a49a15af406a 100644 --- a/src/txmempool.cpp +++ b/src/txmempool.cpp @@ -534,7 +534,7 @@ void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendhei TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass CAmount txfee = 0; assert(!tx.IsCoinBase()); - assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee)); + assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee, /*enforce_bip54=*/true)); for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout); AddCoins(mempoolDuplicate, tx, std::numeric_limits::max()); } diff --git a/src/validation.cpp b/src/validation.cpp index 924b7f60f350..57133f954d27 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -894,7 +894,7 @@ bool MemPoolAccept::PreChecks(ATMPArgs& args, Workspace& ws) } // The mempool holds txs for the next block, so pass height+1 to CheckTxInputs - if (!Consensus::CheckTxInputs(tx, state, m_view, m_active_chainstate.m_chain.Height() + 1, ws.m_base_fees)) { + if (!Consensus::CheckTxInputs(tx, state, m_view, m_active_chainstate.m_chain.Height() + 1, ws.m_base_fees, /*enforce_bip54=*/true)) { return false; // state filled in by CheckTxInputs } @@ -2527,6 +2527,7 @@ bool Chainstate::ConnectBlock(const CBlock& block, BlockValidationState& state, std::optional> control; if (auto& queue = m_chainman.GetCheckQueue(); queue.HasThreads() && fScriptChecks) control.emplace(queue); + const bool enforce_bip54{DeploymentActiveAt(*pindex, m_chainman, Consensus::DEPLOYMENT_CONSENSUSCLEANUP)}; std::vector prevheights; CAmount nFees = 0; int nInputs = 0; @@ -2543,7 +2544,7 @@ bool Chainstate::ConnectBlock(const CBlock& block, BlockValidationState& state, { CAmount txfee = 0; TxValidationState tx_state; - if (!Consensus::CheckTxInputs(tx, tx_state, view, pindex->nHeight, txfee)) { + if (!Consensus::CheckTxInputs(tx, tx_state, view, pindex->nHeight, txfee, /*enforce_bip54=*/enforce_bip54)) { // Any transaction validation failure in ConnectBlock is a block consensus failure state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, tx_state.GetRejectReason(), diff --git a/test/functional/mempool_sigoplimit.py b/test/functional/mempool_sigoplimit.py index 5b129c146265..8eeecaabc9cf 100755 --- a/test/functional/mempool_sigoplimit.py +++ b/test/functional/mempool_sigoplimit.py @@ -183,7 +183,7 @@ def create_bare_multisig_tx(utxo_to_spend=None): assert_greater_than(2000, tx_parent.get_weight() + tx_child.get_weight()) def test_legacy_sigops_stdness(self): - self.log.info("Test a transaction with too many legacy sigops in its inputs is non-standard.") + self.log.info("Test a transaction with too many legacy sigops in its inputs is invalid.") # Restart with the default settings self.restart_node(0) @@ -204,20 +204,19 @@ def test_legacy_sigops_stdness(self): outpoints.append(COutPoint(txid, res["sent_vout"])) self.generate(self.nodes[0], 1) - # Spending all these outputs at once accounts for 2505 legacy sigops and is non-standard. + # Spending all these outputs at once accounts for 2505 legacy sigops and is invalid. nonstd_tx = CTransaction() nonstd_tx.vin = [CTxIn(op, CScript([b"", packed_redeem_script])) for op in outpoints] nonstd_tx.vout = [CTxOut(0, CScript([OP_RETURN, b""]))] - assert_raises_rpc_error(-26, "bad-txns-nonstandard-inputs, non-witness sigops exceed bip54 limit", - self.nodes[0].sendrawtransaction, nonstd_tx.serialize().hex()) + assert_raises_rpc_error(-26, "bad-txns-legacy-sigops", self.nodes[0].sendrawtransaction, nonstd_tx.serialize().hex()) - # Spending one less accounts for 2490 legacy sigops and is standard. + # Spending one less accounts for 2490 legacy sigops and is valid and standard. std_tx = deepcopy(nonstd_tx) std_tx.vin.pop() self.nodes[0].sendrawtransaction(std_tx.serialize().hex()) - # Make sure the original, non-standard, transaction can be mined. - self.generateblock(self.nodes[0], output="raw(42)", transactions=[nonstd_tx.serialize().hex()]) + # The invalid transaction also cannot appear in a block. + assert_raises_rpc_error(-25, "bad-txns-legacy-sigops", self.generateblock, self.nodes[0], "raw(42)", [nonstd_tx.serialize().hex()]) def run_test(self): self.wallet = MiniWallet(self.nodes[0]) From b8ffa1e6c3cf2dfd581171739541262ecf7d6a64 Mon Sep 17 00:00:00 2001 From: Antoine Poinsot Date: Tue, 16 Sep 2025 13:09:04 -0400 Subject: [PATCH 05/20] qa: add to utilities a version of SignSignature for Taproot inputs In Taproot the signature commits to the list of spent outputs. --- src/test/util/transaction_utils.cpp | 14 ++++++++++++++ src/test/util/transaction_utils.h | 3 +++ 2 files changed, 17 insertions(+) diff --git a/src/test/util/transaction_utils.cpp b/src/test/util/transaction_utils.cpp index cf4ed9346690..c0c67ca40804 100644 --- a/src/test/util/transaction_utils.cpp +++ b/src/test/util/transaction_utils.cpp @@ -91,6 +91,20 @@ void BulkTransaction(CMutableTransaction& tx, int32_t target_weight) assert(GetTransactionWeight(CTransaction(tx)) <= target_weight + 3); } +bool SignSignature(const SigningProvider &provider, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, + const CAmount& amount, std::vector&& spent_outputs, int nHashType, SignatureData& sig_data) +{ + assert(nIn < txTo.vin.size()); + + PrecomputedTransactionData txdata; + txdata.Init(txTo, std::forward>(spent_outputs), /*force=*/true); + MutableTransactionSignatureCreator creator(txTo, nIn, amount, &txdata, {.sighash_type = nHashType}); + + bool ret = ProduceSignature(provider, creator, fromPubKey, sig_data); + UpdateInput(txTo.vin.at(nIn), sig_data); + return ret; +} + bool SignSignature(const SigningProvider &provider, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, const CAmount& amount, int nHashType, SignatureData& sig_data) { assert(nIn < txTo.vin.size()); diff --git a/src/test/util/transaction_utils.h b/src/test/util/transaction_utils.h index ca643f0be52f..ac6ba2464cb5 100644 --- a/src/test/util/transaction_utils.h +++ b/src/test/util/transaction_utils.h @@ -49,5 +49,8 @@ bool SignSignature(const SigningProvider &provider, const CScript& fromPubKey, C unsigned int nIn, const CAmount& amount, int nHashType, SignatureData& sig_data); bool SignSignature(const SigningProvider &provider, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType, SignatureData& sig_data); +bool SignSignature(const SigningProvider &provider, const CScript& fromPubKey, CMutableTransaction& txTo, + unsigned int nIn, const CAmount& amount, std::vector&& spent_outputs, int nHashType, + SignatureData& sig_data); #endif // BITCOIN_TEST_UTIL_TRANSACTION_UTILS_H From 85a48938357a83227d5fb1af0d441d3e612d739a Mon Sep 17 00:00:00 2001 From: Antoine Poinsot Date: Mon, 22 Sep 2025 13:53:14 -0400 Subject: [PATCH 06/20] qa: extensive unit tests for BIP54 legacy sigops limit Test the newly introduced limit with various combinations of inputs and outputs types, historical transactions, and exercise some implementation-specific edge cases. Record each test case and optionally write them to disk as JSON to generate the BIP test vectors. --- src/test/CMakeLists.txt | 1 + src/test/bip54_tests.cpp | 1311 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 1312 insertions(+) create mode 100644 src/test/bip54_tests.cpp diff --git a/src/test/CMakeLists.txt b/src/test/CMakeLists.txt index c9b6de0baca8..471cbf4deaeb 100644 --- a/src/test/CMakeLists.txt +++ b/src/test/CMakeLists.txt @@ -19,6 +19,7 @@ add_executable(test_bitcoin bech32_tests.cpp bip32_tests.cpp bip324_tests.cpp + bip54_tests.cpp blockchain_tests.cpp blockencodings_tests.cpp blockfilter_index_tests.cpp diff --git a/src/test/bip54_tests.cpp b/src/test/bip54_tests.cpp new file mode 100644 index 000000000000..3702949c7aaa --- /dev/null +++ b/src/test/bip54_tests.cpp @@ -0,0 +1,1311 @@ +// Copyright (c) The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include