Skip to content

Encapsulation for CTransaction - #35569

Open
purpleKarrot wants to merge 7 commits into
bitcoin:masterfrom
purpleKarrot:transaction-abstraction
Open

purpleKarrot wants to merge 7 commits into
bitcoin:masterfrom
purpleKarrot:transaction-abstraction

Conversation

@purpleKarrot

@purpleKarrot purpleKarrot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

CTransaction currently exposes its data members publicly. This makes the implementation details of the type part of its interface.

This PR encapsulates the data members behind public observer functions. The existing users of CTransaction are migrated to the observers, after which the data members are made private.

The refactoring is deliberately split into three steps:

  1. Add observer functions corresponding to the existing data members.
  2. Migrate all users from direct data-member access to the observers.
  3. Make the data members private.

The migration is automated with a new bitcoin-tidy use-observers check. This both makes the large mechanical change straightforward and provides a reusable tool for similar refactorings.

The split into separate commits allows reviewers to review handwritten changes independently of the automated changes. It also simplifies rebasing: if the mechanical migration conflicts, individual files can be reset to their new base versions and the migration tool can be run on them again. This works because the old interface remains available until the final commit, so the reset code is still valid while the mechanical migration is reapplied.

This PR does not change the semantics of CTransaction. In particular, regular value semantics are intentionally left for a subsequent change.

Why Encapsulation? Why CTransaction?

Public data members make the representation of a type part of its API. Once access goes through observers, the representation can change without requiring its users to change as well. Potential changes are using shared immutable transaction state, or even an offset into shared immutable block state.

This establishes a clean boundary between the transaction's data and functionality that operates on it. In particular, it allows serialization/deserialization and other functionality to be separated from the data layout itself in subsequent refactorings.

This work is part of the broader interface-segregation direction described in #35904, but is not a prerequisite for the stateless validation library proposed there. The encapsulation has value independently of that work.

CTransaction is a good type to start this migration with: it is widely used, its interface is relatively simple, and its data members are already effectively immutable. This allows the migration to establish the pattern and tooling without first requiring changes to the semantics of the type.

@DrahtBot

DrahtBot commented Jun 19, 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 NACK ajtowns
Concept ACK w0xlt, janb84, willcl-ark, ryanofsky
Approach NACK l0rinc
Stale ACK alexanderwiederin, josibake

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:

  • #36606 (test, bench: construct inputs/outputs declaratively in context-dependent cases by alexanderwiederin)
  • #36598 ([Demo] validation: remove AssumeUTXO by l0rinc)
  • #36521 (Keep witness stacks in serialized form in CScriptWitness by sipa)
  • #36496 (coins: avoid redundant prevout preparation allocations by l0rinc)
  • #36480 (txospenderindex: hash keys and pack positions to reduce disk usage by arejula27)
  • #36466 (policy: make unstructured Taproot annexes standard by RobinLinus)
  • #36395 (script: clarify implicit signature-cache input requirements by l0rinc)
  • #36357 (mining: move BlockAssembler statics into BlockTemplateManager by w0xlt)
  • #36122 (BIP460: CISA for Taproot key path spends by fjahr)
  • #36015 (txorphanage: bound orphan memory by storing transactions serialized by brunoerg)
  • #35793 (Implement BIP 54 (Consensus Cleanup) without mainnet activation by darosior)
  • #35786 (wallet: drop spent parents redundant cache invalidation and notification by furszy)
  • #35747 (wallet: Fix FillPSBT failing to sign owned inputs when UTXOs disagree by nervana21)
  • #35713 (Remove boost as a unit test runner by rustaceanrob)
  • #35671 (mining: add TxCollection to bandwidth-efficiently validate external block templates by Sjors)
  • #35662 (script: prevent partial reinitialization of sighash data by l0rinc)
  • #35570 (refactor: Change some validation.cpp methods to return BlockValidationState by optout21)
  • #35511 (RFC: consensus: Make CAmount a class by hodlinator)
  • #35302 (Silent Payments: Sending (take 2) by Eunovo)
  • #34864 (coins: tighten cache entry state invariants by l0rinc)
  • #32575 (consensus: Remove special treatment for single threaded script checking by fjahr)
  • #31252 (rpc: print P2WSH and P2SH redem Script in getrawtransaction and getblock by polespinasa)
  • #29843 (policy: Allow non-standard scripts with -acceptnonstdtxn=1 (test nets only) by ajtowns)
  • #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 named args for integral literals may be used (e.g. func(x, /*named_arg=*/0) in C++, and func(x, named_arg=0) in Python):

  • Coin(tx->GetOutputs()[n], MEMPOOL_HEIGHT, false) in src/txmempool.cpp
  • Coin(ptx->GetOutputs()[outpoint.n], MEMPOOL_HEIGHT, false) in src/txmempool.cpp
  • emplace_back(coins[tx.GetInputs()[i].prevout.n].out, tx, signature_cache, i, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, false, &txdata) in src/test/transaction_tests.cpp

2026-09-24 18:29:12

@fanquake

Copy link
Copy Markdown
Member

More details at

Can you put all the parts relevant to reviewers into the PR description?

@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task lint: https://github.com/bitcoin/bitcoin/actions/runs/27835663586/job/82382956280
LLM reason (✨ experimental): CI failed because the lint scripted-diff check errored out with cmake: not found (and run-clang-tidy: not found), indicating missing tools in the lint container.

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.

@purpleKarrot
purpleKarrot force-pushed the transaction-abstraction branch from 4541201 to 853db19 Compare June 20, 2026 03:42
@purpleKarrot
purpleKarrot marked this pull request as ready for review June 20, 2026 03:55
@purpleKarrot

Copy link
Copy Markdown
Contributor Author

export CXX="$(which clang)"

should be clang++. But before I push that change and trigger another rebuild, I will wait for more comments.

The linter fails validating the scripted_diff due to cmake and run-clang-tidy not being found. How can this be fixed?

@ajtowns

ajtowns commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

The result is that CTransaction has regular semantics for copy, move, and assignment.

This doesn't seem like a good idea at all to me. If you want an object that can represent different transactions over its lifetime, you should be using CMutableTransaction, and afaics we don't want that for things like the mempool, or for anything we reference via a CTransactionRef.

Note that the comment ("CTransaction is not actually immutable; deserialization and assignment are implemented, and bypass the constness.") was made incorrect by #8580 in 2016.

@janb84

janb84 commented Jun 21, 2026

Copy link
Copy Markdown
Contributor

export CXX="$(which clang)"

should be clang++. But before I push that change and trigger another rebuild, I will wait for more comments.

The linter fails validating the scripted_diff due to cmake and run-clang-tidy not being found. How can this be fixed?

I do not think you can do this, as far as I can tell the linter container image does not contain cmake. Drop the scripted diff validation ?

@purpleKarrot

purpleKarrot commented Jun 21, 2026 •

Copy link
Copy Markdown
Contributor Author

The result is that CTransaction has regular semantics for copy, move, and assignment.

This doesn't seem like a good idea at all to me.

Just to make sure there is no misunderstanding here. All builtin types in C++ as well as nearly all types in the standard library have regular semantics. You are saying that is a bad design, right?

we don't want [an object that can represent different transactions over its lifetime] for things like the mempool

So instead, the mempool uses CTransactionRef, an object that can not only represent different transactions over its lifetime, but can also change whether it actually holds a transaction or not. I don't get how that is better.

@w0xlt

w0xlt commented Jun 21, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

@ajtowns

ajtowns commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

The result is that CTransaction has regular semantics for copy, move, and assignment.

This doesn't seem like a good idea at all to me.

Just to make sure there is no misunderstanding here. All builtin types in C++ as well as nearly all types in the standard library have regular semantics. You are saying that is a bad design, right?

No, I said exactly what I intended to say: making CTransaction mutable is a bad idea. We already have CMutableTransaction for cases where mutability is needed.

we don't want [an object that can represent different transactions over its lifetime] for things like the mempool

So instead, the mempool uses CTransactionRef, an object that can not only represent different transactions over its lifetime, but can also change whether it actually holds a transaction or not. I don't get how that is better.

