Skip to content

Primitives: Combine assignments - #35994

Draft
purpleKarrot wants to merge 8 commits into
bitcoin:masterfrom
purpleKarrot:combine-assignments
Draft

purpleKarrot wants to merge 8 commits into
bitcoin:masterfrom
purpleKarrot:combine-assignments

Conversation

@purpleKarrot

Copy link
Copy Markdown
Contributor

#35904 mentions that validation code does not require the data members of COutPoint, CTxOut, and CTxIn to be individually mutable. This requirement instead comes from test code being written in a procedural rather than declarative style.

This PR presents a bitcoin-tidy check that identifies consecutive assignments to annotated data members of the same object and suggests rewriting them with a constructor invocation. This allows a mechanical refactoring of the majority of mutations and it paves the road for making the types fully immutable.

@DrahtBot

DrahtBot commented Aug 17, 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
Concept ACK l0rinc, josibake, alexanderwiederin

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:

  • #35733 (sign: Remove FillableSigningProvider by achow101)
  • #35580 (bugfix: compare non-adjusted chunk weight against block weight limit by ismaelsadeeq)
  • #35569 (Encapsulation for CTransaction by purpleKarrot)
  • #35477 (test: exercise Schnorr signature cache in txvalidationcache_tests.cpp by theStack)
  • #34360 (bench: add WalletBalanceManySpent for high-history wallet scenario by w0xlt)

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.

@purpleKarrot
purpleKarrot force-pushed the combine-assignments branch 3 times, most recently from 58e4280 to da83f70 Compare August 17, 2026 19:29
@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task 32 bit ARM: https://github.com/bitcoin/bitcoin/actions/runs/32057506973/job/95470930565
LLM reason (✨ experimental): CI failed at compile time because transaction.h is inconsistent with the COutPoint/CTxIn/CTxOut class definitions (missing fields like hash/n, prevout, scriptSig, etc.).

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.

@l0rinc

l0rinc commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

I understand that it's not always trivial to run every check locally, but we're getting notifications about every push and it doesn't really increase the confidence in changes like this if they don't even pass CI.
I usually push these to my own fork first to make sure the change makes sense before pushing here.
Also, the Primitives: Combine assignments give no clue about what this PR is about, but reading the code seems to make sense, concept ACK.

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

Looks like this is mostly a test-only cleanup (modulo ~6 instances in real code).

Seems fine, as this should reduce test issues due to re-using dirty state accidentally (c.f. #35863 et al)

Txid hash;
uint32_t n;
CONSTRUCTOR_ARGUMENT(1, 2) Txid hash;
CONSTRUCTOR_ARGUMENT(2, 2) uint32_t n;

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.

Is the annotation really required? I'd guess that clang-tidy should be able to iterator over all ctors with args itself and then derive this itself?

The benefit would be that there is only a single source of truth and this won't go stale. Also, manual marking wouldn't be needed. (If you want to limit this to a selected set of classes, it would be better to pass the list as an option to clang-tidy?)

@purpleKarrot purpleKarrot Aug 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I don't want to build too many heuristics into the clang-tidy check. But depending on how we approach the change, it may be less of an issue or not be needed at all (see #35994 (comment)).

t1.vin[1].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4);
t1.vin[2].prevout.hash = dummyTransactions[1].GetHash();
t1.vin[2].prevout.n = 1;
t1.vin[2].prevout = COutPoint(dummyTransactions[1].GetHash(), 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.

Is there a reason to not use the C++11 narrowing checks for new code? Other places use a static_cast<uint32_t>() for the second arg, and I think this is useful to know about and be explicit.

Suggested change
t1.vin[2].prevout = COutPoint(dummyTransactions[1].GetHash(), 1);
t1.vin[2].prevout = COutPoint{dummyTransactions[1].GetHash(), 1};

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, there are a few places where aggregate initialization would not compile, unfortunately.

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.

Ok, I see. I wonder if it is worth it to update them manually (either by adding a static_cast, or by updating the outer type to unsigned, or so)?

Given that such a patch should be easy to review and test-only, with other benefits, it seems fine to submit it and I'd be happy to review it, but no strong opinion.

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 tried switching the fix-it to emit {}. From what I can tell everything that then fails to compile is in test/bench.

public:
void addCheckFactories(clang::tidy::ClangTidyCheckFactories& CheckFactories) override
{
CheckFactories.registerCheck<CombineAssignments>("bitcoin-combine-assignments");

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.

Suggested change
CheckFactories.registerCheck<CombineAssignments>("bitcoin-combine-assignments");
CheckFactories.registerCheck<CombineAssignments>("bitcoin-prefer-ctor");

Given that the was confusion about the name, maybe name it differently?

@purpleKarrot

purpleKarrot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor Author

I pushed this both to back the claim that most mutations appear in test code, but also as a base for discussion about the approach.

One approach would be to submit this PR as is.

An alternative approach would be to focus on one class at a time, like "COutPoint: Make type immutable". Such a PR would then apply bitcoin-prefer-ctor as introduced here, bitcoin-use-observers from #35569, some manual fixes, plus the change to make the data members private. In this approach, #35994 (comment) would be less of an issue, because the annotations would be temporary anyway.

Yet another approach would be to just use this PR as a backlog to identify "places of interest" and then rewrite the code manually, one file at a time, in a declarative style. For example, this code:

CMutableTransaction t1;
t1.vin.resize(3);
t1.vin[0].prevout.hash = dummyTransactions[0].GetHash();
t1.vin[0].prevout.n = 1;
t1.vin[0].scriptSig << std::vector<unsigned char>(65, 0);
t1.vin[1].prevout.hash = dummyTransactions[1].GetHash();
t1.vin[1].prevout.n = 0;
t1.vin[1].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4);
t1.vin[2].prevout.hash = dummyTransactions[1].GetHash();
t1.vin[2].prevout.n = 1;
t1.vin[2].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4);
t1.vout.resize(2);
t1.vout[0].nValue = 90 * COIN;
t1.vout[0].scriptPubKey << OP_1;
// Benchmark.
const CTransaction tx_1(t1);

could be rewritten (assuming the necessary constructors are made available) as:

const CTransaction tx_1{
    std::vector{
        CTxIn{COutPoint{dummyTransactions[0].GetHash(), 1}, CScript{} << std::vector<unsigned char>(65, 0)},
        CTxIn{COutPoint{dummyTransactions[1].GetHash(), 0}, CScript{} << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4)},
        CTxIn{COutPoint{dummyTransactions[1].GetHash(), 1}, CScript{} << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4)},
    },
    std::vector{
        CTxOut{90 * COIN, CScript{} << OP_1},
        CTxOut{},
    },
};

In this approach, #35994 (comment) can be applied directly, with explicit conversions where necessary.

@janb84

janb84 commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

If i'm not mistaken, I read 3 options from the comment of purpleKarrot:

A. Merge this PR as is. The tooling lands in this PR but needs annotations to work. The drawback is that the CONSTRUCTOR_ARGUMENT annotations stay in primitives/transaction.h with no guarantee that a follow-up removes them, and reviewers approve a large mechanical diff with the justification in a future PR.

B. One class at a time, ending in "immutability". For example "COutPoint: Make type immutable": annotate, run the check, run use-observers from #35569, fix the rest by hand, make the members private, and delete the annotations in the same PR. Each PR is self contained and can be judged as a whole if the change is worth the churn.

C. Use the check as a backlog only. Never merge the annotations. Run the check locally to find candidate files and rewrite them by hand in declarative style.

--

Personally I would opt for option B, where a tracking issue can be used to identify and coordinate the effort, keep this bitcoin-tidy code etc. If i'm not mistaken (or mis-understood the comment) this will result in PR's that are self contained with no, or little, follow ups so that the benefits, churn and results are clearly visible in one PR.

@maflcko

maflcko commented Aug 18, 2026

Copy link
Copy Markdown
Member

I am not sure about throwing this in the same bucket as #35569. I think it is pretty clear that a CTransaction should not be mutable (otherwise there wouldn't be a MutableTransaction).

However, for other structs, is there much value/benefit? #35569 seems a bit controversial, so expanding it to stuff that has even less benefit may not be the best approach?

I'd leave this a mostly test-only cleanup (plus maybe #35994 (comment)), but no strong opinion.

@josibake

Copy link
Copy Markdown
Member

Concept ACK

However, for other structs, is there much value/benefit?

Cleaning up the tests is a convention. It does nothing to stop the same buggy behaviour being repeated in the future. Can you explain what benefit you see to keeping the structs in this PR mutable?

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

Concept ACK

Do the checks here need to be run to a fixed point or is a single pass sufficient? Might be worth adding the invocation in the commit messages, so the mechanical changes can be verified.

txSpend.vin[0].nSequence = CTxIn::SEQUENCE_FINAL;
txSpend.vout[0].scriptPubKey = CScript();
txSpend.vout[0].nValue = txCredit.vout[0].nValue;
txSpend.vin[0] = CTxIn(COutPoint(txCredit.GetHash(), 0), scriptSig, 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.

Does this drop the witness?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Indeed.

@purpleKarrot

Copy link
Copy Markdown
Contributor Author

I am not sure about throwing this in the same bucket as #35569. I think it is pretty clear that a CTransaction should not be mutable (otherwise there wouldn't be a MutableTransaction).

They do belong into the same bucket. As I wrote in #35569 (comment):

The idea of having an immutable type associated with a "builder" is alien to C++. It is a necessary evil in languages built on reference semantics, where this pattern is very common. You can compare how strings work differently in C++ vs C#. The fundamental idea is that mutability and sharing should be mutually exclusive to prevent conflicts. Where everything is shared by default (C#), you want to restrict mutation. When things are copied by default (C++), mutation is less of an issue.

For CTransaction however (and also for CBlock, CTxIn, CTxOut, and COutPoint), mutation is a rare use case.
Those types should be made immutable, with no associated builder (no CMutableTransaction), and code that "builds" those types in procedural code should be rewritten in a declarative style (this mostly affects test code).

Which is exactly the claim that I wanted to back with this draft.

Concerning the approach, I actually lean towards C.

@alexanderwiederin

Copy link
Copy Markdown
Contributor

I actually lean towards C.

That sounds reasonable to me. It means the surrounding context gets read, the narrowing conversions get made explicit and comments in the affected blocks survive.

I've started on a couple of these in /bench. Happy to keep going if that's useful.

fanquake added a commit that referenced this pull request Aug 21, 2026
…ssion

950bdb7 bench: Construct CTxOut and COutPoint in a single expression (Alexander Wiederin)

Pull request description:

  Replaces field-by-field mutation of `CTxOut` and `COutPoint` in two bench files with brace initialisation, which requires the `size_t` conversions to be made explicit.

  Noticed while looking at #35994, where switching the proposed fix-it to `{}` surfaces implicit narrowing conversions like these.

  The constructed values are unchanged.

  *Note: Only the sites where a conversion is involved are included in this PR; the remaining field-by-field construction in `bench/` would be covered by #35994's follow-ups.*

ACKs for top commit:
  l0rinc:
    code review ACK 950bdb7
  maflcko:
    review ACK 950bdb7 🐯

Tree-SHA512: c664d41eeeb9241d381e5fa27689f18d9445a942055734463978498f60d0f2c495a0d7a58131493bb63267371bb6fe2d45ac124d910c919c8905322948d17a23
@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task tidy: https://github.com/bitcoin/bitcoin/actions/runs/32467526648/job/96727213621
LLM reason (✨ experimental): Clang-tidy failed due to bitcoin-combine-assignments warnings-as-errors in test/mempool_fee_estimator_tests.cpp (separate member assignments not combined).

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.

coinbaseTx.vout.resize(1);
coinbaseTx.vout[0].scriptPubKey = SCRIPT_PUB;
coinbaseTx.vout[0].nValue = GetBlockSubsidy(nHeight, chainparams.GetConsensus());
coinbaseTx.vout[0] = CTxOut(GetBlockSubsidy(nHeight, chainparams.GetConsensus()), SCRIPT_PUB);

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.

should probably use init-list, like #36019 (comment)

@DrahtBot

Copy link
Copy Markdown
Contributor

🐙 This pull request conflicts with the target branch and needs rebase.

fanquake added a commit that referenced this pull request Oct 29, 2026
…context-dependent cases

bdf58dd test: construct transaction_tests test_Get inputs/outputs declaratively (Alexander Wiederin)
24d00c4 bench: construct ccoins_caching inputs/outputs declaratively (Alexander Wiederin)
a45478a test: construct sigopcount_tests BuildTxs inputs/outputs declaratively (Alexander Wiederin)
524d554 test: construct CreateBlockChain coinbase declaratively (Alexander Wiederin)
60be093 test: construct transaction_utils inputs/outputs declaratively (Alexander Wiederin)

Pull request description:

  Part of #36692 (previously discussed in #35994): replace procedural, field-by-field construction of `COutPoint`, `CTxIn` and `CTxOut` in test code with constructor calls.

  This PR covers cases that are context-dependent and need manual changes, independent of a scripted-diff for the trivial bulk:
  - `test/util/transaction_utils`: in `BuildSpendingTransaction`, the `scriptWitness` assignment has to be moved after `vin` is replaced, otherwise the witness is dropped.
  - `test/util/mining`: in `CreateBlockChain`, the coinbase input's fields were split by the output assignments, with comments that are now kept next to the constructor arguments.
  - `sigopcount_tests`: `BuildTxs` has the same witness ordering issue as `BuildSpendingTransaction`.
  - `bench/ccoins_caching`: The `scriptSig`s are built with `<<` appends, and the second output was created by `vout.resize(2)` but never assigned, so it is kept as a null `CTxOut{}`.
  - `transaction_tests`: `test_Get` builds the same transaction as `bench/ccoins_caching`, with the same `<<` appends and null second output.

  **This change is test- and bench-only and does not change the constructed transactions.**

  Notes for reviewers:
  - `CTxIn` has no witness constructor argument, so `scriptWitness` is assigned after `vin` is replaced.
  - `BuildTxs` is called repeatedly on the same transaction objects. Previously, `resize(1)` kept the existing inputs and only overwrote some of their fields; now they are replaced entirely. The fields that were left untouched by `BuildTxs` are never modified by the test, so the transactions are unchanged.
  - The null second output in `ccoins_caching` is copied from `test_Get` in `transaction_tests` and looks like an oversight. It is kept here to avoid behaviour changes.

ACKs for top commit:
  maflcko:
    review ACK bdf58dd 🍠
  purpleKarrot:
    But even when the approach does not follow the steps 1 and 2, it is a step in the right direction, hence ACK bdf58dd

Tree-SHA512: af4c7489ddc553eda466b7ac4ca33cff400a495264b8cb2d869929e108fab8dac08f3cc164be79a3505b7c8b461514fc6f87f5afd42919f0712dd1d325d824b7
@maflcko

maflcko commented Oct 29, 2026

Copy link
Copy Markdown
Member

CI is red and this draft is inactive for months. I guess it can be closed?

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants