Repository navigation
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, this pull request conflicts with the following ones:
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.
Possible places where comparison-specific test macros should replace generic comparisons:
2026-10-03 07:29:49 |
821d4c2 to
34d9d3d
Compare
|
The PR description describes IBD speedup. But, wouldn't the point of something like this be that we could process messages while validating at steady-state, so a block that takes a long time to validate does not hold up responding to compact block transaction requests or other messages? And eventually we could also process competing sibling blocks in parallel? |
34d9d3d to
5922474
Compare
|
@andrewtoth Yes, keeping other peers responsive during block validation, including at the tip, is the main motivation. I used IBD as a repeatable workload with sustained validation to measure that benefit. The shorter IBD time was a secondary observation; the main measured gains were faster PING/PONG and block-serving responses, as shown in the table. Your compact-block example fits. Parallel validation of competing sibling blocks would require further work on shared chainstate and synchronization. This PR keeps a single worker processing blocks serially. I see this separation of networking and block processing, along with fewer unnecessary waits for cs_main, as a starting point for further concurrency improvements. |
Pass a caller-owned BlockValidationState through ProcessNewBlock's CheckBlock and AcceptBlock stages, keeping chain-activation states local. Update callers to supply fresh states while preserving synchronous BlockChecked delivery, processing success, and new_block semantics. Cover initial rejection, valid and duplicate submissions, and a block that passes admission but fails validation when connected. This prepares callers to distinguish initial validation results from future completion, following the API preparation in PR bitcoin#18963.
Move BlockProcessingResult from PeerManagerImpl into the validation API and return it from ProcessNewBlock instead of returning bool and writing new_block through an output parameter. Update all callers while keeping validation, notifications, and peer completion synchronous. Preserve both outcomes independently, including new_block remaining true on a write failure. Neither field implies full consensus validity. Extend the initial-state regression test to check both result fields and exercise a real block-file write failure. Capture and assert its expected error notification to keep successful test output clear. This prepares the API for a future carrying both completion outcomes.
Wrap BlockProcessingResult in a future, fulfilling its promise at each existing return. Keep validation synchronous and fulfill successful completion after active and historical chainstate activation. Update callers to consume the ready future before their existing completion actions, preserving initial-state reporting, both result fields, and notification ordering. Explicitly discard unused test results for libc++ compatibility. Check future validity and immediate readiness in the existing outcome regression scenarios.
Retain completion futures for full blocks, completed compact blocks, and optimistic reconstruction. Poll without waiting, pausing new-message dequeuing and the normal send loop for the submitting peer while its completion is pending. Continue servicing previously queued getdata and orphan work before checking for pending block processing. Keep records in the peer manager by peer ID and poll them even when no peers remain, so download cleanup survives source disconnection. Preserve newer source attribution, check optimistic transaction validity at completion, and apply punishment before dequeuing another message. Handle failed futures without letting exceptions escape the message loop. Add controlled-future coverage for peer pause/resumption, queued getdata work, ordinary messages from other peers, disconnection, completion ordering, and errors. Validation still executes synchronously and returns ready futures.
Add a single-worker FIFO with owned blocks, processing callbacks, and completion futures. Accept submissions while running and complete futures with either a result or the callback's exception. Report inactive or stopping queues without retaining the submitted work. Make ChainstateManager own the queue. Support explicit startup, interruption, and draining shutdown, and stop before node and test dependencies are removed. Keep the kernel context alive throughout manager destruction. Move BlockProcessingResult into the queue header without changing its API. Add tests covering lifecycle, ownership, exceptions, FIFO processing, concurrent producers and shutdown, and callback submission. Production startup leaves the worker inactive and ProcessNewBlock remains synchronous; validation admission, worker processing, and completion wakeups follow separately.
Exclude received blocks awaiting processing completion from automatic download selection and compact-block reconstruction. Avoid attributing download stalls to peers when local processing holds back or advances the download window.
Run initial validation and admission on the caller, then submit blocks needing storage for persistence and chain activation. Retain inline execution before the queue is started for kernel, fuzz, and other standalone callers. Return initial errors directly and deferred cached-invalid outcomes through the future so peer attribution remains tied to each submission. Notify listeners when completions become available and adapt blocking callers to the split result contract.
Start the block-processing queue during node and ordinary test setup. Keep fuzz and kernel callers on the inline path, and stop the worker before its callback, networking, mempool, and index dependencies are destroyed. Add coverage for queued parent invalidation, duplicate rejection attribution, pending downloads and stalling, disconnected sources, and worker-gate and subscriber lifetimes.
Move mapBlockSource from cs_main to a PeerManager bookkeeping mutex, following the source-attribution change in PR bitcoin#18963. Source insertion and ordinary completion cleanup can run while validation holds cs_main. Skip BlockChecked work for blocks with no peer source before acquiring cs_main. This keeps local block processing from waiting unnecessarily when BlockChecked notifications are subsequently moved to the callback queue. Recheck the source after acquiring both locks for peer-supplied blocks. Acquire cs_main before the new mutex where chain state is also needed, matching the modern PeerManager lock order. Preserve source ownership, compact-block punishment exceptions, and callback ordering. Add a regression that completes source cleanup while another thread holds cs_main.
Deliver BlockChecked through the validation task runner, retaining the block and validation state until delivery. Keep peer completions pending until a queued marker has run so validation feedback precedes source cleanup and message processing resumption. Wait for queued results before unregistering mining catchers. Adapt the network fuzz targets to a scoped scheduler and serial runner, with explicit callback and completion draining between messages, so callbacks can acquire cs_main without blocking the emitter under that lock. Cover queued ownership, callback ordering, peer teardown, and the fuzz runner's deferred delivery. Cover no-source BlockChecked callbacks completing while cs_main is held, using the fast path installed by the preceding block-source mutex change.
Move per-peer in-flight blocks and download/stalling timers out of CNodeState, following PR bitcoin#16324. Protect them, mapBlocksInFlight, and the downloading-peer count with the block bookkeeping mutex. Serialize request registration and cleanup with peer removal, retaining the Peer until its request entries are cleared. Keep cs_main for chain dependent reads and preserve request selection, limits, and timeouts. When new_block is true, skip the redundant optimistic validity recheck and its chain-lock acquisition after request cleanup. Retain the recheck for completions with new_block=false. Add a regression that registers and completes requests for both full blocks and optimistic reconstructions while another thread holds cs_main. Freeze its node clock so the completion timestamp assertion cannot race a wall-clock second boundary.
Skip taking the chain lock when a peer has no orphan transactions to reconsider. Defer the remaining send work when cs_main is unavailable so the shared message handler can service other peers. Keep fee-filter calculation inside the successful chain-lock scope so block validation cannot acquire the mempool lock before the calculation. Require cs_main in the helper's lock annotation. Add a regression covering PING/PONG output, punishment, and deferred header requests while another thread holds cs_main.
Use the validated header already stored with the download request to determine SegWit activation. This lets BLOCKTXN bookkeeping and reconstruction proceed under m_block_mutex while another block is being validated. Release the lock before the existing admission checks. Add a regression covering unexpected responses and reconstruction failures while another thread holds cs_main, including full-block fallback.
Clear other peers' requests after successful initial admission of an optimistically reconstructed compact block, following bitcoin#16324. Pending processing still suppresses automatic downloads and pauses the source until its completion and validation callbacks have been handled. Remove the optimistic flag from pending completions and the remaining completion-time validity recheck under cs_main. Cover admission with a parked worker, queued duplicates, source disconnection, initial rejection, and interrupted submission. Validation: 41 unit tests passed in regular and ThreadSanitizer builds; six compact-block, invalid-block and unrequested-block functional tests passed.
5922474 to
28aa6cc
Compare
|
🐙 This pull request conflicts with the target branch and needs rebase. |
|
Concept ACK I think it would be great to finally get this rolling. However, I'm not sure if this should be one big pull request. Reviewing the pure validation changes with the net processing changes at once seems a bit much. A good candidate for a first pull request seems to me changing AcceptBlock to write blocks without holding cs_main in the meantime. |

The shared P2P message thread currently waits for block processing to finish before it can process messages from other peers.
This PR moves block processing to a dedicated worker after the initial checks, following the approach of #18963 and #16324:
cs_main, the chain lock.cs_mainis busy,SendMessages()defers work such as requesting headers, blocks or transactions and announcing new blocks or transactions. This allows the P2P message thread to move on to other peers.A controlled 10,000-block IBD benchmark showed these response-time improvements, measured as the median of four per-run medians:
With four download connections, the median time to download and validate the 10,000 tested blocks during IBD fell by approximately 5%, from 473.6 s to 450.3 s.
The comparison used matching Clang 18 Release builds of baseline
4519933391ddand this branch, mainnet blocks 910,489 - 920,488, one local source node, and-assumevalid=0 -blocksonly=1. Each setup ran four times per build. PINGs ran at 10/s; the block probe requested the same previously validated block after warmup, at most once per second, timing receipt of the full block.These results apply to this controlled IBD workload; they do not establish gains for other services, hardware, or network conditions. Performance outside IBD was not measured.
Tests and test infrastructure account for approximately 67% of the diff. Production code and build integration account for 1,132 changed lines (883 additions and 249 deletions).
I’m opening this PR as a draft primarily to gather feedback on the overall approach.