mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 09:08:37 +00:00
Encapsulation for CTransaction #35569
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!35569
Loading…
Reference in a new issue
No description provided.
Delete branch "transaction-abstraction"
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?
CTransactioncurrently 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
CTransactionare migrated to the observers, after which the data members are made private.The refactoring is deliberately split into three steps:
The migration is automated with a new
bitcoin-tidyuse-observerscheck. 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.
CTransactionis 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.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:
CAmounta class by hodlinator)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++, andfunc(x, named_arg=0)in Python):Coin(tx->GetOutputs()[n], MEMPOOL_HEIGHT, false)insrc/txmempool.cppCoin(ptx->GetOutputs()[outpoint.n], MEMPOOL_HEIGHT, false)insrc/txmempool.cppemplace_back(coins[tx.GetInputs()[i].prevout.n].out, tx, signature_cache, i, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, false, &txdata)insrc/test/transaction_tests.cpp2026-09-24 18:29:12
Can you put all the parts relevant to reviewers into the PR description?
🚧 At least one of the CI tasks failed.
Task
lint: https://github.com/bitcoin/bitcoin/actions/runs/27835663586/job/82382956280LLM reason (✨ experimental): CI failed because the lint scripted-diff check errored out with
cmake: not found(andrun-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.
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_diffdue tocmakeandrun-clang-tidynot being found. How can this be fixed?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 aCTransactionRef.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.
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 ?
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?
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.Concept ACK
No, I said exactly what I intended to say: making
CTransactionmutable is a bad idea. We already haveCMutableTransactionfor cases where mutability is needed.Passing a CTransactionRef around prevents the recipient from modifying it (ignoring const casts), but doesn't prevent the creator from doing so.
Concept ACK
Moving the data members behind observers, vs having the class layout define the API seems a solid improvement.
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:
TransactionDatawould of course containvin,vout,version,nLockTime, cached hashes, etc., and would be immutable after construction fromCMutableTransactionor deserialisation. Now assignment has normal value semantics:That is different from mutating a shared transaction object:
While we still use
using CTransactionRef = std::shared_ptr<const CTransaction>, perhaps its best to haveCTransactionassignment deleted, or the ref type needs to be updated so the shared thing is the immutableTransactionData, 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.
https://stackoverflow.com/questions/18709647/shared-pointer-to-an-immutable-type-has-value-semantics ↩︎
@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,for what benefit? It is pointing to a
constobject. 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.The benefit is removing a footgun while refactoring. As long as
CTransactionRefshares theCTransactionwrapper, making that wrapper assignable leaves a possible non-const-alias footgun. So we either keep assignment deleted during that transition, or move the shared state behind the API boundary first.Once we reach stage 7 detailed in your bitcoin-tidy blog (which more or less matches my earlier comment, perhaps sans a few details),
CTransactionis the value handle and the shared state is behind the API boundary and thus default assignment is fine (and desirable!) because it only rebinds to the handle.Concept ACK
I second this approach. Also reaching "stage 7" can take a while, if ever reached.
Intentional skipped ? (It's ok as is)
Interesting catch. The
clang-tidycheck was not fired on this code and making the data members private did not break it. Apparently, the function template is never instantiated withCTransaction; only withCMutableTransaction. There is alsoCTransaction::GetValueOut().I get it now.
CTransactionRefbeing ashared_ptr<const>can only prevent mutation through that handle, it cannot prove that no non-const alias exists. Yes, as long asshared_ptr<const>is used, it would be better to explicitly disallow both assignment operators. I'll update that.As part of reviewing this, I nerd sniped myself into reading about move semantics and had the thought: are vectors treated differently than fixed length values? Turns out they are! So for
uint256moves are copy like, but for vin/vout, being vectors, move could actually mean move the underlying storage. In light of that, I think we should delete the move constructer during the transition.Concretely, if vin/vout are no longer const then this would be a memberwise move. Shouldn't matter for the moved to transaction, but the moved from one could be left with
m_witness_hash,m_has_witnessetc members that still describe the pre-moved state, but the vin/vouts of the moved from could now be empty.Obviously, this would no longer be a problem once
CTransactionrepresents a value reference to an immutable struct, at which point the move constructer can be added back along with the assignment operation.I applied this suggestion locally and everything compiled, so doesn't seem to break any existing behaviour.
Good point! But instead of deleting the move constructor, we should simply not provide it.
I find the commit message in a35a2b1 a bit confusing, specifically: "Make sure to add the same member functions to
CMutableTransactionfor symmetry, so that they can be used in generic code."It seems clear from the PR description and the code that the observer is not concerned with
CMutableTransactionin this PR. Is this a stale commit message or a directive for a follow-up? If its a directive for a follow-up, I think it could be made more clear, e.g., "CMutableTransaction should have the the same member functions to allow both classes to be used in generic code. This is deferred to a follow-up."I don't see anything that would prevent this from being used with
CTransaction, though? Seems we could handle this case cleanly by recognisingTxTypein a template argument as actually aCTx. This would avoid more broadly rewriting vout, vin, version, etc in other places.@josibake, adding the observers to
CMutableTransactioncannot be deferred to a follow-up. Adding them to bothCTransactionandCMutableTransactionis a precondition for the automatic refactoring that follows. The reason is that we have code like this:If that
.vinis refactored to.GetInputs(), the function template can no longer be instantiated withCMutableTransactionunless the observer is added there as well.@purpleKarrot thanks for clarifying, I realised I was confusing myself. I do think a nice polish would be to update the
tx-observercode to handle the template case. I started tinkering with it as a way of getting more familiar with the code and came up with this:I ran this and it does catch the case pointed out by @janb84.
This, however, is a non-blocking suggestion and rather a nice to have, or even just a review tool. I mainly did this to convince myself there weren't other template functions that could take both
CMutableTransactionandCTransactionthat had been missed. In doing so, I ended up convincing myself its not really an issue considering there is no current usage ofCTransactionin these template functions and if someone were to attempt it in the future, it would be a compile error.Per https://github.com/bitcoin/bitcoin/pull/35569#issuecomment-4778806596, I convinced myself this isn't an issue.
ACK https://github.com/bitcoin/bitcoin/pull/35569/commits/c2dbec1ed279d73c76a28d23d02fcc3bdd433a1f
Adding observer functions for data members moves towards an overall better design where the caller does not depend on the class layout. While not fully implemented in this PR, this is the first step towards a transaction type with regular semantics.
More concretely, direct access to
vin,vout,version, andnLockTimeeffectively makes the class layout the public API. Rather, we should have serialisation and the transaction API be expressed in an implementation agnostic interface instead of tightly coupled to today's concrete implementation.Thanks for taking the suggestions regarding removing the assignment operator, and removing the default move constructor. These changes ensure we preserve the same class invariants while refactoring.
@josibake, I don't want to add the names of one particular class into
ObserversBase. That class is intended to be a common base and provides the logic for checks that inherit from it and parameterize it with names in their constructor.The mutation check in the current implementation is not powerful; it has some false negatives. For
CTransaction, that is not an issue, because its members cannot be mutated anyway. But if I fix it and add a checker forCMutableTransaction, I get changes in another 119 lines, including the one that @janb84 identified.I can integrate that into this PR, or keep this PR focused on
CTransactionand doCMutableTransactionas a follow-up.Absolutely! "tinkering" was meant to imply this was not the proper way to do it, rather I do think it would be nice to detect the template case in a more clean way. However, once I ran the hacked code and realised there were no other such cases, it started to feel like a waste of time.
I think this is the right call. As you said, it keeps this PR focused, and it may be that
CMutableTransactionis made unnecessary as this refactor progress, but that is not a topic for this PR.left some nits, but feel free to ignore.
nit in the last commit: Using the
std::prefix may be minimally more correct, but there is no place in the current codebase that uses the prefix for such integral types. It may be better to drop it for consistency. Also, while it doesn't help type safety, I minimally prefer to have named types here. It is unlikely that the type is going to change again (27e70f1f5b), but it can't hurt. Just a nit, though.a35a2b108acf355293443d5ad42cbf84152a3363: I don't think nodiscard should be added here, because the boilerplate adds basically no value. It isn't in the dev notes, but the pattern is documented in:
github.com/bitcoin/bitcoin@7b84e5106c/src/kernel/bitcoinkernel.h (L32-L40)a35a2b108acf355293443d5ad42cbf84152a3363: You say that a span can not be returned here in the blog, but I wonder why that is. The blog says that some call sites have hard-coded vector::iterator types. However, those should be trivial to adjust as well.
I think the real reason is that span serialization doesn't support non-Byte spans, and also doesn't support the length prefix.
a bit unrelated, but I wonder if it could make sense to allow all spans to be serialized (iff the element can be serialized), but require an explicit mode to be set: Either without serializing the size prefix, or without.
In any case, I think
LIFETIMEBOUNDcould be added here?edit: I read your other blog post and I see you want to replace this by
encode_range(w, tx.vin, encode_txin);in which case my alternative suggestion may be stale.I can remove it if there is consensus that
[[nodiscard]]is not wanted here. I just got used to following clang-tidy's modernize-use-nodiscard, which adds it to allconstmember functions.Yes, they could be automatically refactored with clang-tidy's modernize-use-auto and further with modernize-loop-convert.
But those cleanups are orthogonal. They could be done as a follow-up, or they could be done before this one. But I'd rather not squash them into this PR.
I think the modernize-use-discard is harmful for promoting the exact opposite of a meaningful policy. I wonder if anyone has this check enabled in a useful way. Let's recall that in modern C++ (smart pointers and optional values), the isn't really a risk of resource leaks (like in the kernel C-header). So the remaining use cases are legacy code, or error/status codes, but both of those use-cases are excluded in modernize-use-discard.
If we wanted to follow the clang-tidy rule, it should be enabled in the config, but again I don't think that is useful.
Instead, it could make sense to copy-paste the existing kernel header policy to the dev notes, so that it is clear it applies to all C++ code in this repo?
I don't consider passing around smart pointers modern C++. Pointers ("smart" or not) are low level utilities that should be used exclusively for implementing composite types and never appear in function signatures, neither as arguments nor as return type.
The purpose of
modernize-use-nodiscardis not to avoid resource leaks, but to indicate: "This function has no observable side effect. Only call this function if you are interested in its returned value."I removed
[[nodiscard]]andstd::as per @maflcko's comments. I still think they make sense in both places, but maybe it is better to add them with a repository wide cleanup, by applyingmodernize-use-nodiscard.Edit: Also added
LIFETIMEBOUND.Just read this comment, and deleting (or better not providing it) is fine, because a move ctor didn't exist before either. Though, in this project it should be fine to provide one, as
bugprone-use-after-moveprevents unwanted access to the moved-from object.I am still thinking about this change conceptually. As of this pull request, the changes are mostly a no-op cleanup. Yes, it is a bit nicer to use
privateoverconsthere, but externally, the same copy and move ctors are provided, so I think this change is mostly a style change. It seems there are several goals:CTransactionRefis used (but it is not really a reference), so hiding the shared pointer and allowing to passCTransactionas-is with shared pointer semantics seems simpler and nicer.I am happy to review this pull as-is, and it seems fine to merge as-is, but I wonder if other reviewers think that step 7 is worthwhile, (and whether step 4 is worthwhile or can be skipped)?
I think this PR can be assessed independent from steps 4 and 7. The old design violated the C++ Core Guidelines C.12.
Perhaps we use the word style differently, but I tend to think of style as two different representations of the same architectural principle.
I'd argue that style is the wrong framing here since we are talking about an architectural refactor, specifically encapsulation. This PR makes the invariant the responsibility of the class, enforced through a private representation rather than a
constkeyword on a public field. This fundamentally changes which designs are possible, now and in the future. Identical semantics today, as you point out, but the set of possibilities open for discussion is now open.Said differently, I don't think reviewers being interested in exactly 4 and 7 as they are proposed today is particularly relevant for merging this PR. Rather, being interested in discussing 4 and 7 at all and perhaps other follow ups is the strongest argument for this PR on its own: these follow up discussions are now possible.
reACK https://github.com/bitcoin/bitcoin/pull/35569/commits/a2b339547f6c8acc34ec18d6b44abf0d728a9886
This still seems a waste of review resources to me. If you want to be able to mutate a transaction, use
CMutableTransaction, don't add a +644-513 PR because you dislike the coding style.That guideline only says "Don’t make data members const or references in a copyable or movable type" which is fine --
CTransactiondoesn't have much need to be copied or moved (if different parts of the code want different handles on the same tx, that's whatCTransactionRefis for), and copying/moving is only possible because of implicit constructors. Deleting those constructors catches a few mistakes: https://github.com/ajtowns/bitcoin/commits/202606-del-tx-copy-cons/I disagree with this framing, and I don't think your objections apply here. This PR is not talking about mutating a transaction. The new API is const observer access, assignment remains deleted, and move is not provided.
Furthermore,
CMutableTransactionexisting is not a reason forCTransactionto expose its layout. The question here is not whether mutation should exist somewhere. It is whether callers of the immutable transaction type should depend directly onvin,vout,version, andnLockTime. They should not. Those fields make up the invariant that transaction data,hash,m_witness_hash, andm_has_witnessall describe the same object. That invariant belongs behind theCTransactionAPI boundary.CTransactionRefis also not a sufficient answer.CTransactionRefisstd::shared_ptr<const CTransaction>exposed as a public vocabulary type. What I mean here is APIs that want “a transaction” therefore inherit pointer semantics: ownership, nullability, aliasing,.get(),.reset(), anduse_count(). Those are not transaction semantics. If shared immutable storage is useful (it is), it should be an implementation detail behind a transaction API, not something every caller has to pull in.This is why I said “coding style” is the wrong characterisation. Public fields vs private fields behind observers are not two styles of implementing the same abstraction. Public fields make the class layout the API. Private fields make
CTransactionresponsible for its own representation and invariants. I very much disagree that reviewing these types of architectural changes are a waste of reviewer time as they have implications on what is possible or not possible in the codebase today and into the future. They also matter for the safety, correctness, and maintainability of the code. These seem like topics reviewers would be interested in, to me.Regarding the copy/move branch you posted, this reinforces the C.12 point rather than refuting it. Public
constdata members create an irregular type surface where copy exists, assignment does not, and move behaviour is surprising. If making those operations explicit exposes call sites that need cleanup (which your branch does), then the current design already has accidental special member semantics. C.12’s point is that those semantics should be intentional, not side effects ofconstfields. Deleting copy/move might be an interesting follow up, but it is not an alternative to this PR. It addresses one symptom while leaving layout as API (the root cause) untouched. This PR instead establishes the boundary: callers should not depend on the storage layout of a type whose fields participate in an invariant. Said differently, your branch seems to be treating a symptom, not addressing the root cause.I will reiterate: we do not need agreement on those future designs for this PR to be valuable today. Reviewers can still argue later for non copyable
CTransaction, an internal shared immutable body, a differentCTransactionRef, or a value handle over an immutable body. We could also agree on no further change. This PR only establishes the prerequisite boundary for those discussions: callers stop depending on concrete layout, while today’s immutability and aliasing needs are preserved.I can give a few more guidelines that are violated in the current design:
Should I continue and dig out more C++ Core Guidelines that are violated here? Or would you rather prefer examples from C++ literature? Conference talks? You name it.
Concept NACK. At this point my impression is that providing the kernel API is primarily acting as a supply-chain attack vector, encouraging multiple significant refactors into consensus critical code for extremely spurious reasons, and wasting limited development resources on low and negative impact activities.
Perhaps you should review the introductory section: "We do not suffer the delusion that every one of these rules can be effectively applied to every code base.", "The rules are not perfect. A rule can do harm by prohibiting something that is useful in a given situation."
I could see the argument for declaring
CTransactionas-is as a struct rather than a class per C.2 or C.8, but that's not a rule we consistently use in this codebase, and because we don't do that, the follow-on assumptions about how classes should act are also not justified:Yes, that one is a good idea, and it catches real implementation flaws, and I included it in the patchset I linked.
"Should I continue with arguments to authority?" No, you shouldn't. You should justify changes with the practical benefits they achieve.
In this case, separating an implementation and interface allows you to change the implementation without impacting the places where that interface is used, but that's not the case here: we shouldn't be changing the implementation because "create a CTransaction, cache its hashes, treat it as immutable, and keep it around as a shared_ptr" is already what we want. Instead, for 0% benefit, this PR is hitting 100% of the cost by changing every place that touches the interface. The only way you could get a worse tradeoff is by actively introducing bugs, as well.
The only reason for making that change now is to prepare for making it mutable in future. Pretending otherwise just comes across as dishonest. I am not currently very convinced that the proposed serialization changes are a worthwhile improvement (eg, where are the benchmarks, if compile time improvements are the main argument?), but claiming that is the rationale while constantly arguing about style guidelines and private fields also comes across as fairly dishonest.
The reason for
CTransactionto expose its layout is that adding an abstraction layer over the top buys nothing but complexity and code churn. Dealing with transactions is pretty much the primary job of our codebase, so the implementation details are relevant to pretty much every part of the code, not something that should be abstracted away.APIs that want "a transaction" can accept
const CTransaction&if they simply want to use it for the lifetime of that call, or aCTransactionRefif they want to be able to extend the lifetime of that transaction, at which point ownership/lifetime/etc are worth worrying about anyway. If they want to modify the transaction, they can either copy it or accept some form ofCMutableTransactionin the first place.re: https://github.com/bitcoin/bitcoin/pull/35569#issuecomment-4843836472
For the record, josibake's description is accurate: as of the latest revision, assignment is deleted and the observers are const.
On the direction: step 6 from the blog post would have
CTransactionholdshared_ptr<const TransactionData>internally, making the shared body immutable at the type level. That reads to me as increasing immutability guarantees rather than decreasing them. Am I reading the end goal right? If there's a specific harm you see in the steps between here and there, it would be useful to understand concretely.EDIT: Corrected reference to step 6 instead of step 7 in blog post.
100%, @ryanofsky. My goal is to make
CBlock,CTransactionand a few more primitive types immutable. But a properly immutable type is a type that has no accessible modifier functions. It is not a type with deleted copy/assignment.Making
CTransactionnon-copyable and then storing it as a pointer inCBlockand making it publicly accessible does not gain any immutability at all, as clients can freely reassign it to another transaction object or even tonullptr. I understand that some clients need nullability, butCBlockis not one of them and consensus code is not defined to operate on nullable transactions.Where did you read that, @ajtowns? My blog mentions compile times, but then proceeds with:
The proposed direction is not toward mutable transaction data. It is toward a value handle over immutable transaction data, as explained in the blogs, by @purpleKarrot , and myself in this PR. This is a stronger immutability model than exposing shared pointer semantics as the transaction API.
Verified 858899e reproduces.
Checked out ede288d1 and ran the documented fixup with clang/clang-tidy 22.1.8 (per
ci/test/00_setup_env_native_tidy.sh):The resulting
git diffis identical to 858899e.Tests: suite passes on tip
Ran the full unit test suite. The tip (
CTransaction: Make data members private) depends on every external access having been correctly converted to observer calls in the prior commit.I disagree with that. In my opinion, refactors of the very basic consensus code should have a concrete advantage and should not be done on general grounds such as C++ guidelines alone.
So I do think that this would need to be justified by possible follow-ups, or at least some non-generic examples such as preventable bugs or footguns (which @ajtowns alternative branch does).
On a language level, terms such as
vin,voutetc. have long become part of the public protocol:For example encapsulating
vinthroughGetInputs()internally within bitcoin core, just to expose them asvinagain to the outside via RPC (getrawtransaction) seems weird to me and it would probably be a nuisance for devs to remember the right term on the right level.In summary, I think that
CTransactionis not just a random C++ class, but at the heart of the bitcoin protocol itself, so I don't think arguing only with generic C++ guidelines re: encapsulation is sufficient here.The kernel project is mentioned neither in the PR description nor the blog post.
If this helps the kernel project to design their API better (or if there is any other relation to the kernel work) it would be good to explain this in more detail.
Approach NACK for now.
I don't see a concrete benefit here that justifies rewriting so many transaction call sites in consensus, policy, mempool, wallet, tests, fuzzers, and kernel-facing code.
Technically, the current patch seems mostly behavior-preserving: callers could not mutate
CTransactionbefore because the public fields wereconst, and callers still cannot mutate it after because the new observers are const. Assignment remains deleted and move is not provided. So the practical safety delta appears small, while the review cost is high.I also share the concern raised above about “arguments to authority.” Guidelines and literature can be useful for framing, but they should not substitute for showing why this particular change improves Bitcoin Core specifically.
The PR also has knock-on effects that make the abstraction feel premature:
CMutableTransactiongets duplicate const observers just so generic code keeps compiling.If the goal is a later shared immutable transaction body or a new serialization boundary, I think that design should be motivated directly first, with concrete examples of why it is worth doing. Without that, this feels like a broad mechanical refactor of very central code for speculative follow-up work.
I agree that this check is useful during development, but I'm not sure it should remain in the tree after the migration.
After the final commit, the compiler enforces the
CTransactionboundary, so this check is only scaffolding unless we plan to keep using it for other classes. If it is only scaffolding, could the PR end with a commit that removes it, or could the helper live outside the repo?If it is meant to stay as reusable
bitcoin-tidyinfrastructure, could we align it with the existing check style first? The new files currently use different conventions fromnontrivial-threadlocal(no MIT header,#pragma once, global namespace, 2-space indentation). Or is that also something we should change because other other guidelines request it?It's awkward to keep these references now that the field is hidden:
I would be for these changes in a separate PR.
What's the purpose of introducing trailing-return syntax here? What role does
autoserve, apart from aligning the names? Seems aggressive...More broadly, as @mzumsande also mentioned, I am not convinced that introducing new names for vin, vout, version, and nLockTime is an improvement. Could we keep the protocol names instead?
With indexed helpers, the diff becomes even closer (and safer) to the current code:
For example:
That would make the mechanical diff much easier to review manually.
The renaming question can be debated separately, but as-is the change reads like a broad spelling rewrite with non-negligible review cost and little immediate benefit.
What's the reason for dropping the consts from these?
These extra accessors feel awkward, especially on
CMutableTransaction.This seems like a code smell worth addressing before adding more API surface.
If the issue is that some generic read-only code is instantiated with both
CTransactionandCMutableTransaction, could we make that dependency explicit instead of adding duplicate read APIs to the mutable builder type?Or could the generic read-only code use an immutable transaction view instead?
For example, serialization/read-only helpers could depend on a cheap non-owning transaction view constructible from both types, or mutable transactions could be moved into an immutable serializable type at the boundary where that is needed. That would let
CTransactionown its private representation whileCMutableTransactionremains the straightforward mutable construction type.Another option would be to move a mutable transaction into an immutable serializable type at the boundaries where serialization is needed.
Readability. Did you see how the names of the function names are nicely aligned? Is this not something that directly jumps to the eye?
I have explained the naming choice in my blog referenced in the PR description. It is not possible in C++ because it creates a naming conflict. You cannot overload a member function with a data member.
Let's not create more technical debt. We currently have lots of index based loops that could be rewritten as range based loops or algorithms. Introducing "helpers" complicates such modernization. When only the first element is needed,
.front()should be preferred.Sure, I even mentioned it on the same line: "What role does auto serve, apart from aligning the names?"
Are you planning on changing it in the whole codebase? Or will this be the only place where we use "readable" code?
Not sure what you mean, I simply didn't migrate
CMutableTransactionand renamed the fields to start withm_prefix locally.Sure, the naming conflict can be solved by changing the data members, but then the three-step refactoring approach is not possible:
Since you said you disagree with the "Approach", can you explain another approach and also explain what problems you see with the approach that I follow?
The approach that I'm objecting to is aiming to do things "by the book" without understanding the project specifics. I fell into the same trap at the beginning, and I also received a lot of pushback. This is a huge refactor at the most critical part of the code, and it's not obvious what we're getting in return (besides appeals to authority, which most of us are allergic to). Especially since the refactor revealed incidental loose coupling (
CMutableTransactionandCTransactionhaving to have the same field names) which should be hardened instead of papered over by adding yet another getter to the already public fields. It's also trying to force new names instead of considering what the domain already has. When I suggest alternatives, the reply is just a patronizing "that's impossible in C++". This approach seems too aggressive and dismissive to me, hence my nack.Your response seems to be arguing against a claim I did not make. My argument is not “merge this because the C++ Core Guidelines say so.” The guidelines are excellent supporting evidence, but not the justification. The justification I am arguing for is that
CTransactioncurrently exposes the layout as the API. By making fields participating in the invariant public, we are tightly coupling all callers to the representation. This is a fragile design. Rather, the representation of the invariant should be owned entirely byCTransactionbehind an API, i.e. encapsulation.The question is not whether encapsulation is idiomatic in the abstract, or performative to some set of guidelines. The question is whether
CTransaction’s concrete layout defining its public API is better thanCTransactionexposing transaction behaviour while owning its representation and invariants internally. I have not seen an argument for why the current public layout design is better. Most objections seem to defend the status quo by pointing to review cost or familiarity, but those are not arguments that public storage is the better abstraction.@ajtowns 's branch, as I already pointed out, illustrates my point. It found places where the current design allows accidental full transaction copies when the intent was to keep or pass a transaction reference. Deleting copy/move catches some of those mistakes, which is good, but it addresses one symptom. The broader issue remains: callers depend directly on the storage layout of a type whose fields participate in an invariant. Encapsulation gives us a boundary where those semantics can be made intentional, whether the followup is deleting copy/move, using an internal immutable body (as explained in the blogs and the design I strongly prefer!), changing
CTransactionRef, or something else. The C++ core guidelines are relevant here because they describe the class of failure mode ajs branch attempts to fix. This is not to say "oh we must have strict adherence to the guidelines," rather its the C++ core guidelines pointing out: "you guys aren't the first project to make this mistake."The naming concern you raise is orthogonal, imo. Whether the observers should be called
GetInputs()/GetOutputs()or use familiar vocabulary such asvin()/vout()is a separate API naming discussion (and likely a mechanical rename/scripted diff). It is not an argument for keeping the storage layout public. Likewise,vinandvoutbeing protocol vocabulary does not mean the in-memory C++ representation must expose public fields. I do not agree with the the framing ofCTransactionas being the heart of the bitcoin protocol. Its not. Its a C++ class in this project that represents protocol data. The protocol and serialisation format must remain precise and stable (and implementation agnostic!), but that does not require class layout to be the public API. This is mentioned explicitly in the serialisation blog.As I argued before: this refactor stands own its own because it establishes a clear API boundary not tightly coupled to representation. This enables the discussion and implementation of future design, e.g. the stronger immutability model detailed by @purpleKarrot in his blogs. The status quo keeps API defined by class layout, which is fragile and forces us into suboptimal design space.
To be clear, I can agree with the concept of moving
CTransactionaway from public storage given good motivation and easy review. My main concern is the approach: I could agree with it if the path were broken into smaller manually reviewable steps with non-general, concrete Bitcoin Core reasoning for each step: what each step enables, what reviewers should check, and why it is worth doing even if the later design changes.General C++ best-practice arguments are not enough for me here.
It would also help to have the rest of the intended series prepared as draft PRs or demonstration branches, so reviewers can evaluate the path end-to-end instead of reviewing a preparatory refactor against a series of "to be continued" blog posts.
For comparison, I tried a smaller shape here over the weekend: l0rinc/bitcoin#212 commits.
It differs from this PR in three main ways:
CMutableTransactioncan stay the mutable builder instead of getting mirror observers just to preserve shared public field spelling.bitcoin-tidyfield-observer helper and runs it one field at a time (nLockTime,version,vout,vin), so each scripted diff is a smaller, CI-passing review unit.tx.vout(),tx.vin(), etc.) instead of renaming the API toGetOutputs()/GetInputs(), and updates the related code comments.That shape makes the call-site diff mostly adding parentheses after the generic-read split, keeps mutable writes and exceptional serialization paths out of the immutable-transaction migration, and should reduce the need for repository-specific macro skips such as
READWRITEorVARINTin the tidy check.If compile-time improvements, a future serialization boundary, kernel API shape, or stronger immutability motivate this refactor, it would be helpful to state that in the PR with concrete examples or evidence.
Linked posts can provide background, but the GitHub PR itself should carry the reviewer-relevant motivation and tradeoffs.
will this be executed by tidy on every run now?
"The refactoring is a prerequisite for further refactoring that will untangle the type from serialization logic (...) which will result in ... faster compilation."
🐙 This pull request conflicts with the target branch and needs rebase.
Needs rebase.
🚧 At least one of the CI tasks failed.
Task
i686, no IPC: https://github.com/bitcoin/bitcoin/actions/runs/30276063951/job/90010322508LLM reason (✨ experimental): CI failed during the C++ build because
src/coins.cpptried to accessCTransaction::vin, which is private (error: ... is private within this context).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.
Maybe turn into draft while CI is red?
The
clang-tidycheck is now using annotations rather than hardcodingCTransactionand the names of the data members.@theuni, should
bitcoin-tidylive in a separate repository?@ajtowns, @mzumsande, @l0rinc, and others:
I want to assure you, that this refactoring is not motivated on "general grounds such as C++ guidelines" or "appeals to authority". It was also not done "without understanding the project specifics" or "without considering why certain decisions were taken".
It is a byproduct of a very deep analysis of the consensus validation code with the goal of providing a stateless validation component: #35904
I do understand the motivations that led to the data members being
const, which then led to the split betweenCTransactionandCMutableTransaction, which then led to the requirement for certain function templates taking a generic transaction type, which then led to the problem that it is no longer obvious whether the template instantiations that are tested are actually the ones that are used in production. It is an intervention spiral: A hack always demands further hacks.I also do understand the project's requirements on stability and performance and I have identified places where those requirements are not fulfilled, like the errors that are thrown during deserialization, for which I have provided a proof-of-concept solution that also does not rely on overload resolution and is therefore easier to reason about than the current deserialization code.
Am I not allowed to identify such problems just because the original authors provided more proof of work? How is that not "appeals to authority"?
This is an amazing use of
bitcoin-tidy. Nice work getting the attribute/annotation machinery working. It's a thing of beauty :)At least for now, I think it makes sense to keep it part of this repo. Allowing the plugin to be updated in the same PR as the changes that use it makes life substantially easier. I realize it could be helpful (and more secure) to separate the concerns, but I think it makes sense to defer that move until there's a concrete reason to do it.
I have rewritten the check in a way that it no longer hardcodes any concrete symbol names. This makes the check generally useful for other places and should stay.
I have no strong opinion on the code style of bitcoin-tidy. Ideally, it would follow LLVM's style just in case we want to upstream any of those.
The motivation for this change is mentioned in #35904. Please stop making those unfounded claims. This is a tiny, straightforward change, as most if it is automated and reproducible.
I agree. Lesson to learn: Avoid referring to concrete symbol names in technical writing. But this is a much larger issue that should be approached independently. See also https://github.com/bitcoin/bips/pull/2195#discussion_r3747735099.
I have moved them to a separate commit.
The code smell is
CMutableTransactionas a whole. There is no real use-case for a mutable transaction type. As explained in #35904, there are only a limited amount of places where transactions are mutated, and those actually benefit from being rewritten anyway.Yes, so let's clean that up first - please see my branch where I did just that.
You did not remove
CMutableTransactionin your branch. Instead, you added yet another layer of indirection on top, proving my theory of the intervention spiral. https://github.com/bitcoin/bitcoin/issues/35904 explains what refactoring steps are needed to makeCMutableTransactionobsolete.Is this the vocabulary that we want Bitcoin to maintain for the next hundred years across implementations? In that case we should specify that in BIP453. But if we assume that coming generations will find terms like
inputsandoutputseasier to reason about, we should specify those instead and then slowly converge code bases and RPC protocols towards that BIP. A function likeGetInputs()can be interpreted as applying a coding style on the standardized terminputs.Sure, why not - it's just words, I have no intentions of telling people what terms to use or not to use.
First, it is already specified in the linked BIP453 draft, as one of multiple synonyms, see "transaction output list"/"transaction input list".
More importantly, BIP453, as I understand it, is descriptive and not normative in nature. If many code bases would start using a different term for something, we should amend the BIP by adding this term as a synonym instead of telling the code bases to change.
Well, in your original comment you had a very strong opinion that
vinandvouthave to stay, because they "have long become part of the public protocol". That sounds very normative.I'm not sure if you are serious, and I will leave this unproductive discussion after this, but normative/descriptive are categories for universal language-defining documents such as BIPs, and I only brought them up in response to you talking about "future generations" using terms. ("we should specify those instead and then slowly converge code bases and RPC protocols towards that BIP").
Me having an opinion to a proposed change in a single local project that I contribute to has nothing to do with that.
Besides, I did not even utter a "very strong opinion that vin and vout have to stay" as you allege, but pointed out the potential confusion of encapsulating things on an intermediate level under a different name, that are then exposed under the internal name with the RPC interface: I wrote "For example encapsulating vin through GetInputs() internally within bitcoin core, just to expose them as vin again to the outside via RPC (getrawtransaction) seems weird to me".
I did not opine on whether to resolve this confusion by keeping the terms, or by removing
vinalso from the rpc.And I certainly don't care what terms other projects or future generations use. So please stop putting words in my mouth that I didn't say.
@purpleKarrot, you're receiving valuable feedback, but instead of learning from it, you act offended and try to force your subjective opinion even harder.
The responsibility falls on you to argue for the change, but completely ignoring the established culture and trying to force your own opinion won't scale in this environment.
There are many things we need to fix here (especially now that AI scanning reveals hundreds of potential attack angles), and these opinionated refactors are not the best use of our time.
I will unsubscribe from this thread. I'm not here to continue arguing.
In the "valuable feedback", the change is descibed as:
It also continued in a similar style in private conversation.
Not one single comment was articulating that in this particular case,
publicconstdata members should be preferred.The only complains were about
Concept ACK
The larger motivation is still not mentioned in this PR description and I think that's part of the issue here causing disagreement.
My impression is that the author's view is that this refactoring by itself serves the long term good, and that PRs should stay very "low-level" building blocks which may be referenced by larger projects but for some reason shouldn't spell out the larger goal. Is the expectation that people reviewing should either be aware of the larger goal anyway, and otherwise not review?
It's not immediately obvious why the Kernel API would be concerned with internals of Bitcoin Core. Kernel as it stands today is a bigger higher level wrapper of Core features than the prior libconsensus approach. But I've heard rumors of a surviving subdomain of Kernel which aspires to expose a stateless/pure block/transaction validation API, with part of the goal being that Bitcoin Core should use that API. That would in turn justify "reaching in" to refactor these Core types. The validation library is mentioned in the linked serialization article, but I think spelling it out in the PR description together with the end goal of making Bitcoin Core use it is not too much to ask.
I'm not experienced with the benefits and pitfalls of public
interfacewith privateshared_ptr<implementation>member vs passing aroundshared_ptr<type>, norconstvariants. The former promotes hidden indirection/pointer chasing while the latter has explicit pointer chasing but also risks accidental copying (https://github.com/bitcoin/bitcoin/pull/35569#issuecomment-4835740603). I think many other seasoned devs here (both proponents and opponents of the PR) are also not deeply familiar with the subculture of "regular types" and their trade-offs.Especially without knowing the overarching desired end state of Bitcoin Core using the public validation library, I can really understand judging this refactoring as overrated off-hand.
(In the past I've been annoyed at
CTransactionon master and thought a better name would beImmutableTransaction).The PR is older than https://github.com/bitcoin/bitcoin/issues/35904 and I haven't updated the description yet to mention it. It is also not strictly required for a stateless validation library. The issue description makes a clear separation between the necessary refactoring steps and additional "interface segregation" steps. This PR falls into the second category.
But I doubt that the missing link in the description is the root cause of the disagreement here.
This is correct.
I did not make it a secret that this serves https://github.com/bitcoin/bitcoin/issues/35904. But I also don't want to frame it as a requirement of that issue. Encapsulation has benefits by itself.
It has got little to do with the Kernel API and it is not a rumor. It has its own issue. Discussion about validation should take place there. This PR is about providing encapsulation for
CTransaction.That is a different stance than "you don't understand the project's specifics". For those willing to get familiar and experienced, I am happy to provide explanations or point to articles, books, videos. But those that dismiss any best practice of the larger C++ community as "preachy", or "appeal to authority", I cannot help.
That should not be the case. As I stated above, and as @josibake has pointed out repeatedly above, this PR provides benefits by itself.
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
CTransactionhowever (and also forCBlock,CTxIn,CTxOut, andCOutPoint), 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).The following code builds a transaction using the
CMutableTransactionbuilder:github.com/bitcoin/bitcoin@11090c8bb3/src/test/miner_tests.cpp (L162-L168)The same logic in declarative style does not need a builder:
The best way to make a type immutable in C++ is to not provide any mutating member function. This does not include
operator=, however. Removingoperator=does not make a type less mutable, it makes it less usable. For example, it can no longer be stored in a vector. One workaround (note: intervention spiral!), is to wrap it in astd::shared_ptr, which is whatCTransactionRefis doing. But this has two nasty consequences: It introduces sharing, so now you really need to prevent mutation. The much bigger issue is that it introduces emptyness. EachCTransactionRefcan hold a transaction, it can be changed to a different transaction, and it can hold not a transaction at all. Making thestd::shared_ptran implementation detail ofCTransactionallows providing a never-empty guarantee, which makes this type easier and safer to use.Those benefits are completely orthogonal to https://github.com/bitcoin/bitcoin/issues/35904. It should be possible to judge this PR even without knowing the desired shape of the validation library.
An object with a functioning
operator=is mutable.Operations are defined on the type, not on the object. A type that does not provide any mutating member functions is immutable. An immutable type can still be regular (regularity requires
operator=).Whether an object can be modified through a variable, depends on the declaration of that variable (controlled with
constandmutable).This is consistent with other languages: In C# or JavaScript, it is possible to reassign to a variable that holds an object of an immutable type, unless reassignment is explicitly prevented through that variable. Further, this is the current behaviour of
CTransactionRef.reACK
github.com/bitcoin/bitcoin@ef3a175126I find the new approach with clang-tidy annotations to be much easier to follow and, as you mention, gets rid of hardcoding the class names. Nicely done!
Concept ACK. I don't see practical downsides worth blocking over, and the techniques and direction seem valuable.
I've also been thinking that
CBlockmight be an interesting place to apply the same ideas. It's mutable right now, so unlikeCTransactionthe benefits of locking down the interface would be more visible, especially in mining code. If this PR is stuck, maybeCBlockcould be a more useful place to apply the same techniques?@ryanofsky
CBlock, along with a few other primitive types, are mentioned in https://github.com/bitcoin/bitcoin/issues/35904 to be made immutable. Not sure if there is a required / desirable order to do them in, I'll let @purpleKarrot speak to that.EDIT: Although, I suspect its better to have
CTransactionbe a regular, immutable type first since a block is a collection of transactions.🐙 This pull request conflicts with the target branch and needs rebase.
CTransactionis the easiest start, because all member accesses are read accesses.COutPointis also fairly easy, because most member accesses are either read accesses or assignments. Most assignments of one member are directly followed by an assignment of the other member (the order is not always the same), which can be rewritten with another bitcoin-tidy check (WIP: https://github.com/purpleKarrot/bitcoin/commits/outpoint-encapsulation).CTxInandCTxOutare a bit more tricky, because it is much harder to determine whether a member access is mutating or not. It may be obvious when looking at the code, but for clang-tidy, it requires much deeper analysis of the AST.CBlockinvolves even more work. If we order this from lowest to highest hanging fruits, it would beCTransaction,COutPoint,CTxOut,CTxIn,CBlock. But it would just as well be possible to parallelize some work.Coinmay also be an interesting candidate to look at.Note: The three step approach, where
really pays off when rebasing: Conflicting files can be reset completely and the bitcoin-tidy check can be rerun on them.
With the approach that does all three changes in a single clang-tidy check as suggested by @l0rinc, resetting individual files leaves them in an uncompilable state, as they use an interface that is no longer available.
The commits in https://github.com/l0rinc/bitcoin/pull/212 all compile just fine.
Sure, each commit compiles as a whole. But how do you resolve merge conflicts? When resetting a subset of a commit, it does not compile and the clang-tidy is not able to run either. You either need to resolve manually, or you need to reset completely.
Being deliberately obtuse is not helpful. If you're going to insist on unnecessary precision: mutable types are types whose objects can be mutated after construction. In C++, objects can be mutated by non-member functions, so not providing mutating member functions is no guarantee of immutability; in particular
operator=is often not a member function.CTransactionRefis an alias forshared_ptr, it is not surprising that you a pointer can point at different objects over its lifetime. Other languages put different priorities on the relationship between references and the objects they reference; eg python makes numbers immutable, with every change to a number resulting in the reference pointing at a different object.Edited
I redact my comment. I still want to highlight this quote, but leave it uncommented.
I don't think anyones being obtuse, I think you're not following the discussion. Furthermore, what you claim is "often" isn't possible in C++. You cannot have a non-member
operator=, as a language design choice.This PR encapsulates
CTransactionby making the data members private and and providing access through const readers. Making the data members non-const here in no way weakens the immutability ofCTransaction. If you disagree, an example specific to this PR would be great.It was also stated in the original blog, reiterated by me, and corroborated by @ryanofsky that the desired end goal stated by the author is a stronger immutability guarantee than what we have today. To reiterate again:
This gives a
CTransactiontype with regular value semantics, which serves as a handle to an immutable transaction body. If you believe this introduces mutability or is worse than the current design, please provide an example specific to what I reiterated above.As I was testing this PR, inspired by my comment on the
bugprone-use-after-movebehaviour, I noticed the flag isn't smart enough to catch aliases. So its possible to create something like:So its possible to write perfectly valid code that does not exploit UB etc, that compiles and violates the invariant of the class by mutating
CTransactionafter construction. I've only spent a day or two looking into this so I don't want to overstate the claim, but I do feel increasingly strongly that moving towards regular types with value semantics and more explicit ownership will help us fix these bugs. By more explicit, I mean the constructor needs to own its storage exclusively. This is the thing that matters for closing footguns like the one mentioned above, afaict. Why does it matter thatCTxInandCTxOutare regular types? Cheap copies!reACK
github.com/bitcoin/bitcoin@13b62f714aLast push was a rebase.
Without wading into the meta-discussion here, or picking a specific approach to support, I'd like to bring up a concrete potential advantage of better
CTransactionencapsulation (not as a suggestion for inclusion in this PR, but perhaps as motivation for it).One of the ideas I had when I introduced the
CTransaction/CMutableTransactionsplit, was thatCTransactioncould use more efficient memory allocation. For example, all dynamically-allocated memory within a transaction could be placed in a single allocator arena owned by theCTransaction, avoiding the overhead of individual vectors + allocation overheads for all inputs, outputs, scriptsigs, scriptpubkeys, witnesses, and witness stack elements, also reducing memory fragmentation and improving locality.I never explored that idea further at the time, but #36015 makes this suddenly a lot more relevant again.
I think this is a good point, but I don't think it is fixed by this pull. IIUC this is only fixed by the next pull that re-writes the deserialize approach. If we wanted to fix it today, it could be done by passing the mutable tx as
const&(at the cost of a copy). An alternative to fix it today would be to implement a simple/stricter version of use-after-move that detects use after moved fields (partial moves) or partial uses after full moves.Also, if we wanted to implement an arena, it could be done today, without changing code outside of
src/primitives, with something like:Encapsulate only the heap
(No strong opinion, just wanted to drop this off here)
Correct. My claim wasn't that this is fixed by this pull, rather the direction this pull moves us in should make it easier for us to fix this bug. I kept riffing on that idea here https://github.com/bitcoin/bitcoin/issues/35904#issuecomment-5331901823 and came up with something that composes well with the deserialisation approach proposed by @purpleKarrot (still working out some rough edges) and doesn't sacrifice performance (via copies) where it matters, e.g., block validation and reading transactions off the wire.
I don't want to understate the benefits of the other follow ups proposed by the author, but I am strongly in favour of what you mention here, and it is my primary interest in better encapsulation for our primitive types. This idea has been gnawing at me since Research Week a few years back where, if you recall, myself and a few others proposed an idea of completely getting rid of transactions and thinking only in terms of blocks and block chunks.
Obviously, we still need a transaction API for this codebase, but encapsulating the concrete layout allows us to have a single transaction type that works with an arena that is allocated for an entire block and also for a single transaction off the wire (perhaps even a cluster, but I haven't thought about this deeply yet):
Transactions as views over a block backed arena
This is a code golf'd version of a proof of concept I've been working on to benchmark, and to illustrate the idea. Needs more refinement, but the early benchmark numbers I've been getting from toy code is ~15x improvement on block parsing. I also strongly suspect block validation itself can be improved by >10% because of how much easier bytes can be slurped into hashes, signatures validated, arrays can be traversed etc etc, and as a long term goal having a block representation in memory that is set up for batch validation. Said differently, having proper encapsulation allows us to maintain a stable API for testing and use, while having the freedom to adapt the concrete representation of the data over time to adapt to the needs of the workflow.
Its also worth point out how it reduces opportunities for error: ask the OS 250k times for allocations, you have 250k opportunites for error. Ask 6 times, you have 6 opportunities for error.
Yeah, seems fine to leave all of them const? The benefit is that initialization is enforced by the compiler and assignment-ctor is deleted anyway?
🐙 This pull request conflicts with the target branch and needs rebase.
Yeah, I had
operator=confused withoperator+etc for no good reason. Surprisingly, when I'm annoyed I don't think as clearly as I might at other times; glad to see your response to that is to try annoy me further, rather than, say, trying to reconstruct whatever part of my claim might have been valid, and finding a way to find some actual common ground.In any event, even though that example was wrong, the point it was trying to support ("not providing mutating member functions is no guarantee of immutability") is not:
The "edited" above elided this comment, which I assume remains your opinion, and seems to me to warrant a response:
Encapsulation alone simply buys code churn and inefficiency; hence the 93-files-touched and the "you need to look at the blog posts and followup PRs to see why this is cool" advocacy. Except for sipa's recent suggestion, I don't think any of the followups actually have significant benefit from encapsulation. The original, now long distant, justification for this PR seemed to be making the object non-const so that some (de)serialization changes could be made, . I'm very skeptical that those changes are necessary of even very useful for those changes, and I think that reducing the const-ness of CTransaction is unnecessarily dangerous.
My impression is you've been assuming that I'm "sabotaging and trolling" since my first comments on this PR. While I'm sure you're predisposed to disbelieve me, I'm not attempting to troll or sabotage; at CoreDev Oct 2025, we identified "PRs don't get a response; it would be better to have early negative feedback than nothing" as a potential improvement, so I've been trying to do that since then, at least in areas I care a little about. It has certainly made it clear to me why "no response" is preferable from a reviewer's perspective.
If your reaction to criticism is both to reject it and ridicule the critic, rather than try to make absolutely sure there is no substance to it, I don't think you have any business touching consensus critical code. Beyond that, that you've changed the PR to somewhat avoid the criticism while still denying its validity comes across as deceptive to me; my expectation is you're deferring the changes you actually want, hoping to game the review process rather than address the criticism directly.
josi:
I gave such an example here https://github.com/bitcoin/bitcoin/pull/35569#issuecomment-4765667849
The current version of the PR doesn't provide any mutating functions on CTransaction, as can be seen by re-adding the "const" modifier to all its member variables and recompiling. See also https://github.com/bitcoin/bitcoin/pull/35569/changes#r3516547054 That comment hasn't been replied to in 50 days, despite being listed as a key property of the PR in the description ("after which the data members are made private and non-const."). My assumption is that the functions that will mutate those members have been deferred to a future PR.
The type that we have as a shared pointer to transaction data is called
CTransactionRef, notCTransaction.Yes, and you can achieve that result much more simply without any assistance from the constructor with
const_casteven with the best attempts at making the type immutable:The only answer C++ has for that is things like "don't use const_cast" and "don't create confusing aliases" and "don't write buggy code". The point of defensive coding, like having CTransaction objects be immutable is to make code that does weird things either fail to compile or at least look strange (
*const_cast<...>(...)) so it at least takes deliberate effort to introduce bugs, not, sadly, to make them entirely impossible.This is my objection as well, treating everyone else like idiots doesn't seem like a winning strategy.
+1
@purpleKarrot, what is your goal here - to make Bitcoin and Core better in any way you can, or to improve your blog? To learn from others, or to force your opinion and act like a CTO? You haven't contributed enough for me to tell whether you're here because you care or because Bitcoin would look good on your CV. Nothing personal, but Bitcoin is about PoW - do the work before the announcements.
We need more experts in this project, but so far you haven't demonstrated that: you're not learning, you're not reacting, you're not actually building. Try reviewing more PRs, be helpful, be less entitled - before you start rearchitecting everything you personally disagree with. I understand the drive, I have the same impulse, others have helped me align with the project. We don't need heroes here, we need team players.
That is a mutating function provided by the class.
friendfunctions have the same access rights as member functions. Yes, you have proven that it is possible to provide a mutating function that is not a member function, but that is not an argument against encapsulation. It still stands that an object of a type that is designed for immutability by not providing mutating functions cannot have its value mutated from outside (except withconst_castwhich is also not an argument against encapsulation).Zero-overhead encapsulation is the whole reason why C++ was invented in the first place. It allows changing the implementation of a class without requiring changes in the clients and has no runtime cost. Sure, fixing a class that leaks implementation details requires changing all clients. But that is a one-time change. Once encapsulation is established, then changing the implementation in a way described by sipa becomes possible without affecting the clients.
I still haven't seen a single technical argument against encapsulation. You two are trying to attack me on a non-technical level for reasons that I don't follow.
Let me invert that: it's your job to sell your idea, not our job to attack it. The change might make sense conceptually, and I even provided a full end-to-end alternative (which you also ignored), but you arrogantly dismiss most review comments because you think you always know better. Please read our replies - most of our concerns are about you not listening to feedback and acting entitled and offended. This change affects all of us, it's not just your decision to make.
Show us the full vision (in code, not blog posts) so we can consider it ourselves.
And when you get pushback, work with the people instead of trying to shame them into obedience.
Reminder for everybody here to keep the comments on topic. If you wish to offer meta-commentary, take it to the meta repository https://github.com/bitcoin-core/meta (and maybe take a breather and read through the guidelines there).
I think the changes here introduce some interesting concepts. Interrogating them for their perceived and actual capabilities is part of the review process, especially if they revolve around concepts that have not been widely perceived by contributors to Bitcoin Core as problems to be solved with priority. I'm happy that this is getting attention and review in the first place and is not facing stonewalled silence.
I'm sorry this discussion has gotten away from the technical merit. I commit to getting back on track and hope others will too.
I have also raised two issues in https://github.com/bitcoin-core/meta.
🐙 This pull request conflicts with the target branch and needs rebase.
This is the "we have a value type at home" argument, except whats at home is a generic CRef, i.e.
std::shared_ptr<const CTransaction>. Its nullable, needs.get()to open and has never once enforced "this is a transaction" as an invariant. And, I'm not just complaining about style or ergonomics:CBlock::vtxisstd::vector<CTransactionRef>, so a block can represent a null transaction slot. This is a state the protocol has no meaning for at all, but the type allows it anyway. Sounds footgunny!The reason its nullable in the first place is that deserialisation fills in a declared, possibly empty handle. Your own example needs
footo exist as an emptyshared_ptrbefore the read succeeds. Make deserialisation an explicit construct-or-fail step (as demonstrated in those pesky blogs) and theres no moment left where the type needs to represent "empty." Thats what lets the proposed version ofCTransactionenforce "always valid" the way it already enforces its other invariants, and whyCTransactionRefcall sites would becomeCTransactionand be able to drop an unnecessary null check.reACK
github.com/bitcoin/bitcoin@402500baadI went through the discussion and collected the questions that appeared to require a decision or clarification. The current resolutions are:
Why use trailing-return syntax for the accessors?
The motivation is readability: using
auto ... -> Typealigns the function names, making the API easier to scan. This is a stylistic choice for this API; it is not intended to imply that all existing code should be rewritten to use trailing-return syntax.Why not name the accessors after the protocol fields (
version(),vin(),vout(),nLockTime())?C++ does not allow a member function and a data member to have the same name. Renaming the data members would prevent the desired 3-step migration. The
Get*names allow the new API to be introduced without changing the representation. Most importantly, the naming scheme is consistent with the Symbol naming conventions documented in the developer notes.Why add the same accessors to
CMutableTransaction?The accessors are needed because generic read-only code is currently instantiated with both transaction types. Providing the same read-only interface keeps that code generic without introducing an abstraction or additional conversion at serialization boundaries and it will simplify making the code concrete once it is only ever instantiated with a single transaction type.
Should the read-only code instead use an immutable transaction view?
No. This would add yet another transaction type, resulting in a total of four:
CTransaction,CMutableTransaction,CTransactionRef, andCImmutableTransactionView. Instead, the goal is to reduce the number of transaction types to one:CTransaction. OnceCTransactionhas regular value semantics,CTransactionRefwill be obsolete. Once all procedural transaction building code is written in a declarative style,CMutableTransactionwill be obsolete. Generic code that is parameterized on the transaction type will then become concrete.Should indexed
vin(index)/vout(index)helpers be added?No. They would preserve the existing index-based access patterns rather than encouraging migration toward ranges and standard algorithms. Where only the first element is needed,
.front()is preferred.Should
LIFETIMEBOUNDbe added to accessors returning references?Yes. This has been done for
GetInputs()andGetOutputs().Why remove
constfrom the data members if they are not going to be modified?To align with common practice. In C++20, it is discouraged to have
constdata members, because they make the type's semantics hard to understand. WG21 P3812 discusses this limitation and may change this practice in a future version of the language.This does not imply any plan to introduce mutation of individual transaction fields.
Why disable assignment operations?
CTransactionis currently passed around asCTransactionRef(akastd::shared_ptr<const CTransaction>). This prevents mutation through that particular handle, but it does not guarantee that there is no mutable alias to the sameCTransactionobject elsewhere. Such an alias could modify the object behind theconstshared pointer, causing spooky action at a distance. The longer-term goal is to makeCTransactiona proper value type with immutable underlying state and then use it to replace all occurrences ofCTransactionRef, at which point this concern goes away.Should the new
bitcoin-tidycheck remain after the migration?Yes. The check has been generalized so that it does not hard-code the particular symbols involved in this migration, making it useful beyond this one conversion.
What coding style should the new
bitcoin-tidycode follow?No strong preference. Following LLVM's style is has an advantage should the code eventually be upstreamed to clang-tidy.
Show us the full vision (in code, not blog posts)
The reference implementation for
std::bitcoinhas it all. Here is how a transaction may look like as an immutable value type with a remote body and a never-empty guarantee. Here is how deserialization is completely orthogonal, does not require access to the private data members and does not require transactions to be held by a pointer.Overall, the remaining questions are therefore either resolved by the current implementation or concern larger architectural cleanups that are intentionally outside the scope of this PR.
ACK
402500baadReproduced the fixup commit. Built
79319ebwith clang 22.1.8 (-DBUILD_GUI=ON -DBUILD_BENCH=ON -DBUILD_FUZZ_BINARY=ON -DBUILD_KERNEL_LIB=ON -DBUILD_UTIL_CHAINSTATE=ON) and ran the check per the commit message.Result: 86 files, 485 insertions, 485 deletions, and git diff
6b99660empty.Also compared object files across the fixup commit: 53 of the 86 modified files compile to byte-identical object files, the rest differ only in register allocation and assertion-string lengths.
Unit and Functional tests green
nit: missing the MIT header - same for the header file.
Might be valuable to document the check's boundaries to reduce surprises like
CalculateOutputValuelater on.Does this fire in the current tree?
Left over from annotating something else, or anticipating a future use of the check?
copy-assignment is deleted anyway (due to the footgun explained in the source comment above the deletion), before and after this pull, so the paper doesn't directly apply here anyway right now. I think it is nice to have minimally more compiler checks to enforce initialization, also to keep the code as-is for now, and only change this in the future, when there is a real need or real observable benefit.
@maflcko, fine. It would be cool if we could proceed so we can fix the footgun at the root cause and stop passing around
std::shared_ptr.🚧 At least one of the CI tasks failed.
Task
TSan: https://github.com/bitcoin/bitcoin/actions/runs/35414089932/job/105819188987LLM reason (✨ experimental): CI failed due to a C++ build error in
src/wallet/wallet.cppwhere it accessesCTransaction::vin, a private member, causing compilation to fail with-Werror.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.
reACK https://github.com/bitcoin/bitcoin/pull/35569/commits/4c7f4aed9a40f250bc6b21d51e09572a9e690b61
Given the silent and non-silent conflicts, I wonder when it is the least-bad time to merge this? Probably not right now, to not conflict with any backports of the next release, so maybe end of November, when the release is out and the backports are hopefully less? Also, there are open nits/questions in https://github.com/bitcoin/bitcoin/pull/35569#discussion_r3966283402
This PR does not "stop passing around
std::shared_ptr".I'm not sure if this is intended to imply that merging this PR is already a foregone conclusion. For the record, I don't believe it should be, and don't believe it adds enough value to even warrant the level of review it's been given.
If it is too controversial for merge, it should be closed (or moved to draft for now). It can always be re-opened later, maybe along with a pull to stop passing around shared_ptr, or with a pull to change the memory allocation (with benchmarks), or with a pull to optimize the ser-/deserialize code (with benchmarks)?
Can you explain what you find controversial about the PR?
Nor have I claimed that it does. I am not starting with the followup work until this is merged.
I also want to know.
Why would we be merging this? At least 3 people objected, the author just keeps ignoring and pushing harder instead of listening to feedback. As mentioned before, many of us are not comfortable with that.
Yes, we already have, multiple times in multiple issues. The author should understand the culture instead/before trying to force their subjective opinion on everyone else. This issue wasted a lot of our time.
TL;DR: My attempt at partially reconciling current differences.
Late response to: https://github.com/bitcoin/bitcoin/pull/35569#issuecomment-5281383955
"Marketing"
My impression from the discussion is still that more direct marketing would have helped limit disagreement. Glad you since added a "Why"-section!
Again, adding (or modifying into) 2 more specific marketing sentences such as these could be beneficial:
"In the longer term, this could enable passing
CTransactioninto a public-facing thin validation API which is also used inside Bitcoin Core. Once theshared_ptris made internal it would enable API-users to work withCTransactionobjects without unexpected external constraints such as them themselves needing to wrap them in ashared_ptrto avoid needless memory growth."Potential argument: Pooled allocation benefits?
Not sure if it's been explicitly said elsewhere, but it might be beneficial to have a "transaction slab allocator" where
CTransactionor futureTransactionDataare allocated into large multi-transaction slabs of memory withvin/voutbeing spans into those slabs instead of vectors. Maybe we could reach a serialization-format where one can simply cast bytes intoTransactionDatawithout running a constructor. (Edit: I probably got most of this from sipa's https://github.com/bitcoin/bitcoin/pull/35569#issuecomment-5347587737).There's no harm in dangling possible benefits in front of reviewers as long as they don't come with guarantees of being delivered.
Rubbing people the right way
FWIW I'm happy you are bringing another way of using C++ to this project. Regular types may be axiomatic at Adobe, Apple and in the C++ committee. However, based on my pre-bitcoin C++ usage on large teams on large projects, I doubt it's internalized by a majority of long-term C++ users. Let us call it getting experienced in Regular types specifically, rather than implying general inexperience among the detractors of this PR.
I'd say this is not how C++ was birthed into the world, but C++ with decades of hindsight and competition from Rust+Swift.
I agree with supporting a way to declaratively specify
CTransactions without requiring theCMutableTransaction-builder type. It is possible by just adding another ctor to master without changing anything else. In fact, if it weren't for the private fields, one could write it exactly like that without a ctor at all (modulo field reordering). So that's fairly orthogonal to the current PR.The status quo
CTransactionon master is immutable due to havingconstnon-reference members. This serves a kind of inverse of local reasoning, informing us of how it can be used everywhere else in the codebase. I'd say it's a fairly benign case of a non-regular type, which makes the refactoring appear arbitrary and subjective by itself. Introducing more accessor methods as this PR does would require an equal or greater amount of lines inspected in order to asses the constraints of a type.In Bitcoin Core we have some domain-specific restraints, we want to store transactions both in the mempool, in the transaction orphanage, the recently evicted list, possibly in the peer templates. The current approach on master intentionally discourages copying in order to minimize memory usage.
Agree with many of your points I didn't quote, but want to make it easier to understand how someone could prefer the status quo.
Snippet from: https://github.com/bitcoin/bitcoin/pull/35569#issuecomment-5762019739:
This seems a bit counter-productive. I'm sure this PR represents a step along a beneficial path. But working through some of the remaining steps ahead of time can help uncover major roadblocks hiding in the codebase which would have to be dealt with in order to continue. Conversely it could also provide concrete proof of the benefits. If you're lucky it could show that there aren't any major roadblocks.
Conclusion: I understand the skepticism to the PR but I'm positive to it and hope we can at least reach Concept ~0 from one detractor.
Don't get me wrong on this. I do have a proof of concept of the final interface of all necessary vocabulary types for stateless, side-effect-free consensus validation library ready in
std::bitcoin. If you want proof of the benefits, want to see how transaction can be an immutable value type, how blocks can hold transactions that cannot be null, or if you want to know how serialization/deserialization is supposed to work in this approach, look there. I am just not wasting too much time integrating the proven design into Core as long as there is an ongoing debate on whether encapsulation is beneficial or whether it "simply buys code churn and inefficiency" (https://github.com/bitcoin/bitcoin/pull/35569#issuecomment-5384474842).That's not what we're discussing
Personally, I don't consider telling a contributor to understand the culture before proposing changes, or characterising their participation as forcing an opinion on everyone, is appropriate review feedback. We should be able to disagree firmly about whether work is worthwhile without making someone's standing in the project part of the argument.
In any case I think claiming that the purpleKarrot is ignoring feedback is disingenuous here; he has accepted suggestions above e.g. retaining
constand addressing assignment and move concerns.That said, I think we are still disagreeing about what would justify this migration at a fundamental level...
As I read it the strongest argument in favour is that observer functions establish a boundary between transaction users and storage. Some seem to consider that worthwhile independently, and see applications in allocation changes, serialization, and ownership.
The strongest objection seems to be that the migration has an immediate review and integration cost, while much of the benefit depends on later work. I think asking whether that tradeoff is worthwhile is a legitimate engineering objection though. This has to be balanced with the view that a refactor can have value without fixing an immediate bug. Better architecture can be a legitimate benefit.
In this case, the architectural argument is more specific than encapsulation for its own sake. As I understand purpleKarrot's longer-term plan,
CTransactionwould become a regular value type backed by immutable shared state, with theshared_ptrhidden behind its API. That would strengthen the model we have today. For example,CBlock::vtxis currently a vector ofCTransactionRefs, so the type permits a block to contain a null transaction slot or for a slot to be rebound to a different transaction. Neither state has a useful meaning for a block. The proposed model would let a block hold transaction values that cannot be null while preserving shared immutable storage.This PR does not deliver that design by itself, but it establishes the boundary needed to pursue it without changing every transaction user again. The linked blog posts describe the larger sequence. Russ also noted that moving the shared state inside
CTransactionwould strengthen its immutability guarantees, and separately suggested applying the same ideas toCBlock, whose interface is mutable today. I think that context belongs in the "better architecture" side of the tradeoff because it is the concrete argument purpleKarrot is making, rather than a generic preference for private fields.I think we can ~ consider a few points settled about the current patch:
CTransactionRef.constand become private as suggested by maflcko (note: @purpleKarrot the PR description does not match here currently).I think therefore we can drop any arguments which reference these points?
I suggest we concentrate on remaining questions:
Do we consider encapsulation to be beneficial?
What concrete benefit is sufficient to justify the migration? Sipa's allocation proposal seems like a direct example, but purpleKarrot, josibake and others have also chimed in on other use-cases.
Which migration choices are actual blockers? Naming, matching observers on
CMutableTransaction, and splitting the migration by field have all been discussed.Side note: I also can't help but feel that we should apply more of a consistent bar for changes if we possibly can. e.g. we recently merged a pretty icky equality change to
CTransactionbut it received quite a different level of scrutiny to this change, with IMO a much more questionable motivation ("upstream" wallet issue).🐙 This pull request conflicts with the target branch and needs rebase.
Pushed to resolve merge conflicts and updated the description. Removed all mentions of
constand 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".🟠 Minor · Exclude owner methods from observer rewrites
use-observers.cpp:12-21 skips only implicit or defaulted function ancestors and implicit-this access. An explicit
this->field = valuein an owner method is therefore rewritten tothis->GetField() = value, which does not compile against a const-reference observer. Latent, because no src/ field is annotated.Location:
contrib/devtools/bitcoin-tidy/use-observers.cpp:8(head).🟠 Minor · CalculateOutputValue no longer works with CTransaction
At transaction.h:274, CalculateOutputValue still reads
tx.vout, which this PR makes private in CTransaction, so a CTransaction instantiation now fails access checking. Latent: the only callers (wallet/spend.cpp) pass CMutableTransaction txNew.Location:
src/primitives/transaction.h:271(head).🟠 Minor · Auto-fix can rewrite owner-class accesses into recursive observers
use-observers.cpp:21 skips only implicit-this access, so an explicit
return this->field;in the field's own observer would be rewritten toreturn this->GetField();, which recurses infinitely. Latent: current observers use implicit access and no src/ field is annotated.Location:
contrib/devtools/bitcoin-tidy/use-observers.cpp:18(head).🔵 Suggestion · Clarify the collection-representation boundary
At transaction.h:319-320, GetInputs/GetOutputs still return const std::vector references, and callers use
.at(), DynamicUsage and explicit vector iterators. The offset-into-block representation cited in the description would require materializing vectors or another caller migration.Location:
src/primitives/transaction.h:318(head).🔵 Suggestion · Add a test fixture for the observer check
At CMakeLists.txt:67, bitcoin-tidy-tests still compiles only example_nontrivial-threadlocal.cpp, and no src/ field carries USE_OBSERVER. Nothing exercises the use-observers diagnostic or fix-it, so matcher or replacement regressions would go unnoticed.
Location:
contrib/devtools/bitcoin-tidy/CMakeLists.txt:66(head).Review coverage was incomplete.
Reviewed:
5bffd2c47a44· Full review report · Previous reportsSomewhat related, in #36521 I change the representation of
CScriptWitnessto 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 (CScriptWitnessis a per-CTxInmember), 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
CTransactiontoo, 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.@sipa, there are hundreds of possibilities of changing the in-memory representation of these types. Keeping
CScriptWitness,CTxIn,CTransaction, and evenCBlockin 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.
🐙 This pull request conflicts with the target branch and needs rebase.
It's not clear to me to what extent getting rid of the distinction between
CTransactionandCMutableTransactionis 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-
CTransactionpacked representation, and needs even more invasive changes throughout the codebase.@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 https://github.com/bitcoin/bitcoin/issues/36692 that writing unit tests in a way that does not rely on
CMutableTransactionbrings 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,CMutableTransactionwill be no longer be needed and many function templates that currently rely on aTxTypetemplate argument can become concrete functions.In https://github.com/bitcoin/bitcoin/pull/36696#issuecomment-6518387886, I show concrete examples how
CTransactionwould 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.I think there are two views, which are both subjectively valid and don't come to an agreement: