Repository navigation
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. LLM Linter (✨ experimental)Possible places where comparison-specific test macros should replace generic comparisons:
2026-11-13 16:40:38 |
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
|
Congrats! Excited to see this work make it to this point 🎉 |
ariard
left a comment
There was a problem hiding this comment.
Let's start at least the review for the fix of the long validation block time.
| // 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 |
There was a problem hiding this comment.
i was reading again the BIP part on the new CheckSigops limit and the computation price for each type of legacy checksig operations, i.e CHECKSIG counts as 1 signature operation, CHECKMULTISIG as 1 to 16 signature operation and (empty) CHECKMULTISIG as 20 signatures operation.
the asymmetry between OP_1 CHECKMULTISIG and (empty) CHECKMULTISIG sounds striking as the vbyte cost of a single CHECKMULTISIG is going to be 1 vbyte and the fee cost of a OP_1 CHECKMULTISIG, so in any collaborative txn among multi parties, one can force the tx to reach the new 2500 limit at a vbyte cost inferior rather than putting a OP_1 CHECKMULTISIG coming with a higher absolute vbyte cost, whatever the feerate.
curious if there is any rational somewhere in all the design notes, that's explaining that choice for the asymmetry in the legacy signature accounting for CHECKMULTISIG
There was a problem hiding this comment.
Absolutely, the rationale is to reuse BIP 16 accounting, instead of introducing another opcode counting method in consensus rules.
There was a problem hiding this comment.
@darosior So I'm saying this because in fact before the fix for this class of vulnerabilities: https://bitcoincore.org/en/2025/10/24/disclose-cve-2025-46598/ one could have abuse the new 2500 sigops rule, at a lower marginal feerate cost.
Before #33050 a tx could have been executed twice, the first with standardness rule, the second with consensus check. An attacker could have done a marginal attack, where the tx would have had a huge OP_SHA256 element to hash and the minimal number of accounted for 20 OP_CHECKMULTISIG.
Therefore the transaction would have failed a first time on the standard check and then a second time on the consensus check with a reduced liquidity cost for the attacker (due to the lower feerate surface). and there was easy way to optimize the attack.
This one of the attack I did mention there even if never went to communicate it properly. I might have still have the python test vectors I played with at the time. Somehow the 20 OP_CHECKMULTISIG is a compact trick to render a tx invalid with the minimal of tx surface.
There was a problem hiding this comment.
I benchmarked the worst case processing time for various types of standard transactions back when i disclosed CVE-2025-46598. As far as i know the worst case for legacy transaction does not involve OP_SHA256. It does involve OP_CHECKMULTISIG, but not with the minimal amount of sigop accounted for (since you need it to actually do compute).
I am not sure what you are trying to get at. Could your point be related to this previous one you raised on the list?
There was a problem hiding this comment.
I am not sure what you are trying to get at. Could your point be related to this previous one you raised on the list?
No it's something quite different. What I'm talking about in the present issue, it was relying on crafting small weight unit transaction to provoke the most of OP_SHA256 (it's less expensive than sigs, but it's still consuming some CPU cycles) during a validation, and therefore the smallest cost.
Note, it was strictly before #33050 that I did the test. It's not only the worst-case in CPU time to consider it's for a minimal mempool min fee, what's the average satoshis liquidity must avails to consume useless CPU cycles. I'll find back my notes on this and come back to you.
|
Concept ACK |
4 similar comments
|
Concept ACK |
|
Concept ACK |
|
Concept ACK |
|
Concept ACK |
|
Concept ACK |
64-byte transactions are also now treated as a consensus failure in PreChecks, like BIP54-sigops check failures. Note this only changes the RPC error, and not the disconnection behaviour in P2P since 266dd0e.
… vectors) This adds tests exercising the bounds of the checks on the invalid transaction size, for various types of transactions (legacy, Segwit, bytes in input/output to get to 64 bytes) as well as sanity checking against some known historical violations. Thanks to Chris Stewart for digging up the historical violations to this rule.
The previously introduced unit tests extensively test the specific implementation of each mitigation. This functional test complements them by end-to-end testing all mitigations. For the added timestamp constraints, it mimicks how they would get exploited (by implementing pseudo timewarp and Murch-Zawy attacks) and demonstrates those exploits are not possible anymore after BIP54 activates.
|
Rebased, and addressed both human and bot review. I updated the functional test to run the post activation checks on the first block for which the rules are active. In addition, it now mines a BIP 54 invalid block as the last block for which the rules are inactive. This kills some of the mutants shared by @ViniciusCestarii, and more generally better guards against off-by-one errors (such as that which could come from mixing up I addressed a bunch of cleanups and fixups suggested by @optout21, @ViniciusCestarii and @nervana21. Because they pointed a number of small mistakes in the extensive sigops unit test, i had a bot comprehensively check for those. I fixed a few more inconsistencies (invalid CHECKSIG counts, sigops counts, etc..) and also a stale comment that was referring to a test that did not exist anymore. The test made sense (check that a CMS for I also had a clanker check for arithmetic nits like #35793 (comment) in the functional test. It found a few more nits that did not impact the test, but should be fixed for correctness or consistency (for instance a comment that would say "reach the end of the period" instead of "reach the beginning of the next period", etc..) I'll update the test vectors in the BIP in time, but i want to check for more similar human slop in the pre-generated tests first (my bot already detected an off-by-one in the timestamps JSON). |
|
reACK 58b418f Test and comment fixes, plus Mutants for activation boundary are now killed for sigops rule early/late, 64 byte tx on block late, and coinbase-locktime one block late |
|
tACK 58b418f |
There was a problem hiding this comment.
ACK 58b418f
Can confirm the 2 mutants were killed.
nit: the timewarp activation mutant can be killed without a full retarget setup:
Diff
diff --git a/test/functional/feature_bip54.py b/test/functional/feature_bip54.py
index b6271d866d..c7a557efec 100755
--- a/test/functional/feature_bip54.py
+++ b/test/functional/feature_bip54.py
@@ -407,6 +407,29 @@ class Bip54Test(BitcoinTestFramework):
assert_equal(cc_dep["status"], "locked_in")
assert_equal(cc_dep["status_next"], "active")
+ # The first active block starts a retarget period, so the timewarp rule must apply to it.
+ # Fork the tip with a header in the future to leave room above the MTP.
+ assert_equal((node.getblockcount() + 1) % 144, 0)
+ parent_hash = node.getblockhash(node.getblockcount() - 1)
+ future_time = node.getblockheader(parent_hash)["time"] + 3 * 60 * 60
+ node.setmocktime(future_time)
+ fork = create_block(tmpl={
+ "previousblockhash": parent_hash,
+ "height": node.getblockcount(),
+ "curtime": future_time,
+ })
+ fork.solve()
+ node.submitheader(CBlockHeader(fork).serialize().hex())
+
+ block = create_block(tmpl={
+ "previousblockhash": fork.hash_hex,
+ "height": node.getblockcount() + 1,
+ "curtime": future_time - 2 * 60 * 60 - 1, # 2h + 1s before its parent.
+ })
+ block.solve()
+ assert_raises_rpc_error(-25, "time-timewarp-attack", node.submitheader, CBlockHeader(block).serialize().hex())
+ node.setmocktime(0)
+
# Perform as many post activation checks as we can right on the first block
# with the rules active, to also check for an off-by-one mistake.
self.log.info("BIP54 tests after activation")
optout21
left a comment
There was a problem hiding this comment.
ACK 58b418f
Performed review on the whole changeset. Only found some nits.
A general remark: I think a release not would make sense, mentioning:
- The chains where BIP54 is active (regtest)
- On chains where it is active, the new and changed error cases
- The
getblocktemplatechanged requirement, see #35793 (comment)
I consider the changes correct and acceptable in the current form already (in spite the minor findings).
| #include <coins.h> | ||
| #include <consensus/amount.h> | ||
| #include <consensus/consensus.h> | ||
| #include <consensus/tx_verify.h> |
There was a problem hiding this comment.
af2a89f validation: make BIP54 sigops check consensus-critical:
Nit: tx_verify.h include no longer needed.
|
|
||
| class SizeSub64(BadTxTemplate): | ||
| reject_reason = "tx-size-small" | ||
| expect_disconnect = False |
There was a problem hiding this comment.
8499388 [test] Separate 64B and 63B tx size tests:
Nit: expect_disconnect field is no longer exists, should be removed from here.
| except Exception as e: | ||
| raise e |
There was a problem hiding this comment.
fa2c08f qa: end-to-end test all BIP54 mitigations:
Nit: These lines are useless in this form. Also one more occurrence of the same pattern further below.
| return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "time-negative-interval", | ||
| "the last block’s timestamp in the difficulty adjustment interval is earlier than the first block’s"); |
There was a problem hiding this comment.
Nit: consider avoiding using ’ character in error message, may cause issues in RPC calls. Use simple quote ', or "timestamp of the block" construct.
| const bool check_txs_size{DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_CONSENSUSCLEANUP)}; | ||
| for (const auto& tx : block.vtx) { | ||
| if (check_txs_size && GetSerializeSize(TX_NO_WITNESS(tx)) == INVALID_TX_NONWITNESS_SIZE) { | ||
| return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-size", "block contains a 64 bytes transaction"); |
There was a problem hiding this comment.
Nit: wording "64 bytes transaction" -> "64-byte transaction"
| return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-size", "block contains a 64 bytes transaction"); | |
| return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-size", "block contains a 64-byte transaction"); |
theStack
left a comment
There was a problem hiding this comment.
ACK on the actual consensus changes, planning to look closer to the tests within the next days
| // Uncomment to output updated JSON tests. | ||
| // #define UPDATE_JSON_TESTS |
There was a problem hiding this comment.
The generated .json test vector files (bip54_{sigops,txsize}.json.gen) both differ from the ones currently included in the BIPs repo ({sigops,txsize}.json). Didn't look closer on the details, I assume there were (minor) changes triggered by review comments and one could just update them on the latter repo, as previously done in bitcoin/bips#2122 / bitcoin/bips@ff39733?
There was a problem hiding this comment.
Yes. There is a bunch of small fixes and a couple new tests included. I plan to do another round of updates of the BIP test vectors (similar to bitcoin/bips#2122) after this PR is merged.
ariard
left a comment
There was a problem hiding this comment.
Aiming to have a complete a real serious re-review of the whole code change before the end of year vacations.
Not forgetting to re-check if there is no bad interactions with the disconnectpool due to the new rules applying on the coinbase or the max sigops for old inputs spends, among other concerns.
| if (block.vtx[0]->nLockTime != static_cast<uint32_t>(nHeight - 1)) { | ||
| return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-locktime", "block height mismatch in coinbase nLockTime"); | ||
| } | ||
| if (block.vtx[0]->vin[0].nSequence == CTxIn::SEQUENCE_FINAL) { |
There was a problem hiding this comment.
This new consensus sanitization check is stateless, that it whatever the inclusion height of the coinbase, after the activation of BIP54, the nSequence of the 1st input should NOT be equal to SEQUENCE_FINAL.
There is nothing which is context-dependent or even tx-structure dependent (like the BIP141 commitment which is allowed to be in any scriptpubkey of the coinbase tx), so this check could be replicated in other code paths to proceed to the early rejection of ill-crafted transactions.
E.g I wonder if the check should be added in CheckTransaction() and be used in the PreChecks() code path (where CheckTransaction() is called before IsCoinBase() detection) or in CheckBlock() (where we do a CheckTransaction()).
I have not test it but lacking to do so, it sounds you can mutate a valid coinbase to alter its nSequence field and provoke the invalidity of the whole block. It sounds there are code paths where CheckBlock() is done before ContextualCheckBlock() (e.g in AcceptBlock()). It sounds as such you might have CheckBlock() result where the validity is not wholly complete, at least the state of information that is available in the code path.
There is also the question of compact block (BIP152), the spec says "When in doubt, nodes SHOULD only include the coinbase transaction in prefilledtxn." This is unsure if the compact block validation code already sanitize on the reception of a coinbase (to avoid fulfilling resources after the CMPCTBLOCK), I have no re-checked fully, though looking shortly in blockencoding.cpp it doesn't sound to.
|
ACK 58b418f |
| # Disable the consensus cleanup for the BIP30 checks. | ||
| self.restart_node(0, ["-vbparams=consensuscleanup:0:0"]) |
There was a problem hiding this comment.
in a730c78: nit: not an issue now, but I think for disabling BIP 54, setting the start time to -2 (NEVER_ACTIVE), e.g. -vbparams=consensuscleanup:-2:0, would be more robust here. With 0:0 the deployment still goes through the regular versionbits state machine, and since the node's miner signals once it's in started, it can still lock in and activate if the node mines enough blocks itself. The current tests don't run into this as their chains are too short or don't contain enough signalling blocks.
There was a problem hiding this comment.
ACK 58b418f
I did a review of the consensus rules here, cross-checking with the specification in https://github.com/bitcoin/bips/blob/master/bip-0054.md. I think they are correct and mirror it.
I did manual mutations of the rules and saw failures from the test vectors added.
I did not look at the test vectors in depth; I was mostly interested in the production code correctness.
I left a few comments but nothing major.
| max_timewarp = MAX_TIMEWARP_BIP54; | ||
| } | ||
| if (max_timewarp && block.GetBlockTime() < pindexPrev->GetBlockTime() - *max_timewarp) { | ||
| return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "time-timewarp-attack", "block's timestamp is too early on diff adjustment block"); |
There was a problem hiding this comment.
nit: will be good for debugging to see the values that trigger the failure here and the murch zawy check?
| return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "time-timewarp-attack", "block's timestamp is too early on diff adjustment block"); | |
| return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "time-timewarp-attack", | |
| strprintf("block's timestamp is too early on diff adjustment block: %d < %d - %d", | |
| block.GetBlockTime(), pindexPrev->GetBlockTime(), *max_timewarp)); |
|
|
||
| // Now assert the validity status of each case under the new rules. | ||
| { | ||
| auto test_setup{TestingSetup{ChainType::MAIN, {.extra_args = {"-vbparams=consensuscleanup:-1:-1"}}}}; |
There was a problem hiding this comment.
This brings noisy logs when you execute the test without ctest, worth suppressing?
❯ ./build/bin/test_bitcoin --run_test=bip54_tests
Running 4 test cases...
Error: The -vbparams option may not be used on mainnet.
Error: The -vbparams option may not be used on mainnet.
Error: The -vbparams option may not be used on mainnet.
Error: The -vbparams option may not be used on mainnet.
Error: The -vbparams option may not be used on mainnet.
Error: The -vbparams option may not be used on mainnet.
Error: The -vbparams option may not be used on mainnet.
Error: The -vbparams option may not be used on mainnet.
Error: The -vbparams option may not be used on mainnet.
Error: The -vbparams option may not be used on mainnet.
Error: The -vbparams option may not be used on mainnet.
Error: The -vbparams option may not be used on mainnet.
Error: The -vbparams option may not be used on mainnet.
Error: The -vbparams option may not be used on mainnet.
Error: The -vbparams option may not be used on mainnet.
Error: The -vbparams option may not be used on mainnet.
*** No errors detected
| } | ||
|
|
||
| // Make sure the coinbase transaction is timelocked to the block's height. (BIP 54) | ||
| if (nHeight > 0 && DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_CONSENSUSCLEANUP)) { |
There was a problem hiding this comment.
It seems that this nHeight > 0 check is never gonna be false, so belt and suspenders? Removing it has no test failing, and adding an assert indicates no genesis block goes through that path?
There was a problem hiding this comment.
If you want to rely on that, then an assert(pindexPrev != nullptr); // genesis block never goes through this path at the top of the function would make sense?
If it did ever go through the path, the exception is necessary since otherwise versionbits activation set to "always active" would incorrectly apply the rule to the genesis block.
There was a problem hiding this comment.
FWIW, I seem to get an error around test/kernel/test_kernel.cpp(935) (so chainman->ImportBlocks) if I add a pindexPrev != nullptr assert at the top of ContextualCheckBlock; haven't looked in any further detail.
| 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)) { |
There was a problem hiding this comment.
nitty-nit feel free to ignore: As more input-level rules get added here, that grows into a list of bools. Could mirror the script-verification flags, pass an unsigned int bitfield (TX_INPUT_CHECK_BIP54_SIGOPS, …) the same way SCRIPT_VERIFY_* flows into CheckInputScripts.
|
|
||
| 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"); |
There was a problem hiding this comment.
in af2a89f validation: make BIP54 sigops check consensus-critical
maybe add BOOST_CHECK(state.GetResult() == TxValidationResult::TX_CONSENSUS); ?
| 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, |
There was a problem hiding this comment.
in fae79e5 qa: add to utilities a version of SignSignature for Taproot inputs
I think we can drop fromPubKey and amount since spent_outputs[nIn] already contains both, passing them separately lets a caller supply conflicting values.
| // monotonic (modulo the timewarp fix grace period). | ||
| const bool is_last_block{nHeight % dai == dai - 1}; | ||
| if (is_last_block && DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_CONSENSUSCLEANUP)) { | ||
| int first_height{nHeight - dai + 1}; |
There was a problem hiding this comment.
in b438185 validation: prevent negative difficulty adjustment intervals
maybe could make this int const?
There was a problem hiding this comment.
It's a more BIP feedback, but "Transactions whose witness-stripped serialized size is exactly 64 bytes are invalid" would win to explicitly reference BIP 144.
At first sight, without going to read the code implementation, it's ambiguous if the 64 byte serialized size is including the witness marker and flag (2-bytes).
| const bool check_txs_size{DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_CONSENSUSCLEANUP)}; | ||
| for (const auto& tx : block.vtx) { | ||
| if (check_txs_size && GetSerializeSize(TX_NO_WITNESS(tx)) == INVALID_TX_NONWITNESS_SIZE) { | ||
| return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-size", "block contains a 64 bytes transaction"); |
There was a problem hiding this comment.
thinking the comment should be "bad-txn-size" and not "bad-txns-size" the plural form.
i think it's okay not to cache all the 64-byte transactions of a block as in case of malicious crafted list of block transactions all composed of a 64-byte transaction, a BLOCK_CONSENSUS error is yield and the whole block is marked as invalid. the peer should punished accordingly to MaybePunishNodeForBlock() unless it's a compact block (L2042 in src/net_processing.cp) where the trick is repeated. if we're caching well the block invalidity at reception of CMPCTBLOCK message, i think it should be good as it's doesn't matter than one or many invalid 64 byte transactions are existent.
maybe you're able to encumber the txn_available between the completion of a compact block message round trip with junk, though doesn't change from already existent garbage fulfilling vector, i'm thinking.

This implements the Consensus Cleanup validation rules proposed in BIP 54. These rules are only enabled on regtest. Mainnet activation, if any, is to be considered separately.
This patchset is based on the code that was previously reviewed (1, 2) and tested (for instance here) on Bitcoin Inquisition. The tests and documentation have since been improved, but the consensus-critical commits have been carried over with only minor differences (the only behavioural one being the addition of the stripped-size check to
PreChecks).Roughly 95% of the added lines are tests or test data. The format, contents, and reproduction procedure for the BIP 54 test vectors are documented here. The
bip54_testsunit test module exercises each mitigation extensively in isolation. Thefeature_bip54.pyfunctional test verifies all of them end-to-end after and prior to activation. For the timestamp rules, it simulates timewarp and Murch–Zawy attacks, demonstrating the new timestamp rules prevent these exploits. A fuzz harness for the sigop accounting logic is also included, which can be seeded from the BIP test vectors (implemented here).See commit messages for details.