Skip to content

Implement BIP 54 (Consensus Cleanup) without mainnet activation - #35793

Open
darosior wants to merge 22 commits into
bitcoin:masterfrom
darosior:bip54
Open

darosior wants to merge 22 commits into
bitcoin:masterfrom
darosior:bip54

Conversation

@darosior

Copy link
Copy Markdown
Member

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_tests unit test module exercises each mitigation extensively in isolation. The feature_bip54.py functional 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.

@DrahtBot

DrahtBot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

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.

Type Reviewers
ACK instagibbs, nervana21, ViniciusCestarii, optout21, fanquake, theStack, ismaelsadeeq, polespinasa
Concept ACK dergoegge, hsjoberg, fjahr, stickies-v, 0xB10C
Stale ACK fametrano

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:

  • #37006 (fuzz: add Silent Payments targets by devdavidejesus)
  • #36990 (test: replace hard-coded RPC error codes by l0rinc)
  • #36847 (test: cover BIP30 for non coinbase txs by ViniciusCestarii)
  • #36455 (Test: Add legacy script edge case spender test by benthecarman)
  • #36122 (BIP460: CISA for Taproot key path spends by fjahr)
  • #34864 (coins: tighten cache entry state invariants by l0rinc)
  • #32468 (rpc: generateblock to allow multiple outputs with custom payouts by polespinasa)
  • #29491 ([EXPERIMENTAL] Schnorr batch verification for blocks by fjahr)

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 → Prefer assert_equal(len(tx.serialize_without_witness()), 63).
  • test/functional/data/invalid_txs.py: assert MIN_STANDARD_TX_NONWITNESS_SIZE - 1 == 64 → Prefer assert_equal(MIN_STANDARD_TX_NONWITNESS_SIZE - 1, 64).

2026-11-13 16:40:38

@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task macOS native: https://github.com/bitcoin/bitcoin/actions/runs/30100472888/job/89504946717
LLM reason (✨ experimental): CI failed because bip54_tests aborted on an assertion failure in CExtKey::SetSeed (seed.size() was outside the expected 16–64 byte range) during bip54_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.

@Christewart

Copy link
Copy Markdown
Contributor

Congrats! Excited to see this work make it to this point 🎉

@ariard ariard left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Let's start at least the review for the fix of the long validation block time.

Comment thread src/consensus/consensus.h Resolved
// 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Absolutely, the rationale is to reuse BIP 16 accounting, instead of introducing another opcode counting method in consensus rules.

@ariard ariard Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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?

@ariard ariard Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@dergoegge

Copy link
Copy Markdown
Member

Concept ACK

4 similar comments
@fanquake

Copy link
Copy Markdown
Member

Concept ACK

@polespinasa

Copy link
Copy Markdown
Member

Concept ACK

@theStack

Copy link
Copy Markdown
Contributor

Concept ACK

@hsjoberg

Copy link
Copy Markdown
Contributor

Concept ACK

@fjahr

fjahr commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

Comment thread src/node/miner.cpp Resolved
Comment thread src/kernel/chainparams.cpp Resolved
ajtowns and others added 5 commits November 13, 2026 11:28
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.
@darosior

Copy link
Copy Markdown
Member Author

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_0 keys 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 #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).

@instagibbs

Copy link
Copy Markdown
Member

reACK 58b418f

Test and comment fixes, plus INVALID_TX_NONWITNESS_SIZE usage 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

@nervana21

Copy link
Copy Markdown
Contributor

tACK 58b418f

@ViniciusCestarii ViniciusCestarii left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 optout21 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 getblocktemplate changed requirement, see #35793 (comment)

I consider the changes correct and acceptable in the current form already (in spite the minor findings).

Comment thread src/policy/policy.cpp
#include <coins.h>
#include <consensus/amount.h>
#include <consensus/consensus.h>
#include <consensus/tx_verify.h>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

8499388 [test] Separate 64B and 63B tx size tests:

Nit: expect_disconnect field is no longer exists, should be removed from here.

Comment on lines +196 to +197
except Exception as e:
raise e

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment thread src/validation.cpp
Comment on lines +4208 to +4209
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");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit: consider avoiding using ’ character in error message, may cause issues in RPC calls. Use simple quote ', or "timestamp of the block" construct.

Comment thread src/validation.cpp
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");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit: wording "64 bytes transaction" -> "64-byte transaction"

Suggested change
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 theStack left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ACK on the actual consensus changes, planning to look closer to the tests within the next days

Comment thread src/test/bip54_tests.cpp
Comment on lines +30 to +31
// Uncomment to output updated JSON tests.
// #define UPDATE_JSON_TESTS

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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 ariard left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment thread src/validation.cpp
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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@fanquake

Copy link
Copy Markdown
Member

ACK 58b418f

@DrahtBot
DrahtBot requested a review from theStack November 25, 2026 18:15

@theStack theStack left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ACK 58b418f

Comment on lines +847 to +848
# Disable the consensus cleanup for the BIP30 checks.
self.restart_node(0, ["-vbparams=consensuscleanup:0:0"])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@ismaelsadeeq ismaelsadeeq left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Comment thread src/validation.cpp
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");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit: will be good for debugging to see the values that trigger the failure here and the murch zawy check?

Suggested change
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));

Comment thread src/test/bip54_tests.cpp

// Now assert the validity status of each case under the new rules.
{
auto test_setup{TestingSetup{ChainType::MAIN, {.extra_args = {"-vbparams=consensuscleanup:-1:-1"}}}};

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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

Comment thread src/validation.cpp
}

// Make sure the coinbase transaction is timelocked to the block's height. (BIP 54)
if (nHeight > 0 && DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_CONSENSUSCLEANUP)) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment thread src/validation.cpp
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)) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@polespinasa polespinasa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

ACK 58b418f

Left some small feel-free-to-ignore nits

in de464d3 the commit message says as 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.


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");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Comment thread src/validation.cpp
// 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};

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

in b438185 validation: prevent negative difficulty adjustment intervals

maybe could make this int const?

@ariard ariard left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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).

Comment thread src/validation.cpp
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");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.