1 suggestion
Optional improvements
[suggestion] · JSON REST headers reacquire cs_main for every header
With REST enabled, which is off by default, JSON header batches now incur up to 2000 avoidable cs_main acquisitions; their latency impact is unmeasured.
Location: src/rpc/blockchain.cpp:215 (head).
Details and suggested fix
rest_headers in src/rest.cpp already collects active-chain pointers and tip under one cs_main lock, then calls blockheaderToJSON after releasing it. For /rest/headers/<hash>.json?count=2000, the new WITH_LOCK runs once per returned header. Each lock only copies nTx; JSON construction stays outside the lock, and binary/hex responses bypass this path.
Capture (pindex, nTx) pairs in the existing collection loop and allow the serializer to accept the copied count for this batch. This removes the extra lock/unlock cycles while keeping the read synchronized with ReceivedBlockTransactions and taking the count from the same locked snapshot as the header list and tip. Other callers can retain the current synchronized read. In particular, avoid moving getblock's read to its initial lookup: it could capture zero before a block body arrives and GetRawBlockChecked subsequently succeeds.
Background
Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.
Documented decisions
Headers-first synchronization separates knowledge of the header tree from possession of block transactions to support parallel downloading while constraining resource-exhaustion attacks. The original proposal used a bounded moving download window, disconnected peers that stalled it, and required verified headers before requesting and storing block bodies, making a disk-fill attack require proof of work.
This explains why a CBlockIndex can exist before its transaction count is known. In both pinned versions, ReceivedBlockTransactions sets nTx when block data arrives and propagates m_chain_tx_count through descendants only once the required ancestor counts are available. These counts describe progressively acquired local knowledge, not immutable header fields.
Assumeutxo was proposed to make a node and wallet usable much sooner without abandoning eventual historical validation. Its design allows a snapshot-based chainstate to follow the network tip while another chainstate validates from genesis, temporarily relaxing the trust model until the historical work catches up.
The pinned snapshot activation code checks snapshot contents against configured assumeutxo data and seeds the snapshot base's m_chain_tx_count from that data. Earlier blocks can still lack known counts while background validation proceeds. Thus being behind the active tip does not by itself mean every transaction-count field is already populated.
Unknown transaction counts were deliberately restored to zero rather than represented by fabricated values. The historical change explained that fabricated nTx and nChainTx values could leak into RPC results and made block-index state difficult to reason about because real and artificial values were hard to distinguish.
This is the background for the pinned zero-as-unknown convention and getchaintxstats omitting totals and derived rates when the necessary counts are unavailable. HaveNumChainTxs tests availability of the cumulative count; its documented meaning does not imply full consensus validation or continued possession of block data on disk.
Keeping JSON serialization outside cs_main was an intentional concurrency optimization. A historical performance report found that JSON construction occupied most of a verbose getblock call while holding the global lock; the follow-up moved serialization outside that lock so separate calls could perform that work in parallel.
Both pinned versions retain blockheaderToJSON's AssertLockNotHeld(cs_main) with a performance comment. The head adds a short locked nTx read rather than placing the entire serializer under cs_main. The historical tradeoff is reducing time spent in a shared critical section, not treating every property reachable through a block-index pointer as immutable.
The earlier snapshot-activation discussion explicitly articulated that mutable state accessed by multiple threads must be protected by a mutex or made atomic. It emphasized that permissive behavior on one CPU architecture does not guarantee visibility, ordering, or access granularity on others.
ReceivedBlockTransactions already asserts that cs_main is held in the pinned base. The current annotations make that protection explicit for nTx, m_chain_tx_count, and HaveNumChainTxs, while the RPC changes synchronize the corresponding reads. This connects the change to an established shared-state discipline rather than a new Bitcoin consensus requirement.
Ralph's inferences
Historical validation, current block-file availability, and whether an index field can be written again are separate properties. A block's age or previous validation is therefore not a sufficient basis for assuming its transaction-count storage is permanently untouched.
The pinned receipt path explicitly handles previously pruned blocks being downloaded again and snapshot-base counts supplied before historical validation. A separate historical discussion confirms that getblockfrompeer can restore a pruned block body without reconstructing its undo record. Together these explain why RPC readers of old blocks still participate in synchronization with block-receipt processing, even when a repeated assignment has the same numerical result.
Unresolved disagreements
The original assumeutxo discussion contains competing assessments of its temporary trust relaxation: the proposal presents fast usability followed by background validation as a useful tradeoff, while objections characterize it as a significant security-model change and stress that accepting an incorrect UTXO state has different consequences from skipping historical script checks. The inspected record does not resolve that broader disagreement.
This is context for why snapshot-based operation distinguishes assumed state from historically validated state and why transaction-count availability can lag active-chain usability. It is not evidence for or against the present locking change.