utxo split/0 tx read

willcl-ark/bitcoin: PR #38

1 minor finding · 5 suggestions

Earlier concerns neither republished nor resolved: 1 suggestion. See the Run archive for their assessments.

Findings

Link

[minor] · Two IPC mining assertions still expect SpanReader errors

Source inspection shows that two error-prefix assertions in interface_ipc_mining.py will fail when IPC and pycapnp are available.

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

Details and suggested fix

IPC deserialization wraps a SpanReader in a ParamsStream, so DeserializeHashed now selects TxSegmentRecorder. The nonempty submitSolution(..., b"\x00") input fails on the transaction version read, and submitBlock(block.serialize()[:-15]) fails inside the last transaction. Both therefore report TxSegmentRecorder::read(): end of data, while the assertions at lines 548-549 and 734-735 of test/functional/interface_ipc_mining.py require a prefix containing SpanReader::read(): end of data. Update those two expected prefixes. Leave the empty-block expectation unchanged, since its header still fails in SpanReader.


Optional improvements

Link

[suggestion] · Raw-byte hash tests omit deterministic CompactSize boundaries

The new hash-equivalence suite lacks deterministic multi-byte CompactSize cases, although canonical encoding is part of the raw-byte hashing invariant.

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

Details and suggested fix

Every unmutated transaction from RandomTransaction has fewer than six inputs and outputs, scripts of at most 80/60 bytes, and witness items shorter than 72 bytes. The fixed cases are similarly small, and increasing the block's transaction count does not widen a prefix inside a transaction preimage. Add fixed input/output counts around 252/253 and script or witness-item lengths around 252/253 and 65535/65536. Compare both hashes through CheckTransactionBytes in both witness modes and through CheckBlockBytes for witness-enabled block decoding. Also replace a count prefix in an otherwise parseable transaction with a nonminimal encoding and require both paths to reject it.


Link

[suggestion] · The duplicate-input optimization lacks current measurements

The supplied performance rationale cites a historical worst-case result, which does not establish the benefit of the new pairwise/sort threshold on current code.

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

Details and suggested fix

HasDuplicateInputs replaces the single std::set loop with pairwise comparisons up to eight inputs and sorting above that threshold. The historical #14397 figure concerns the sorted-vector approach, not the new small-input branch. Report before-and-after results for DuplicateInputs, which exercises the sort branch with roughly 24,000 inputs, and CheckBlockTest, which measures CheckBlock over block 413567's 1,557 transactions. These would quantify the worst-case and whole-block gains before taking on the two-algorithm implementation of this consensus check. If the gain is negligible, retaining the base loop preserves the required behavior.


Link

[suggestion] · Splitting the vin count adds an unnecessary decoding path

The current recorder can record identical ranges around s >> tx.vin, avoiding a separate legacy-input path and the new VectorFormatter::UnserElements API.

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

Details and suggested fix

TxidHold saves an offset, TxidCommit does nothing, and TxidDiscard closes the segment at that saved offset. Place TxidHold() before the original s >> tx.vin and decide the framing from tx.vin.empty() afterward. An empty vector means exactly one canonical zero count byte was consumed, while a nonempty vector needs no framing discarded. With TxSegmentRecorder as the only current hook implementation, this preserves the ranges, batched allocation and framing rejection. It also lets VectorFormatter::Unser retain its original implementation and removes UnserElements, whose only external caller is this new split path.


Link

[suggestion] · ReadBlock short-payload rejection lacks an end-to-end test

The uninitialized-buffer path relies on rejecting short disk reads before parsing, but the block-file tests do not exercise a payload shorter than its advertised size.

Location: src/node/blockstorage.cpp:1059 (head).

Details and suggested fix

Existing blockmanager_tests cover complete reads, partial ranges, hash mismatches and junk headers; the stream EOF tests do not exercise the ReadBlock result check. Add a block file with valid magic, a complete valid block, an advertised payload length one byte larger than that block, and EOF immediately afterward with no preallocated tail. Require ReadRawBlock to return ReadRawError::IO and ReadBlock to return false. Because the complete block prefix can deserialize without consuming the missing byte, this fixture would detect a regression that ignored the read failure instead of merely failing later in the parser.


Link

[suggestion] · Parse-side allocation failure handling is undocumented

The first commit explains raw-read error handling, but also makes std::bad_alloc during ReadBlock parsing propagate instead of logging and returning false.

Location: src/node/blockstorage.cpp:1069 at 5e2430917ef5 (commit) (commit).

Details and suggested fix

Commit 5e2430917ef58525f53d6f5c2a6d65184cc6d3c4, the initial overwrite-buffer optimization, changes the catch around SpanReader{block_data} >> TX_WITH_WITNESS(block) from std::exception to std::runtime_error. A std::bad_alloc thrown while constructing transaction fields therefore escapes ReadBlock. The message explains why failure to allocate the raw buffer is not a read error, but does not explain this separate parse-side change. Amend that commit's message to state that allocation failures during parsing should propagate as well; no split or reordering is needed.


Coverage details

Earlier concerns

Earlier reports raised these, with the titles and severities shown there. This review neither republished nor resolved them.

Background

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

Documented decisions

Canonical CompactSize decoding was introduced specifically to eliminate deserialize/reserialize byte mismatches. Bitcoin Core #2884 explained that multiple encodings could deserialize to the same transaction and that such subtle mismatches could enable exploits. Its compatibility argument relied on older nodes normalizing transactions through reserialization before hashing or relay.

The raw-byte hashing path depends on this normalization no longer being necessary for accepted CompactSize fields. Both pinned base and head reject extended encodings below their respective minimum values: 253, 65536, and 4294967296. This is an encoding requirement, distinct from the separate maximum-size resource limit.

Source 1

SegWit's marker/flag framing serves backward compatibility and unambiguous parsing. BIP144 specifies a zero marker so legacy parsers cannot interpret the extended form as a valid transaction. It explicitly rejects using only a zero marker because empty transactions used in tests would then be mistaken for extended data. The nonzero flag is a bitvector reserved for extensibility; BIP141 currently requires 0x01.

The affected parser must distinguish a zero input count followed by a zero byte—an empty-input, empty-output transaction—from a zero marker followed by a nonzero flag. Only the latter framing is excluded from the txid preimage. Empty transactions can deserialize even though CheckTransaction subsequently rejects them.

Source 1 · Source 2

BIP141 preserves txid as SHA256d of the traditional version/input/output/locktime serialization and defines wtxid using the extended serialization, including marker, flag, and witnesses. BIP144 requires transactions with empty witness data to use the traditional serialization, making their witness hash equal to their txid. The separation keeps transaction effects identifiable independently of witness signatures and supports soft-fork-compatible witness commitments.

The historical preimages explain why hashing the entire received transaction is appropriate for wtxid only when witness framing is present, whereas txid excludes marker, flag, and witness bytes. The pinned base computes these identities by reserialization; the head records the corresponding byte ranges.

Source 1 · Source 2

Rejection of superfluous witness records enforces BIP144's requirement to use legacy encoding when all witness stacks are empty. Bitcoin Core #14039 restored this check after an earlier refactor had dropped it. Its author explicitly described the permissive behavior as mostly harmless because hashes, txids, and weights were computed from reserialized transactions.

This is a direct historical example showing why accepted-byte hashing cannot rely merely on transaction semantics. Without this rejection, extended bytes could deserialize to a transaction whose serializer emits the shorter legacy form. Both pinned parsers reject that case.

Source 1 · Source 2

CVE-2018-17144 established that checking input availability and later marking inputs spent does not substitute for rejecting repeated spends of the same output within one transaction. The disclosure explains that skipping the early check caused assertion crashes and, after a UTXO representation change, could let miners count an earlier output's value twice. The 2019 follow-up removed the option to skip duplicate-input checking and documented the crash-or-inflation consequence.

The changed duplicate detector implements a security-critical context-free invariant, not merely a redundant database check. Rejection must occur before processing that assumes distinct inputs. Historical discussion also explains that fixing block connection alone would not keep duplicate-input transactions out of the mempool.

Source 1 · Source 2 · Source 3

The earlier sorted-input proposal, Bitcoin Core #14397, sought a smaller, easier-to-review performance improvement than a probabilistic alternative. Pieter Wuille attributed vector sorting's advantage over a set to memory locality and lower allocation overhead; incremental set updates were unnecessary for this check. The proposal was closed for inactivity while needing a rebase, rather than documenting adoption of a new validation rule.

This is the historical tradeoff behind replacing per-input tree nodes with a sorted copy. It supports the optimization's provenance without making the old benchmark a present performance guarantee or changing the duplicate-spend invariant.

Source 1 · Source 2 · Source 3 · Source 4

Error ordering was recognized as observable behavior in the contemporary optimization discussion. The alternative proposal #14387 explicitly disclosed that transactions containing both duplicate and null inputs could receive a different DoS error because the first detected error would be reported. The inspected record does not establish that every diagnostic priority is itself a consensus requirement.

This distinguishes mandatory duplicate rejection from preservation of the existing reject reason when multiple checks fail. In the pinned code, duplicate checking remains after output-value checks and before null-prevout checks.

Source 1

Ralph's inferences

For a successfully parsed transaction, these constraints support byte-identical reserialization of the consumed transaction range under the same witness setting: CompactSize has a unique representation; only the understood witness flag survives parsing; extended framing requires a nonempty witness stack; and the empty-vin/zero-flag case retains both zero count bytes. Consequently, the prescribed raw-byte preimages can match reserialized txid/wtxid preimages. This is conditional on the decoder and serialization mode, not a timeless guarantee about all historically accepted encodings or every byte in the surrounding buffer.

This is the precise premise needed by raw-byte hashing. Unknown flags are rejected rather than silently dropped, and superfluous witness framing is rejected rather than normalized away. The historical CompactSize and superfluous-witness discussions demonstrate that earlier permissive decoders did not provide the same premise.

Source 1 · Source 2

Duplicate-outpoint equivalence is equality of both the previous transaction ID and output index, regardless of scriptSig, sequence, or witness. In the pinned COutPoint definition, ordering compares the same pair that equality compares, so set-equivalence and equality of adjacent sorted outpoints express the same relation. Sharing only a transaction ID or only an index is insufficient.

This identifies the exact relation that the pairwise and sorted-copy paths must preserve. The pinned base and head also retain the same first-failure position and bad-txns-inputs-duplicate reason; that diagnostic preservation is separate from the CVE's requirement to reject repeated spends before unsafe processing.

Source 1

Unresolved disagreements

The historical discussion did not resolve whether the measured duplicate-check speedup justified added complexity. John Newbery requested an end-to-end cost/benefit argument; Pieter Wuille was not convinced either optimization was needed; Gregory Maxwell noted that relay-before-validation reduced propagation urgency and suggested validity caching might yield greater benefits.

The earlier proposal supplies an implementation tradeoff and benchmark context, not settled evidence that duplicate checking remains a dominant block-read or propagation cost. These historical reservations do not determine the correctness or value of the present change.

Source 1 · Source 2 · Source 3