utxo split/0 tx read

willcl-ark/bitcoin: PR #38

7 suggestions

Optional improvements

Link

[suggestion] · Byte-derived hashes leave their canonical-decoding requirement undocumented

The hashing paths agree today, but DeserializeHashed() does not record why canonical decoding makes hashes independent of the input stream type.

Location: src/primitives/transaction.h:501 (head).

Details and suggested fix

DeserializeHashed() hashes recorded input bytes for contiguous streams but calls HashBySerialising() for other streams, including the BufferedFile used by LoadExternalBlockFile(). Their equivalence relies on accepted encodings round-tripping exactly: ReadCompactSize() rejects non-minimal prefixes, and UnserializeTransaction() rejects unknown flags and superfluous witness records. The comments assert equal hashes without recording this prerequisite. Add a short invariant comment explaining that accepting and normalizing an alternative encoding would require canonicalizing the hash preimage or using the reserialization path. The existing unit comparisons and transaction fuzz assertions already guard equality; this recommendation makes its current correctness premise explicit.


Link

[suggestion] · Hash assertions in the transaction fuzz target miss HasWitness() disagreement

The fuzz target's hash comparisons would not detect a legacy transaction incorrectly marked as having witness, because they do not independently check the recorder-derived HasWitness() value.

Location: src/test/fuzz/transaction.cpp:58 (head).

Details and suggested fix

For a legacy transaction, the complete consumed byte range is also the txid preimage. If segments.has_witness were incorrectly true, HashTransactionSegments() would still produce matching txid and wtxid values, so both existing fuzz assertions could pass despite the wrong witness flag. The precomputed constructor stores that boolean without deriving it from the fields. Add assert(tx.HasWitness() == mutable_tx.HasWitness()); beside the hash assertions. The unit helpers already compare this flag, but the fuzz target currently only invokes tx.HasWitness() without checking its result.


Link

[suggestion] · Duplicate-input rewrite lacks current performance measurements

The allocation savings are concrete, but the supplied results do not measure the benefit of the new pairwise and sorted-copy paths on current block-checking workloads.

Location: src/consensus/tx_check.cpp:23 (head).

Details and suggested fix

HasDuplicateInputs() replaces the simple std::set loop with two algorithms and an eight-input cutoff. The consistent outpoint comparisons and set-oracle tests support equivalent verdicts, but the cited historical result does not measure this implementation or its small-input branch. Report before/after results for DuplicateInputs and CheckBlockTest. The former spends nearly all its work on one roughly 24,000-input transaction; its one-input coinbase performs no pairwise comparisons. The latter checks 1,557 transactions from mainnet block 413567 and supplies a real-block workload. A measurable gain supports the additional validation-code complexity; if the gain is negligible, retain the std::set implementation.


Link

[suggestion] · The buffer-refactor commit also changes exception policy

Commit aba49a5 combines the overwrite-buffer refactor with two catch narrowings, but its message explains only the shared-helper change.

Location: src/node/blockstorage.cpp:1159 at aba49a539d7e (commit) (commit).

Details and suggested fix

In the buffer-refactor commit aba49a539d7eb5ae31b2ab6398377d0536f2b867 itself, the shared helper's catch changes from std::exception to std::ios_base::failure, while ReadBlock()'s parsing catch changes from std::exception to std::runtime_error. The message explains the first policy change but omits the second. The helper also serves every ReadRawBlock() caller, including peer block serving, REST, RPC, and ZMQ, rather than only the new overwrite-buffer allocation.

Keep both broad catches in the refactor commit and move the narrowings into a following policy-only commit whose message explains both changes and their shared-caller scope. Neither narrowing is required for the buffer refactor or the subsequent changes. This separates review of buffer lifetime and full-read-before-parse ordering from exception policy. Normal bitcoind allocation exhaustion already terminates through new_handler_terminate, so this is not a claim of a new ordinary out-of-memory crash.


Link

[suggestion] · txhashing_tests miss fixed multi-byte CompactSize cases

The new differential tests do not deliberately exercise successful transactions with multi-byte CompactSize prefixes, including the separately read input count.

Location: src/test/txhashing_tests.cpp:45 (head).

Details and suggested fix

