Skip to content

fix(types): input validation and bounds checks - #1342

Merged
lklimek merged 6 commits into
v1.6-devfrom
fix/types-validation-bounds
Jun 17, 2026
Merged

lklimek merged 6 commits into
v1.6-devfrom
fix/types-validation-bounds

Conversation

@lklimek

@lklimek lklimek commented Jun 15, 2026 •

Copy link
Copy Markdown
Collaborator

Why this PR exists

  • Problem: a few entry points in the types package accept values without fully validating their ranges or bounding resource use, and the threshold-signature recoverer aborts the process on inconsistent input instead of returning an error.
  • What this prevents: out-of-range or inconsistent inputs are rejected early (before allocation) and surfaced as errors, rather than producing incorrect behavior, excessive memory allocation, or a process abort.

What was done

  • Bound PartSetHeader.Total to MaxBlockPartsCount in ValidateBasic, so an oversized declared part count is rejected on the proposal path (Proposal → BlockID → PartSetHeader.ValidateBasic) before allocation.
  • Bind a block part's outer Index to its proof Index in both Part.ValidateBasic and PartSet.AddPart, preventing a part from being relabeled into another slot. Adds the ErrPartSetIndexMismatch sentinel.
  • Make the threshold-signature recoverer return errors instead of terminating: NewSignsRecoverer now returns (*SignsRecoverer, error), and the count-mismatch, non-precommit, and AddThresholdSignature paths return errors that propagate to the recovery call site. (The quorum-time hard failure is left intentional and documented.) All in-tree callers are updated.
  • Cap the number of tracked peer majority claims per vote set (maxPeerMaj23s), dropping excess claims from unseen peers without erroring so honest peers are not disconnected.

How Has This Been Tested?

  • Added table-driven tests for each change.
  • go build ./..., go test ./types/..., and -race runs over the changed areas (PartSet / SignsRecoverer / VoteSet) pass locally; CI runs the full suite.

Breaking Changes

  • NewSignsRecoverer signature changes from *SignsRecoverer to (*SignsRecoverer, error). It is exported from the types package; all in-repo callers are updated in this PR. External importers that construct a recoverer directly will need to handle the returned error.

Checklist

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have made corresponding changes to the documentation (n/a)

Attribution

🤖 Co-authored by Claudius the Magnificent AI Agent

Summary by CodeRabbit

  • New Features

    • Added bounded tracking for peer 2/3 majority claims in vote sets.
    • Enforced stricter part set header validation, including a total upper bound.
  • Bug Fixes

    • Improved signature recoverer construction and error handling (including vote-extension rule validation).
    • Added explicit part index/proof index mismatch checks and a dedicated mismatch error for safer insertion.
  • Tests

    • Expanded coverage for part set header boundaries, part/proof binding, vote-extension length validation, and recoverer error scenarios (plus vote set peer-cap behavior).

Tighten validation and resource bounds in the types package:

- Bound PartSetHeader.Total to MaxBlockPartsCount in ValidateBasic, so an
  oversized declared part count is rejected on the proposal path (via
  Proposal -> BlockID -> PartSetHeader.ValidateBasic) before allocation.
- Bind a block part's outer Index to its proof Index in both Part.ValidateBasic
  and PartSet.AddPart, preventing a part from being relabeled into another slot.
  Adds the ErrPartSetIndexMismatch sentinel.
- Make the threshold-signature recoverer return errors instead of terminating
  on inconsistent input: NewSignsRecoverer now returns (*SignsRecoverer, error)
  and the count-mismatch, non-precommit, and AddThresholdSignature paths return
  errors that propagate to the recovery call site. The quorum-time hard failure
  is left intentional and documented.
- Cap the number of tracked peer majority claims per vote set (maxPeerMaj23s),
  dropping excess claims from unseen peers without erroring so callers do not
  disconnect honest peers.

Adds table-driven tests for each change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a457eae0-abaf-49ac-a4c7-5628a02c8b10

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

NewSignsRecoverer is changed from returning *SignsRecoverer to (*SignsRecoverer, error), converting all internal panics to returned errors. PartSet and Part gain index/proof binding validation and a PartSetHeader.Total upper-bound check. VoteSet gains a maxPeerMaj23s cap silently dropping excess peer-majority claims and propagates recoverer-construction errors. ThresholdVoteExtension.AddThresholdSignature validates input byte lengths. All callsites, test helpers, test fixtures, and test coverage are updated accordingly.

Changes

SignsRecoverer error refactor and core validation hardening

Layer / File(s) Summary
SignsRecoverer constructor and initialization return errors
types/signs_recoverer.go
NewSignsRecoverer now returns (*SignsRecoverer, error); init, addVoteSigs, and addVoteExtensionSigs all return errors replacing previous panics on invalid vote-extension rules and mismatch counts.
PartSet and Part validation: index binding and total bounds
types/part_set.go
New ErrPartSetIndexMismatch error constant; Part.ValidateBasic checks Index == Proof.Index; PartSetHeader.ValidateBasic rejects Total > MaxBlockPartsCount; PartSet.AddPart returns ErrPartSetIndexMismatch on early index guard.
VoteSet peer maj23 cap and threshold-signs error propagation
types/vote_set.go
Introduces maxPeerMaj23s and enforces it in SetPeerMaj23 by silently dropping excess claims; recoverThresholdSigns now returns NewSignsRecoverer construction errors.
ThresholdVoteExtension length validation for signatures
types/vote_extension.go
AddThresholdSignature now validates validator and signature input byte lengths before storing, rejecting mismatches with formatted errors.

Tests covering validation changes

Layer / File(s) Summary
SignsRecoverer tests: error capture and invalid-extension scenarios
types/signs_recoverer_test.go
TestSigsRecoverer updated to capture NewSignsRecoverer error return; new TestSignsRecovererErrors covers invalid vote-extension rules across multiple table-driven subtests.
VoteSet peer cap boundary and behavior tests
types/vote_set_test.go
New TestSetPeerMaj23Cap validates cap acceptance, silent dropping, bounded growth, no-op repeats, and conflict errors using deterministic binary-encoded peer identifiers.
PartSet validation tests: Total bounds and index/proof binding
types/part_set_test.go
TestPartSetHeaderValidateBasicTotal covers boundary values; TestProposalPartSetHeaderTotalPropagation asserts oversized-Total validation chain; TestPartIndexProofBinding verifies index/proof binding and mismatch behavior.

Test callsites and helpers

Layer / File(s) Summary
Callsites adopt two-step recoverer: construct, assert, then recover
types/validation_test.go, internal/state/helpers_test.go, internal/state/test/factory/block.go, internal/state/validation_test.go, light/helpers_test.go
All callers of NewSignsRecoverer split into construction, require.NoError assertion, then separate Recover() call.
store_test.go makeTestCommit: add testing.T and explicit error assertions
internal/store/store_test.go
makeTestCommit now accepts *testing.T and asserts SignVote/Recover errors with require.NoError; all test usages updated to pass testing.T.
Test fixtures: BlockID.PartSetHeader.Total reduced to valid bounds
types/vote_test.go, types/evidence_test.go, types/proposal_test.go
Vote, evidence, and proposal test fixtures change BlockID.PartSetHeader.Total from large values (MaxInt32, 1000000) to 1 to satisfy new PartSet validation bounds.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant NewSignsRecoverer
    participant init as sigs.init
    participant addVoteExtensionSigs

    Caller->>NewSignsRecoverer: votes []*Vote
    NewSignsRecoverer->>init: sigs.init(votes)
    loop each vote
        init->>addVoteExtensionSigs: validate extension state
        alt extension rule violation or count mismatch
            addVoteExtensionSigs-->>init: fmt.Errorf(...)
            init-->>NewSignsRecoverer: error
            NewSignsRecoverer-->>Caller: nil, error
        else valid
            addVoteExtensionSigs-->>init: nil
        end
    end
    init-->>NewSignsRecoverer: nil
    NewSignsRecoverer-->>Caller: *SignsRecoverer, nil
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested reviewers

  • QuantumExplorer
  • thepastaclaw

🐇 A hop and a skip through the code today,
Panics replaced with errors—hooray!
The peer cap holds, the parts align,
Index and proof now match just fine.
From MaxInt32 to 1 we go,
Safe and sound, with errors in tow! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.93% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix(types): input validation and bounds checks' accurately and concisely summarizes the main focus of the changeset—adding validation and bounds checking throughout the types package.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/types-validation-bounds

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@lklimek
lklimek marked this pull request as ready for review June 15, 2026 11:53
@lklimek
lklimek requested a review from QuantumExplorer as a code owner June 15, 2026 11:53
@thepastaclaw

thepastaclaw commented Jun 15, 2026 •

Copy link
Copy Markdown

✅ Review complete (commit 9d7a400)

@thepastaclaw thepastaclaw left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

PR cleanly delivers its stated goals: PartSetHeader.Total bounded before allocation in ValidateBasic, Part.Index pinned to Proof.Index in both ValidateBasic and AddPart, NewSignsRecoverer returns errors instead of aborting on inconsistent input (with the remaining quorum-time panic documented as intentional), and maxPeerMaj23s caps peer-driven map growth without spurious peer disconnects. Test coverage tracks each change. Two non-blocking observations remain about the new code: a silent/order-dependent peer-cap drop path, and an ordering issue in addVoteExtensionSigs where state is initialized before the type guard. Claude's two findings were validated against source. Codex coverage was degraded: the Codex ACP session exited nonzero and did not produce usable review findings, so no Codex findings were carried forward.

🟡 1 suggestion(s) | 💬 1 nitpick(s)

🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `types/vote_set.go`:
- [SUGGESTION] types/vote_set.go:397-430: maxPeerMaj23s cap is silent and order-dependent — log dropped claims and document the chosen bound
  The cap correctly prevents unbounded growth of `peerMaj23s` and `votesByBlock`, but the drop path is invisible to operators and the chosen value is undocumented:

  1. **First-come-first-served, silently.** Once 256 distinct peer IDs are recorded (line 427), every later first-time peer is dropped with `return nil`. Because `votesByBlock.peerMaj23` is only set when a peer's claim is accepted (lines 433-444), the late-arriving honest peer's claim is invisible — including to the conflicting-vote bypass that gates on `!votesByBlock.peerMaj23`. On a catching-up node whose first 256 peer slots happen to be filled by stale or attacker-driven claims for the wrong block, a legitimate maj23 signal for the actual winning block can be lost with no log line or metric to attribute the loss after the fact.
  2. **256 vs. Dash LLMQ sizes.** Dash mainnet uses LLMQ types like `LLMQ_400_60` (400 members), and non-validator peers can also gossip `VoteSetMaj23Message`. 256 is plausibly above any realistic per-node peer count but is also close enough to one live quorum size that a future operator will want to know why this number was chosen. Add a justification on the `maxPeerMaj23s` doc comment ("chosen because…") and at minimum a `logger.Debug` (or a counter) on the drop path. Neither point is a blocker; flagging because silent dropping is the only safety net the reactor now has.

Comment thread types/vote_set.go Resolved
Comment thread types/signs_recoverer.go Resolved

Copilot AI 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.

Pull request overview

This PR strengthens input validation and bounds-checking in the types package to reduce DoS/memory-growth risk and to ensure inconsistent threshold-signature recovery inputs surface as errors rather than causing process aborts. It also updates in-repo call sites/tests to accommodate an exported API change (NewSignsRecoverer now returns an error).

Changes:

  • Add bounds checks for PartSetHeader.Total and bind Part.Index to its proof’s index to prevent relabeling.
  • Make NewSignsRecoverer (and related vote-extension processing) return errors instead of panicking; update call sites accordingly.
  • Cap the number of tracked peer 2/3-majority claims per VoteSet to bound peer-driven memory growth, with tests.

Reviewed changes

Copilot reviewed 15 out of 15 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
types/vote_test.go Adjust test data to stay within new PartSetHeader.Total validation bounds.
types/vote_set.go Adds maxPeerMaj23s cap and updates threshold-signature recovery to handle NewSignsRecoverer errors.
types/vote_set_test.go Adds coverage for the peer-majority cap behavior and its effect on tracked state.
types/validation_test.go Updates tests for new NewSignsRecoverer return signature.
types/signs_recoverer.go Converts constructor/init paths from panics to errors and documents the new contract.
types/signs_recoverer_test.go Updates existing tests and adds new error-path test coverage.
types/proposal_test.go Adjusts part count values to satisfy new bounds checks.
types/part_set.go Adds PartSetHeader.Total upper bound check and enforces part index/proof index binding.
types/part_set_test.go Adds tests for PartSetHeader.Total validation and part index/proof binding.
types/evidence_test.go Adjusts part count values to satisfy new bounds checks.
light/helpers_test.go Updates for new NewSignsRecoverer return signature.
internal/store/store_test.go Updates call site for new signature (but currently drops the constructor error).
internal/state/validation_test.go Updates for new NewSignsRecoverer return signature.
internal/state/test/factory/block.go Updates for new NewSignsRecoverer return signature.
internal/state/helpers_test.go Updates for new NewSignsRecoverer return signature.

Comment thread types/signs_recoverer.go Resolved
Comment thread internal/store/store_test.go Resolved
Comment thread types/vote_set.go Resolved
- raise maxPeerMaj23s to 4096 (above any realistic peer count / LLMQ size) and document the bound; log dropped claims when the cap is hit
- signs recoverer: check vote type before initializing extensions, and reject a vote whose extension count differs from the established count (was silently accepted on the zero-extension path)
- store test: handle NewSignsRecoverer/Recover errors instead of discarding them

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

Copilot AI 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.

Pull request overview

Copilot reviewed 15 out of 15 changed files in this pull request and generated 1 comment.

Comment thread types/part_set.go Resolved

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

The PR's added validation in NewSignsRecoverer leaves one concrete hole: a zero-extension vote arriving before the first extension-carrying vote silently bypasses the new mismatch detection, defeating the constructor's promised contract. A secondary defensive-depth gap remains in ThresholdVoteExtension.AddThresholdSignature where slice→array conversions can panic on malformed input; this is not reachable through normally validated votes (ValidatorProTxHash length is enforced in Vote.ValidateBasic), so it is a suggestion only. Note: validation was static; I did not run go test ./types.

🔴 1 blocking | 🟡 1 suggestion(s)

1 additional finding(s) omitted (not in diff).

🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `types/signs_recoverer.go`:
- [BLOCKING] types/signs_recoverer.go:118-130: Zero-extension vote before the first extension-carrying vote bypasses mismatch detection
  The new establishment logic only records the expected extension count from the first vote that actually carries extensions. With input order `[precommit(0 extensions), precommit(N extensions), ...]`, the first vote returns early at lines 120-122 without setting `v.voteExtensions`, the second vote then initializes `v.voteExtensions` from itself at line 123, and the length check at lines 127-130 sees `N == N` for every later vote. `NewSignsRecoverer` returns no error even though the input set is inconsistent. The added test (`zero extensions after non-zero established count`) only covers the reverse order. To honor the PR's promised constructor contract, track whether any vote has been observed (e.g., a separate `initialized` bool seeded on the first vote regardless of extension count), and reject a later non-empty extension set if earlier votes had zero, mirroring the existing reverse-direction check.