Passing a CTransactionRef around prevents the recipient from modifying it (ignoring const casts), but doesn't prevent the creator from doing so.

    std::shared_ptr<CTransaction> foo;
    vRecv >> TX_WITH_WITNESS(foo);

    ProcessTransaction(foo); // add to mempool

    foo->version = 42; // mempool copy is automatically updated, how neat!

@josibake

josibake commented Jun 22, 2026 •

Copy link
Copy Markdown
Member

Concept ACK

Moving the data members behind observers, vs having the class layout define the API seems a solid improvement.

The result is that CTransaction has regular semantics for copy, move, and assignment
..making CTransaction mutable is a bad idea

Porque no los dos? Turns out, afaict, there is a C++ idiom for this: handle/body idiom with shared immutable representation! What I mean by this is we want to make the exposed transaction type a regular value handle to immutable transaction data1. Concretely, something like this:

class CTransaction {
public:
    CTransaction(const CTransaction&) = default;
    CTransaction(CTransaction&&) noexcept = default;
    CTransaction& operator=(const CTransaction&) = default;
    CTransaction& operator=(CTransaction&&) noexcept = default;

    // the observers added in this PR 
   ...

private:
    std::shared_ptr<const TransactionData> m_data;
};

TransactionData would of course contain vin, vout, version, nLockTime, cached hashes, etc., and would be immutable after construction from CMutableTransaction or deserialisation. Now assignment has normal value semantics:

auto a = tx1;
auto b = a;
a = tx2; // b still observes tx1

That is different from mutating a shared transaction object:

auto p = std::shared_ptr<CTransaction>{...};
ProcessTransaction(p);
*p = tx2; // bad: existing users may observe changed transaction contents

While we still use using CTransactionRef = std::shared_ptr<const CTransaction>, perhaps its best to have CTransaction assignment deleted, or the ref type needs to be updated so the shared thing is the immutable TransactionData, not the assignable wrapper.

Based on my understanding of the linked blogs, this seems in line with their stated goals. We can get rid of the "class layout is the API," eventually allowing serialisation/deserialisation to move behind an explicit construction/codec boundary as described in the blogs. It also plays nice with the vocabulary type direction: the eventual public transaction type can be regular and idiomatic, while preserving the invariant of once a transaction contents are published/shared, they are immutable.

Footnotes

  1. https://stackoverflow.com/questions/18709647/shared-pointer-to-an-immutable-type-has-value-semantics ↩

@purpleKarrot

Copy link
Copy Markdown
Contributor Author

@josibake, exactly. As highlighted in my blog post, the next refactoring step would be moving the std::shared_ptr<const> behind the API boundary. This would result in the exact same runtime indirection as currently, it is just a different level of abstraction. However,

While we still use using CTransactionRef = std::shared_ptr<const CTransaction>, perhaps its best to have CTransaction assignment deleted.

for what benefit? It is pointing to a const object. The pointer can be changed to point to a different object (or no object at all) but the shared pointee can not be changed. There can be no spooky action at a distance.

Perform an automated replacement of all direct accesses of
`CTransaction`'s data members, each with it's associated
observer function.

Produce the changeset with the following commands:

```sh
export CC="$(which clang)"
export CXX="$(which clang++)"
cmake -B build -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DBUILD_BENCH=ON -DBUILD_FUZZ_BINARY=ON -DBUILD_GUI=ON -DBUILD_KERNEL_LIB=ON -DBUILD_UTIL_CHAINSTATE=ON
cmake -B build/tidy -S contrib/devtools/bitcoin-tidy
cmake --build build
cmake --build build/tidy
run-clang-tidy -p build -load='build/tidy/libbitcoin-tidy.so' -checks='-*,bitcoin-use-observers' -fix
```
Now that `CTransaction`'s data members are no longer accessed
outside of member functions, they can be made `private`.
@purpleKarrot
purpleKarrot force-pushed the transaction-abstraction branch from 4c7f4ae to 5bffd2c Compare September 24, 2026 18:28
@purpleKarrot

Copy link
Copy Markdown
Contributor Author

Pushed to resolve merge conflicts and updated the description. Removed all mentions of const and added potential representation chances that would be allowed without touching all clients again: "Potential changes are using shared immutable transaction state, or even an offset into shared immutable block state".

@sipa

sipa commented Oct 16, 2026

Copy link
Copy Markdown
Member

Somewhat related, in #36521 I change the representation of CScriptWitness to remain in serialized form in memory, for compactness and performance reasons. That also involves introducing abstractions for access to those elements, though at a lower level than what this PR does (CScriptWitness is a per-CTxIn member), and with an interface that's demonstrated to be sufficient for achieving the goal of significantly reducing worst-case memory usage per weight and deserialization time.

I've experimented with extending this approach to CTransaction too, having all data packed together in just 2-3 allocated blobs, which would improve the worst cases even further. I think that's technically even better, but probably not worth the cost of making the change. If we want to go that route, the approach in this PR may be useful, but I think it's easier to argue for when paired with practical advantages like performance/memory usage.

@purpleKarrot

Copy link
Copy Markdown
Contributor Author

@sipa, there are hundreds of possibilities of changing the in-memory representation of these types. Keeping CScriptWitness, CTxIn, CTransaction, and even CBlock in their serialized format augmented with offsets is a possibility. There are other possibilities that parse the serialized format into an in-memory format that is even more optimized.

But instead of coming up with a "better" representation, I think we should focus on the change that will allow changing the representation independently of all user code. This is the benefit that I see in encapsulation per se.

With encapsulation in place, all changes to the representation are internal. This allows us to experiment with different data layouts and gives us an easy way to compare different implementations.

Introducing encapsulation is expected to touch all client code. It is a necessary precondition to make future changes to the client code unnecessary.

@DrahtBot

Copy link
Copy Markdown
Contributor

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

@sipa

sipa commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

It's not clear to me to what extent getting rid of the distinction between CTransaction and CMutableTransaction is your goal still, but if it is, I'd like to argue against it based on what I learned working on #36521.

Significant memory usage and performance gains are possible by exploiting packed in-memory representations. That included keeping witnesses in serialized form as my PR does, and experimenting shows that even more is possible by packing everything at a transaction level. When taken far enough, such representations are incompatible with easy and efficient modifications. But modifications are very localized in wallet/signing logic, while most of the codebase only needs immutable transactions. Because of that, I think it's reasonable to keep them separate in representation, and possibly also in interface.

I'm aware further abstraction is possible, where we have for example one or multiple "transaction view" objects, which can be backed by independent allocation pool objects (which could be per transaction, or even per block), some of which could be optimized for modification and some aren't. I think that's a step too far, as the gains are minimal beyond a specialized per-CTransaction packed representation, and needs even more invasive changes throughout the codebase.

@purpleKarrot

Copy link
Copy Markdown
Contributor Author

It's not clear to me to what extent getting rid of the distinction between CTransaction and CMutableTransaction is your goal

@sipa, my goal is not getting rid of the distinction, my goal is getting rid of CMutableTransaction. There are two places where this class is used at the moment: transaction signing and unit tests.

I have shown in #36692 that writing unit tests in a way that does not rely on CMutableTransaction brings advantages with no disadvantage. I am pretty sure that a similar statement can be made for signing, I will prepare a demonstration to back that claim. With those two places refactored, CMutableTransaction will be no longer be needed and many function templates that currently rely on a TxType template argument can become concrete functions.

In #36696 (comment), I show concrete examples how CTransaction would benefit from having regular semantics for move and copy. Its current inconsistencies can be removed by making the data members non-const, as is recommended by many coding guidelines. It has never been my goal to allow the mutation of individual data members.

@maflcko

maflcko commented Nov 6, 2026

Copy link
Copy Markdown
Member

Can you explain what you find controversial about the PR?

I also want to know.

I think there are two views, which are both subjectively valid and don't come to an agreement:

  • Encapsulation is useful by itself, because it can make changes like this easier in theory in the future, and doing it stand-alone may be worth the churns.
  • Encapsulation should be motivated by a change like this, and doing it stand-alone may not be worth the churns.

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

Projects

Status: Architecture & Performance

Development

Successfully merging this pull request may close these issues.