mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 15:11:38 +00:00
Implement BIP 54 (Consensus Cleanup) without mainnet activation #35793
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!35793
Loading…
Reference in a new issue
No description provided.
Delete branch "bip54"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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.
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.
External sites
Reviews
See the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste
<!--meta-tag:bot-skip-->into the comment that the bot should ignore.Conflicts
Reviewers, 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:
test/functional/data/invalid_txs.py:assert len(tx.serialize_without_witness()) == 63→ Preferassert_equal(len(tx.serialize_without_witness()), 63).test/functional/data/invalid_txs.py:assert MIN_STANDARD_TX_NONWITNESS_SIZE - 1 == 64→ Preferassert_equal(MIN_STANDARD_TX_NONWITNESS_SIZE - 1, 64).2026-11-13 16:40:38
🚧 At least one of the CI tasks failed.
Task
macOS native: https://github.com/bitcoin/bitcoin/actions/runs/30100472888/job/89504946717LLM reason (✨ experimental): CI failed because
bip54_testsaborted on an assertion failure inCExtKey::SetSeed(seed.size()was outside the expected 16–64 byte range) duringbip54_legacy_sigops.Hints
Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:
Possibly due to a silent merge conflict (the changes in this pull request being
incompatible with the current code in the target branch). If so, make sure to rebase on the latest
commit of the target branch.
A sanitizer issue, which can only be found by compiling with the sanitizer and running the
affected test.
An intermittent issue.
Leave a comment here, if you need help tracking down a confusing failure.
Congrats! Excited to see this work make it to this point 🎉
Let's start at least the review for the fix of the long validation block time.
there could be a definition of what is understood as a "legacy signature ops" even if it's just echoing the bip doc, it's
consensus/consensus.hwhere one can reasonably expect to find the definition of a "legacy signature" in opposition to signatures included in the witness for SegWit spends.i was reading again the BIP part on the new
CheckSigopslimit and the computation price for each type of legacy checksig operations, i.eCHECKSIGcounts as 1 signature operation,CHECKMULTISIGas 1 to 16 signature operation and (empty)CHECKMULTISIGas 20 signatures operation.the asymmetry between
OP_1 CHECKMULTISIGand (empty)CHECKMULTISIGsounds striking as the vbyte cost of a singleCHECKMULTISIGis going to be 1 vbyte and the fee cost of aOP_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 aOP_1 CHECKMULTISIGcoming 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
CHECKMULTISIGConcept ACK
Concept ACK
Concept ACK
Concept ACK
Concept ACK
Ok, i can replace with "non-Segwit signature operations". I've also checked all other instances of "legacy" in the diff here, and it's only used in tests, where the term is already present and i think fine to use.
Concept ACK
The miner currently does not enforce the murch-zawy rule but I think it should. Suggested change along with a test:
github.com/fjahr/bitcoin@edbc841eb5I considered it for #31376 and decided against because it's strictly theoretical. But your patch looks good. Could you PR it to master? This one is already large, and i think that commit can be merged on its own.
Absolutely, the rationale is to reuse BIP 16 accounting, instead of introducing another opcode counting method in consensus rules.
I understand that the BIP mentions 2016/2015 because it describes mainnet's adjustment period. Since this PR applies the deployment only to regtest by default, could we adjust the BIP text, or add a note here to clarify that these values are derived from the network's adjustment period rather than fixed constants?
Concept ACK
Did a 1st read of the fix for long block validation time, I'll continue after the vacation.
Faut pas deconner c'est le mois d'aout.
i would check the test before if it's covered though getting tortuous and valid control flow redeemScript with 10-depth OP_IF then the OP_CHECKSIG, then 10-depth OP_ENDIF, or with OP_ELSE to exerciser the consensus sigops script parser. not guarantee the fuzzer randomness might never yield a structured script for nested control flow.
should this check be reflected in
getblocktemplategiven it's already caring about "sigoplimit", "weightlimit" etc. not infringing tx should be selected in the template and yield back in the template.now of course, this check is enforced at tx mempool processing, so it should never appear in the template already, though having a sanitization check in
getblocktemplatemight good.and there is the more transient aspect, than until BIP54 is activated a block is legit to have an infringing tx, even if it has been deployed as policy, though once it's activated, it should not be okay anymore (so don't go to produce an invalid block for the boundary block).
in fact it's a dumb nuisance attack vector for the few transition blocks during activation if the miners are running "lax" mempools. a tx might be okay at mempool reception, is stuck in the mempools, and even after few blocks is selected in a template rendering it invalid.
there could be a test for the case where the tx has
2501 sigopsand as such is invalid per BIP54 new rule. to demonstrate the code is not doing < 2500 => good ; 2500 => not good ; > 2500 => good.there might be a test for it elsewhere for the exact test vector. good to have it in the python framework.
@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 https://github.com/bitcoin/bitcoin/pull/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.
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 involveOP_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?
I think your comment applies to the difficulty adjustment period values used by the timewarp and Murch-Zawy mitigations, not that commit (which sets a largely inconsequential dummy BIP 9 deployment for regtest), correct?
So i went and looked for a way to maybe clarify this for the code implementing those checks, but it's already pretty clear these values are derived from the network's adjustment period. Timewarp:
Murch-Zawy:
Happy to consider any improvement to the comments there.
Bound checking for sigops accounting is tested extensively in unit tests (
d75143d393). I think it makes more sense for the integration tests to check higher-level boundaries, like for instance activation periods, than duplicate those tests.Done now here: #35949
Yes, it's already an assumption we make that no invalid transaction make it to our mempool. Note how this commit changes two things in this regard:
-acceptnonstdtxs.Yes, added the code comment to that line simply to demonstrate that regtest has a different difficulty adjustment period than what's documented in the BIP itself:
The code looks fine, was just wondering if we could update the BIP to make 2016 and 2015 variables, and in this PR draw attention to the fact that - strictly speaking - we're diverging from the BIP.
🐙 This pull request conflicts with the target branch and needs rebase.
Did a swift first read to the code (skipping test code) while preparing for the PR review club.
The code looks pretty good, just left a comment. Will re-review again in more detail.
in
29d1f3fd45validation: make BIP54 sigops check consensus-criticalThis signals the state as TX_CONSENSUS even if this is a policy check.
Does not affect in debug/log messages or the rejected reason message, but feels weird to miss-categorize it.
If we care about this, could set a three value struct{consensus, policy, ignore} and set the state according to it.
in
67ebb0d57dvalidation: prevent timewarp attacks with a 2h grace periodnit:
max_timewarp.has_value()?started to review the timewarp fix.
the comment could be "strictly inferior" which is more defined mathematically than "must not be more than 2 hours", where you never know if
=is included, at least imhoI think the description comment can be adjusted above to say it's only applied to testnet4 and not to signet, regtest, testnet3 (I guess from the
enforce_BIP94).BLOCK_INVALID_HEADERcomment insrc/consensus/validation.hcould be updated to include "invalid proof of work or time too old".Okay if
-acceptnonstdtxseffect starts to kickoff as short as there is a release including this code, I think this is limiting the risk surface for transaction blocks that could violate the rule by accident.I'll re-check that.
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.
I think the BIP should always optimize to be maximally clear for mainnet. When it does not affect clarity of the mainnet specifications, diverging values for public test networks may be integrated in the BIP (probably in a separate section). I don't think the values for a Bitcoin Core specific local test network should be mentioned in the BIP.
What are you suggesting doing here? I agree code coverage guidance is sometimes lacking when fuzzing stateful logic. I think we can improve things a little with tweaks like Libfuzzer's extra counters. I had briefly looked into it in the past, and may pick it up in the future, but this improvement is largely orthogonal to this PR.
I went back and forth on this. I ended up picking the current version because the error type is not used to choose whether to disconnect a peer anymore, nor exposed to the user.
Making the error depend on the activation status would only change the error string on RPC errors from "bad-txns-legacy-sigops"/"txn-size-64" to "bad-txns-nonstandard-inputs"/"tx-size-small" prior to activation. I have implemented this in https://github.com/bitcoin-inquisition/bitcoin/pull/118 before, but ended up discarding it because i don't think it is worth introducing more complexity and divergence from what has been tested on Inquisition just for this.
See this comment and the comments it links to for more details.
If i did that it would make sense to change the dereference to a
max_timewarp.value()as well and together it makes the line unnecessarily long, in my opinion.I did check and in the entire diff of this PR there is no use of
has_value()/value(), so that change also can't be justified on consistency grounds.For these reasons and because this is just a style nit, i'll keep it like that and resolve this comment.
Then a comment in the code could be usefull, to not create confusion with the
consensuswordThe constant was renamed with a TESTNET4 a suffix with the purpose of making it clear it's only used for testnet4. I think adding it to the description too would be redundant because it already mentions BIP 94 (which defines BIP 94), and because it's in the name of the constant already.
"No more" pretty explicitly means it can be equal, just not more. But fair enough, i updated the comment to use "superior or equal" language, and took the opportunity to define it positively "must be superior or equal to" rather than negatively "must not be inferior or equal".
This is already what the comment says:
github.com/bitcoin/bitcoin@17817818da/src/consensus/validation.h (L68)Sure. I gave the rationale for this decision in the commit message though, because i could not find a satisfactory place where to put a comment about it.
Rebased now that #35949 is merged.
Addressed all outstanding comments and rebased on master. The most significant change is the modification of the test introduced in
6e60c362bcto use BIP54-valid blocks, prior to enforcing the sigops rule by consensus.🚧 At least one of the CI tasks failed.
Task
lint: https://github.com/bitcoin/bitcoin/actions/runs/34782490024/job/103791923572LLM reason (✨ experimental): CI failed due to a Python lint (ruff) error:
test_framework.script_util.MAX_TX_BIP54_SIGOPSis imported but unused intest/functional/p2p_segwit.py.Hints
Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:
Possibly due to a silent merge conflict (the changes in this pull request being
incompatible with the current code in the target branch). If so, make sure to rebase on the latest
commit of the target branch.
A sanitizer issue, which can only be found by compiling with the sanitizer and running the
affected test.
An intermittent issue.
Leave a comment here, if you need help tracking down a confusing failure.
Concept ACK
🐙 This pull request conflicts with the target branch and needs rebase.
🚧 At least one of the CI tasks failed.
Task
ASan + LSan + UBSan + integer: https://github.com/bitcoin/bitcoin/actions/runs/36150952253/job/108123775607LLM reason (✨ experimental): CI failed because
ipc_testscrashed with akj::ExceptionImpltimer error (“can't advance backwards in time”), aborting the subprocess.Hints
Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:
Possibly due to a silent merge conflict (the changes in this pull request being
incompatible with the current code in the target branch). If so, make sure to rebase on the latest
commit of the target branch.
A sanitizer issue, which can only be found by compiling with the sanitizer and running the
affected test.
An intermittent issue.
Leave a comment here, if you need help tracking down a confusing failure.
With recent actualities, I was musing if there can be issues with the caches, including the
disconnectpoolone with the novel consensus rules, especially for the new sigops limit and the proposed 64-byte size tx inclusion. I don't think there is issues withMaybeUpdateMempoolForReorg, including if there is a reorg on the transient block of consensus rules activation, as there is aPolicyChecksdone at some point.Same with the cache as they're either script-indexed (
m_script_execution_cache) or signature-indexed (m_signature_cache) and all the new checks are at the tx-level. I don't remember to have seen test coverage for all those edge cases, even if it's to demonstrate there is no unexpected interactions, though I'll re-check that. Better safe than not safe.6 additional verified findings in the Review report.
Earlier concerns remain unresolved; see the Run archive linked from the Review report.
🟠 Minor · BIP54 sigops rejections lose txid-level reject caching
Witness-bearing BIP54 sigops rejections now lose txid-level download suppression on every network, although no in-tree producer of the triggering transaction was found.
Location:
src/consensus/tx_verify.cpp:205(head).🟠 Minor · The future-tapleaf test vector reuses the Tapscript witness
The unit-test case and generated vector labelled as a spend of the 0xc2 leaf repeat the preceding Tapscript spend, leaving the intended future-leaf case untested.
Location:
src/test/bip54_tests.cpp:1060(head).🟠 Minor · Clarify whether the first post-activation retarget checks the preceding interval
The negative-interval check at src/validation.cpp:4131 runs only on a period's last block, and only once BIP54 is active. The interval just before activation is never checked, yet it sets the first post-activation retarget. Every soft fork has this property, and rejecting the first active block based on pre-activation history could leave the chain with no valid successor.
Location:
src/validation.cpp:4130(head).🟠 Minor · Always-active BIP54 removes valid-block coverage from two fuzz targets
Making BIP54 always active on regtest leaves two unchanged regtest fuzz targets building invalid blocks:
utxo_total_supplyresets every prepared coinbase'snLockTimeto 0 on purpose, so it can duplicate one later. Its chain cannot grow past height 1, so the BIP30 duplicate-coinbase and deeper supply/CVE-2018-17144 paths stop being exercised.cmpctblockbuilds every new coinbase withnLockTime0 and the default final sequence. Those blocks never reach the valid-block branch that selects high-bandwidth peers.Location:
src/test/fuzz/utxo_total_supply.cpp:57(head).🔵 Suggestion · BIP54 upgrade changes lack release notes
Default regtest activation changes
getblocktemplatenegotiation and old-chain compatibility, while mempool rejections change on every network; the release notes provide no upgrade guidance.Location:
src/kernel/chainparams.cpp:639(head).🔵 Suggestion · Mempool sigops coverage omits disabled standardness
The mempool sigops test requires standardness and has BIP54 active, so its rejection assertions do not protect the new unconditional enforcement against option-dependent regressions.
Location:
test/functional/mempool_sigoplimit.py:231(head).Review coverage was incomplete.
Reviewed:
3f0f142b1d0d· Review report · Previous reportspermalink
Concept ACK on implementing BIP 54 code and functionality here without mainnet activation to have it available.
I don't think I have the expertise nor the bandwidth to review this in detail soon.
I gave this a first read. The PR structure works well, it was easy to follow each commit. The consensus rules appear to match the BIP, I still have to look at the tests more closely.
Nit: I think “greater” is more common in this expression:
Given that Genesis blocks of chains are hardcoded, should it be active for the Genesis block? Wouldn’t height 1 make more sense?
In "Avoid creating <= 64-byte transactions in most functional tests" (
f09286f609):I was trying to figure out why the output script padding is necessary.
My explanation is that the coinbase field ("input script" of the coinbase transaction) must have at least 2 bytes, which means that the input has at least 43 bytes (36+4+1+2), the transaction header is 10 bytes, output amount is 8 bytes, output script length is 1 byte. Thus, to guarantee at least 65 bytes, the output script needs to have at least three bytes.
Concept ACK
Reviewed commits up to
2afc853fc2, left a couple of comments. The commits are well structured so far. I plan to review the rest later.In "validation: make BIP54 sigops check consensus-critical"
2afc853fc2The following mutant passes all test suite:
Since regtest has BIP54 always active and
test_legacy_sigops_stdnessnow only covers post-activation andfeature_bip54.pyonly checks block acceptance pre-activation. Nothing covers the pre-activation mempool rejection anymore, which is the rule in effect on mainnet until activation.Maybe add a
testmempoolacceptrejection (bad-txns-legacy-sigops) for the many-sigops tx in the pre-activation section offeature_bip54.py? Running it with-acceptnonstdtxn=1would also cover the new behaviour that the check can't be bypassed with that option.In "validation: make BIP54 sigops check consensus-critical"
2afc853fc2nit: now that this checks invalidity rather than non-standardness test_legacy_sigops_stdness / nonstd_tx / std_tx are misleading. Maybe test_legacy_sigops_limit / invalid_tx / valid_tx?
reviewed through
fa6b7a7480Logic matches up with the inquisition branch I reviewed, with a few differences:
Ran a set of mutation tests focusing on things like off-by-one errors, only thing that wasn't killed was a test where rules are enforced one block late, for each rule. Bot implemented a throwaway test for that and passed.
Mutant list and results
Sigops
sigops >= 2500instead of>fAccurate=falseGetSigOpCount(true)(no P2SH redeemScript)enforce_bip54=falseTimewarp
<=instead of<Murch-Zawy
<=instead of<first_height = nHeight - dai + 2first_height = nHeight - dai(Assert crash)nHeight % dai == dai - 2(Assert crash)Coinbase
nLockTime == nHeightnLockTime == nHeight - 264-byte transactions
tx-size-small)Minor comments only
fa6b7a7480v33* 🤞
b52976de09Commit message could be pedantic and say it's already the bip54 sigops limit. I'd forgotten it was already the case and was confused
d2094c8f48Since DEPLOYMENT_HEIGHTINCB check above would already violate this, do we want to do this assert near the top of CheckContextualBlock?
f09286f609self-documenting assert on witness-stripped serialization before returning the coinbase?
The ALWAYS_ACTIVE start time always takes priority, so while it can't be validated on the genesis block, changing this value would just be an aesthetic change (which i'd rather not make because it would be misleading). Also, min activation height is merely a lower bound on the transition from LOCKED_IN to ACTIVE, so setting it to 0 would not prevent validation on the genesis block.
Yes, that looks correct to me.
Done, thanks.
Updating the comments to say "invalid" was a compromise between a larger diff and being too misleading. I think it's fine if the variable / test names stay as the comments are updated. I'm also happy to go all the way if you feel strongly.
But isn't this expected, since
DeploymentActiveAfteris alwaystruefor regtest?On mainnet before activation, the mempool rejection is the one tested here: "bad-txns-legacy-sigops".
The title already reads "rename BIP54-sigops constants", but sure, added a sentence to this effect in the body.
Makes sense, done.
Meh, if that didn't hold, tests using this would all fail anyways.
Updated. :)
ACK https://github.com/bitcoin/bitcoin/pull/35793/commits/3f0f142b1d0d08a18152d6b100e12d1abf09d58e
Minor changes only, including hte
Assert()move inCheckContextualBlockYes, on regtest, but the mutant changes behaviour on mainnet before activation and no test catches that.
The unit test calls CheckTxInputs directly with a hardcoded enforce_bip54=true, bypassing what PreChecks passes.
tACK
3f0f142b1dI checked the sigop count against btclib, a library I maintain, on the 39 published sigop vectors and on 27 cases of my own: the 2500/2501 bound across P2SH, bare multisig and
CHECKMULTISIGin the scriptSig, oversized redeem scripts, and scriptSigs whose last item is not the redeem script. The PR and btclib agree on all of them. The size, timestamp and coinbase vectors also agree with a short checker I wrote from the BIP text. The unit suite, the touched functional tests and a 5-minute run ofbip54_sigopspass.Nit: the
txsize.jsoncase "A 61-byte legacy transaction with a witness" is 60 bytes stripped and 64 with its witness, as theAsserts inbip54_txsizesay. The BIP'stxsize.jsonhas the same comment.@ViniciusCestarii's mutant can be caught on regtest. On a node started with
-vbparams=consensuscleanup:0:3999999999 -acceptnonstdtxn=1, the deployment is only started, and the PR rejects a 2501-sigop transaction intestmempoolacceptwithbad-txns-legacy-sigops. Under the mutant it is accepted, whilefeature_bip54.py,mempool_sigoplimit.pyandmempool_accept.pystill pass. That check could go infeature_bip54.py. I can share it and my other scripts as a gist.Performed a review pass, only over the 64-byte-tx changes. Looks correct and complete.
I've left some comments, notably about
getblocktemplatebreakage (on regtest), and the inconsistency in mempool vs. block acceptance rejection reason in non-BIP54-active chains.(
3f0f142b1d)This commit breaks existing
getblocktemplatecalls on Regtest. Withgbt_optional_rule = falseandALWAYS_ACTIVEon Regtest, agetblocktemplatecall now has to include"consensuscleanup"in the"rules"({"rules": ["segwit", "consensuscleanup"]}). Otherwise the error"Support for 'consensuscleanup' rule requires explicit client support"is returned. This affects external mining software, Stratum proxies, and other projects' integration tests. In our tests this works asNORMAL_GBT_REQUEST_PARAMSis updated too.This is a behavior change that warrants mentioning in release notes. Making the rule optional (
gbt_optional_rule = true) is another option for discussion.The 64-byte rule is tested on BIP54-active chain (RegTest) only, not on non-active chain. I recommend adding a test on mainnet, to verify non-activation on mainnet (at current heights).
Minor: Isn't this 60 bytes, not 61?
INVALID_TX_NONWITNESS_SIZE - 4Elsewhere (in
ContextualCheckBlock) the valuebad-txns-sizeis used. I propose using the same value here as well, and droppingtxn-size-64, for consistency.Whether the error code should be 64-byte specific or not, is up for discussion. (I lean towards the more generic
bad-txns-size, but I'm indifferent.)Order of checks: I believe any validity check should come before standardness checks. Otherwise a tx that fails both checks is reported as non-standard, instead of the stronger invalid.
I propose moving the 64-byte invalid check before the
IsStandardTxcall before.Unconditional consensus error at mempool check. 64-byte transactions are rejected from mempool with consensus error now, regardless of deployment (so on mainnet as well). This is inconsistent, as such transactions are considered consensus-valid at block checking. The status quo is rejecting 64-byte transactions with non-standardness error. Therefore the behavior is unchanged, only the error is changed from non-standard to invalid in this case.
All this seems intended behavior. Nonetheless, I think it would make sense to explicitly mention this inconsistency in:
The discarded alternative is to reject with consensus failure only if BIP54 is active, otherwise leave the non-standardness rejection.
Nit: The
64here could be replaced byINVALID_TX_NONWITNESS_SIZEnow.Minor optimization observation: a custom,
IsSizeInvalid()method could perform faster than the generic compute-size-and-compare-to-64. However, the difference is minimal, especially compared to costly part of block validation.Nonetheless, a custom method would make the intent more explicit and leave room for further optimization.
Sample `IsSizeInvalid()` implementation
Nit: There is no assert here that indeed the tx is 64 bytes, I suggest adding one, like in
submit_block_64byteabove.I ran some mutation testing and found 3 live mutants besides https://github.com/bitcoin/bitcoin/pull/35793#discussion_r4338365979. These 3 move BIP54 enforcement by one block at activation.
I also published them at https://mutanthub.space/projects/bitcoin/bitcoin/pulls/35793, where they can be discussed.
src/validation.cpp (3)
Sigops limit enforced a block early
Timewarp skipped at activation block
Coinbase locktime skipped at activation
Reviewed the rest of the code, looks good. Left some nits.
nit:
nit: this should be
start_time + 2 * 4 * interval_expected_sec. As is, period 2's elapsed time is 0, so difficulty goes D -> D/4 -> D -> 4D instead of D -> D/4 -> D/16 -> D/4. The mitigation is still covered either way.nit: could assert:
nit:
🐙 This pull request conflicts with the target branch and needs rebase.
ralph referenced this pull request2026-11-04 10:09:08 +00:00
Yes, this is intentional. The point of having mandatory rules is to alert miners for soft forks that require a change in pool software. So making the rule optional is a non-starter.
Mentioning it in the release notes could make sense, indeed.
Errors use different short names for standalone and block transactions. The current names were chosen to be consistent with the vast majority of prefixes used in each context.
It's not practical to check standardness rules after consensus rules, if only because some standardness rules are meant to protect from consensus validation DoS. As a result, we return a standardness error for a consensus-invalid transaction in plenty of cases. Therefore i don't think it's worth trying to avoid that in some specific situations for that specific check, and i prefer to keep the newly introduced consensus check next to the related existing standardness check.
Previous discussion on this in https://github.com/bitcoin/bitcoin/pull/35793#discussion_r3994152368.
This is mentioned in the commit message. More rationale for the decision is given in the earlier commit message for the other newly introduced TX_CONSENSUS error.
I've reviewed the code and it lgtm. Needs rebase. I've left small, non-blocking suggestions
0d14d064f4: qa: extensive unit tests for BIP54 legacy sigops limitThis case is bare CMS.
0d14d064f4: qa: extensive unit tests for BIP54 legacy sigops limitThis case is bare CMS.
0d14d064f4: qa: extensive unit tests for BIP54 legacy sigops limit62 * 40 = 2480
0d14d064f4: qa: extensive unit tests for BIP54 legacy sigops limit63 * 40 = 2520.
Exceed case has 63 inputs.
0d14d064f4: qa: extensive unit tests for BIP54 legacy sigops limit0d14d064f4: qa: extensive unit tests for BIP54 legacy sigops limit166 * 15 = 2490
Right, good catch.
Great catch.
Good catch, looks like i updated these tests at some point, without updating the comments.
Same here. Thanks for the careful read here, i'll make sure to point an LLM to this file to surface any inconsistency before pushing again.
no problem!
I'm not sure what you suggest here? Clearly we can't bootstrap a mainnet chainstate at the current height in our unit test, and we have other ways of being confident our inactive BIP 9 deployments are not incorrectly treated as active.
I think this is unnecessary complexity: i would rather keep the consensus check simple and "obvious" than get some minimal performance gains, especially on a path that is currently not a bottleneck.
Taken, thanks.
Taken.
Taken.
Taken.
Done.
Done, thanks.
Oh, the pre-LLM-enlightenment times where we hand rolled thousands of lines of tests and made silly copy-pasta mistakes along the way. Dark, uncertain times.
Done, thanks!
Done.
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
DeploymentActiveAt()/DeploymentActiveAfter()). Some mutants remain for the timewarp check for instance, because it requires a full retarget period setup. I think the test now strikes a good balance between better checking the activation boundaries but keeping the test easy to follow.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
OP_0keys is correctly accounted for 20 sigops as in BIP 16), so i (re-)added it instead of updating the outdated comment.I also had a clanker check for arithmetic nits like https://github.com/bitcoin/bitcoin/pull/35793#discussion_r4401934437 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 https://github.com/bitcoin/bitcoin/pull/35793/commits/58b418f85582b559ad9ac718e42251e5bc5aab3a
Test and comment fixes, plus
INVALID_TX_NONWITNESS_SIZEusage swapped in IsBlockMutated.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
58b418f855Got it, thx
ACK
58b418f855Can confirm the 2 mutants were killed.
nit: the timewarp activation mutant can be killed without a full retarget setup:
ACK
58b418f855Performed review on the whole changeset. Only found some nits.
A general remark: I think a release not would make sense, mentioning:
getblocktemplatechanged requirement, see https://github.com/bitcoin/bitcoin/pull/35793#discussion_r4387647295I consider the changes correct and acceptable in the current form already (in spite the minor findings).
Nit:
tx_verify.hinclude no longer needed.Nit: consider avoiding using
’character in error message, may cause issues in RPC calls. Use simple quote', or "timestamp of the block" construct.Nit: wording "64 bytes transaction" -> "64-byte transaction"
Nit:
expect_disconnectfield is no longer exists, should be removed from here.Nit: These lines are useless in this form. Also one more occurrence of the same pattern further below.
ACK on the actual consensus changes, planning to look closer to the tests within the next days
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 https://github.com/bitcoin/bips/pull/2122 / https://github.com/bitcoin/bips/pull/2122/changes/ff39733e70a237d3472af68ddf68441e6ecbab51?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 https://github.com/bitcoin/bips/pull/2122) after this PR is merged.
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
disconnectpooldue to the new rules applying on the coinbase or the max sigops for old inputs spends, among other concerns.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
scriptpubkeyof 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 thePreChecks()code path (whereCheckTransaction()is called beforeIsCoinBase()detection) or inCheckBlock()(where we do aCheckTransaction()).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 beforeContextualCheckBlock()(e.g inAcceptBlock()). It sounds as such you might haveCheckBlock()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 inblockencoding.cppit doesn't sound to.ACK
58b418f855ACK
58b418f855in
a730c789ce: 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.ACK
58b418f855I 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.
This brings noisy logs when you execute the test without ctest, worth suppressing?
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 waySCRIPT_VERIFY_*flows intoCheckInputScripts.nit: will be good for debugging to see the values that trigger the failure here and the murch zawy check?
It seems that this
nHeight > 0check 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?If you want to rely on that, then an
assert(pindexPrev != nullptr); // genesis block never goes through this pathat 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.
FWIW, I seem to get an error around
test/kernel/test_kernel.cpp(935)(sochainman->ImportBlocks) if I add apindexPrev != nullptrassert at the top ofContextualCheckBlock; haven't looked in any further detail.ACK
58b418f855Left some small feel-free-to-ignore nits
in
de464d3e35the commit message saysas it will be made consensus-critical in the next commit, but that is not true, next two commits only clarifies a documentation comment and modifies some testing.in
af2a89fe33validation: make BIP54 sigops check consensus-criticalmaybe add
BOOST_CHECK(state.GetResult() == TxValidationResult::TX_CONSENSUS);?in
fae79e5112qa: add to utilities a version of SignSignature for Taproot inputsI think we can drop
fromPubKeyandamountsincespent_outputs[nIn]already contains both, passing them separately lets a caller supply conflicting values.in
b4381856ddvalidation: prevent negative difficulty adjustment intervalsmaybe could make this int const?
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).
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_CONSENSUSerror is yield and the whole block is marked as invalid. the peer should punished accordingly toMaybePunishNodeForBlock()unless it's a compact block (L2042 insrc/net_processing.cp) where the trick is repeated. if we're caching well the block invalidity at reception ofCMPCTBLOCKmessage, 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_availablebetween the completion of a compact block message round trip with junk, though doesn't change from already existent garbage fulfilling vector, i'm thinking.