In `types/vote_extension.go`:
- [SUGGESTION] types/vote_extension.go:404-413: AddThresholdSignature panics on short validator/sig slices instead of returning an error
  `AddThresholdSignature` converts `validator` to `[crypto.ProTxHashSize]byte` and `sig` to `ThresholdSignature` ([bls12381.SignatureSize]byte) without length checks. In Go 1.20+ both conversions panic when the slice length differs from the array length. Through the normal `NewSignsRecoverer` flow this is currently shielded because `Vote.ValidateBasic` (vote.go:268) enforces `ValidatorProTxHash` length and signature verification rejects malformed signatures, but this PR is explicitly about ensuring `NewSignsRecoverer` returns errors rather than aborting the process for inconsistent input. Adding length checks here closes the defensive gap and removes a latent panic from any future caller. The fix is local: validate both lengths, return an error, and only then perform the conversion (the existing length check in `ThresholdRecover` at line 422 happens too late).

Comment thread types/signs_recoverer.go Resolved
lklimek and others added 2 commits June 15, 2026 16:58
…lidation

- signs recoverer: establish the expected vote-extension count from the first vote observed (regardless of count) so a mixed-presence set is rejected in both orders, not only when zero-extension votes arrive last
- part set: return ErrPartSetIndexMismatch from Part.ValidateBasic so callers can match it with errors.Is (PartSet.AddPart already did)
- vote extension: validate validator/signature lengths in AddThresholdSignature before the array conversion, returning an error instead of panicking on malformed input

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

Copilot AI 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.

Pull request overview

Copilot reviewed 17 out of 17 changed files in this pull request and generated no new comments.

@lklimek
lklimek requested a review from thepastaclaw June 16, 2026 11:00
@lklimek

lklimek commented Jun 16, 2026

Copy link
Copy Markdown
Collaborator Author

@thepastaclaw I need your review and approval

@lklimek

lklimek commented Jun 17, 2026

Copy link
Copy Markdown
Collaborator Author

@thepastaclaw I need your review and approval

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

PR cleanly resolves the prior recoverer/length-validation blockers. One in-scope suggestion remains: Commit.ValidateBasic does not propagate the new PartSetHeader.Total bound through BlockID.ValidateBasic, leaving CommitMessage as the only p2p-layer entry point that bypasses the validation contract the rest of this PR establishes. Go toolchain access was not granted to the Codex agent, so focused tests were not run; reasoning is from code inspection.

🟡 1 suggestion(s)

1 additional finding(s) omitted (not in diff).

🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `types/block.go`:
- [SUGGESTION] types/block.go:855-866: Propagate PartSetHeader bound through Commit.ValidateBasic
  Commit.ValidateBasic only rejects a nil BlockID; it never calls BlockID.ValidateBasic. Vote.ValidateBasic (types/vote.go:258), Proposal.ValidateBasic (types/proposal.go:78), Header.ValidateBasic (types/block.go:490), and BlockMeta.ValidateBasic (types/block_meta.go:82) all route through BlockID.ValidateBasic, which now enforces the new PartSetHeader.Total <= MaxBlockPartsCount bound this PR added. CommitMessage.ValidateBasic (internal/consensus/msgs.go:276) delegates straight to Commit.ValidateBasic, so an oversized commit BlockID.PartSetHeader.Total passes the p2p message-layer check and is only stopped later by the threshold-signature verify before NewPartSetFromHeader allocates in state_try_add_commit.go:61. That is defense-in-depth rather than a directly exploitable bug, but it leaves the exported ValidateBasic contract inconsistent with the rest of the PR. Add BlockID.ValidateBasic here so the new bound is enforced uniformly.

Commit.ValidateBasic checked for a nil BlockID but never called
BlockID.ValidateBasic(), leaving the PartSetHeader.Total > MaxBlockPartsCount
bound unenforced on the CommitMessage / p2p path.  Add the call (after the
nil check, consistent with every other ValidateBasic in the file) so an
oversized PartSetHeader.Total is rejected before allocation.

Also update TestCommit_ValidateBasic: add a dedicated case for the
oversized-Total rejection, and supply a valid StateID in the fixtures that
carry a non-nil Hash so they pass BlockID.ValidateBasic's StateID length
check (which was added as part of this PR).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

Cumulative re-review of PR #1342 at head 48220d4. The prior finding about Commit.ValidateBasic not propagating the new PartSetHeader.Total bound is FIXED in the latest commit (BlockID.ValidateBasic is now invoked from Commit.ValidateBasic, with a regression test added). No new in-scope findings: the codex-flagged vote-extension payload-identity gap in addVoteExtensionSigs is a real but pre-existing issue, present before the PR and neither introduced nor exposed/worsened by the PR's panic-to-error conversion and length/initialization tightening; recorded as out-of-scope for separate maintainer follow-up. PR is ready to merge.

@lklimek
lklimek enabled auto-merge (squash) June 17, 2026 10:29
@lklimek
lklimek merged commit 060fc07 into v1.6-dev Jun 17, 2026
16 checks passed
@lklimek
lklimek deleted the fix/types-validation-bounds branch June 17, 2026 10:45
lklimek added a commit that referenced this pull request Jun 24, 2026
…nsensus (SEC-001) (#1362)

* fix(types): stop vote-extension count mismatch from halting consensus (SEC-001)

A single Byzantine validator could broadcast a precommit for the
about-to-commit block carrying a mismatched (e.g. zero) vote-extension
count. Its own signatures are valid, so it passed every admission check
and entered votesByBlock. Once the quorum threshold was crossed,
types.SignsRecoverer either returned a length-mismatch error or - if the
bad vote was in the minimal quorum-crossing set - left too few consistent
extension shares to recover, and addVerifiedVote panicked, halting every
node (a network-wide liveness DoS). PR #1342 relocated rather than removed
this panic; v1.5.x silently skipped zero-extension precommits and so was
not affected.

Fix (both parts are needed):

- signs_recoverer.go: restore the v1.5.x behaviour - a precommit with no
  vote extensions contributes only its block signature and is skipped for
  vote-extension recovery instead of producing an error. Dropping the share
  is safe: every vote's own extension signatures are verified against its
  validator key before admission (Vote.Verify -> QuorumSignData.Verify), so
  a Byzantine validator can influence only the count of extensions it
  offers, never their content. A genuine non-zero count mismatch is still
  reported (it has no safe canonical interpretation).

- vote_set.go: addVerifiedVote no longer commits maj23 and crashes at the
  exact crossing vote. Because the BLS recovery threshold equals the
  consensus quorum threshold, the minimal crossing set may not yet hold
  enough consistent extension shares. It now tentatively sets maj23 (so the
  recoverer sees the correct quorum-reached state), attempts recovery, and
  on failure rolls maj23 back and retries as more honest votes arrive;
  maj23 is finalized only once recovery actually succeeds. A hard fail is
  retained solely for the genuinely-unattributable case where every
  validator has already voted for the block and recovery still fails.

Adds TestVoteSet_AddVote_MismatchedVoteExtensionCountDoesNotHalt, which
drives the real AddVote -> addVerifiedVote -> recovery path with the
Byzantine vote added first and asserts no panic, quorum still reached, and
a commit that verifies against the threshold public key. Updates two
TestSignsRecovererErrors cases that asserted the removed #1342 behaviour.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(types): recover vote-extensions from the count-consistent majority (SEC-001)

Follow-up to 69ef559. That commit fixed the ZERO-extension trigger but a
NON-ZERO count mismatch still halted: a Byzantine validator that precommits
the winning block with, say, 1 extension while honest validators produce 2
would, once all validators had voted, hit the retained hard-fail panic
("received vote extensions with different length") - an ATTRIBUTABLE
Byzantine input, contradicting the comment that the panic only covers
unattributable errors. Root cause: addVoteExtensionSigs seeded the canonical
extension count from the first vote and errored on any mismatch, so recovery
could never fall back to the consistent honest majority.

Fix: recover from the count-consistent majority, not the first vote.

- vote_set.go: new canonicalVoteExtensionCount groups a block's votes by
  extension count and sums each group's voting power; the canonical count is
  the one backed by >= the threshold-signature recovery power. The bar is the
  FIXED, LLMQ-type-derived recovery threshold (QuorumTypeThresholdVotingPower),
  NOT the configurable commit gate (QuorumVotingThresholdPower). This matters:
  the VotingPowerThreshold override (GO-003) can set the commit gate below 1/2
  of the power, under which two count-groups could both clear it and the
  smallest-count tie-break could wrongly pick a Byzantine count - starving
  recovery and halting the chain. The recovery threshold is always >= ~2/3
  (> 1/2) of the quorum power, so at most one group can ever reach it: the
  selection is deterministic across nodes (no fork), the tie-break is
  unreachable, and the canonical count is always the honest one under < 1/3
  Byzantine power. recoverThresholdSigns passes it to the recoverer and returns
  an error when no count reaches the threshold (handled by the existing
  retry/backstop).

- validator_set.go: add QuorumTypeThresholdVotingPower (the type-derived
  recovery threshold, ignoring the override) and route QuorumVotingThresholdPower's
  fallback through it (no behaviour change); document that QuorumVotingThresholdPower
  honors the override.

- signs_recoverer.go: WithCanonicalVoteExtensionCount makes addVoteExtensionSigs
  contribute extension shares only from votes carrying the canonical count -
  excluding a differing-count minority (zero OR non-zero) - while every vote
  still contributes its block signature. No count mismatch is treated as an
  error on this path. Excluding a vote is safe: each vote's own extension
  signatures are verified at admission, so a Byzantine validator can influence
  only the count it offers, never the content.

The retained panic now fires only when every validator has voted yet no count
is backed by the recovery threshold power (> 1/3 Byzantine, a BFT-safety
violation) or the BLS layer is broken - genuinely unattributable, as the
comment states.

Also folds in two low-severity review items:
- Document IsQuorumReached as lock-free, internal-use-only (called under
  voteSet.mtx) and non-monotonic during recovery (nil -> tentative -> nil),
  steering external callers to the locked accessors. No behaviour change.
- Make the regression test name/coverage honest.

Tests (types/vote_set_test.go):
- TestVoteSet_AddVote_InconsistentVoteExtensionCountDoesNotHalt: table-driven
  over zero-count (all voted), non-zero mismatch (all voted), non-zero mismatch
  (not all voted); each asserts no panic + valSet.VerifyCommit.
- TestVoteSet_AddVote_SubThirdCommitGateUsesRecoveryThreshold: with a sub-1/3
  VotingPowerThreshold override, a Byzantine count must NOT be selected; asserts
  the honest count is canonical and the commit verifies. Fails (halts) on revert.
- TestVoteSet_AddVote_NoRecoverableExtensionCountPanics: a > 1/3 split where no
  count reaches the recovery threshold must fire the backstop hard-fail.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(types): correct recovery-threshold comments for quorum-type variability

The three inline comments in vote_set.go and validator_set.go incorrectly
asserted that the LLMQ recovery threshold is always >= ~2/3 (> 1/2) of quorum
power. In practice some devnet/test types (LLMQType_DEVNET, TEST_DIP0024,
DEVNET_DIP0024) have exactly 50% thresholds, while all production Platform
types are >= 60%.

The uniqueness argument (at most one extension-count group can reach the
threshold) does not require > 1/2: under the standard < 1/3 Byzantine
assumption the Byzantine group holds < 1/3 < 50% <= threshold for all
supported types and therefore cannot form a qualifying group on its own.
For > 1/2 threshold types the stronger pigeonhole guarantee additionally
applies. The tiebreak is exercisable only under BFT-violating Byzantine stake.

No logic changes; comments only.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(types): build threshold-sign verification from canonical vote, not triggering vote (SEC-001)

quorumDataSigns was constructed from the just-added triggering vote
(MakeQuorumSignsWithVoteSet at line 241) and passed into
recoverThresholdSignsAndVerify. After recoverThresholdSigns selected
the canonical-count group (votes backed by >= QuorumTypeThreshold power)
and populated thresholdVoteExtSigs with canonicalCount signatures,
makeQuorumSigns() returned a QuorumSigns with VoteExtensionSignatures
of length == canonicalCount. But quorumDataSigns.VerifyVoteExtensions
checked against the *triggering* vote's extension count via
len(q.VoteExtensionSignItems) — causing a spurious length-mismatch
error whenever the triggering vote carried a Byzantine-crafted count
different from the canonical one.

Attack scenario (gate > recovery threshold, supported by validateThreshold
when VotingPowerThreshold is set): 10 validators @ 100 power, recovery=700,
commit gate=800, 3 Byzantine with ext=1 voting last. 7 honest votes (ext=2)
reach 700 (below gate); Byzantine vote 8 triggers (sum=800), recovery
succeeds with canonical count 2 but verify fails (1 vs 2 sign items) →
maj23 rollback. Same for votes 9 and 10 → all-voted backstop panic.
Deterministic liveness DoS under an operator-configurable and validated
configuration.

Fix: after recoverThresholdSigns returns, find any vote in blockVotes
whose total extension count matches len(thresholdVoteExtSigs) (the
canonical count) and build the verification QuorumSignData from it.
This guarantees sign-item count == recovered-signature count regardless
of what the triggering vote carries.

Also removes the now-dead quorumDataSigns parameter from
recoverThresholdSignsAndVerify and addVerifiedVote, and the
MakeQuorumSignsWithVoteSet call that only existed to supply it.

Adds a deterministic regression test (gate=800 > recovery=700,
Byzantine votes last) that panics pre-fix and passes with the fix.

Adds a TODO for the perf suggestion (🟡 thepastaclaw): skip BLS
recovery re-attempts when no count-group's power changed since last
attempt (deferred; correctness before optimization).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(consensus): log swallowed recovery error, reset stale threshold sigs on rollback, clarify vote-copy

Follow-up to the SEC-001 vote-extension fix in addVerifiedVote. Three
self-review items on the recovery/rollback path:

1. Observability (:342): the error from recoverThresholdSignsAndVerify was
   surfaced only on the all-votes-present panic path; on the soft-retry path it
   was silently discarded. Thread a log.Logger into types.VoteSet (no-op
   default via functional option, so existing NewVoteSet callers compile
   unchanged) and propagate the real logger from consensus State through
   HeightVoteSet. Log the failure at Debug - it is an expected, benign retry
   that fires on every post-gate vote while maj23 is unset, so Warn/Error would
   be noise. The error is NOT propagated to AddVote (callers treat that as a
   rejected/punishable vote).

2. Stale-state rollback (:361): recoverThresholdSigns may set
   thresholdBlockSig/thresholdVoteExtSigs before the later verification fails.
   The rollback previously reset only maj23, leaving stale, unverified
   signatures behind. Reset both signature fields alongside maj23 so they are
   recomputed on the next successful recovery.

3. Clarity (:365): document why the error path intentionally skips copying
   votes into voteSet.votes - the vote already lives in the persistent
   votesByBlock bucket that the next recovery attempt reads, and voteSet.votes
   is the finalization "publish" step, which must not run while maj23 is rolled
   back.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(lint): correct British spelling flagged by misspell (behaviour→behavior)

Two comment-only changes in height_vote_set.go and vote_set.go; swept all
PR-changed Go files — no further British spellings found.

Co-authored-by: Claudius the Magnificent <[email protected]>

* style(types): convert TODO(perf) to NOTE(perf) per STYLE_GUIDE

STYLE_GUIDE.md forbids TODO in source; single token change on vote_set.go:346.

Co-authored-by: Claudius the Magnificent <[email protected]>

---------

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants