Repository navigation
Description
This is a tracking issue for individual refactorings of unit tests.
Rationale: Primitive types like CTxOut currently provide read and write access to their data members like scriptPubKey. Consensus validation does not require write access. Hence, it is forced to depend on functionality that it does not use, which is a violation of the Interface Segregation Principle (ISP). A whole category of bugs could be eliminated if this functionality was removed.
One case where write access to those data members is extensively used, is the imperative building of test data in unit tests like this:
bitcoin/src/bench/ccoins_caching.cpp
Lines 36 to 52 in 9bf4815
| CMutableTransaction t1; | |
| t1.vin.resize(3); | |
| t1.vin[0].prevout.hash = dummyTransactions[0].GetHash(); | |
| t1.vin[0].prevout.n = 1; | |
| t1.vin[0].scriptSig << std::vector<unsigned char>(65, 0); | |
| t1.vin[1].prevout.hash = dummyTransactions[1].GetHash(); | |
| t1.vin[1].prevout.n = 0; | |
| t1.vin[1].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4); | |
| t1.vin[2].prevout.hash = dummyTransactions[1].GetHash(); | |
| t1.vin[2].prevout.n = 1; | |
| t1.vin[2].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4); | |
| t1.vout.resize(2); | |
| t1.vout[0].nValue = 90 * COIN; | |
| t1.vout[0].scriptPubKey << OP_1; | |
| // Benchmark. | |
| const CTransaction tx_1(t1); |
The imperative building could be replaced with declarative construction:
const CTransaction tx_1{
std::array{
CTxIn{COutPoint{dummyTransactions[0].GetHash(), 1}, CScript{} << std::vector<unsigned char>(65, 0)},
CTxIn{COutPoint{dummyTransactions[1].GetHash(), 0}, CScript{} << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4)},
CTxIn{COutPoint{dummyTransactions[1].GetHash(), 1}, CScript{} << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4)},
},
std::array{
CTxOut{90 * COIN, CScript{} << OP_1},
CTxOut{},
},
};This example shows several advantages:
- It reduces the amount of necessary boilerplate.
- It is necessarily honest: The fact that the outputs contain an empty element is plain to see rather than hidden in a
resize(2)call. - It removes the need for a dedicated "builder" type, like
CMutableTransactionin this case.
Another case where write access is currently used, is the reuse of test data, like in this example:
bitcoin/src/test/script_tests.cpp
Lines 1287 to 1339 in 9bf4815
| CMutableTransaction txFrom = BuildCreditingTransaction(GetScriptForDestination(PKHash(keys[0].GetPubKey()))); | |
| CMutableTransaction txTo = BuildSpendingTransaction(CScript(), CScriptWitness(), CTransaction(txFrom)); | |
| CScript& scriptPubKey = txFrom.vout[0].scriptPubKey; | |
| SignatureData scriptSig; | |
| SignatureData empty; | |
| SignatureData combined = CombineSignatures(txFrom.vout[0], txTo, empty, empty); | |
| BOOST_CHECK(combined.scriptSig.empty()); | |
| // Single signature case: | |
| SignatureData dummy; | |
| BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL, dummy)); // changes scriptSig | |
| scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]); | |
| combined = CombineSignatures(txFrom.vout[0], txTo, scriptSig, empty); | |
| BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig); | |
| combined = CombineSignatures(txFrom.vout[0], txTo, empty, scriptSig); | |
| BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig); | |
| SignatureData scriptSigCopy = scriptSig; | |
| // Signing again will give a different, valid signature: | |
| SignatureData dummy_b; | |
| BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL, dummy_b)); | |
| scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]); | |
| combined = CombineSignatures(txFrom.vout[0], txTo, scriptSigCopy, scriptSig); | |
| BOOST_CHECK(combined.scriptSig == scriptSigCopy.scriptSig || combined.scriptSig == scriptSig.scriptSig); | |
| // P2SH, single-signature case: | |
| CScript pkSingle; pkSingle << ToByteVector(keys[0].GetPubKey()) << OP_CHECKSIG; | |
| BOOST_CHECK(keystore.AddCScript(pkSingle)); | |
| scriptPubKey = GetScriptForDestination(ScriptHash(pkSingle)); | |
| SignatureData dummy_c; | |
| BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL, dummy_c)); | |
| scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]); | |
| combined = CombineSignatures(txFrom.vout[0], txTo, scriptSig, empty); | |
| BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig); | |
| combined = CombineSignatures(txFrom.vout[0], txTo, empty, scriptSig); | |
| BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig); | |
| scriptSigCopy = scriptSig; | |
| SignatureData dummy_d; | |
| BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL, dummy_d)); | |
| scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]); | |
| combined = CombineSignatures(txFrom.vout[0], txTo, scriptSigCopy, scriptSig); | |
| BOOST_CHECK(combined.scriptSig == scriptSigCopy.scriptSig || combined.scriptSig == scriptSig.scriptSig); | |
| // Hardest case: Multisig 2-of-3 | |
| scriptPubKey = GetScriptForMultisig(2, pubkeys); | |
| BOOST_CHECK(keystore.AddCScript(scriptPubKey)); | |
| SignatureData dummy_e; | |
| BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL, dummy_e)); | |
| scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]); | |
| combined = CombineSignatures(txFrom.vout[0], txTo, scriptSig, empty); | |
| BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig); | |
| combined = CombineSignatures(txFrom.vout[0], txTo, empty, scriptSig); | |
| BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig); |
The test data txFrom is constructed in line 1287 and later modified in lines 1315 and 1331, through the scriptPubKey reference defined in line 1289. Notably, each block of code that uses a different state of the test data is introduced by a comment containing the word "case" ("Single signature case", "P2SH, single-signature case", "Hardest case: Multisig 2-of-3").
Separating the individual "cases" into actually independent test cases would remove the need for write access in addition to providing additional advantages:
- Easier to reason about: The test input data is visible in a single place. It does not depend on modifications elsewhere or side effects of other tests.
- Easier to parallelize: Individual test cases can run concurrently.
Refactoring the imperative code in unit tests is a precondition for solving the ISP issues of the primitive types. The two examples above show that such a refactoring is self-contained (it only affects test code, and in most cases only individual tests, so it can be done one test at a time). It also shows that it provides benefits for each individual test on its own.
Activity
maflcko commentedon Oct 29, 2026
This change is tedious to review, but I think worth it. Having tests that use mutable structs over hundreds of lines and separate unit test cases and each case may modify some fields of the struct leads to test bugs (copy-paste errors) and makes it harder to read the test, because more time is spent on trying to figure out the current state than the test logic itself.
So rough Concept ACK, but obviously the approach may differ on a case-by-case basis.
maflcko commentedon Oct 29, 2026
btw, I am not sure on forcing the call sites to specify a container. This is verbose and distracting in test code. If this is done, the ctor should simply accept a
std::vector<T> vin/out. This keeps all call sites clean and possibly also avoids a copy on the stack (not that performance is relevant here)? Of course, fancy callers can still do fancy stuff like passing(std::views::concat(a, b) | std::ranges::to<std::vector>());, but then the fancy stuff only requires verbose code at the fancy call sites. So my preference would be to keep this plain and simple C++11.Merge #36606: test, bench: construct inputs/outputs declaratively in …
purpleKarrot commentedon Oct 29, 2026
@maflcko, the problem is that moving a vector into place allows the following:
So it is better to not try to avoid the copy. But if a copy needs to be made, why should we enforce the type of the temporary? The compiler cannot deduce template arguments from bare braced initializer lists, which I would not consider a big problem here. I think it actually helps readability to specify a type because it communicates to the reader: "I am creating a container" rather than "I am creating some object". Using
std::arrayseems to have less overhead thanstd::vectorhere and is easier to type thanstd::initializer_list<CTxIn>, though all three would work in the same way.If performance of the copy becomes a concern, we should strive for making construction
constexpr(not proposed here).maflcko commentedon Oct 29, 2026
Right, but I'd still prefer the plain and less verbose C++11 ctor here. Recall the goal is to mostly catch accidental bugs in tests, not intentional bugs. If we are worried about the mutable reference backdoor, I think it can be trivially fixed in C++11 by just doing the copy (performance doesn't matter for this test-only code). While clang-tidy use-after-free doesn't catch such partial moves, I am sure human or LLM reviewers will catch it, so I wouldn't worry too much about it.
alexanderwiederin commentedon Oct 30, 2026
To summarise where the constructor discussion stands as I understand it: the aliasing concern can be addressed by either design, as noted above, so it does not decide between them. What remains:
Literal lists: explicit
std::array{...}versus plain braces (with one element per line and trailing commas). The explicit container makes it clear that the inputs and outputs are each a collection, and where each one ends. Plain braces are less verbose, and since every element already names its type, the container name adds little. For an empty list, however, a{}doesn't say what it is, whereasstd::array<CTxIn, 0>{}is unambiguous.Flexibility: the range constructor accepts any range directly, including views of derived inputs. The vector constructor needs those converted first: through the iterator-pair constructor on a separate line in C++20, or inline with
| std::ranges::to<std::vector>()in C++23. If it also copies to avoid aliasing, the elements are copied twice. For example, with the range constructor, a child spending output 0 of every parent (as intxpackage_tests) could be written as:Complexity: a constrained template versus a plain C++11 constructor.
Let me know if I've missed or misrepresented anything.
Merge #36750: test: construct multisig_tests inputs/outputs declarati…
yuvicc commentedon Nov 6, 2026
Thanks for the summary @alexanderwiederin. Going through your point and also while converting #36750 and #36788, almost every call site I converted is a literal list while empty case came up once in
script_p2sh_tests, for that named-argument comment seems enough:Regarding flexibility, in the
txpackage_testsexample, the parents are created in the same loop that adds the child's inputs:With a vector ctor,
child.vinwould just become a localstd::vector<CTxIn>filled in that loop and passed in afterwards. No extra conversion line, and it reads no worse than the transform. I agree the extra copy is real, but for test callers I don't think it matters. I think the template's flexibility is rarely used in practice, so the simpler constructor seems the better trade.Looks like aliasing is already possible on master through
CTransaction(CMutableTransaction&&), which movestx.vin/tx.voutinto place (transaction.cpp#L96, and #36696 keeps this as well. That said aliasing can't be deciding between the designs.On the side of the range constructor: following #35569, it avoids tying the interface to
std::vector, so the representation could change later.So my weak preference is the plainstd::vectorctor.I now lean towards the range ctor.
purpleKarrot commentedon Nov 6, 2026
@yuvicc, I think your example can show the advantage of a constructor accepting ranges, because the loop can be refactored to:
Merge #36694: test: construct `mempool_tests` inputs/outputs declarat…
Merge #36788: test, bench: construct inputs/outputs declaratively in …
yuvicc commentedon Nov 9, 2026
I've opened #36798 which could be a a good example of why the second part of this issue, splitting shared-state tests into independent cases, matters as much as the constructor.
Merge #36798: test: spend an existing output in `TestBasicMining` dou…
alexanderwiederin commentedon Nov 10, 2026
On the range-vs-vector question, I lean towards the range ctor for caller flexibility (e.g. passing views directly) and for not adding another
std::vectorto the interface. No strong opinion though.Since no one seems to consider this blocking, I suggest going with the author’s choice so this can move forward, unless someone feels otherwise.
Merge #36810: test: construct `miner_tests` transactions declaratively
Merge #36888: test: construct `coinselection_tests` output declaratively
test: avoid mutating the scriptSig in bip352 p2pkh extraction test
test: construct group_outputs_tests output declaratively
bench: construct mempool_ephemeral_spends inputs/outputs declaratively
test: construct group_outputs_tests output declaratively
bench: construct mempool_ephemeral_spends inputs/outputs declaratively
Merge #36830: test: make `tx_mempool_block_doublespend` cases indepen…
test: construct descriptor_tests spend transaction declaratively
Merge #36950: test, bench: construct inputs/outputs declaratively in …
Merge #36923: test: construct `miniminer_tests` inputs/outputs declar…
Merge bitcoin#36923: test: construct `miniminer_tests` inputs/outputs…