Skip to content

fix(consensus): guard nil/out-of-range validator lookup in vote index validation - #1331

Merged
lklimek merged 2 commits into
v1.6-devfrom
fix/consensus-vote-validator-index-nil-deref
Jun 12, 2026
Merged

lklimek merged 2 commits into
v1.6-devfrom
fix/consensus-vote-validator-index-nil-deref

Conversation

@lklimek

@lklimek lklimek commented Jun 12, 2026 •

Copy link
Copy Markdown
Collaborator

Issue being fixed or feature implemented

PR #1329 (merged to v1.6-dev at commit 8ab6adbf25294b83d92beae2fbf2572bba918eba) introduced a nil-pointer panic in the vote-add path. CI surfaced it as:

panic: runtime error: invalid memory address or nil pointer dereference
  types/validator_set.go:371                       <- nil deref happens HERE
  internal/consensus/state_add_vote.go:96          <- new code added by #1329 calls into it
  internal/consensus/state_add_vote_test.go:162    <- #1329's own new test that triggers it

Root cause. As part of validating the vote validator index, #1329 switched addVoteToVoteSetFunc from looking the voter up against stateData.state.Validators to stateData.Validators (the embedded RoundState set). When RoundState.Validators is unset, vals.GetByIndex(vote.ValidatorIndex) becomes a method call on a nil *ValidatorSet, and the len(vals.Validators) bounds check inside GetByIndex (types/validator_set.go:371) dereferences the nil receiver. The panic happens inside GetByIndex, before the if val != nil guard #1329 added at the call site can take effect — so that guard never gets a chance to reject the lookup.

What was done?

Made ValidatorSet.GetByIndex honor its documented contract on a nil receiver. The method already documents that it returns nil for an out-of-range index, and its sibling methods (Copy, Equals, IsNilOrEmpty, VerifyCommit, ...) all guard a nil receiver. This extends GetByIndex to do the same — returning nil instead of panicking when vals == nil:

func (vals *ValidatorSet) GetByIndex(index int32) *Validator {
	if vals == nil || index < 0 || int(index) >= len(vals.Validators) {
		return nil
	}
	return vals.Validators[index].Copy()
}

The fix is intentionally placed at the exact panic site (types/validator_set.go:371) rather than at one call site, so it protects every caller. The nil-check that #1329 already added at each call site (state_add_vote.go:96, state_add_vote.go:256, state_apply_commit.go:128) then handles the nil result correctly: an invalid/nil lookup skips the metric / rejects the vote instead of crashing the node.

state_add_vote.go itself is left untouched — #1329's guards there are correct once GetByIndex stops panicking on a nil receiver.

A regression test (TestValidatorSetGetByIndexNilReceiver) asserts GetByIndex never panics on a nil receiver for negative, zero, in-range, and out-of-range indexes.

How Has This Been Tested?

  • Reproduced the panic at the merged HEAD (8ab6adbf2): TestAddVote/TestAddVoteToVoteSet/1 panicked at types/validator_set.go:371 via state_add_vote.go:96.
  • After the fix, the full internal/consensus AddVote suite (TestAddVote, TestAddVoteValidatorIndexBounds, TestAddVoteVerifyExtensionMwIndexNotInStateValidators) passes with no panic.
  • New TestValidatorSetGetByIndexNilReceiver passes; full ./types/ package is green.
  • gofmt/lint clean on changed files (types/validator_set.go, types/validator_set_test.go).

Commands (CGO + BLS, build tags tenderdash netgo osusergo):

  • go test ./internal/consensus/ -run 'TestAddVote|TestAddVoteValidatorIndexBounds|TestAddVoteVerifyExtensionMwIndexNotInStateValidators' -v
  • go test ./types/ -run 'TestValidatorSetBasic|TestValidatorSetGetByIndexNilReceiver' -v
  • go test ./types/

Breaking Changes

None. GetByIndex already promised to return nil for invalid input; this only stops it from panicking on a nil receiver. All callers either already nil-check the result or operate on non-nil sets, so behavior is strictly safer.

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

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Fixed a crash condition in validator retrieval that occurred when processing nil validator sets. The method now safely returns nil instead of panicking.
  • Tests

    • Added comprehensive test coverage to verify nil validator set handling across various edge cases.

…idation

PR #1329 (commit 8ab6adb) switched addVoteToVoteSetFunc to look up the
voter against stateData.Validators (RoundState) instead of
stateData.state.Validators. When RoundState.Validators is unset, that
turned GetByIndex into a method call on a nil *ValidatorSet, and the
len(vals.Validators) bounds check in GetByIndex dereferenced the nil
receiver, panicking before the new `if val != nil` guard could help:

  panic: runtime error: invalid memory address or nil pointer dereference
    types/validator_set.go:371
    internal/consensus/state_add_vote.go:96
    internal/consensus/state_add_vote_test.go:162

GetByIndex already documents that it returns nil for an out-of-range
index, and its sibling methods (Copy, Equals, IsNilOrEmpty, ...) all
guard a nil receiver. This extends GetByIndex to honor the same contract
on a nil receiver, returning nil instead of panicking. The nil-check that
#1329 added at every call site then handles the result correctly, and all
other callers are strictly safer.

Adds a regression test asserting GetByIndex never panics on a nil
receiver for any index.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@lklimek
lklimek requested a review from QuantumExplorer as a code owner June 12, 2026 09:25
@coderabbitai

coderabbitai Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a67d417b-df33-45e2-a327-20d5ae73461f

📥 Commits

Reviewing files that changed from the base of the PR and between faae10f and 8e1ffbb.

📒 Files selected for processing (2)
  • types/validator_set.go
  • types/validator_set_test.go

📝 Walkthrough

Walkthrough

(*ValidatorSet).GetByIndex is hardened to safely return nil when called on a nil receiver, replacing a potential panic with graceful nil handling. The method documentation is clarified, and a test validates the new behavior across representative indices.

Changes

Validator Set Nil-Receiver Safety

Layer / File(s) Summary
Nil-receiver safety for GetByIndex
types/validator_set.go, types/validator_set_test.go
GetByIndex adds a nil receiver check before accessing vals.Validators, preventing panics on nil receivers and returning nil instead. Documentation updated to clarify the bounds behavior. New test TestValidatorSetGetByIndexNilReceiver validates the method returns nil and does not panic for several index values (-1, 0, 1, 100).

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Poem

🐰 A method once panicked with nil in its hand,
Now checks with such care, a defensive command,
With tests standing guard on the boundary line,
The ValidatorSet's GetByIndex now shines! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: fixing a nil-pointer panic by adding nil-safety guards to ValidatorSet.GetByIndex for validator lookup during vote validation.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/consensus-vote-validator-index-nil-deref

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 requested a review from Copilot June 12, 2026 09:26

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 fixes a nil-pointer panic in consensus vote processing by making (*types.ValidatorSet).GetByIndex safe to call on a nil receiver, matching the method’s documented “return nil on invalid input” contract, and adds a regression test to ensure it never panics.

Changes:

  • Updated ValidatorSet.GetByIndex to return nil when called on a nil receiver (instead of panicking).
  • Clarified the method’s doc comment to include the nil-receiver behavior.
  • Added a unit test to assert GetByIndex does not panic on a nil receiver across several index values.

Reviewed changes

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

File Description
types/validator_set.go Adds a nil-receiver guard to GetByIndex and updates its documented contract.
types/validator_set_test.go Adds a regression test ensuring GetByIndex never panics when the receiver is nil.

Comment thread types/validator_set.go
Comment on lines 366 to +369
// GetByIndex returns the validator's address and validator itself (copy) by
// index.
// It returns nil values if index is less than 0 or greater or equal to
// len(ValidatorSet.Validators).
// It returns nil if the receiver is nil, or if index is less than 0 or greater
// or equal to len(ValidatorSet.Validators).
@lklimek
lklimek merged commit 50ed453 into v1.6-dev Jun 12, 2026
16 checks passed
@lklimek
lklimek deleted the fix/consensus-vote-validator-index-nil-deref branch June 12, 2026 09:50
lklimek added a commit that referenced this pull request Jun 12, 2026
…(follow-up to #1331) (#1334)

* fix(types): guard nil receiver in ValidatorSet.Size/TotalVotingPower (follow-up to #1331)

#1331 hardened GetByIndex but left Size() and TotalVotingPower() with
bare nil-pointer dereferences. A nil *ValidatorSet receiver on either
method panics at len(vals.Validators). Since TotalVotingPower delegates
to Size, a single guard in Size fixes both.

Add regression tests matching the GetByIndex nil-receiver test pattern
added in #1331.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(types): nil-harden remaining ValidatorSet receiver methods

Guard HasProTxHash, GetByProTxHash, GetProTxHashes,
GetProTxHashesAsByteArrays, GetPublicKeys, GetProTxHashesOrdered, and
Iterate with a leading `vals == nil` check so callers on a nil set
receive the documented zero value instead of a panic.

Extends PR #1334 which guarded Size/TotalVotingPower; all previously
guarded methods (GetByIndex, Size, Copy, Equals, IsNilOrEmpty, Hash,
String variants, MarshalZerologObject, ToProto) are left untouched.

Regression tests added in TestValidatorSetNilReceiverHardened
(table-driven, one sub-test per newly-hardened method).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

---------

Co-authored-by: Claude Sonnet 4.6 <[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.

2 participants