Repository navigation
feat(consensus)!: recover a beacon from prevotes and sign precommits over the randomness-applied app hash - #1583
QuantumExplorer wants to merge 25 commits into
Conversation
…over the randomness-applied app hash At consensus version 2 the threshold signature recovered from a block's prevotes is the block's random beacon. Validators hand it to the application with ApplyBlockRandomness, and precommits and the commit sign the app hash it returns. Nothing changes before the application sets consensus version 2. - params: CONSENSUS_VERSION_2, VersionParams.RandomBeacon(), unknown consensus versions refused; proposer selection as in version 1. - vote set: WithRandomBeacon makes a prevote majority for a block count only once its threshold signature is recovered, since the majority gate can be below the recovery threshold; ThresholdBlockSignature exposes the beacon. - precommit signing: ApplyBlockRandomness with the round's beacon, state ID over the returned app hash, then ExtendVote, then sign; the state ID is cached per height, round and block so a node never signs two. - commit: carries the beacon and the final app hash; Commit.VerifyRandomBeacon checks the beacon against the quorum key over the prevote sign item and the state ID against the header with that app hash. Commits built from own precommits wait for the beacon or a peer's commit. Pre-version-2 peer commits have both fields dropped; parked commit keys include them. - BlockID.SameBlock for commit-vs-proposal comparisons; FinalizeBlock uses the commit's BlockID, applies the commit's beacon before the application's FinalizeBlock and stops on an app hash mismatch; state.LastAppHash is the commit's app hash; new State.LastBlockBeacon, which the next block's LastCommit must match. - block sync, replay, peer commits: randomness applied after ProcessProposal and before the commit's extension check, stopping on a mismatch; rollback restores the commit's BlockID, app hash and beacon. - light client and state sync use the app hash the commit signs; state sync restores LastAppHash and LastBlockBeacon from the snapshot commit at version 2. - kvstore example: toy translation sha256(app hash || beacon). Refs dashpay/platform#4682 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
|
…vation of the random beacon - A block locked in round 0 and voted again in round 1 gets the round 1 beacon: the round 1 precommit signs another final state ID, and the block commits at round 1 with that beacon. - The final state ID a validator signs is cached per block and round: a second precommit does not ask the application again, even if it would answer differently. - A node outside the validator set finalizes every block from peers' commits at consensus version 2 and reaches the validators' beacon and final app hash. - The rotate e2e network activates consensus version 2 at height 1010, so state sync, block sync and restarts run with it before the network moves back to versions 1 and 0. TestApp_Hash and TestBlock_Header compare with the app hash the commit signs instead of the header's. Refs dashpay/platform#4682 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
⛔ Final review complete — 6 blocking finding(s) (commit 5a99acf) · triage: critical |
TestRandomBeaconRelockNewBeacon copied the validator set with GetValidatorSet while the consensus goroutine was entering round 1, which moves the set's proposer index in place. Copy the set before consensus starts: the test only reads its quorum type, hash and threshold key, which do not change within the height. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…andom-beacon Bring in the review fixes of the ABCI PR: commits with malformed beacon or app hash sizes are refused, blocks whose LastCommit carries mistyped beacon fields still decode, and the kvstore picks the ApplyBlockRandomness state by block hash. The kvstore equivocation test now expects the toy translation this branch adds. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…cessProposal At consensus version 2, RequestFinalizeBlock.commit carried the commit's beacon and app hash, but local_last_commit and proposed_last_commit of the next height's PrepareProposal and ProcessProposal always carried them empty, although CommitInfo documents both as set from consensus version 2. buildLastCommitInfo now sets them at version 2, from the state, which holds the values the last block was finalized with. The proposer's copy in block.LastCommit is checked against them only when the block is validated, after ProcessProposal, so it is never passed to the application. Refs dashpay/platform#4682 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…covers Commit.app_hash is not covered by the commit's signature. Before consensus version 2 a proposer could fill a block's LastCommit with a 32-byte app hash that binds nothing; VerifyAppHash, used by light blocks and state sync, then refused the height for good, so light clients could not verify it. VerifyAppHash now returns the header's app hash whenever the signed state ID is the header's, and requires the commit's app hash to bind the state ID only otherwise. VerifyRandomBeacon still requires the commit's own app hash to be the signed one. Refs dashpay/platform#4682 Co-Authored-By: Claude Opus 5.5 <[email protected]>
… consensus version 2 The mempool's per-transaction size pre-check reserves room for the next block's last commit. From consensus version 2 that commit also carries its beacon and app hash, so TxPreCheckForState now subtracts MaxCommitRandomnessBytes when the consensus params use the random beacon, and only then. Refs dashpay/platform#4682 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings in the source-derived consensus specification (#1562). Conflict in spec/abci++/abci++_tmint_expected_behavior.md: v1.8-dev drops the Commit call from the ABCI grammar, and this branch adds check-commit and apply-randomness. The resolution keeps both, and notes that from consensus version 2 the state FinalizeBlock persists has the root ApplyBlockRandomness returned. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…andom-beacon Brings in the decoder fix and the proposal-side CommitInfo change from review. Conflict in internal/state/execution.go: the base branch builds the proposal requests' last commit info with Commit.ToCommitInfo, which copies the proposer's beacon and app hash, and this branch takes them from the state the last block was finalized with. The resolution uses ToCommitInfo for the other fields and keeps the state's beacon and app hash, leaving both empty before consensus version 2. TestProposalRequestsCarryLastCommitRandomness now expects the state's values. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…andom-beacon Co-Authored-By: Claude Opus 5.5 <[email protected]>
…andom-beacon Bring in v1.8-dev's dependency bumps through PR 1, whose merge resolved the go.mod conflict. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…andom-beacon PR 1 now drops a relayed commit's beacon and app hash when it builds a proposal. Here that applies until the last block is committed with a beacon: from then on validateBlock checks both against the state, so the commit keeps them. Commit.WithoutRandomBeacon moves to types/block.go with PR 1, and TestProposalRequestsCarryLastCommitRandomness keeps this branch's state-sourced expectations. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…andom-beacon TestMaxProposalBlockSize sets the state's last block beacon here, so the proposal keeps the commit's beacon and app hash and the commit is still at its largest, with them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…andom-beacon PR 1 now drops a commit's beacon and app hash wherever a commit is adopted. Here that applies before consensus version 2 only: - TryAddCommitAction, the block sync applier and buildLastCommitInfo keep this branch's version-aware code; - state sync drops them from the snapshot commit unless the state holds its verified beacon, and backfill keeps them only when they verify against the height's validator set; - the docs no longer say this release never calls ApplyBlockRandomness. TestProposalRequestsCarryLastCommitRandomness keeps this branch's state-sourced expectations, next to PR 1's merged TestProposalDropsRelayedCommitRandomness. The kvstore's toy randomness looks its state up by block hash only, as in PR 1. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…andom-beacon Bring in v1.8-dev (mdBook docs migration, dependency and CI updates) through PR 1, whose merge resolved the docs conflict. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…andom-beacon Brings in the dev merge from the base PR. Drops the "never calls it" line from the relocated spec/abci/methods.md, as this branch did in the old file. dev's replay fix for historical quorums returned two values from replayBlock, which returns three here, so its error path and new test are updated to match. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…andom-beacon Co-Authored-By: Claude Opus 5.5 <[email protected]>
The base branch drops the beacon and app hash of block.LastCommit from the stored previous-height commit, since nothing signs them. From consensus version 2 that record has to keep them for /commit and state sync. Keep them only when they match the commit this node saved for that height, which holds for no pre-version-2 commit and for every block validateBlock accepted after. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…andom-beacon Brings in dev through #1582's merge, including proposer liveness and round skip certificates (#1572). Conflict resolutions: - CONSENSUS_VERSION_2 keeps dev's meaning (proposer liveness); VersionParams keeps both RandomBeacon and ProposerLivenessEnabled. - execBlock and BlockReplayer.publishEvents take dev's form, finalizing with commit.BlockID (#1595), which the beacon path already required. - makeConsensusStateWithParams takes dev's signature without cfg. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…andom-beacon Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Dev's CONSENSUS_VERSION_2 now means proposer liveness (#1572), so the same-block random beacon gets its own version: - VersionParams gains CONSENSUS_VERSION_3: the beacon recovered from prevotes, with precommits signing the randomness-applied app hash. Consensus-param validation accepts it, and the proposer selector uses the height-and-round rotation for versions 1, 2 and 3. - VersionParams.RandomBeacon, the single gate for every beacon path, starts at version 3; proposer liveness stays at version 2 and later. - Comments, specs, UPGRADING and the e2e rotate network say version 3. - Beacon tests run at version 3, and new cases check that version 2 neither recovers nor applies a beacon. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…andom-beacon Co-Authored-By: Claude Opus 5.5 <[email protected]>
Stack #1583 on #1582: take the current head of the ApplyBlockRandomness ABCI surface PR so the beacon-recovery consensus change builds on it. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Audit SummaryFull multi-reviewer audit of the top of the #1582 ← #1583 stack (the merge of #1582's head into this branch), reviewed against Only the findings in this PR's consensus-version-3 layer are reported here. This is a draft (pending) review — the inline comments are not submitted. Assessment: changes requested. One blocking data-integrity defect; the rest are single-node, recoverable correctness or consistency issues that nonetheless touch consensus-critical replay, state-sync and persistence paths.
Detailed reproduction and a concrete recommendation for each finding are in the inline comments of the accompanying draft review (CALL-002, whose anchor line is outside this PR's diff, is in that review's body). Positive observations: the beacon's BLS threshold-signature recovery is sound and deterministic across honest nodes; the pre-v3 stripping and tolerant block decoding correctly keep upgraded and pre-upgrade nodes from splitting; the merge of #1582's head into this branch is clean and the touched packages pass race tests. 🤖 Co-authored by Claudius the Magnificent AI Agent |
| signedHeader := *resp.block.SignedHeader | ||
| signedHeader.Commit = signedHeader.Commit.WithoutRandomBeacon() | ||
| if signedHeader.Commit.VerifyRandomBeacon(chainID, resp.block.ValidatorSet, signedHeader.Header) != nil { | ||
| signedHeader.Commit = signedHeader.Commit.WithoutRandomBeacon() | ||
| } | ||
| if err := r.blockStore.SaveSignedHeader(&signedHeader, trustedBlockID); err != nil { | ||
| return err | ||
| } |
There was a problem hiding this comment.
CODE-002 · MEDIUM · BLOCKING — State sync backfill strips AppHash and Beacon on a tampered v3 beacon, persisting an unverifiable commit in BlockStore
Introduced in 0ef2a67b7 and updated in ebd8cc2f5 (internal/statesync/reactor.go:924-932).
During state-sync backfill, a peer supplies a LightBlock whose Commit.Beacon is not covered by Commit.ThresholdBlockSignature. If a malicious peer sends an authentic consensus-version-3 LightBlock (where Commit.BlockID.StateID != Header.StateID().Hash() and Commit.AppHash is valid) with any single byte flipped in the 96-byte Commit.Beacon:
LightBlock.ValidateBasicpasses (Commit.ValidateBasicaccepts 96-byte beacon + 32-byte app hash;Commit.VerifyAppHashpasses becauseCommit.AppHashmatchesCommit.BlockID.StateID).ValidatorSet.VerifyCommitpasses because the threshold signature does not coverBeacon.- At
reactor.go:927,signedHeader.Commit.VerifyRandomBeacon(...)returns an error. - Instead of rejecting the peer's response and retrying from another peer, line 928 executes
signedHeader.Commit = signedHeader.Commit.WithoutRandomBeacon(), stripping BOTHBeaconandAppHash, and line 930 saves that commit intoBlockStore.
The persisted commit now has Commit.BlockID.StateID != Header.StateID().Hash() with Commit.AppHash == nil, so SignedHeader.CommittedAppHash() and LightBlock.ValidateBasic() permanently fail on it whenever this node serves /commit or fetchLightBlock/LightBlockRepository.Get to light clients or state-sync peers.
Recommendation: When signedHeader.Commit.VerifyRandomBeacon(...) fails in backfill, check whether !bytes.Equal(signedHeader.Header.StateID().Hash(), signedHeader.Commit.BlockID.StateID). If the commit's StateID differs from the header's StateID, Beacon and AppHash are mandatory for that block: reject the light block, withdraw/penalize the peer, and re-queue the height for another peer instead of stripping AppHash and saving a corrupted commit.
| func setLastBlockRandomness(state *sm.State, lastLightBlock *types.LightBlock) error { | ||
| params := state.ConsensusParams | ||
| if !params.Version.RandomBeacon() || !bytes.Equal(lastLightBlock.ConsensusHash, params.HashConsensusParams()) { | ||
| return nil | ||
| } | ||
| appHash, err := lastLightBlock.CommittedAppHash() | ||
| if err != nil { | ||
| return fmt.Errorf("app hash of the commit at height %d: %w", lastLightBlock.Height, err) | ||
| } | ||
| commit := lastLightBlock.Commit | ||
| if err := commit.VerifyRandomBeacon(state.ChainID, state.LastValidators, lastLightBlock.Header); err != nil { | ||
| return fmt.Errorf("random beacon of the commit at height %d: %w", lastLightBlock.Height, err) | ||
| } | ||
| state.LastAppHash = appHash | ||
| state.LastBlockBeacon = bytes.Clone(commit.Beacon) | ||
| return nil | ||
| } |
There was a problem hiding this comment.
CODE-003 · MEDIUM — State sync setLastBlockRandomness drops beacon and LastAppHash whenever any hashed consensus param changes at a v3 snapshot height
Introduced in 90884b8bb, 0ef2a67b7, and ebd8cc2f5 (internal/statesync/stateprovider.go:393-409, internal/statesync/reactor.go:405-407).
setLastBlockRandomness assumes snapshot height H (lastLightBlock) used consensus version 3 only when BOTH state.ConsensusParams.Version.RandomBeacon() (height H+1's params) is true AND lastLightBlock.ConsensusHash == state.ConsensusParams.HashConsensusParams(). If height H ran under consensus version 3 and block H updated ANY hashed consensus parameter (Block.MaxBytes, Block.MaxGas, ProposerHeartbeat, ProposerSilence, or downgraded ConsensusVersion from 3 to 2/1/0 — as test/e2e/networks/rotate.toml does at snapshot-interval height 1070 = 1), the early return triggers and leaves:
state.LastBlockBeaconempty (nil) andstate.LastAppHashset tocurrentLightBlock.AppHash(Header(H+1).AppHashinstead oflastLightBlock.CommittedAppHash()), breaking restart handshake at heightH.internal/statesync/reactor.go:405-407stripsBeaconandAppHashfromcommitbeforeSaveSeenCommit(commit).- At height
H+1,buildLastCommitInfopasses emptyBeaconandAppHashinProposedLastCommit/LocalLastCommitto the application, diverging from all non-state-synced nodes. - If the state-synced node proposes height
H+1,CreateProposalBlock(internal/state/execution.go:248-250) stripsBeaconandAppHashfromblock(H+1).LastCommit, causing all other validators to reject the proposal inverifyLastCommitBeacon(internal/state/validation.go:177-190). - When
H+1is saved toBlockStore,canonicalLastCommitsees the strippedseenCommit(H)and stripsBeaconandAppHashfromblockCommitKey(H), corrupting the stored canonical commit for heightH.
internal/statesync/random_beacon_test.go:109-120 currently asserts this defective behavior under the subtest "activation height" by mutating Block.MaxBytes++ on a light block whose commit actually has a v3 beacon and modified StateID.
Recommendation: Determine whether snapshot height H (lastLightBlock) used consensus version 3 from height H's own authenticated consensus parameters (fetched and verified against lastLightBlock.ConsensusHash, just as H+1's params are fetched and verified against currentLightBlock.ConsensusHash) rather than requiring lastLightBlock.ConsensusHash == params(H+1).HashConsensusParams(). Update TestSetLastBlockRandomness to distinguish a true v2->v3 activation height (where lastLightBlock has v2 params and no beacon) from a v3 height whose Block.MaxBytes or ConsensusVersion updates for H+1.
| func (bs *BlockStore) canonicalLastCommit(block *types.Block) *types.Commit { | ||
| commit := block.LastCommit | ||
| if commit == nil || (len(commit.Beacon) == 0 && len(commit.AppHash) == 0) { | ||
| return commit | ||
| } | ||
| seen := bs.LoadSeenCommit() | ||
| if seen != nil && seen.Height == commit.Height && | ||
| bytes.Equal(seen.Beacon, commit.Beacon) && bytes.Equal(seen.AppHash, commit.AppHash) { | ||
| return commit | ||
| } | ||
| return commit.WithoutRandomBeacon() | ||
| } |
There was a problem hiding this comment.
CODE-004 · MEDIUM — BlockStore.canonicalLastCommit reads unheighted LoadSeenCommit(), stripping v3 Beacon and AppHash from blockCommit(H-1) after rollback --store
Introduced in 1b1713022 and updated in ebd8cc2f5 (internal/store/store.go:631-642).
SaveBlock writes blockCommitKey(height-1) using bs.canonicalLastCommit(block), which calls seen := bs.LoadSeenCommit() (reading the single unheighted seenCommitKey() / prefix 3) and strips Beacon and AppHash unless seen != nil && seen.Height == commit.Height and both fields match.
When an operator runs tenderdash rollback --store (cmd/tenderdash/commands/rollback.go:62-70) at a consensus-version-3 height H:
state.RollbackrestoresStateto heightH-1withLastBlockBeaconandLastAppHashfromblockCommit(H-1).blockStore.DeleteBlock(H)(internal/store/store.go:402-449) deletesblockMeta(H),blockParts(H),blockCommit(H), andseenCommitAtKey(H), but leavesseenCommitKey()pointing at heightH.- When the node restarts and saves the newly committed block
H,canonicalLastCommitloadsseenCommitKey()(heightH != H-1), fails the height check, and returnscommit.WithoutRandomBeacon(). SaveBlockoverwritesblockCommitKey(H-1)withBeacon = nilandAppHash = nil.
Because height H-1's Commit.BlockID.StateID signs the post-randomness AppHash, stripping AppHash and Beacon from blockCommitKey(H-1) permanently corrupts the canonical commit stored for H-1: /commit?height=H-1, LightBlockRepository.Get(H-1), and fetchLightBlock(H-1) subsequently serve a commit that fails CommittedAppHash() and LightBlock.ValidateBasic().
Recommendation: In BlockStore.canonicalLastCommit, look up seen := bs.LoadSeenCommitAt(commit.Height) first and fall back to bs.LoadSeenCommit() only when seen == nil (covering the state-sync bootstrap height saved via SaveSeenCommit). Also consider restoring or clearing seenCommitKey() in DeleteBlock when deleting the tip height, and add a unit test covering DeleteBlock(H) followed by SaveBlock(H) at consensus version 3.
| ucState, err := r.blockExec.ProcessProposal(ctx, block, commit.Round, state, false, | ||
| types.VerifiedCommit{}) |
There was a problem hiding this comment.
CALL-001 · MEDIUM — replayBlock passes future committed state to ProcessProposal, sending wrong-height Beacon and AppHash in ProposedLastCommit
Walked via: git grep + Read (buildLastCommitInfo -> ProcessProposal -> BlockReplayer.replayBlock -> BlockReplayer.replayBlocks).
Commits 616ef06fd, 774a2545b, 90884b8bb, and ebd8cc2f5 changed buildLastCommitInfo(block, state) (internal/state/execution.go:898-912) to strip block.LastCommit's Beacon and AppHash and replace them with state.LastBlockBeacon and state.LastAppHash. That contract requires state to be the committed state at block.Height - 1.
BlockReplayer.replayBlock (internal/consensus/replayer.go:273-295), called from replayBlocks (replayer.go:242-249), always passes the persisted tip state (at rs.stateHeight >= height > height - 1). Even for a single-block replay (appHeight == stateHeight - 1, storeHeight == stateHeight), state.LastBlockHeight == height, so buildLastCommitInfo pairs height height - 1's Round/QuorumHash/BlockSignature from block.LastCommit with height rs.stateHeight's future LastBlockBeacon and LastAppHash in RequestProcessProposal.ProposedLastCommit.
Three failure modes follow:
- Replaying any consensus-version-3 block sends a future height's
BeaconandAppHash(including the block's own future beacon when replaying the tip block) insideProposedLastCommit. - Replaying a pre-version-3 block when
stateis already at version 3 injects a non-emptyBeaconandAppHashintoProposedLastCommit, violating the ABCI contract (CommitInfo.beacon/app_hashempty before consensus version 3). - Replaying a version-3 block after a downgrade to version <= 2 sends empty
BeaconandAppHashinProposedLastCommit.
replayBlock already adjusts state.Validators for quorum rotations (replayer.go:281-288) and loads per-height ConsensusParams in replayBlockRandomness (replayer.go:337), but leaves state.LastBlockBeacon and state.LastAppHash at rs.stateHeight.
Recommendation: In BlockReplayer.replayBlock, populate a per-height copy of state.LastBlockBeacon and state.LastAppHash for height - 1: clear both when height == state.InitialHeight or when r.stateStore.LoadConsensusParams(height-1) has !Version.RandomBeacon(); otherwise load the stored commit for height - 1 (r.store.LoadSeenCommitAt(height-1), falling back to r.store.LoadBlockCommit(height-1)) and set state.LastBlockBeacon = prevCommit.Beacon and state.LastAppHash = prevCommit.AppHash. Add a replay test asserting RequestProcessProposal.ProposedLastCommit.Beacon and AppHash across multi-block replay and version transitions.
| // From consensus version 3 the commit also carries the beacon and the app hash the state was | ||
| // finalized with. | ||
| if len(state.LastBlockBeacon) > 0 { | ||
| s.LastCommit.Beacon = state.LastBlockBeacon |
There was a problem hiding this comment.
CODE-006 · LOW — LastCommit beacon/app_hash aliased from state without cloning (inconsistent with surrounding clone discipline)
In updateToState, the node's own LastCommit is given the beacon and app hash by direct slice assignment:
if len(state.LastBlockBeacon) > 0 {
s.LastCommit.Beacon = state.LastBlockBeacon
s.LastCommit.AppHash = state.LastAppHash
}Every neighbouring code path that moves these two values copies them — FinalizeBlock (commit.AppHash.Copy(), bytes.Clone(commit.Beacon)), buildLastCommitInfo (bytes.Clone), ThresholdBlockSignature/WithoutRandomBeacon (bytes.Clone). Here the State's slices are aliased into the mutable Commit. No current writer mutates these backing arrays in place, so there is no live bug, but the aliasing is a latent footgun and departs from the established discipline.
Recommendation: Clone for symmetry with the rest of the change: s.LastCommit.Beacon = bytes.Clone(state.LastBlockBeacon) and s.LastCommit.AppHash = state.LastAppHash.Copy().
| | **POLRound** | The round whose polka a proposal claims as justification; `-1` when the proposal claims none. | `types.Proposal.POLRound` | | ||
| | **BlockID** | `(Hash, PartSetHeader, StateID)`. Nil block id = all three empty. | `types/block.go`, `types/block_meta.go` | | ||
| | **StateID** | Hash of `{AppVersion, Height, AppHash, CoreChainLockedHeight, Time}` of the block header; the app hash is the state **after** executing that block (same-block execution). | `Header.StateID` in `types/block.go` | | ||
| | **Commit** | `(Height, Round, BlockID, QuorumHash, ThresholdBlockSignature, ThresholdVoteExtensions, Beacon, AppHash)`: a single aggregate BLS threshold signature plus one threshold signature per threshold-recoverable vote extension. There are no per-validator signatures in a commit. Beacon and AppHash, set from consensus version 2, are not covered by the signature; before it, nodes drop them where they adopt a commit. | `types.Commit` in `types/block.go` | | ||
| | **Commit** | `(Height, Round, BlockID, QuorumHash, ThresholdBlockSignature, ThresholdVoteExtensions, Beacon, AppHash)`: a single aggregate BLS threshold signature plus one threshold signature per threshold-recoverable vote extension. There are no per-validator signatures in a commit. Beacon and AppHash, set from consensus version 3, are not covered by the signature; before it, nodes drop them where they adopt a commit. | `types.Commit` in `types/block.go` | | ||
| | **Locked block / round** | The block the node precommitted most recently and the round it did so; `-1`/nil when none. | `RoundState.LockedRound/LockedBlock` | | ||
| | **Valid block / round** | The most recent block (and round) for which the node saw a polka in a round `≥` any previous one. | `RoundState.ValidRound/ValidBlock` | | ||
| | **CurrentRoundState** | The application's answer to the latest `PrepareProposal`/`ProcessProposal` for the block held in `ProposalBlock`, tagged with the round it was processed for. | `RoundState.CurrentRoundState`, `RoundState.ProcessedBlockID`; `processedFor` in `internal/consensus/block_executor.go` | |
There was a problem hiding this comment.
DOC-002 · LOW — Specs and vote_signer comment contradict consensus-version-3 behavior (ExtendVote, StateID, round-skip gating, Commit handling)
Introduced/left stale across fef45324f, 90884b8bb, and ebd8cc2f5.
Multiple protocol specs and one inline comment contradict the implemented consensus-version-3 behavior:
- Direct contradiction on
ExtendVotevs randomness state (internal/consensus/vote_signer.go:113): the comment states"The application applies it before ExtendVote, so the extensions see that state.", directly contradictingspec/abci/methods.md:458-461andproto/tendermint/abci/types.proto:276-277, which require that vote extensions MUST NOT depend on the beacon or on the stateApplyBlockRandomnessproduced. - Incorrect version-2-only gating statements:
spec/consensus/consensus.md:76(edited by this PR at line 72) says round skip certificates are"CONSENSUS_VERSION_2 only", andspec/abci/methods.md:644/spec/abci/api.md:873/proto/tendermint/abci/types.protosaypropose_next_block_immediatelyapplies after a skipped round"on consensus version 2". In code,VersionParams.ProposerLivenessEnabled()(types/params.go:91) is>= CONSENSUS_VERSION_2, so both remain active inCONSENSUS_VERSION_3. - Stale
StateIDand prevote maj23 definitions:spec/consensus/consensus.md:67,71,spec/consensus/signing.md:142-143, andproto/tendermint/types/types.proto:84state thatStateID.app_hashis always equal toHeader.AppHashand that only precommit vote sets wait for threshold recovery. At consensus version 3, non-nil prevote sets also wait for threshold recovery (types/vote_set.go:490-499) and precommits/commits signStateIDwithCommit.AppHash. - Stale commit-handling spec:
spec/consensus/consensus-commit.md:57-63,121-129,170-171(edited at line 8) still statesverifyCommitBlockrequirescommit.BlockID.StateID == block.StateID(), omitscompleteCommit,VerifyRandomBeacon, andVerifyBlockRandomness, and sayscommitKeyhashes only(height, round, blockID, extensions)rather than also hashingBeaconandAppHash(internal/consensus/commit_candidates.go:36-41). - Ambiguous/incomplete ABCI call-sequence notes:
spec/abci/expected-behavior.md:27-28placesApplyBlockRandomnessafterVerifyVoteExtensionin the table and says"before verifying the commit and again before FinalizeBlock"(ambiguous vs signature verification; andBlockReplayer.replayBlockcallsApplyBlockRandomnessonce, not twice), whilespec/abci/methods.md:591mentionsCommitInfo.beacon/app_hashonly inRequestFinalizeBlock, omittingRequestPrepareProposal.local_last_commitandRequestProcessProposal.proposed_last_commit. - Stale state spec:
spec/core/state.md:16,42-45omitsState.LastBlockBeaconandCONSENSUS_VERSION_3.
Recommendation: Update the comment in internal/consensus/vote_signer.go:113 to match the ABCI spec, change "CONSENSUS_VERSION_2 only" / "on consensus version 2" to "from CONSENSUS_VERSION_2" in spec/consensus/consensus.md:76 and proto/tendermint/abci/types.proto (regenerating spec/abci/api.md) + spec/abci/methods.md:644, update StateID / prevote recovery / commit handling in spec/consensus/consensus.md, spec/consensus/signing.md, spec/consensus/consensus-commit.md, proto/tendermint/types/types.proto:84, spec/core/state.md, and clarify spec/abci/expected-behavior.md:27-28 and spec/abci/methods.md:591.
|
CALL-002 · LOW · addVoteVerifyVoteExtensionMw uses At consensus version 3, a non-nil precommit's The compared line is pre-existing in Recommendation: use 🤖 Co-authored by Claudius the Magnificent AI Agent |
thepastaclaw
left a comment
There was a problem hiding this comment.
Final validation — Phase 1 + Phase 2
Changes requested: 6 blockers
- Different rounds can finalize the same block with different application states —
internal/consensus/vote_signer.go:170-187(new)
Impact: At consensus version 3, honest nodes that finalize the same block in different rounds can store incompatible state IDs and reject each other's next block. - State-sync backfill saves an unverifiable commit when beacon verification fails —
internal/statesync/reactor.go:924-932(new)
Impact: A state-syncing node can persist a version-3 historical commit that its RPC and state-sync peers cannot validate. - State sync drops the snapshot's beacon when a version-3 block updates hashed consensus parameters —
internal/statesync/stateprovider.go:393-408(new)
Impact: A node syncing to a version-3 snapshot that changes hashed parameters for the next block can fail its next restart or propose a block that peers reject. - Handshake replay sends the tip's beacon as the previous block's beacon —
internal/consensus/replayer.go:289-292(new)
Impact: When a restored application is behind Tenderdash's saved state, startup replay can fail because the application receives the wrong previous commit metadata. - Saving the next block after
rollback --storecorrupts the previous version-3 commit —internal/store/store.go:631-642(new)
Impact: After an operator rolls back both stores and resumes with the application at the matching height, the next block save can make the retained commit unusable for light-client proofs. - The renamed test-helper parameter fails the Go linter —
internal/consensus/common_test.go:857(new)
Impact: Thegolangci-lintcheck fails on this head even though the unit-test jobs pass.
This PR enables a prevote-derived randomness beacon at consensus version 3 and makes precommits sign the application state after randomness is applied. On the reviewed head, the Linux build, all six unit-test groups, go vet, and both end-to-end jobs passed; golangci-lint failed on an unused parameter, and PR Hygiene and the automated review are pending.
🔴 6 blocking | 🟡 3 suggestion(s) | 💬 1 nitpick(s)
1 finding(s) not shown inline (the lines are not part of this PR's diff)
🟡 Suggestion: Rejected precommits stop triggering the warning when randomness changes the application hash
Impact: Operators lose the warning when the application rejects a precommit's extensions for a block it already processed and the precommit signs a different state ID from the header's.
internal/consensus/state_add_vote.go:359-361
The vote is still dropped, but the rejection is no longer surfaced at warning level. ProcessedBlockID is taken from the proposal and retains the header's state ID; a version-3 precommit uses the post-randomness state ID. Equals checks that field even though this branch only needs to identify the same block and round. Use SameBlock for the vote comparison and retain the existing processedFor and deduplication checks.
if errors.Is(err, sm.ErrVoteExtensionRejected) &&
processedFor(rs, vote.Round) && rs.ProcessedBlockID.SameBlock(vote.BlockID) &&
rejected.remember(vote) {
source: grok-4.7 (phase2-reviewer: general, tenderdash-consensus-security)
Review provenance
Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: grok-4.7 (standing in for gpt-6.2-astra) (agent: phase2-reviewer, role: general); reviewer 3: grok-4.7 (standing in for gpt-6.2-astra) (agent: phase2-reviewer, role: tenderdash-consensus-security); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.2-sol(effort low) — The diff changes consensus and signing across multiple phases: types/vote_set.go gates a prevote majority on BLS beacon recovery, internal/consensus/vote_signer.go signs precommits over the randomness-applied app hash, and validation, replay, and sync must agree on the resulting commit. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity quota lookup failed),glm-5.3-flash(not used above high effort; tier asks max) - Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
- Fresh verifier:
gpt-6.2-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
grok-4.7(standing in forgpt-6.2-astra) — general (completed, effort high); agentphase2-reviewer,grok-4.7(standing in forgpt-6.2-astra) — tenderdash-consensus-security (completed, effort high); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `internal/consensus/vote_signer.go`:
- [BLOCKING] internal/consensus/vote_signer.go:170-187: Different rounds can finalize the same block with different application states
Impact: At consensus version 3, honest nodes that finalize the same block in different rounds can store incompatible state IDs and reject each other's next block.
The lock protects the proposal's header-based BlockID, but the value that gets finalized also depends on the round. A node can advance on the precommit-wait timeout after seeing enough precommits in total without having seen a commit; that timeout does not invalidate a certificate other nodes already hold. The later round can re-propose and relock the same block, and `finalStateID` then uses the later round's prevote signature. `TestRandomBeaconRelockNewBeacon` explicitly asserts that the two rounds produce distinct precommit state IDs. Signing in both rounds is permitted, and each round's certificate verifies independently. Finalization stores the commit's BlockID, so `validateBlockPosition` at the next height cannot accept the same `LastBlockID` on both histories. Define and verify a beacon and final-state binding that survives re-proposal and relocking. Using `Proposal.POLRound` alone is not enough: the proposer uses `ValidRound`, which can advance after a new polka.
- [SUGGESTION] internal/consensus/vote_signer.go:112-113: The precommit comment implies vote extensions can use randomness-applied state
Impact: An ABCI application that builds vote extensions from randomness-applied state can produce extensions that peers cannot verify.
The comment gives the wrong reason for the call order. `ApplyBlockRandomness` does run before `ExtendVote` on the signing path, but `RequestExtendVote` and the ABCI methods spec expressly forbid extensions from depending on the beacon or its resulting state. A peer verifying a precommit may not have recovered that beacon. The protocol docs also still describe round-skip certificates as version-2-only and commit state IDs as always matching the header; update those descriptions to reflect the version-3 behavior alongside the comment.
In `internal/statesync/reactor.go`:
- [BLOCKING] internal/statesync/reactor.go:924-932: State-sync backfill saves an unverifiable commit when beacon verification fails
Impact: A state-syncing node can persist a version-3 historical commit that its RPC and state-sync peers cannot validate.
Backfill can turn a commit with a valid signed application root into one that no longer exposes that root. `LightBlock.ValidateBasic` checks that `Commit.AppHash` matches the signed state ID when that ID differs from the header's, and `VerifyCommit` authenticates the state ID but does not authenticate `Commit.Beacon`. If the beacon then fails its separate check, `WithoutRandomBeacon` clears both fields while leaving the signed state ID unchanged. `SaveSignedHeader` persists that commit and the queue marks the height complete. Historical readers subsequently fail `CommittedAppHash` or light-block validation. Reject and requeue the response when the signed state ID requires `Commit.AppHash`; if the height is known to be version 3, require a valid beacon even when randomness left the application hash unchanged.
In `internal/statesync/stateprovider.go`:
- [BLOCKING] internal/statesync/stateprovider.go:393-408: State sync drops the snapshot's beacon when a version-3 block updates hashed consensus parameters
Impact: A node syncing to a version-3 snapshot that changes hashed parameters for the next block can fail its next restart or propose a block that peers reject.
Both state providers can bootstrap a state that disagrees with the snapshot the application restored. `setLastBlockRandomness` compares the snapshot block's `ConsensusHash` with the next height's parameters. A change in block size, gas, effective proposer timeouts, or consensus version makes it skip the snapshot's valid beacon and keep the next header's application hash instead of the snapshot's signed root. The snapshot verifier checks the application against the signed root independently, so it does not catch this discrepancy. `Reactor.Sync` then strips both fields from the saved seen commit. If the hashes differ, a restart at the snapshot height fails the handshake; even if they match, `CreateProposalBlock` strips the beacon that fully synced peers require. Authenticate the snapshot height's own parameters and use its version to decide whether to verify and restore the beacon. The current `activation height` test changes `MaxBytes` on a version-3 fixture and asserts that the beacon is dropped; it should distinguish that case from actual activation, where the snapshot block was still pre-v3.
In `internal/consensus/replayer.go`:
- [BLOCKING] internal/consensus/replayer.go:289-292: Handshake replay sends the tip's beacon as the previous block's beacon
Impact: When a restored application is behind Tenderdash's saved state, startup replay can fail because the application receives the wrong previous commit metadata.
Replay changes the ABCI input even if the application is only one block behind. When the store and state are both at H, `replayBlocks` passes that tip state to `ProcessProposal(H)`. `buildLastCommitInfo` takes the round and signature from the block's previous commit but replaces its beacon and app hash with the tip state's fields. On a version-3 tip that is H's own beacon, not H−1's; across activation or downgrade the fields can also be wrongly present or absent. An application that validates or uses these inputs can reject replay or return a different root. Build the request from trusted local commit data for H−1, clearing the fields for a pre-v3 predecessor and leaving the initial block's last commit empty. Account for replay at the retention or state-sync boundary, where a separate H−1 parameter record may not exist.
In `internal/store/store.go`:
- [BLOCKING] internal/store/store.go:631-642: Saving the next block after `rollback --store` corrupts the previous version-3 commit
Impact: After an operator rolls back both stores and resumes with the application at the matching height, the next block save can make the retained commit unusable for light-client proofs.
The recovery command leaves the retained commit intact, but the next save overwrites it without its beacon or app hash. If `rollback --store` deletes H, `DeleteBlock` removes the height-indexed seen commit for H but leaves the unheighted seen key pointing to H. When H is saved again with a valid version-3 `LastCommit` for H−1, `canonicalLastCommit` reads that stale key, fails the height check, and clears the fields before overwriting `blockCommitKey(H-1)`. If the commit signed a post-randomness root different from the header's, historical RPC and light-block readers can no longer verify that root. Select the reference commit by height, using the height-indexed seen commit or the already stored canonical commit when the unheighted key is stale. Keep the unheighted fallback for a matching state-sync bootstrap commit.
In `internal/consensus/common_test.go`:
- [BLOCKING] internal/consensus/common_test.go:857: The renamed test-helper parameter fails the Go linter
Impact: The `golangci-lint` check fails on this head even though the unit-test jobs pass.
The failing GitHub Actions job reports `internal/consensus/common_test.go:857:2: unused-parameter: parameter 'cfg' seems to be unused, consider removing or renaming it to match ^_ (revive)`. The helper does not read or forward the parameter, and the target branch already named it `_cfg`. Restore that name to keep the existing callers and satisfy the linter. The cache extraction warning in the same job did not prevent the linter from running and reporting this error.
In `internal/state/rollback.go`:
- [SUGGESTION] internal/state/rollback.go:107-110: Rollback cannot return to a state-sync snapshot whose parameters were not saved
Impact: An operator can no longer roll back the first block applied after state sync, even on a chain that has not activated version 3.
After a fresh state sync at H and application of H+1, rollback to H now returns a missing-parameters error. `Bootstrap` saves consensus parameters starting at H+1; backfill saves historical headers, commits, and validator sets, but not parameters. The old rollback path only needed H+1's parameters, and `LoadValidators(H)` already falls back to defaults when H's parameter record is missing. The new unconditional `LoadConsensusParams(H)` makes that gap fatal. Persist authenticated snapshot-height parameters during state sync or provide a rollback path that can use the authenticated snapshot commit when the parameter record is absent.
In `internal/consensus/state_add_vote.go`:
- [SUGGESTION] internal/consensus/state_add_vote.go:359-361: Rejected precommits stop triggering the warning when randomness changes the application hash
Impact: Operators lose the warning when the application rejects a precommit's extensions for a block it already processed and the precommit signs a different state ID from the header's.
The vote is still dropped, but the rejection is no longer surfaced at warning level. `ProcessedBlockID` is taken from the proposal and retains the header's state ID; a version-3 precommit uses the post-randomness state ID. `Equals` checks that field even though this branch only needs to identify the same block and round. Use `SameBlock` for the vote comparison and retain the existing `processedFor` and deduplication checks.
In `internal/consensus/state_data.go`:
- [NITPICK] internal/consensus/state_data.go:251-254: The rebuilt last commit shares its beacon and app hash with in-memory state
Impact: A future in-place edit to either last-commit field would also change the consensus state's copy.
`updateToState` assigns both slice headers directly to the rebuilt commit, unlike the copies made by `FinalizeBlock` and `buildLastCommitInfo` at their respective boundaries. No current writer mutates these bytes in place, so there is no present corruption or race. Copying here gives the state and the commit independent ownership.
Out-of-scope follow-up suggestions (1)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Beacon fairness below the honest recovery threshold needs an explicit guarantee — Uniqueness of the threshold signature within a round does not establish unbiased randomness across abandoned rounds when honest participation alone cannot recover a beacon. This is distinct from agreement on the final state after a polka.
- Follow-up: Track the required fairness guarantees for application payouts when honest participation falls below the recovery threshold.
| prevotes := stateData.Votes.Prevotes(round) | ||
| polka, ok := prevotes.TwoThirdsMajority() | ||
| if !ok || !polka.SameBlock(blockID) { | ||
| return nil, fmt.Errorf("no prevote majority for block %X in round %d", blockID.Hash, round) | ||
| } | ||
| beacon := prevotes.ThresholdBlockSignature() | ||
| if len(beacon) == 0 { | ||
| return nil, errors.New("random beacon of the prevote majority not recovered") | ||
| } | ||
| if s.randomness == nil { | ||
| return nil, errors.New("no application to apply the block's randomness") | ||
| } | ||
| appHash, err := s.randomness.ApplyBlockRandomness(ctx, block, round, beacon) | ||
| if err != nil { | ||
| panic(fmt.Errorf("ApplyBlockRandomness call failed: %w", err)) | ||
| } | ||
| stateID := block.StateIDWithAppHash(appHash) | ||
| s.finalStateIDs[key] = stateID.Hash() |
There was a problem hiding this comment.
🔴 Blocking: Different rounds can finalize the same block with different application states
Impact: At consensus version 3, honest nodes that finalize the same block in different rounds can store incompatible state IDs and reject each other's next block.
The lock protects the proposal's header-based BlockID, but the value that gets finalized also depends on the round. A node can advance on the precommit-wait timeout after seeing enough precommits in total without having seen a commit; that timeout does not invalidate a certificate other nodes already hold. The later round can re-propose and relock the same block, and finalStateID then uses the later round's prevote signature. TestRandomBeaconRelockNewBeacon explicitly asserts that the two rounds produce distinct precommit state IDs. Signing in both rounds is permitted, and each round's certificate verifies independently. Finalization stores the commit's BlockID, so validateBlockPosition at the next height cannot accept the same LastBlockID on both histories. Define and verify a beacon and final-state binding that survives re-proposal and relocking. Using Proposal.POLRound alone is not enough: the proposer uses ValidRound, which can advance after a new polka.
source: grok-4.7 (phase2-reviewer: general, tenderdash-consensus-security)
| // save the signed headers; before consensus version 3 a commit carries no beacon (see | ||
| // WithoutRandomBeacon), so its beacon and app hash are kept only when they verify | ||
| signedHeader := *resp.block.SignedHeader | ||
| signedHeader.Commit = signedHeader.Commit.WithoutRandomBeacon() | ||
| if signedHeader.Commit.VerifyRandomBeacon(chainID, resp.block.ValidatorSet, signedHeader.Header) != nil { | ||
| signedHeader.Commit = signedHeader.Commit.WithoutRandomBeacon() | ||
| } | ||
| if err := r.blockStore.SaveSignedHeader(&signedHeader, trustedBlockID); err != nil { | ||
| return err | ||
| } |
There was a problem hiding this comment.
🔴 Blocking: State-sync backfill saves an unverifiable commit when beacon verification fails
Impact: A state-syncing node can persist a version-3 historical commit that its RPC and state-sync peers cannot validate.
Backfill can turn a commit with a valid signed application root into one that no longer exposes that root. LightBlock.ValidateBasic checks that Commit.AppHash matches the signed state ID when that ID differs from the header's, and VerifyCommit authenticates the state ID but does not authenticate Commit.Beacon. If the beacon then fails its separate check, WithoutRandomBeacon clears both fields while leaving the signed state ID unchanged. SaveSignedHeader persists that commit and the queue marks the height complete. Historical readers subsequently fail CommittedAppHash or light-block validation. Reject and requeue the response when the signed state ID requires Commit.AppHash; if the height is known to be version 3, require a valid beacon even when randomness left the application hash unchanged.
source: muse-spark-1.3-contributor (phase1-reviewer: general); grok-4.7 (phase2-reviewer: general, tenderdash-consensus-security)
| func setLastBlockRandomness(state *sm.State, lastLightBlock *types.LightBlock) error { | ||
| params := state.ConsensusParams | ||
| if !params.Version.RandomBeacon() || !bytes.Equal(lastLightBlock.ConsensusHash, params.HashConsensusParams()) { | ||
| return nil | ||
| } | ||
| appHash, err := lastLightBlock.CommittedAppHash() | ||
| if err != nil { | ||
| return fmt.Errorf("app hash of the commit at height %d: %w", lastLightBlock.Height, err) | ||
| } | ||
| commit := lastLightBlock.Commit | ||
| if err := commit.VerifyRandomBeacon(state.ChainID, state.LastValidators, lastLightBlock.Header); err != nil { | ||
| return fmt.Errorf("random beacon of the commit at height %d: %w", lastLightBlock.Height, err) | ||
| } | ||
| state.LastAppHash = appHash | ||
| state.LastBlockBeacon = bytes.Clone(commit.Beacon) | ||
| return nil |
There was a problem hiding this comment.
🔴 Blocking: State sync drops the snapshot's beacon when a version-3 block updates hashed consensus parameters
Impact: A node syncing to a version-3 snapshot that changes hashed parameters for the next block can fail its next restart or propose a block that peers reject.
Both state providers can bootstrap a state that disagrees with the snapshot the application restored. setLastBlockRandomness compares the snapshot block's ConsensusHash with the next height's parameters. A change in block size, gas, effective proposer timeouts, or consensus version makes it skip the snapshot's valid beacon and keep the next header's application hash instead of the snapshot's signed root. The snapshot verifier checks the application against the signed root independently, so it does not catch this discrepancy. Reactor.Sync then strips both fields from the saved seen commit. If the hashes differ, a restart at the snapshot height fails the handshake; even if they match, CreateProposalBlock strips the beacon that fully synced peers require. Authenticate the snapshot height's own parameters and use its version to decide whether to verify and restore the beacon. The current activation height test changes MaxBytes on a version-3 fixture and asserts that the beacon is dropped; it should distinguish that case from actual activation, where the snapshot block was still pre-v3.
source: muse-spark-1.3-contributor (phase1-reviewer: general); grok-4.7 (phase2-reviewer: general, tenderdash-consensus-security)
| ucState, err := r.blockExec.ProcessProposal(ctx, block, commit.Round, state, false, | ||
| types.VerifiedCommit{}) |
There was a problem hiding this comment.
🔴 Blocking: Handshake replay sends the tip's beacon as the previous block's beacon
Impact: When a restored application is behind Tenderdash's saved state, startup replay can fail because the application receives the wrong previous commit metadata.
Replay changes the ABCI input even if the application is only one block behind. When the store and state are both at H, replayBlocks passes that tip state to ProcessProposal(H). buildLastCommitInfo takes the round and signature from the block's previous commit but replaces its beacon and app hash with the tip state's fields. On a version-3 tip that is H's own beacon, not H−1's; across activation or downgrade the fields can also be wrongly present or absent. An application that validates or uses these inputs can reject replay or return a different root. Build the request from trusted local commit data for H−1, clearing the fields for a pre-v3 predecessor and leaving the initial block's last commit empty. Account for replay at the retention or state-sync boundary, where a separate H−1 parameter record may not exist.
source: muse-spark-1.3-contributor (phase1-reviewer: general); grok-4.7 (phase2-reviewer: general, tenderdash-consensus-security)
| func (bs *BlockStore) canonicalLastCommit(block *types.Block) *types.Commit { | ||
| commit := block.LastCommit | ||
| if commit == nil || (len(commit.Beacon) == 0 && len(commit.AppHash) == 0) { | ||
| return commit | ||
| } | ||
| seen := bs.LoadSeenCommit() | ||
| if seen != nil && seen.Height == commit.Height && | ||
| bytes.Equal(seen.Beacon, commit.Beacon) && bytes.Equal(seen.AppHash, commit.AppHash) { | ||
| return commit | ||
| } | ||
| return commit.WithoutRandomBeacon() | ||
| } |
There was a problem hiding this comment.
🔴 Blocking: Saving the next block after rollback --store corrupts the previous version-3 commit
Impact: After an operator rolls back both stores and resumes with the application at the matching height, the next block save can make the retained commit unusable for light-client proofs.
The recovery command leaves the retained commit intact, but the next save overwrites it without its beacon or app hash. If rollback --store deletes H, DeleteBlock removes the height-indexed seen commit for H but leaves the unheighted seen key pointing to H. When H is saved again with a valid version-3 LastCommit for H−1, canonicalLastCommit reads that stale key, fails the height check, and clears the fields before overwriting blockCommitKey(H-1). If the commit signed a post-randomness root different from the header's, historical RPC and light-block readers can no longer verify that root. Select the reference commit by height, using the height-indexed seen commit or the already stored canonical commit when the unheighted key is stale. Keep the unheighted fallback for a matching state-sync bootstrap commit.
source: muse-spark-1.3-contributor (phase1-reviewer: general); grok-4.7 (phase2-reviewer: general, tenderdash-consensus-security)
| ctx context.Context, | ||
| t *testing.T, | ||
| _cfg *config.Config, | ||
| cfg *config.Config, |
There was a problem hiding this comment.
🔴 Blocking: The renamed test-helper parameter fails the Go linter
Impact: The golangci-lint check fails on this head even though the unit-test jobs pass.
The failing GitHub Actions job reports internal/consensus/common_test.go:857:2: unused-parameter: parameter 'cfg' seems to be unused, consider removing or renaming it to match ^_ (revive). The helper does not read or forward the parameter, and the target branch already named it _cfg. Restore that name to keep the existing callers and satisfy the linter. The cache extraction warning in the same job did not prevent the linter from running and reporting this error.
| cfg *config.Config, | |
| _cfg *config.Config, |
source: grok-4.7 (phase2-reviewer: general, tenderdash-consensus-security)
| rollbackParams, err := ss.LoadConsensusParams(rollbackHeight) | ||
| if err != nil { | ||
| return -1, nil, err | ||
| } |
There was a problem hiding this comment.
🟡 Suggestion: Rollback cannot return to a state-sync snapshot whose parameters were not saved
Impact: An operator can no longer roll back the first block applied after state sync, even on a chain that has not activated version 3.
After a fresh state sync at H and application of H+1, rollback to H now returns a missing-parameters error. Bootstrap saves consensus parameters starting at H+1; backfill saves historical headers, commits, and validator sets, but not parameters. The old rollback path only needed H+1's parameters, and LoadValidators(H) already falls back to defaults when H's parameter record is missing. The new unconditional LoadConsensusParams(H) makes that gap fatal. Persist authenticated snapshot-height parameters during state sync or provide a rollback path that can use the authenticated snapshot commit when the parameter record is absent.
source: muse-spark-1.3-contributor (phase1-reviewer: general)
| // From consensus version 3 the precommit signs the state with the block's randomness applied. | ||
| // The application applies it before ExtendVote, so the extensions see that state. |
There was a problem hiding this comment.
🟡 Suggestion: The precommit comment implies vote extensions can use randomness-applied state
Impact: An ABCI application that builds vote extensions from randomness-applied state can produce extensions that peers cannot verify.
The comment gives the wrong reason for the call order. ApplyBlockRandomness does run before ExtendVote on the signing path, but RequestExtendVote and the ABCI methods spec expressly forbid extensions from depending on the beacon or its resulting state. A peer verifying a precommit may not have recovered that beacon. The protocol docs also still describe round-skip certificates as version-2-only and commit state IDs as always matching the header; update those descriptions to reflect the version-3 behavior alongside the comment.
| // From consensus version 3 the precommit signs the state with the block's randomness applied. | |
| // The application applies it before ExtendVote, so the extensions see that state. | |
| // From consensus version 3 the precommit signs the state with the block's randomness applied. | |
| // ApplyBlockRandomness runs before ExtendVote, but extensions must not depend on the beacon or the state it produced. |
source: muse-spark-1.3-contributor (phase1-reviewer: general); grok-4.7 (phase2-reviewer: general, tenderdash-consensus-security)
| if len(state.LastBlockBeacon) > 0 { | ||
| s.LastCommit.Beacon = state.LastBlockBeacon | ||
| s.LastCommit.AppHash = state.LastAppHash | ||
| } |
There was a problem hiding this comment.
💬 Nitpick: The rebuilt last commit shares its beacon and app hash with in-memory state
Impact: A future in-place edit to either last-commit field would also change the consensus state's copy.
updateToState assigns both slice headers directly to the rebuilt commit, unlike the copies made by FinalizeBlock and buildLastCommitInfo at their respective boundaries. No current writer mutates these bytes in place, so there is no present corruption or race. Copying here gives the state and the commit independent ownership.
| if len(state.LastBlockBeacon) > 0 { | |
| s.LastCommit.Beacon = state.LastBlockBeacon | |
| s.LastCommit.AppHash = state.LastAppHash | |
| } | |
| if len(state.LastBlockBeacon) > 0 { | |
| s.LastCommit.Beacon = bytes.Clone(state.LastBlockBeacon) | |
| s.LastCommit.AppHash = state.LastAppHash.Copy() | |
| } |
source: muse-spark-1.3-contributor (phase1-reviewer: general); grok-4.7 (phase2-reviewer: general, tenderdash-consensus-security)
Basic explanation
When enough validators prevote for a block, their BLS signature shares combine into one threshold signature that nobody could compute in advance and that every node recovers identically. From consensus version 3, Tenderdash uses that signature as the block's random beacon:
ApplyBlockRandomness(added in feat(abci)!: add the ApplyBlockRandomness method and commit beacon fields #1582), which fills its random values and returns the final app hash;Before, for any block:
After, at consensus version 3:
Nothing changes until the application sets
VersionParams.consensus_version = 3(Dash Platform does it at its protocol upgrade), so upgraded nodes behave as today until then.TL;DR: At consensus version 3, recover a random beacon from each block's prevotes, let the application apply it, and make precommits and commits sign the resulting app hash.
User story
As a Dash Platform game developer, I want a random value set in the same block that asks for it, which nobody (the user, the proposer, or any small group of validators) can predict or pick, so that card rarities and payouts are fair.
Scenario
Base flow
A Platform block creates a document with a random property. Drive writes a placeholder while executing the block, so the header app hash commits to the placeholder. The value must come from something nobody can know before the block is voted on, and must be in the state the block commits.
Actual behavior
Validators already produce such a value, the threshold signature of the prevotes, but Tenderdash never recovers it, and precommits always sign the header's app hash, so the committed state cannot depend on anything decided during voting.
Expected behavior
From consensus version 3, the prevote majority's threshold signature is the beacon; the application turns placeholders into values with it before precommitting; the commit signs the final state and carries what any node needs to verify and reproduce it. Client proofs keep verifying against the commit's signed state ID, unchanged.
Detailed discussion
What was done
Activation
CONSENSUS_VERSION_3inVersionParams(the random beacon recovered from prevotes; precommits sign the randomness-applied app hash) andVersionParams.RandomBeacon(), the single gate for every beacon path, which is on from version 3.ValidateConsensusParamsaccepts it. Proposer selection at versions 2 and 3 is the same as at version 1.CONSENSUS_VERSION_2stays proposer liveness (feat(consensus)!: hand a silent proposer's idle round to the next proposer #1572); version 3 includes it, and no beacon path runs at version 2.Beacon recovery (
types/vote_set.go)WithRandomBeaconmakes a prevoteVoteSetrecover the threshold signature of a majority for a block and count the majority only once recovery succeeds, as precommits already do. The majority gate (QuorumVotingThresholdPower) can be below the power BLS recovery needs, so otherwise a polka could form before the beacon exists. Nil prevote majorities are not recovered.VoteSet.ThresholdBlockSignature()exposes the beacon per round.HeightVoteSetturns this on per height from the height's consensus params.Precommit signing (
internal/consensus/vote_signer.go)ApplyBlockRandomnesswith the round's beacon, thenvote.BlockID.StateID = hash(header StateID with the returned app hash), thenExtendVote, then sign. The state ID is cached per (height, round, block) so a node never signs two state IDs for one block and round (that is duplicate-vote evidence). An application error panics, as forExtendVote.Commit
Commit.VerifyRandomBeaconchecks the beacon against the quorum's threshold key over the prevote sign item rebuilt from the header and the commit round, andhash(StateID(header, commit.AppHash)) == commit.BlockID.StateID.Commit.VerifyAppHash/SignedHeader.CommittedAppHashgive the app hash a commit signs at any version: the header's when the signed state ID is over the header (an unsignedapp_hashin the commit is then ignored), otherwisecommit.AppHash, which must be the one the state ID binds.beacon/app_hash(not covered by its signature) are dropped. Parked-commit deduplication keys now include both fields.Same block, two state IDs
BlockID.SameBlock(hash and part set header). Commit-vs-proposal comparisons indropStaleProposaland the proposaler use it;verifyCommitBlockuses the beacon check at version 3.FinalizeBlockuses the commit'sBlockID(it becomesstate.LastBlockIDand the next header'sLastBlockID, and is sent inRequestFinalizeBlock.block_id). At version 3 it callsApplyBlockRandomnesswith the commit's beacon and round right before the ABCIFinalizeBlockand stops on a mismatch withcommit.AppHash(ErrAppHashMismatch).state.LastAppHashbecomescommit.AppHash.PrepareProposal.local_last_commitandProcessProposal.proposed_last_commitcarry the last block's beacon and final app hash at version 3, taken from the node's state (LastBlockBeacon,LastAppHash), the valuesFinalizeBlockreceived incommit. The proposer's copy inblock.LastCommitis checked against the state only when the block is validated, afterProcessProposal, so it is never passed to the application.State.LastBlockBeacon(state proto field 17). The next block'sLastCommitmust carry the same beacon and app hash: neither is covered by the commit hash, and a block carrying others would hand block sync and light clients an unverifiable commit for the previous height.Other paths
BlockID, and applies the randomness afterProcessProposaland before the commit's extension check; a mismatch stops the node.replayBlockapplies the stored commit's beacon afterProcessProposal(decided by the replayed height's own consensus params) and stops on a mismatch;syncStateAtgoes throughApplyBlock, which does the same. Rollback restoresLastBlockID,LastAppHashandLastBlockBeaconfrom the commit of the rolled-back height.ProcessProposaland before the extension check, the same order a validator uses (randomness, thenExtendVote).LightBlock.ValidateBasicaccepts a commit state ID overcommit.AppHash; query proofs verify against the committed app hash.LastAppHashand the verifiedLastBlockBeaconfrom the snapshot height's commit when that height used version 3.kvstore example
ApplyBlockRandomnessreturnssha256(app hash || beacon), so every version 3 block has two different app hashes;FinalizeBlockchecks and commits it.Findings on two open items
checkAppHashEqualsOneFromBlockreceives inreplayBlock: theProcessProposalresult (ucState.AppHash), not the application's committed root. Comparing it with the header's app hash stays correct at version 3. What did break was the next check inreplayBlocks, which compared the same pre-randomness hash withstate.LastAppHash; it now uses the commit's app hash.LastAppHash = header(H+1).AppHash: inherited from upstream Tendermint's next-block execution (P2P state provider, 2021), where header H+1 carried the result of block H. With same-block execution it is the state after H+1, one block ahead of the snapshot;AppHash(H)had already been adapted,State()had not. It has gone unnoticed because nothing readsLastAppHashbefore the node commits H+1, except the handshake check after a restart at exactly the snapshot height.Rollbackhas the same off-by-one. This PR fixes it only for version 3 snapshots, to keep pre-activation behaviour unchanged; fix(statesync): restore LastAppHash of the snapshot height, not the next one #1584 fixes it for earlier versions.Testing
New targeted tests:
TestRandomBeaconConsensusVersion3: a validator at version 3 signs its prevote over the header state ID and its precommit over the final one, callsApplyBlockRandomnessbeforeExtendVote, and commits a beacon and app hash that verify; the state and the next header carry the commit'sBlockID, and the next block validates and commits.TestReactorRandomBeaconConsensusVersion3: four validators over the p2p test network, where each precommit needs the others' prevotes recovered; all nodes commit the same beacon and final app hash for every height.TestReactorRandomBeaconNonValidator: a node outside the validator set, which receives no votes, finalizes every block from peers' commits, applying the beacon itself, and reaches the validators' beacon and final app hash.TestRandomBeaconRelockNewBeacon: a block locked in round 0 and voted again in round 1 gets the round 1 beacon, so the round 1 precommit signs another final state ID, and the block commits at round 1 with that beacon.TestVoteSignerFinalStateIDCached: the final state ID is computed once per block and round; a second precommit does not ask the application again, even if it would now answer differently.TestLastCommitInfoRandomBeacon: at version 3 the next height'sPrepareProposalandProcessProposalget the state's beacon and final app hash in their last commit info, even when the proposer'sLastCommitcopy carries others; before version 3 both stay empty.TestVerifyAppHashIgnoresUnsignedAppHash: a commit whose state ID is over the header gives the header's app hash even when it carries another 32-byteapp_hash, whileVerifyRandomBeaconstill refuses it.FinalizeBlockrefusing a diverged app hash before the application sees the block, block sync refusing a bad beacon and stopping on divergence, replay order and divergence, rollback, and state sync's restored state.Regression runs with
-runover the touched areas of./internal/consensus/...,./internal/state,./internal/blocksync,./internal/statesync,./light/...,./types,./abci/...and./node(block size) pass.make proto-gen,make mockeryandmake lint(new findings againstv1.8-dev) were clean before the move to version 3; for that changeCONSENSUS_VERSION_3was regenerated withbuf generate, andgo build ./...andgo vet ./...are clean.End to end: the CI
rotatenetwork now activates consensus version 3 at height 1010, so its nodes state sync (from 1030 and 1035), block sync and restart at version 3, and the network then moves back to versions 1 and 0 at the existing heights.TestApp_HashandTestBlock_Headercompare with the app hash the commit signs, which is the header's before version 3. The e2e network was not run locally (no Docker here); CI runs it.Breaking changes
ApplyBlockRandomness.ValidateConsensusParamsacceptsCONSENSUS_VERSION_3and still refuses unknown consensus versions (anything but 0, 1, 2, 3).types.MaxCommitRandomnessBytes(132 bytes) more for the last commit's beacon and app hash (TestTxFilterRandomBeacon).sm.ExecutorgainsApplyBlockRandomness;StategainsLastBlockBeacon(new state proto field, empty in existing stores).Prior work
ApplyBlockRandomnessABCI method and commit fields), which should merge first. This PR is stacked on feat(abci)!: add the ApplyBlockRandomness method and commit beacon fields #1582's branchfeat/abci-apply-block-randomness; its own changes are the commits from 90884b8 on, except the merges of feat(abci)!: add the ApplyBlockRandomness method and commit beacon fields #1582's branch (c1a2caf brought in feat(abci)!: add the ApplyBlockRandomness method and commit beacon fields #1582's first review fixes: the commit field size bound, tolerant block decoding and the kvstore lookup by block hash; d5c374e brings the contract docs, theABCISemVerbump and the split commit size reserve).CONSENSUS_VERSION_2. This PR mergesdev, keeps proposer liveness from version 2, and moves the beacon to version 3.TestRandomBeaconOffAtConsensusVersion2checks that a version 2 validator signs precommits over the header's state ID, commits without a beacon or app hash, and never callsApplyBlockRandomness.Open points for review: Tenderdash does not compare a peer's precommit state ID with its own final app hash (not needed for safety: a precommit over another state ID cannot join the honest commit). Like
ExtendVote,ApplyBlockRandomnesshas no deadline on the consensus goroutine, so the application must bound its translation time. The application may be asked to apply the same beacon several times per block (signing, commit checks,FinalizeBlock), so it must answer repeated calls consistently and cheaply.Attribution
Prepared with Claude Code.
🤖 Generated with Claude Code