RandomTransaction() generates at most five inputs and outputs, scripts no longer than 80 or 60 bytes, and at most three witness items shorter than 72 bytes. The fixed transactions are also small. Increasing tx_count in the block tests only widens the block-level prefix, outside the recorded transaction segments. Mutations and fuzzing may encounter larger prefixes but do not guarantee successful cases. Add fixed 252/253 boundary fixtures for input and output counts, scriptSig and scriptPubKey lengths, and witness item lengths or stack counts. Run them through CheckTransactionBytes() and CheckBlockBytes(), requiring successful parsing as well as equal hashes and consumed-byte counts across the contiguous and opaque readers.


Link

[suggestion] · The recorder pulls file-stream headers into primitives/transaction.h

TxSegmentRecorder introduces streams.h and its logging, obfuscation, and file-I/O dependencies into every transaction-header includer; this is header coupling, not a link dependency, and no compilation slowdown has been measured.

Location: src/primitives/txsegments.h:11 (head).

Details and suggested fix

primitives/transaction.h now includes primitives/txsegments.h, whose SpanReader member brings in streams.h and headers such as util/log.h, util/obfuscation.h, and util/syserror.h. The recorder only needs bounded byte reads and position bookkeeping. Store a std::span<const std::byte> directly and implement read() with the same zero-length early return, bounds check before copying, std::ios_base::failure on overrun, and span advancement. Pos() can use the original size minus the remaining span size. This preserves parsing and failure behavior, apart from possible exception-message text, while removing the unrelated stream-header dependencies.


Link

[suggestion] · HashTransactionSegments() duplicates SHA256d finalization

The digests are correct, but HashTransactionSegments() duplicates HashWriter's raw-byte hashing and finalization, adding work to review without changing the preimages.

Location: src/primitives/txsegments.h:99 (head).

Details and suggested fix

HashWriter::write() accepts raw byte spans without adding a serialization prefix, and GetHash() already performs the double SHA256 implemented by the local finish lambda. Write each data.subspan(begin, end - begin) into a HashWriter for the txid and the complete recorded range into another for the wtxid, retaining the early return that reuses the txid when there is no witness. This leaves the selected bytes and digests unchanged while making segment selection the only new hashing logic to review. Since HashTransactionSegments() is not a template, its definition can live in transaction.cpp, which already includes hash.h, without adding that header to the transaction-header include chain.


Coverage details

Background

Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.

Documented decisions

The earlier sorting proposal deliberately traded some potential speedup for lower review complexity. PR #14397 reported about a 2x improvement on its benchmark, versus about 4.5x for a more complex alternative. Wuille characterized his proposal as a smaller improvement at much lower review complexity and said he was not convinced either approach was needed.

The present sorted-copy approach has a direct historical precedent, but the historical measurements are not evidence of its present end-to-end benefit. That discussion made ease of establishing unchanged duplicate-detection semantics a material part of the security/performance tradeoff.

Source 1 · Source 2 · Source 3

Allocation failure is a local operational failure, and continuing after it can produce a false consensus-invalid result if state has been partially modified. Issue #9854 reported an OOM followed by rejection of a valid historical block. Matt Corallo explained a possible path in which a coins-cache flush erased entries while constructing a database batch, then allocation failed and left inconsistent state. Cory Fields proposed immediate termination as the least risky response among approaches he had considered.

This is relevant counter-context for the block-read exception-policy change: historical experience distinguishes failed resource allocation from invalid block data and warns against assuming recovery is safe. It does not establish that block-buffer allocation has the same partial-state consequences, or explain the original broad block-read catch.

Source 1 · Source 2 · Source 3

Unresolved disagreements

The inspected sorting discussion did not resolve whether its microbenchmark improvement justified changing the check. John Newbery requested a cost/benefit argument; James O'Beirne reported no significant IBD or reindex regression from restoring the check; others emphasized propagation. Maxwell observed that relay-before-validation reduced that urgency and that the check's context-independent nature made validity caching another relevant consideration.

The historical record supports a performance-versus-review-complexity question, not an established requirement to sort or to retain a set. Its discussion of propagation and caching is also distinct from this PR's stated block-read and IBD motivation.

Source 1 · Source 2 · Source 3 · Source 4