Skip to content

fix(blocksync): validate blocksync response sender and signature count - #5860

Merged
mattac21 merged 15 commits into
mainfrom
ma/blocksync-sigs
May 11, 2026
Merged

mattac21 merged 15 commits into
mainfrom
ma/blocksync-sigs

Conversation

@mattac21

@mattac21 mattac21 commented May 11, 2026 •

Copy link
Copy Markdown
Collaborator

Adds additional validation to blocksync, ensuring before response unmarshalling that we have made a BlockRequest to the peer that is sending us a BlockResponse recently, and also that the response contains a valid amount of commit signatures (not > MaxVoteCount). To do this preunmarshal validation, we have added a MsgBytesFilter interface that Reactors can implement. Currently only BLOCKSYNC does. The FilterMsgBytes function is called for both comet P2P and libp2p implementations, inside of the onReceive function when setting up a peer for comet p2p, and inside of handleStream for libp2p, just before unmarshalling the message in both.

PR checklist

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

@mattac21
mattac21 requested a review from a team as a code owner May 11, 2026 15:43
@github-actions

github-actions Bot commented May 11, 2026 •

Copy link
Copy Markdown

The latest Buf updates on your PR. Results from workflow Protobuf Lint / lint (pull_request).

BuildFormatLintBreakingUpdated (UTC)
✅ passed✅ passed✅ passed✅ passedMay 11, 2026, 5:11 PM

@mattac21 mattac21 changed the title fix(blocksync): validate blocksync response sender and commit signs count fix(blocksync): validate blocksync response sender and signature count May 11, 2026
@greptile-apps

greptile-apps Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds pre-unmarshal validation to the blocksync reactor, introducing a MsgBytesFilter interface that allows reactors to inspect raw bytes before protobuf decoding. The blocksync Reactor implements it to reject BlockResponse messages from peers it never requested from and to cap the number of commit/extended-commit signatures using a zero-allocation stub deserializer.

  • A new SigCountMessage stub proto type (backed by NoSig zero-size elements) counts commit signatures without allocating per-entry memory, guarding against OOM-via-inflated-commit attacks; the implementation correctly accumulates counts across repeated or concatenated proto fields, closing the split-field bypass.
  • The MsgBytesFilter hook is wired into both the classic p2p/peer.go MConnection receive path (via panic, caught by mconn._recover) and the lp2p/switch.go libp2p path, with StopPeerForError used to disconnect violating peers.
  • The CHANGELOG entry is categorized under IMPROVEMENTS; given that the change defends against a DoS/OOM attack vector, placing it under BUG FIXES or a security section would be more accurate for downstream consumers.

Confidence Score: 5/5

Safe to merge; the pre-unmarshal filter is correctly wired into both transport paths and the stub deserializer properly handles all proto encoding variations including split-field and prepended-field attacks.

The stub deserializer uses full protobuf parsing (not a first-byte heuristic), so encoding tricks cannot bypass sender validation or the signature cap. Lock ordering in HasPendingRequestFrom follows the established pool.mtx then bpr.mtx pattern. The lp2p reordering (resolvePeer before unmarshal) is logically sound, and the new StopPeerForError on unmarshal failure is a reasonable hardening. Test coverage is thorough, including the split-field and first-byte-prepend bypass scenarios.

No files require special attention; all changed files are well-structured and consistent with each other.

Important Files Changed

Filename Overview
blocksync/reactor.go Adds FilterMsgBytes and validateMaxVotes; uses full SigCountMessage.Unmarshal (not a first-byte heuristic) so proto encoding tricks cannot bypass the sender or cap checks.
blocksync/pool.go Adds HasPendingRequestFrom; correctly acquires pool.mtx then bpr.mtx (consistent with existing lock ordering), no deadlock risk.
proto/tendermint/blocksync/stub.pb.go Generated stub deserializer; field numbers match the real Tendermint proto (block_response=3, block=1, ext_commit=2, last_commit=4, signatures=4). Repeated-field accumulation correctly handles split-signature payloads.
proto/tendermint/blocksync/nosig.go Zero-size NoSig type discards per-signature bytes during decode while still incrementing the slice length; correctly enables O(n) counting with minimal heap pressure.
p2p/peer.go FilterMsgBytes rejection triggers panic inside mconn.onReceive, which is already recovered by the MConnection goroutine and routed through onPeerError — same pattern as the existing 'Unknown channel' panic.
lp2p/switch.go Reorders handleStream to resolvePeer before unmarshal, enabling FilterMsgBytes to receive a valid Peer; also adds StopPeerForError on unmarshal failure (new hardening). Log messages corrected (were previously swapped between unmarshal and resolve paths).
p2p/base_reactor.go Clean addition of the optional MsgBytesFilter interface alongside the existing Reactor interface.
blocksync/reactor_test.go Comprehensive table-driven tests for FilterMsgBytes including the split-field and first-byte-bypass cases; TestStubUnmarshalAllocs validates the zero-allocation claim at 1M signatures.

Reviews (2): Last reviewed commit: "fix error string" | Re-trigger Greptile

Comment thread blocksync/reactor.go Resolved
Comment thread blocksync/reactor.go Resolved
Comment thread blocksync/reactor.go Outdated
func (r *Reactor) validateMaxVotes(peer p2p.Peer, msg []byte) error {
// using a custom struct here to do this check without paying allocation
// cost
var stub bcproto.SigCountMessage

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

unmarshaling into this custom proto struct that will do zero allocations when creating the backing slice for commit & ext commit signature. however the slice header will tell us how many of these zero cost elements the slice contains. this way the check is still fast without wasting time on allocs. the alternative here is to parse through the wire format of the proto bytes, but this was awful to implement and this custom structure felt much safer. see the proto/tendermint/blocksync/stub.proto for the proto impl of this, and proto/tendermint/blocksync/nosig.go for the go struct that we unmarshal into.

@mattac21

Copy link
Copy Markdown
Collaborator Author

@greptile re review

Comment thread blocksync/reactor.go Resolved
Comment thread blocksync/pool.go Resolved
Comment thread p2p/peer.go Resolved
Comment thread blocksync/reactor.go Resolved
Comment thread blocksync/reactor.go Resolved
Comment thread blocksync/reactor.go Resolved
Comment thread proto/tendermint/blocksync/stub.proto Resolved
Comment thread proto/tendermint/blocksync/stub.pb.go Resolved
@mattac21 mattac21 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 May 11, 2026
@mattac21
mattac21 enabled auto-merge May 11, 2026 17:14
@mattac21
mattac21 added this pull request to the merge queue May 11, 2026
bar-bera pushed a commit to berachain/cometbft that referenced this pull request May 29, 2026
cometbft#5860)

---

Adds additional validation to blocksync, ensuring _before response
unmarshalling_ that we have made a `BlockRequest` to the peer that is
sending us a `BlockResponse` recently, and also that the response
contains a valid amount of commit signatures (not > MaxVoteCount). To do
this preunmarshal validation, we have added a `MsgBytesFilter` interface
that `Reactors` can implement. Currently only `BLOCKSYNC` does. The
`FilterMsgBytes` function is called for both comet P2P and libp2p
implementations, inside of the `onReceive` function when setting up a
peer for comet p2p, and inside of `handleStream` for libp2p, just before
unmarshalling the message in both.

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

---

Backport adaptations for bera-v1.x:

- enabled atomic.Bool field NOT added.
- internal/blocksync/reactor.go was hand-edited rather than auto-merged.
- bcstub import alias used (proto/tendermint/blocksync) because bcproto
  already points to api/cometbft/blocksync/v1 in this fork.
- lp2p/* hunks dropped — no libp2p reactor in this fork.
- CHANGELOG.md not modified
- Tests
  - pool_test.go kept as is
  - reactor_test.go adapted (different imports)
  - p2p/switch_test.go dropped - needs porting (depends on
    Switch.BroadcastAsync which is not in this fork)

(cherry picked from commit 4590e7a)
bar-bera pushed a commit to berachain/cometbft that referenced this pull request May 29, 2026
cometbft#5860)

---

Adds additional validation to blocksync, ensuring _before response
unmarshalling_ that we have made a `BlockRequest` to the peer that is
sending us a `BlockResponse` recently, and also that the response
contains a valid amount of commit signatures (not > MaxVoteCount). To do
this preunmarshal validation, we have added a `MsgBytesFilter` interface
that `Reactors` can implement. Currently only `BLOCKSYNC` does. The
`FilterMsgBytes` function is called for both comet P2P and libp2p
implementations, inside of the `onReceive` function when setting up a
peer for comet p2p, and inside of `handleStream` for libp2p, just before
unmarshalling the message in both.

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

---

Backport adaptations for bera-v1.x:

- enabled atomic.Bool field NOT added.
- internal/blocksync/reactor.go was hand-edited rather than auto-merged.
- bcstub import alias used (proto/tendermint/blocksync) because bcproto
  already points to api/cometbft/blocksync/v1 in this fork.
- lp2p/* hunks dropped — no libp2p reactor in this fork.
- CHANGELOG.md not modified
- Tests
  - pool_test.go kept as is
  - reactor_test.go adapted (different imports)
  - p2p/switch_test.go dropped adapted (BroadcastAsync/Broadcast, same)

(cherry picked from commit 4590e7a)
bar-bera pushed a commit to berachain/cometbft that referenced this pull request May 29, 2026
cometbft#5860)

---

Adds additional validation to blocksync, ensuring _before response
unmarshalling_ that we have made a `BlockRequest` to the peer that is
sending us a `BlockResponse` recently, and also that the response
contains a valid amount of commit signatures (not > MaxVoteCount). To do
this preunmarshal validation, we have added a `MsgBytesFilter` interface
that `Reactors` can implement. Currently only `BLOCKSYNC` does. The
`FilterMsgBytes` function is called for both comet P2P and libp2p
implementations, inside of the `onReceive` function when setting up a
peer for comet p2p, and inside of `handleStream` for libp2p, just before
unmarshalling the message in both.

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

---

Backport adaptations for bera-v1.x:

- enabled atomic.Bool field NOT added.
- internal/blocksync/reactor.go was hand-edited rather than auto-merged.
- bcstub import alias used (proto/tendermint/blocksync) because bcproto
  already points to api/cometbft/blocksync/v1 in this fork.
- lp2p/* hunks dropped — no libp2p reactor in this fork.
- CHANGELOG.md not modified
- Tests
  - pool_test.go kept as is
  - reactor_test.go adapted (different imports)
  - p2p/switch_test.go dropped adapted (BroadcastAsync/Broadcast, same)

(cherry picked from commit 4590e7a)
fridrik01 added a commit to berachain/cometbft that referenced this pull request Jun 26, 2026
Re-forks the berachain CometBFT customizations from the bera-v1.x line
onto a fresh v0.39.x base (tag v0.39.3), establishing the bera-v0.39.x
line.

Brings over:
 - Proposer-Based Timestamps (PBTS) + removal of per-vote timestamps
 - BLS12-381 signature aggregation (aggregated commits + fast catch-up)
 - NextBlockDelay (ADR-115) and NextProposerAddress in ProcessProposal
 - validator pub-key wire format, Synchrony/Feature params, and supporting
   proto

Forward-compatible: existing bera-v1.x networks can restart on this
binary (on-disk state and consensus sign/wire bytes are byte-identical).

Upstream cometbft#5860 is intentionally excluded (arrives via the v0.39.4 rebase).
fridrik01 added a commit to berachain/cometbft that referenced this pull request Jun 26, 2026
Re-forks the berachain CometBFT customizations from the bera-v1.x line
onto a fresh v0.39.x base (tag v0.39.3), establishing the bera-v0.39.x
line.

Brings over:
 - Proposer-Based Timestamps (PBTS) + removal of per-vote timestamps
 - BLS12-381 signature aggregation (aggregated commits + fast catch-up)
 - NextBlockDelay (ADR-115) and NextProposerAddress in ProcessProposal
 - validator pub-key wire format, Synchrony/Feature params, and supporting
   proto

Forward-compatible: existing bera-v1.x networks can restart on this
binary (on-disk state and consensus sign/wire bytes are byte-identical).

Upstream cometbft#5860 is intentionally excluded (arrives via the v0.39.4 rebase).
fridrik01 added a commit to berachain/cometbft that referenced this pull request Jun 26, 2026
Re-forks the berachain CometBFT customizations from the bera-v1.x line
onto a fresh v0.39.x base (tag v0.39.3), establishing the bera-v0.39.x
line.

Brings over:
 - Proposer-Based Timestamps (PBTS) + removal of per-vote timestamps
 - BLS12-381 signature aggregation (aggregated commits + fast catch-up)
 - NextBlockDelay (ADR-115) and NextProposerAddress in ProcessProposal
 - validator pub-key wire format, Synchrony/Feature params, and supporting
   proto

Forward-compatible: existing bera-v1.x networks can restart on this
binary (on-disk state and consensus sign/wire bytes are byte-identical).

Upstream cometbft#5860 is intentionally excluded (arrives via the v0.39.4 rebase).
pull Bot pushed a commit to mtrackeros/cometbft that referenced this pull request Jul 21, 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]>
fridrik01 added a commit to berachain/cometbft that referenced this pull request Jul 23, 2026
Re-forks the berachain CometBFT customizations from the bera-v1.x line
onto a fresh v0.39.x base (tag v0.39.3), establishing the bera-v0.39.x
line.

Brings over:
 - Proposer-Based Timestamps (PBTS) + removal of per-vote timestamps
 - BLS12-381 signature aggregation (aggregated commits + fast catch-up)
 - NextBlockDelay (ADR-115) and NextProposerAddress in ProcessProposal
 - validator pub-key wire format, Synchrony/Feature params, and supporting
   proto

Forward-compatible: existing bera-v1.x networks can restart on this
binary (on-disk state and consensus sign/wire bytes are byte-identical).

Upstream cometbft#5860 is intentionally excluded (arrives via the v0.39.4 rebase).
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
cometbft#5860)

---

Adds additional validation to blocksync, ensuring _before response
unmarshalling_ that we have made a `BlockRequest` to the peer that is
sending us a `BlockResponse` recently, and also that the response
contains a valid amount of commit signatures (not > MaxVoteCount). To do
this preunmarshal validation, we have added a `MsgBytesFilter` interface
that `Reactors` can implement. Currently only `BLOCKSYNC` does. The
`FilterMsgBytes` function is called for both comet P2P and libp2p
implementations, inside of the `onReceive` function when setting up a
peer for comet p2p, and inside of `handleStream` for libp2p, just before
unmarshalling the message in both.

#### PR checklist

- [x] Tests written/updated
- [x] Changelog entry added in `CHANGELOG.md`
- [ ] Updated relevant documentation (`docs/` or `spec/`) and code
comments
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]>
fridrik01 added a commit to berachain/cometbft that referenced this pull request Aug 13, 2026
Re-forks the berachain CometBFT customizations from the bera-v1.x line
onto a fresh v0.39.x base (tag v0.39.3), establishing the bera-v0.39.x
line.

Brings over:
 - Proposer-Based Timestamps (PBTS) + removal of per-vote timestamps
 - BLS12-381 signature aggregation (aggregated commits + fast catch-up)
 - NextBlockDelay (ADR-115) and NextProposerAddress in ProcessProposal
 - validator pub-key wire format, Synchrony/Feature params, and supporting
   proto

Forward-compatible: existing bera-v1.x networks can restart on this
binary (on-disk state and consensus sign/wire bytes are byte-identical).

Upstream cometbft#5860 is intentionally excluded (arrives via the v0.39.4 rebase).
fridrik01 added a commit to berachain/cometbft that referenced this pull request Aug 13, 2026
Re-forks the berachain CometBFT customizations from the bera-v1.x line
onto a fresh v0.39.x base (tag v0.39.3), establishing the bera-v0.39.x
line.

Brings over:
 - Proposer-Based Timestamps (PBTS) + removal of per-vote timestamps
 - BLS12-381 signature aggregation (aggregated commits + fast catch-up)
 - NextBlockDelay (ADR-115) and NextProposerAddress in ProcessProposal
 - validator pub-key wire format, Synchrony/Feature params, and supporting
   proto

Forward-compatible: existing bera-v1.x networks can restart on this
binary (on-disk state and consensus sign/wire bytes are byte-identical).

Upstream cometbft#5860 is intentionally excluded (arrives via the v0.39.4 rebase).
fridrik01 added a commit to berachain/cometbft that referenced this pull request Aug 13, 2026
Re-forks the berachain CometBFT customizations from the bera-v1.x line
onto a fresh v0.39.x base (tag v0.39.3), establishing the bera-v0.39.x
line.

Brings over:
 - Proposer-Based Timestamps (PBTS) + removal of per-vote timestamps
 - BLS12-381 signature aggregation (aggregated commits + fast catch-up)
 - NextBlockDelay (ADR-115) and NextProposerAddress in ProcessProposal
 - validator pub-key wire format, Synchrony/Feature params, and supporting
   proto

Forward-compatible: existing bera-v1.x networks can restart on this
binary (on-disk state and consensus sign/wire bytes are byte-identical).

Upstream cometbft#5860 is intentionally excluded (arrives via the v0.39.4 rebase).
fridrik01 added a commit to berachain/cometbft that referenced this pull request Aug 13, 2026
Re-forks the berachain CometBFT customizations from the bera-v1.x line
onto a fresh v0.39.x base (tag v0.39.3), establishing the bera-v0.39.x
line.

Brings over:
 - Proposer-Based Timestamps (PBTS) + removal of per-vote timestamps
 - BLS12-381 signature aggregation (aggregated commits + fast catch-up)
 - NextBlockDelay (ADR-115) and NextProposerAddress in ProcessProposal
 - validator pub-key wire format, Synchrony/Feature params, and supporting
   proto

Forward-compatible: existing bera-v1.x networks can restart on this
binary (on-disk state and consensus sign/wire bytes are byte-identical).

Upstream cometbft#5860 is intentionally excluded (arrives via the v0.39.4 rebase).
tqin7 added a commit to dydxprotocol/cometbft that referenced this pull request Oct 28, 2026
…t (backport cometbft#5860) (cometbft#5863) (#66)

---

Adds additional validation to blocksync, ensuring _before response
unmarshalling_ that we have made a `BlockRequest` to the peer that is
sending us a `BlockResponse` recently, and also that the response
contains a valid amount of commit signatures (not > MaxVoteCount). To do
this preunmarshal validation, we have added a `MsgBytesFilter` interface
that `Reactors` can implement. Currently only `BLOCKSYNC` does. The
`FilterMsgBytes` function is called for both comet P2P and libp2p
implementations, inside of the `onReceive` function when setting up a
peer for comet p2p, and inside of `handleStream` for libp2p, just before
unmarshalling the message in both.

- [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#5860 done by
[Mergify](https://mergify.com).

Co-authored-by: mattac21 <[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)
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