Skip to content

fix(blocksync): tolerate late BlockResponse from honest peers after switching to consensus - #5959

Merged
dianab-cl merged 8 commits into
cometbft:mainfrom
JayT106:fix/blocksync-late-response-peer-disconnect
Jul 21, 2026
Merged

dianab-cl merged 8 commits into
cometbft:mainfrom
JayT106:fix/blocksync-late-response-peer-disconnect

Conversation

@JayT106

@JayT106 JayT106 commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Problem

FilterMsgBytes returned an error for any BlockResponse once the block pool had stopped (!r.pool.IsRunning()). That error panicked inside p2p/peer.go's onReceive and was recovered into StopPeerForError — a hard disconnect. Because requests for the last blocks are typically still in-flight when the catch-up ticker fires and pool.Stop() is called, both request targets (primary and secondary peer) were disconnected on every normal sync completion, exactly when the node needs them for consensus gossip.

Root cause introduced by #5860 (FilterMsgBytes). Not covered by #5950, which handles the second-peer race while the pool is still running.

Fix

Split the single || guard into two branches:

  • !r.enabled.Load() — node never ran blocksync; any BlockResponse is genuinely unsolicited → reject (unchanged behaviour)
  • !r.pool.IsRunning() — pool stopped for consensus switch; requests we sent before the transition are still in-flight; the peers are honest → allow, but still run validateMaxVotes on the response

The AddBlock call that follows returns "already committed block" and logs it; no peer state is mutated and no disconnect occurs.

pool.sendError is already a no-op once the pool is stopped (it guards on !pool.IsRunning()), so the pre-fix punishment for genuinely out-of-window responses in this window was already silently dropped the moment poolEventsRoutine exited.

The post-stop branch skips the HasPendingRequestFrom peer-identity check (any peer, not just the one we solicited, may legitimately answer a stale request) but still enforces validateMaxVotes — once the pool stops, any connected peer can reach this path, and the commit-signature cap exists to prevent a heap-amplification DoS regardless of sender. Caught by review on this PR; added a dedicated regression test (rejects oversized BlockResponse after pool stops for consensus switch) so an oversized response is still rejected in this window.


PR checklist

  • Tests written/updated
  • Changelog entry added in CHANGELOG.md
  • Updated relevant documentation (docs/ or spec/) and code comments

…witching to consensus

FilterMsgBytes rejected any BlockResponse once the block pool had stopped,
returning an error that panicked inside p2p/peer.go's onReceive and caused
StopPeerForError — a hard disconnect. Because requests for the last blocks
are typically still in flight when the catch-up ticker fires, both request
targets were disconnected on every normal sync completion, exactly when the
node needs them for consensus gossip.

Split the single || guard into two: !r.enabled.Load() still rejects responses
on nodes that never ran blocksync; !r.pool.IsRunning() now returns nil so
late in-flight responses from our own requests pass through harmlessly. The
AddBlock call that follows returns "already committed block" and logs it;
no peer state is mutated and no disconnect occurs.

Note: pool.sendError is already a no-op once the pool is stopped, so the
pre-fix punishment for genuinely out-of-window responses in this window was
already silently dropped by the time poolEventsRoutine exited.
@JayT106
JayT106 requested a review from a team as a code owner July 3, 2026 17:23
@dianab-cl

Copy link
Copy Markdown
Contributor

@greptile review

@greptile-apps

greptile-apps Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a disconnect regression introduced by #5860 where FilterMsgBytes would return an error for any BlockResponse once the block pool had stopped, causing both the primary and secondary sync peers to be disconnected right when they are needed for consensus gossip. The fix splits the !r.enabled.Load() || !r.pool.IsRunning() guard into two independent branches so that late in-flight responses arriving after the consensus switch are tolerated without triggering StopPeerForError.

  • blocksync/reactor.go: The single compound guard is split; the !r.pool.IsRunning() branch now returns validateMaxVotes(stub.BlockResponse) instead of an error, preserving the sig-count DoS guard while avoiding peer disconnection.
  • blocksync/reactor_test.go: The old "rejects BlockResponse after pool stopped" unit test is removed and replaced with two new unit test cases (allow late response; reject oversized response) and one integration test (TestPeerNotDisconnectedOnLateBlockResponseAfterConsensusSwitch) that drives the full p2p path end-to-end.

Confidence Score: 5/5

The change is safe to merge; it corrects an erroneous peer disconnect on every normal sync completion without weakening any existing guard.

The two-branch split in FilterMsgBytes is logically sound: the never-enabled path retains the hard reject, the post-stop path preserves the sig-count DoS guard via validateMaxVotes and lets the stopped pool's AddBlock absorb the late block silently. pool.sendError is a confirmed no-op when stopped, so no residual disconnect path exists. Test coverage covers both allow and reject in the new branch plus an integration test over the real p2p switch.

No files require special attention.

Important Files Changed

Filename Overview
blocksync/reactor.go Split the compound guard in FilterMsgBytes; stopped-pool branch now calls validateMaxVotes and returns nil on success, preventing spurious peer disconnects without relaxing the sig-count guard.
blocksync/reactor_test.go Removes the now-invalid 'rejects after pool stopped' case; adds two unit test cases covering the new allow/reject split and one integration test verifying the full p2p path with a real peer switch.
CHANGELOG.md Changelog entry added for the blocksync late-BlockResponse fix.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[p2p onReceive: BlockResponse bytes] --> B[FilterMsgBytes]
    B --> C{BlocksyncChannel and len gt 0}
    C -- No --> D[return nil]
    C -- Yes --> E[Unmarshal SigCountMessage stub]
    E --> F{stub.BlockResponse nil}
    F -- Yes --> D
    F -- No --> G{enabled.Load}
    G -- false --> H[error: blocksync not active / StopPeerForError]
    G -- true --> I{pool.IsRunning}
    I -- false: post-consensus switch --> J[validateMaxVotes]
    J --> K{oversized sigs}
    K -- Yes --> L[error: too many sigs / StopPeerForError]
    K -- No --> M[nil: peer kept connected]
    M --> N[Receive dispatch: handlePeerResponse goroutine]
    N --> O[AddBlock on stopped pool - already committed, logged only]
    I -- true: pool running --> P{HasPendingRequestFrom peer}
    P -- No --> Q[error: unsolicited / StopPeerForError]
    P -- Yes --> R[validateMaxVotes]
    R --> S{oversized sigs}
    S -- Yes --> L
    S -- No --> T[nil: normal block processing]
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
flowchart TD
    A[p2p onReceive: BlockResponse bytes] --> B[FilterMsgBytes]
    B --> C{BlocksyncChannel and len gt 0}
    C -- No --> D[return nil]
    C -- Yes --> E[Unmarshal SigCountMessage stub]
    E --> F{stub.BlockResponse nil}
    F -- Yes --> D
    F -- No --> G{enabled.Load}
    G -- false --> H[error: blocksync not active / StopPeerForError]
    G -- true --> I{pool.IsRunning}
    I -- false: post-consensus switch --> J[validateMaxVotes]
    J --> K{oversized sigs}
    K -- Yes --> L[error: too many sigs / StopPeerForError]
    K -- No --> M[nil: peer kept connected]
    M --> N[Receive dispatch: handlePeerResponse goroutine]
    N --> O[AddBlock on stopped pool - already committed, logged only]
    I -- true: pool running --> P{HasPendingRequestFrom peer}
    P -- No --> Q[error: unsolicited / StopPeerForError]
    P -- Yes --> R[validateMaxVotes]
    R --> S{oversized sigs}
    S -- Yes --> L
    S -- No --> T[nil: normal block processing]
Loading

Reviews (3): Last reviewed commit: "Merge branch 'main' into fix/blocksync-l..." | Re-trigger Greptile

Comment thread blocksync/reactor.go Resolved
Comment thread blocksync/reactor_test.go Resolved

@dianab-cl dianab-cl left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please check and address Greptile findings

JayT106 and others added 3 commits July 7, 2026 17:04
Greptile review on cometbft#5959 found that allowing late BlockResponses after
the pool stops also let any connected peer skip the commit-signature
cap, reopening the heap-amplification vector the guard exists to
close. Also replace a time.Sleep-based negative assertion in the new
integration test with require.Never for a deterministic wait.
…sconnect' into fix/blocksync-late-response-peer-disconnect
@dianab-cl
dianab-cl self-requested a review July 8, 2026 09:59
@dianab-cl

Copy link
Copy Markdown
Contributor

@greptile review

@dianab-cl

Copy link
Copy Markdown
Contributor

lgtm

JayT106 added a commit to JayT106/cometbft that referenced this pull request Jul 8, 2026
Greptile review on cometbft#5959 found that allowing late BlockResponses after
the pool stops also let any connected peer skip the commit-signature
cap, reopening the heap-amplification vector the guard exists to
close. Also replace a time.Sleep-based negative assertion in the new
integration test with require.Never for a deterministic wait.

@dianab-cl dianab-cl left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To fix conflicts

@dianab-cl
dianab-cl self-requested a review July 15, 2026 08:58
@dianab-cl

Copy link
Copy Markdown
Contributor

@greptile review

@mergify

mergify Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@dianab-cl
dianab-cl added this pull request to the merge queue Jul 21, 2026
Merged via the queue into cometbft:main with commit 17bb385 Jul 21, 2026
34 checks passed
@swift1337 swift1337 added backport-to-v0.38.x Tell Mergify to backport the PR to v0.38.x backport-to-v0.39.x Tell Mergify to backport the PR to v0.39.x labels Jul 27, 2026
swift1337 added a commit that referenced this pull request Jul 27, 2026
…witching to consensus (backport #5959) (#6003)

### Problem

`FilterMsgBytes` returned an error for any `BlockResponse` once the
block pool had stopped (`!r.pool.IsRunning()`). That error panicked
inside `p2p/peer.go`'s `onReceive` and was recovered into
`StopPeerForError` — a hard disconnect. Because requests for the last
blocks are typically still in-flight when the catch-up ticker fires and
`pool.Stop()` is called, both request targets (primary and secondary
peer) were disconnected on every normal sync completion, exactly when
the node needs them for consensus gossip.

Root cause introduced by #5860 (`FilterMsgBytes`). Not covered by #5950,
which handles the second-peer race while the pool is still running.

### Fix

Split the single `||` guard into two branches:

- `!r.enabled.Load()` — node never ran blocksync; any `BlockResponse` is
genuinely unsolicited → reject (unchanged behaviour)
- `!r.pool.IsRunning()` — pool stopped for consensus switch; requests we
sent before the transition are still in-flight; the peers are honest →
allow, but still run `validateMaxVotes` on the response

The `AddBlock` call that follows returns `"already committed block"` and
logs it; no peer state is mutated and no disconnect occurs.

`pool.sendError` is already a no-op once the pool is stopped (it guards
on `!pool.IsRunning()`), so the pre-fix punishment for genuinely
out-of-window responses in this window was already silently dropped the
moment `poolEventsRoutine` exited.

The post-stop branch skips the `HasPendingRequestFrom` peer-identity
check (any peer, not just the one we solicited, may legitimately answer
a stale request) but still enforces `validateMaxVotes` — once the pool
stops, any connected peer can reach this path, and the commit-signature
cap exists to prevent a heap-amplification DoS regardless of sender.
Caught by review on this PR; added a dedicated regression test (`rejects
oversized BlockResponse after pool stops for consensus switch`) so an
oversized response is still rejected in this window.

---

#### PR checklist

- [x] Tests written/updated
- [x] Changelog entry added in `CHANGELOG.md`
- [ ] Updated relevant documentation (`docs/` or `spec/`) and code
comments
<hr>This is an automatic backport of pull request #5959 done by
[Mergify](https://mergify.com).

---------

Co-authored-by: JayT106 <[email protected]>
Co-authored-by: Dmitry S <[email protected]>
JayT106 added a commit to crypto-org-chain/cometbft that referenced this pull request Jul 28, 2026
…witching to consensus (backport cometbft#5959) (cometbft#6002)

`FilterMsgBytes` returned an error for any `BlockResponse` once the
block pool had stopped (`!r.pool.IsRunning()`). That error panicked
inside `p2p/peer.go`'s `onReceive` and was recovered into
`StopPeerForError` — a hard disconnect. Because requests for the last
blocks are typically still in-flight when the catch-up ticker fires and
`pool.Stop()` is called, both request targets (primary and secondary
peer) were disconnected on every normal sync completion, exactly when
the node needs them for consensus gossip.

Root cause introduced by cometbft#5860 (`FilterMsgBytes`). Not covered by cometbft#5950,
which handles the second-peer race while the pool is still running.

Split the single `||` guard into two branches:

- `!r.enabled.Load()` — node never ran blocksync; any `BlockResponse` is
genuinely unsolicited → reject (unchanged behaviour)
- `!r.pool.IsRunning()` — pool stopped for consensus switch; requests we
sent before the transition are still in-flight; the peers are honest →
allow, but still run `validateMaxVotes` on the response

The `AddBlock` call that follows returns `"already committed block"` and
logs it; no peer state is mutated and no disconnect occurs.

`pool.sendError` is already a no-op once the pool is stopped (it guards
on `!pool.IsRunning()`), so the pre-fix punishment for genuinely
out-of-window responses in this window was already silently dropped the
moment `poolEventsRoutine` exited.

The post-stop branch skips the `HasPendingRequestFrom` peer-identity
check (any peer, not just the one we solicited, may legitimately answer
a stale request) but still enforces `validateMaxVotes` — once the pool
stops, any connected peer can reach this path, and the commit-signature
cap exists to prevent a heap-amplification DoS regardless of sender.
Caught by review on this PR; added a dedicated regression test (`rejects
oversized BlockResponse after pool stops for consensus switch`) so an
oversized response is still rejected in this window.

---

- [x] Tests written/updated
- [x] Changelog entry added in `CHANGELOG.md`
- [ ] Updated relevant documentation (`docs/` or `spec/`) and code
comments
<hr>This is an automatic backport of pull request cometbft#5959 done by
[Mergify](https://mergify.com).

---------

Co-authored-by: JayT106 <[email protected]>
Co-authored-by: Dmitry S <[email protected]>
(cherry picked from commit 6ed1d96)
JayT106 added a commit to crypto-org-chain/cometbft that referenced this pull request Jul 29, 2026
* fix(consensus): release cs.mtx before sending to statsMsgQueue (backport cometbft#5813) (cometbft#5999)

## Problem

`handleMsg` sent to `cs.statsMsgQueue` while holding `cs.mtx`. If the
buffer fills, the send blocks indefinitely — stalling the entire
consensus state machine.

## Fix

Hoist the `statsMsgQueue` send outside the `switch`, release `cs.mtx`
before the send and re-acquire after.

This also removes the duplicated `added` checks inside each `case`
block, replacing them with a single check at the bottom.

## Testing

- `TestHandleMsgReleasesLockBeforeStatsMsgQueueSend`: verifies
`GetRoundState()` is not blocked while `handleMsg` is blocked on the
send.

---

#### PR checklist

- [x] Tests written/updated
- [x] Changelog entry added in `CHANGELOG.md`
- [ ] Updated relevant documentation (`docs/` or `spec/`) and code
comments<hr>This is an automatic backport of pull request cometbft#5813 done by
[Mergify](https://mergify.com).

Co-authored-by: songgaoye <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: Dmitry S <[email protected]>
(cherry picked from commit 4f1535b)

* fix(consensus): correct loop condition in checkDoubleSigningRisk for height=1 (backport cometbft#5668) (cometbft#6000)

Fixes: cometbft#5435

When `double_sign_check_height` is set to `1`, the loop condition `i :=
int64(1); i < 1` is never satisfied, resulting in zero iterations and no
double sign checks being performed. This makes the setting functionally
equivalent to `0` (disabled), silently giving validators false
confidence in their double-sign protection.

Changed the loop condition from `i < doubleSignCheckHeight` to `i <=
doubleSignCheckHeight` so that a value of `1` correctly checks `height -
1`, matching the documented intent of the configuration parameter. The
existing guard `if doubleSignCheckHeight > height` already prevents
out-of-bounds lookups on short chains, so no additional bounds
protection is needed.

- [x] Tests written/updated
- [x] Changelog entry added in `CHANGELOG.md`
- [ ] Updated relevant documentation (`docs/` or `spec/`) and code
comments<hr>This is an automatic backport of pull request cometbft#5668 done by
[Mergify](https://mergify.com).

---------

Co-authored-by: Aditya Mishra <[email protected]>
Co-authored-by: Dmitry S <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
(cherry picked from commit 222949a)

* fix(blocksync): tolerate late BlockResponse from honest peers after switching to consensus (backport cometbft#5959) (cometbft#6002)

`FilterMsgBytes` returned an error for any `BlockResponse` once the
block pool had stopped (`!r.pool.IsRunning()`). That error panicked
inside `p2p/peer.go`'s `onReceive` and was recovered into
`StopPeerForError` — a hard disconnect. Because requests for the last
blocks are typically still in-flight when the catch-up ticker fires and
`pool.Stop()` is called, both request targets (primary and secondary
peer) were disconnected on every normal sync completion, exactly when
the node needs them for consensus gossip.

Root cause introduced by cometbft#5860 (`FilterMsgBytes`). Not covered by cometbft#5950,
which handles the second-peer race while the pool is still running.

Split the single `||` guard into two branches:

- `!r.enabled.Load()` — node never ran blocksync; any `BlockResponse` is
genuinely unsolicited → reject (unchanged behaviour)
- `!r.pool.IsRunning()` — pool stopped for consensus switch; requests we
sent before the transition are still in-flight; the peers are honest →
allow, but still run `validateMaxVotes` on the response

The `AddBlock` call that follows returns `"already committed block"` and
logs it; no peer state is mutated and no disconnect occurs.

`pool.sendError` is already a no-op once the pool is stopped (it guards
on `!pool.IsRunning()`), so the pre-fix punishment for genuinely
out-of-window responses in this window was already silently dropped the
moment `poolEventsRoutine` exited.

The post-stop branch skips the `HasPendingRequestFrom` peer-identity
check (any peer, not just the one we solicited, may legitimately answer
a stale request) but still enforces `validateMaxVotes` — once the pool
stops, any connected peer can reach this path, and the commit-signature
cap exists to prevent a heap-amplification DoS regardless of sender.
Caught by review on this PR; added a dedicated regression test (`rejects
oversized BlockResponse after pool stops for consensus switch`) so an
oversized response is still rejected in this window.

---

- [x] Tests written/updated
- [x] Changelog entry added in `CHANGELOG.md`
- [ ] Updated relevant documentation (`docs/` or `spec/`) and code
comments
<hr>This is an automatic backport of pull request cometbft#5959 done by
[Mergify](https://mergify.com).

---------

Co-authored-by: JayT106 <[email protected]>
Co-authored-by: Dmitry S <[email protected]>
(cherry picked from commit 6ed1d96)

* ci: run e2e-test on ubuntu-latest, not unavailable Depot runner

Fork has no Depot runner registered, so depot-ubuntu-24.04-4 jobs
queue indefinitely and get cancelled at the 24h timeout.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: songgaoye <[email protected]>
Co-authored-by: Dmitry S <[email protected]>
Co-authored-by: Aditya Mishra <[email protected]>
Co-authored-by: jay.tseng <[email protected]>
kevindharmawan pushed a commit to SeeMoReLab/cometbft that referenced this pull request Jul 30, 2026
…witching to consensus (cometbft#5959)

### Problem

`FilterMsgBytes` returned an error for any `BlockResponse` once the
block pool had stopped (`!r.pool.IsRunning()`). That error panicked
inside `p2p/peer.go`'s `onReceive` and was recovered into
`StopPeerForError` — a hard disconnect. Because requests for the last
blocks are typically still in-flight when the catch-up ticker fires and
`pool.Stop()` is called, both request targets (primary and secondary
peer) were disconnected on every normal sync completion, exactly when
the node needs them for consensus gossip.

Root cause introduced by cometbft#5860 (`FilterMsgBytes`). Not covered by cometbft#5950,
which handles the second-peer race while the pool is still running.

### Fix

Split the single `||` guard into two branches:

- `!r.enabled.Load()` — node never ran blocksync; any `BlockResponse` is
genuinely unsolicited → reject (unchanged behaviour)
- `!r.pool.IsRunning()` — pool stopped for consensus switch; requests we
sent before the transition are still in-flight; the peers are honest →
allow, but still run `validateMaxVotes` on the response

The `AddBlock` call that follows returns `"already committed block"` and
logs it; no peer state is mutated and no disconnect occurs.

`pool.sendError` is already a no-op once the pool is stopped (it guards
on `!pool.IsRunning()`), so the pre-fix punishment for genuinely
out-of-window responses in this window was already silently dropped the
moment `poolEventsRoutine` exited.

The post-stop branch skips the `HasPendingRequestFrom` peer-identity
check (any peer, not just the one we solicited, may legitimately answer
a stale request) but still enforces `validateMaxVotes` — once the pool
stops, any connected peer can reach this path, and the commit-signature
cap exists to prevent a heap-amplification DoS regardless of sender.
Caught by review on this PR; added a dedicated regression test (`rejects
oversized BlockResponse after pool stops for consensus switch`) so an
oversized response is still rejected in this window.

---

#### PR checklist

- [x] Tests written/updated
- [x] Changelog entry added in `CHANGELOG.md`
- [ ] Updated relevant documentation (`docs/` or `spec/`) and code
comments

---------

Co-authored-by: dianab-cl <[email protected]>
JayT106 added a commit to crypto-org-chain/cometbft that referenced this pull request Oct 30, 2026
* fix(consensus): release cs.mtx before sending to statsMsgQueue (backport cometbft#5813) (cometbft#5999)

`handleMsg` sent to `cs.statsMsgQueue` while holding `cs.mtx`. If the
buffer fills, the send blocks indefinitely — stalling the entire
consensus state machine.

Hoist the `statsMsgQueue` send outside the `switch`, release `cs.mtx`
before the send and re-acquire after.

This also removes the duplicated `added` checks inside each `case`
block, replacing them with a single check at the bottom.

- `TestHandleMsgReleasesLockBeforeStatsMsgQueueSend`: verifies
`GetRoundState()` is not blocked while `handleMsg` is blocked on the
send.

---

- [x] Tests written/updated
- [x] Changelog entry added in `CHANGELOG.md`
- [ ] Updated relevant documentation (`docs/` or `spec/`) and code
comments<hr>This is an automatic backport of pull request cometbft#5813 done by
[Mergify](https://mergify.com).

Co-authored-by: songgaoye <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: Dmitry S <[email protected]>
On v0.40.0 only the e2e runner change applies; the upstream commits are
already in v0.40.0.

(cherry picked from commit 4f1535b)

* fix(consensus): correct loop condition in checkDoubleSigningRisk for height=1 (backport cometbft#5668) (cometbft#6000)

Fixes: cometbft#5435

When `double_sign_check_height` is set to `1`, the loop condition `i :=
int64(1); i < 1` is never satisfied, resulting in zero iterations and no
double sign checks being performed. This makes the setting functionally
equivalent to `0` (disabled), silently giving validators false
confidence in their double-sign protection.

Changed the loop condition from `i < doubleSignCheckHeight` to `i <=
doubleSignCheckHeight` so that a value of `1` correctly checks `height -
1`, matching the documented intent of the configuration parameter. The
existing guard `if doubleSignCheckHeight > height` already prevents
out-of-bounds lookups on short chains, so no additional bounds
protection is needed.

- [x] Tests written/updated
- [x] Changelog entry added in `CHANGELOG.md`
- [ ] Updated relevant documentation (`docs/` or `spec/`) and code
comments<hr>This is an automatic backport of pull request cometbft#5668 done by
[Mergify](https://mergify.com).

---------

Co-authored-by: Aditya Mishra <[email protected]>
Co-authored-by: Dmitry S <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
On v0.40.0 only the e2e runner change applies; the upstream commits are
already in v0.40.0.

(cherry picked from commit 222949a)

* fix(blocksync): tolerate late BlockResponse from honest peers after switching to consensus (backport cometbft#5959) (cometbft#6002)

`FilterMsgBytes` returned an error for any `BlockResponse` once the
block pool had stopped (`!r.pool.IsRunning()`). That error panicked
inside `p2p/peer.go`'s `onReceive` and was recovered into
`StopPeerForError` — a hard disconnect. Because requests for the last
blocks are typically still in-flight when the catch-up ticker fires and
`pool.Stop()` is called, both request targets (primary and secondary
peer) were disconnected on every normal sync completion, exactly when
the node needs them for consensus gossip.

Root cause introduced by cometbft#5860 (`FilterMsgBytes`). Not covered by cometbft#5950,
which handles the second-peer race while the pool is still running.

Split the single `||` guard into two branches:

- `!r.enabled.Load()` — node never ran blocksync; any `BlockResponse` is
genuinely unsolicited → reject (unchanged behaviour)
- `!r.pool.IsRunning()` — pool stopped for consensus switch; requests we
sent before the transition are still in-flight; the peers are honest →
allow, but still run `validateMaxVotes` on the response

The `AddBlock` call that follows returns `"already committed block"` and
logs it; no peer state is mutated and no disconnect occurs.

`pool.sendError` is already a no-op once the pool is stopped (it guards
on `!pool.IsRunning()`), so the pre-fix punishment for genuinely
out-of-window responses in this window was already silently dropped the
moment `poolEventsRoutine` exited.

The post-stop branch skips the `HasPendingRequestFrom` peer-identity
check (any peer, not just the one we solicited, may legitimately answer
a stale request) but still enforces `validateMaxVotes` — once the pool
stops, any connected peer can reach this path, and the commit-signature
cap exists to prevent a heap-amplification DoS regardless of sender.
Caught by review on this PR; added a dedicated regression test (`rejects
oversized BlockResponse after pool stops for consensus switch`) so an
oversized response is still rejected in this window.

---

- [x] Tests written/updated
- [x] Changelog entry added in `CHANGELOG.md`
- [ ] Updated relevant documentation (`docs/` or `spec/`) and code
comments
<hr>This is an automatic backport of pull request cometbft#5959 done by
[Mergify](https://mergify.com).

---------

Co-authored-by: JayT106 <[email protected]>
Co-authored-by: Dmitry S <[email protected]>
On v0.40.0 only the e2e runner change applies; the upstream commits are
already in v0.40.0.

(cherry picked from commit 6ed1d96)

* ci: run e2e-test on ubuntu-latest, not unavailable Depot runner

Fork has no Depot runner registered, so depot-ubuntu-24.04-4 jobs
queue indefinitely and get cancelled at the 24h timeout.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: songgaoye <[email protected]>
Co-authored-by: Dmitry S <[email protected]>
Co-authored-by: Aditya Mishra <[email protected]>
Co-authored-by: jay.tseng <[email protected]>
On v0.40.0 only the e2e runner change applies; the upstream commits are
already in v0.40.0.

(cherry picked from commit 14b7b93)
JayT106 added a commit to crypto-org-chain/cometbft that referenced this pull request Nov 2, 2026
* fix(consensus): release cs.mtx before sending to statsMsgQueue (backport cometbft#5813) (cometbft#5999)

## Problem

`handleMsg` sent to `cs.statsMsgQueue` while holding `cs.mtx`. If the
buffer fills, the send blocks indefinitely — stalling the entire
consensus state machine.

## Fix

Hoist the `statsMsgQueue` send outside the `switch`, release `cs.mtx`
before the send and re-acquire after.

This also removes the duplicated `added` checks inside each `case`
block, replacing them with a single check at the bottom.

## Testing

- `TestHandleMsgReleasesLockBeforeStatsMsgQueueSend`: verifies
`GetRoundState()` is not blocked while `handleMsg` is blocked on the
send.

---

#### PR checklist

- [x] Tests written/updated
- [x] Changelog entry added in `CHANGELOG.md`
- [ ] Updated relevant documentation (`docs/` or `spec/`) and code
comments<hr>This is an automatic backport of pull request cometbft#5813 done by
[Mergify](https://mergify.com).

Co-authored-by: songgaoye <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: Dmitry S <[email protected]>
(cherry picked from commit 4f1535b)

* fix(consensus): correct loop condition in checkDoubleSigningRisk for height=1 (backport cometbft#5668) (cometbft#6000)

Fixes: cometbft#5435

When `double_sign_check_height` is set to `1`, the loop condition `i :=
int64(1); i < 1` is never satisfied, resulting in zero iterations and no
double sign checks being performed. This makes the setting functionally
equivalent to `0` (disabled), silently giving validators false
confidence in their double-sign protection.

Changed the loop condition from `i < doubleSignCheckHeight` to `i <=
doubleSignCheckHeight` so that a value of `1` correctly checks `height -
1`, matching the documented intent of the configuration parameter. The
existing guard `if doubleSignCheckHeight > height` already prevents
out-of-bounds lookups on short chains, so no additional bounds
protection is needed.

- [x] Tests written/updated
- [x] Changelog entry added in `CHANGELOG.md`
- [ ] Updated relevant documentation (`docs/` or `spec/`) and code
comments<hr>This is an automatic backport of pull request cometbft#5668 done by
[Mergify](https://mergify.com).

---------

Co-authored-by: Aditya Mishra <[email protected]>
Co-authored-by: Dmitry S <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
(cherry picked from commit 222949a)

* fix(blocksync): tolerate late BlockResponse from honest peers after switching to consensus (backport cometbft#5959) (cometbft#6002)

`FilterMsgBytes` returned an error for any `BlockResponse` once the
block pool had stopped (`!r.pool.IsRunning()`). That error panicked
inside `p2p/peer.go`'s `onReceive` and was recovered into
`StopPeerForError` — a hard disconnect. Because requests for the last
blocks are typically still in-flight when the catch-up ticker fires and
`pool.Stop()` is called, both request targets (primary and secondary
peer) were disconnected on every normal sync completion, exactly when
the node needs them for consensus gossip.

Root cause introduced by cometbft#5860 (`FilterMsgBytes`). Not covered by cometbft#5950,
which handles the second-peer race while the pool is still running.

Split the single `||` guard into two branches:

- `!r.enabled.Load()` — node never ran blocksync; any `BlockResponse` is
genuinely unsolicited → reject (unchanged behaviour)
- `!r.pool.IsRunning()` — pool stopped for consensus switch; requests we
sent before the transition are still in-flight; the peers are honest →
allow, but still run `validateMaxVotes` on the response

The `AddBlock` call that follows returns `"already committed block"` and
logs it; no peer state is mutated and no disconnect occurs.

`pool.sendError` is already a no-op once the pool is stopped (it guards
on `!pool.IsRunning()`), so the pre-fix punishment for genuinely
out-of-window responses in this window was already silently dropped the
moment `poolEventsRoutine` exited.

The post-stop branch skips the `HasPendingRequestFrom` peer-identity
check (any peer, not just the one we solicited, may legitimately answer
a stale request) but still enforces `validateMaxVotes` — once the pool
stops, any connected peer can reach this path, and the commit-signature
cap exists to prevent a heap-amplification DoS regardless of sender.
Caught by review on this PR; added a dedicated regression test (`rejects
oversized BlockResponse after pool stops for consensus switch`) so an
oversized response is still rejected in this window.

---

- [x] Tests written/updated
- [x] Changelog entry added in `CHANGELOG.md`
- [ ] Updated relevant documentation (`docs/` or `spec/`) and code
comments
<hr>This is an automatic backport of pull request cometbft#5959 done by
[Mergify](https://mergify.com).

---------

Co-authored-by: JayT106 <[email protected]>
Co-authored-by: Dmitry S <[email protected]>
(cherry picked from commit 6ed1d96)

* ci: run e2e-test on ubuntu-latest, not unavailable Depot runner

Fork has no Depot runner registered, so depot-ubuntu-24.04-4 jobs
queue indefinitely and get cancelled at the 24h timeout.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: songgaoye <[email protected]>
Co-authored-by: Dmitry S <[email protected]>
Co-authored-by: Aditya Mishra <[email protected]>
Co-authored-by: jay.tseng <[email protected]>

Port note (v0.40.0): only the e2e runner change applies; the upstream
commits are already in v0.40.0. Also pins buf to v1.72.0 (upstream
cometbft#6057; buf@latest needs Go 1.26.7 and broke check-proto)
and fixes the flaky TestPEXReactorSeedModeFlushStop.

(cherry picked from commit 14b7b93)
JayT106 added a commit to crypto-org-chain/cometbft that referenced this pull request Nov 4, 2026
Ports the part of fork #64 ("chore: cherry-pick missing upstream v0.39.4
commits") that v0.40.0 still needs. Its upstream backports (cometbft#5813, cometbft#5668,
cometbft#5959) are already in v0.40.0.

- Run e2e-test on ubuntu-latest: the fork has no Depot runner, so
  depot-ubuntu-24.04-4 jobs queue until the 24h timeout.
- Tolerate an already-stopped peer in TestPEXReactorSeedModeFlushStop, since
  the seed may disconnect it first (v0.40 follow-up, not in fork #64).

(cherry picked from commit 14b7b93)
JayT106 added a commit to crypto-org-chain/cometbft that referenced this pull request Nov 5, 2026
Ports the part of fork #64 ("chore: cherry-pick missing upstream v0.39.4
commits") that v0.40.0 still needs. Its upstream backports (cometbft#5813, cometbft#5668,
cometbft#5959) are already in v0.40.0.

- Run e2e-test on ubuntu-latest: the fork has no Depot runner, so
  depot-ubuntu-24.04-4 jobs queue until the 24h timeout.
- Tolerate an already-stopped peer in TestPEXReactorSeedModeFlushStop, since
  the seed may disconnect it first (v0.40 follow-up, not in fork #64).

(cherry picked from commit 14b7b93)
JayT106 added a commit to crypto-org-chain/cometbft that referenced this pull request Nov 5, 2026
* fix(mempool): AppMempool ABCI response handling, callback/cleanup, and lifecycle (#51)

* fix(mempool): AppMempool ABCI response handling, callback/cleanup, and lifecycle

* fix(mempool): don't clear seen cache on nil CheckTx response

* update ResponseCheckTx code

Port note (v0.40.0): also folds in the v0.40 review follow-ups: CHANGELOG
entry for upstream cometbft#5942, nil CheckTx response handled through the
client-error path, tests for nil ReapTxs, CheckTx internal code and the
seen cache, and stale comment fixes. The node, which owns the mempool, now
closes the AppMempool seen-cache guard in its OnStop instead of the reactor.

(cherry picked from commit 524b896)

* fix(lp2p): cap per-reactor priority queue to prevent memory-exhaustion DoS (#53)

* fix(lp2p): cap per-reactor priority queue to prevent memory-exhaustion DoS

The lp2p handleStream path reads and closes the libp2p stream before
enqueueing the decoded message. Stream and connection limits therefore
provide no backpressure against a fast peer: a slow reactor (e.g.
mempool under load) lets the priority queue grow without bound until
OOM.

Fix: add an optional maxSize cap to PriorityQueue. When the limit is
reached, Push returns ErrQueueFull and the message is dropped.
newReactorPriorityQueue now passes concurrentPoolCapacity (512) as
the cap, matching the downstream inbound channel — total per-reactor
buffer stays bounded at 1024 items before drops begin.

Drops are counted in a new p2p_messages_reactor_dropped metric and
logged at Error level so operators can detect a saturated reactor.

The autoscaler's queue-pressure signal still reads only len(inbound),
which remains correct; the priority queue is upstream pre-staging.

Fixes: unbounded per-reactor priority queue (lp2p memory-exhaustion DoS)
(cherry picked from commit 4894956)

* chore: add CHANGELOG entry for cometbft#5955

(cherry picked from commit f14ca91)

* chore: fix CHANGELOG entry wording for cometbft#5955

(cherry picked from commit 8494170)

* fix(lp2p): raise priority queue cap to 200k and make it configurable

512 was too small: normal mempool traffic from two peers (each sending
hundreds of txs) would fill the queue and drop messages before the
mempool's own deduplication cache could filter them.

Decouple the priority queue max from the pool inbound channel capacity
(which stays at 512). Add MaxQueueSize to LibP2PScaler and
LibP2PScalerOverride so operators can tune per-reactor; default is
200_000 (~200 MB at 1 KB/msg average), matching the budget noted in
review feedback.

0 means unbounded and is reserved for tests.

(cherry picked from commit d7d0c4e)

* refactor(lp2p): simplify scaler config access and fix flood count in test

Use a local scalerCfg alias in newReactorPriorityQueue to avoid
repeating the long access chain — consistent with newReactorScaler.

Raise the queue-full test flood count from 64 to 1000 so it reliably
exceeds the total buffer depth (~inbound cap 512 + workers + pq cap 16)
regardless of goroutine scheduling when run alongside other subtests.

(cherry picked from commit 51f7dea)

* fix(config): expose max_queue_size in config.toml template

max_queue_size was added to LibP2PScaler but missing from the TOML
template, so operators couldn't set it via config.toml.

(cherry picked from commit 1e85cb6)

* chore(config): move MaxQueueSize field comments to toml.go

Config struct fields don't need inline comments; the TOML template
is the right place for operator-facing documentation.

(cherry picked from commit 86115a2)

* chore(lp2p): restore original concurrentPoolCapacity comment

(cherry picked from commit c897ca8)

* chore(config): mention default max_queue_size in toml comment

(cherry picked from commit 04707e9)

* fix(lp2p): log error when priority queue is unbounded

max_queue_size = 0 disables the DoS cap silently. Emit an Error-level
log at reactor startup so operators are warned when the node is
vulnerable to memory-exhaustion from a fast peer.

(cherry picked from commit db36a5b)

* chore(config): use 200000 as example max_queue_size in toml comment

(cherry picked from commit e231e50)

* fix(config): make override MaxQueueSize a pointer to distinguish unset from explicit-unbounded

Backport of the fix from cometbft#5955's follow-up commits.
An override's MaxQueueSize as a plain int can't tell "not set in this
config" apart from "explicitly set to 0 for an unbounded reactor" -
both decode to the same zero value. Switching to *int lets nil mean
"inherit the global cap" while an explicit 0 stays a real choice.

* docs(config): trim LibP2PScalerOverride comment

* fix(autopool): evict lower-priority item instead of rejecting on full priority queue

PriorityQueue.Push capped total depth across all priority levels and
rejected any push once full, regardless of the incoming message's
priority. A burst of low-priority traffic could fill the queue and
then starve out higher-priority admissions.

Push now evicts the oldest strictly-lower-priority item to make room
for a higher-priority one. ErrQueueFull is only returned when no
lower-priority item is queued to evict.

* chore(autopool): trim eviction comments to one line each

* fix(config): preserve unset override max_queue_size across toml write and reload

Rendering an unset override MaxQueueSize as literal 0 in config.toml made it
indistinguishable from an explicit unbounded override. Regenerating the file
(e.g. via `cometbft testnet --config`) silently turned "inherit the global
cap" into "no cap", reopening the queue-exhaustion DoS.

Also move the lp2p changelog entry to the top of BUG FIXES per convention.

* fix(lp2p): count evicted messages in reactor metrics

Push() evicting a lower-priority item to make room silently dropped it:
MessagesReactorInFlight was never decremented and MessagesReactorDropped
never counted it, so eviction-based drops were invisible to metrics. Add
an onEvict callback to PriorityQueue and wire it up in the reactor pool so
evicted messages update both metrics with the evicted message's own
labels.

Also extract the duplicated case-insensitive reactor-override lookup into
a shared helper.

* remove comments

---------

Signed-off-by: JayT106 <[email protected]>

Port note (v0.40.0): synced to upstream cometbft#5955 head
(override inheritance, negative-value validation, eviction). Also folds in
the v0.40 review follow-ups: queue-full drops logged at Debug since peers
can trigger them, shared drop-metric helpers, tests pinning the default cap
and its inheritance, and an unbounded queue for the maxed-out lp2p bench.

(cherry picked from commit 76b16e0)

* ci: run e2e on ubuntu-latest and fix flaky PEX seed test (#64)

Ports the part of fork #64 ("chore: cherry-pick missing upstream v0.39.4
commits") that v0.40.0 still needs. Its upstream backports (cometbft#5813, cometbft#5668,
cometbft#5959) are already in v0.40.0.

- Run e2e-test on ubuntu-latest: the fork has no Depot runner, so
  depot-ubuntu-24.04-4 jobs queue until the 24h timeout.
- Tolerate an already-stopped peer in TestPEXReactorSeedModeFlushStop, since
  the seed may disconnect it first (v0.40 follow-up, not in fork #64).

(cherry picked from commit 14b7b93)

---------

Co-authored-by: songgaoye <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport-to-v0.38.x Tell Mergify to backport the PR to v0.38.x backport-to-v0.39.x Tell Mergify to backport the PR to v0.39.x

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants