Skip to content

fix(consensus): count XDPoS_getSigningTxCountByEpoch over the reward window - #2981

Open
benjamin202410 wants to merge 1 commit into
dev-upgradefrom
fix/signing-tx-count-by-epoch-reward-window
Open

benjamin202410 wants to merge 1 commit into
dev-upgradefrom
fix/signing-tx-count-by-epoch-reward-window

Conversation

@benjamin202410

@benjamin202410 benjamin202410 commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

Proposed changes

XDPoS_getSigningTxCountByEpoch(E) should report the sign counts the reward hook (GetSigningTxCount) pays for the epoch that ends at E. It currently differs by one slot at both ends of the epoch:

API before this PR reward hook
sign slots [prevSwitch, E-1], so the previous switch block counts as a slot when it is a multiple of 15 [prevSwitch+1, E-1]
signing txs gathered from [prevSwitch, E-1] [prevSwitch+1, nextSwitch-1], so signatures for the last slots that are mined in the next epoch also count

On testnet (v3.0.0-testnet-2), I compared the API at the buffer checkpoint with an independent recount, and the recount matched the paid rewards to the wei for every owner. 7 of the 21 epochs between 84730623 and 84873177 differed:

  • +1 for nearly every masternode in 5 epochs (84731521, 84734201, 84735099, 84755726, 84795138): the previous switch block was a multiple of 15.
  • −1 for every masternode in 84732420: slot 84731520 is the block right before the switch, so all of its signatures were mined in the next epoch.
  • −1 for one masternode in 84873177.

This PR changes the API so that:

  • it counts the slots of [prevSwitch+1, E-1];
  • it gathers signing txs up to the block before the next epoch switch. If that switch is not mined yet, it gathers them up to the head, so the counts of the latest epoch can still grow;
  • like the hook, it does not treat the first v2 block (SwitchBlock+1) as an epoch boundary.

The return type and the meaning of epochBlockNum (the switch that starts the epoch after the counted one) do not change.

Tests

TestGetSigningTxCountByEpochMatchesRewardWindow (consensus/tests/engine_v2_tests/api_test.go) builds the chain with PrepareXDCTestBlockChainWithProtectorObserver and sets up both boundary cases:

  • signer signs every slot of [2701, 3599], but its signature for the last slot, 3585, is mined in block 3700 of the next epoch.
  • acc1 signs the switch block 2700 and two slots.

The test asserts signer = 59 and acc1 = 2, and that the API returns exactly the counts hooks.GetSigningTxCount returns for header 4500. The test fails on the old code (expected 59, actual 58) and passes with this change. go test ./consensus/XDPoS/ passes, and so do the TestGet* and TestHookReward* tests in consensus/tests/engine_v2_tests.

Types of changes

What types of changes does your code introduce to XDC network?
Put an ✅ in the boxes that apply

  • build: Changes that affect the build system or external dependencies
  • ci: Changes to CI configuration files and scripts
  • chore: Changes that don't change source code or tests
  • docs: Documentation only changes
  • feat: A new feature
  • fix: A bug fix
  • perf: A code change that improves performance
  • refactor: A code change that neither fixes a bug nor adds a feature
  • revert: Revert something
  • style: Changes that do not affect the meaning of the code
  • test: Adding missing tests or correcting existing tests

Impacted Components

Which parts of the codebase does this PR touch?
Put an ✅ in the boxes that apply

  • Consensus
  • Account
  • Network
  • Geth
  • Smart Contract
  • External components
  • Not sure (Please specify below)

Checklist

Put an ✅ in the boxes once you have confirmed below actions (or provide reasons on not doing so) that

  • This PR has sufficient test coverage (unit/integration test) OR I have provided reason in the PR description for not having test coverage
  • Tested on a private network from the genesis block and monitored the chain operating correctly for multiple epochs. (Read-only RPC change; it does not touch consensus or state. Checked against testnet data as described above.)
  • Provide an end-to-end test plan in the PR description on how to manually test it on the devnet/testnet.
    On a node running this branch, for a few epoch switches N and the switch E right before each N, compare XDPoS_getSigningTxCountByEpoch(E) with the signers sign counts in eth_getRewardByHash(hash of N) (needs --store-reward). Every masternode count should be equal. Include epochs whose previous switch is a multiple of 15, and epochs where a signature for the last slot is mined after E.
  • Tested the backwards compatibility. (Same RPC signature and return type. Values change only at the epoch boundaries described above.)
  • Tested with XDC nodes running this version co-exist with those running the previous version. (N/A: an RPC-only change, no effect on consensus or the network protocol.)
  • Relevant documentation has been updated as part of this PR (the doc comment of GetSigningTxCountByEpoch is updated)
  • N/A

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Corrected epoch signing transaction counts to match the epoch’s reward window. Counts now exclude the preceding epoch-switch block and include eligible signing transactions from the current epoch’s switch block up to the next switch or current chain head.
    • Signing transactions mined after the block they sign are included when they fall within the applicable epoch window. Counts now align with the reward hook’s results.

…window

GetSigningTxCountByEpoch disagreed with the sign counts the reward hook pays
for the same epoch, by one slot for most masternodes in about a third of the
testnet epochs checked:

- it counted the previous epoch switch block as a sign slot when that block
  is a multiple of MergeSignRange, while the hook starts the rewarded range
  one block after the switch;
- it only gathered signing txs mined inside the epoch, so signatures for the
  last slots that are mined in the next epoch were missed, while the hook
  gathers them up to the block before the next epoch switch.

Count the slots of [previous switch+1, epochBlockNum-1] and gather signing
txs up to the block before the next epoch switch (or the head if it is not
mined yet), skipping the first v2 block as a boundary like the hook does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

GetSigningTxCountByEpoch counts sign slots without including the preceding epoch-switch block. It collects signing transactions through the next epoch switch or current head. A test checks boundary handling, late-mined signatures, and agreement with reward-hook counts.

Changes: Epoch signing window

Layer / File(s) Summary
Epoch window counting and validation
consensus/XDPoS/api.go, consensus/tests/engine_v2_tests/api_test.go
The API stops backward counting before the preceding epoch boundary and collects signing transactions from the requested switch block up to the next boundary or current head. The test checks counts for eligible slots, including a late-mined signature, and compares API results with reward-hook counts.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Suggested reviewers: wanwiset25, gzliudan, anunay-xin

Merge Risk: Minimal · up to 9fdb4

This change aligns the signing transaction counts returned by the API with those used by the reward hook for the same epoch. It is a read-only RPC change with no consensus or state impact, and a test covers the boundary cases. No concrete merge-blocking risk remains.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the change: the fix counts XDPoS_getSigningTxCountByEpoch over the reward window. The raw summary and objectives confirm the change aligns the API's slot range and signing-tx gathering…
Description check Passed The description follows the template. It states the change and rationale with a comparison table, and marks the fix and test types and the Consensus component. It has a test section, and it gives an e…
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.
Full details: Title check

Explanation

The title names the change: the fix counts XDPoS_getSigningTxCountByEpoch over the reward window. The raw summary and objectives confirm the change aligns the API's slot range and signing-tx gathering range with the reward hook's window. The title is specific and matches the main change, though it is slightly long at 75 characters.

Full details: Description check

Explanation

The description follows the template. It states the change and rationale with a comparison table, and marks the fix and test types and the Consensus component. It has a test section, and it gives an end-to-end test plan for the devnet/testnet. Two checklist items are unchecked with reasons given (backwards compatibility, full private network test). The template's Documentation item is unchecked but the author states the doc comment was updated; that claim is not visible in the raw summary, which lists no doc change. The template's 'Tested the backwards compatibility' item is unchecked with a reason given. Overall the description is mostly complete.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 72f244f3-efca-42a1-8923-2044abda2ded
Commits

Reviewing files that changed from the base of the PR and between 3ef63dd and 9fdb4b6.

Files selected for processing: 2

  • consensus/XDPoS/api.go
  • consensus/tests/engine_v2_tests/api_test.go

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

// epoch switch 2700 is a multiple of MergeSignRange but not a slot, and a signature for the last
// slot that is only mined in the next epoch (block 3700) still counts.
func TestGetSigningTxCountByEpochMatchesRewardWindow(t *testing.T) {
skipLongInShortMode(t)

@gzliudan gzliudan Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

skipLongInShortMode no longer exists in this package: #2947 moved the helper to internal/testshort and deleted the local copy in helper.go. The merge result does not build - GitHub's own merge commit d2686c35 (base c0349fab) fails with consensus/tests/engine_v2_tests/api_test.go:244:2: undefined: skipLongInShortMode. The green CI does not cover this, because the check runs are attached to the head sha, not to the merge commit. Please rebase onto dev-upgrade and use testshort.Skip(t); with testshort.Skip(t) the test passes on today's base (5.5s, above the 4s line #2947 uses, so keeping the gate is consistent).

@gzliudan gzliudan Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Correction to my correction - I re-checked the convention: #2947 measured the suite and gates every test of 4s or more behind -short through testshort.Skip. This test takes 5.68s on today's dev-upgrade (measured), so the original suggestion stands: testshort.Skip(t) is the gate to use, and the package already does that in penalty_test.go, reward_test.go, timeout_test.go, reward_standby_regression_test.go, reward_proportional_test.go and verify_header_test.go.

t.Parallel() is what the other tests in api_test.go use because #2944 made them fast enough to drop the gate; it can be added here as well, but it does not replace the gate for a 4s+ test.

adaptor.CacheSigningTxs(header3599.Hash(), txs)
late, err := signingTxWithSignerFn(last, 0, signer, signFn)
require.NoError(t, err)
adaptor.CacheSigningTxs(header3700.Hash(), []*types.Transaction{late})

@gzliudan gzliudan Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The test pins the counted-slot left edge (2700 is a multiple of 15 but not a slot) and the late-mined signature, but not the right edge: nothing here would fail if the forward walk also collected the next switch block 4500. I checked that both the hook and this implementation currently ignore a signature for slot 3585 mined in 4500 (api = hook = 58).

To pin the boundary, one in-epoch slot has to be signed only in the 4500 block: move, for example, the signature for 2715 out of the header3599 cache and cache it in header4500 instead, then assert signer = 58 (api and hook are both 58 today). A forward walk that collects 4500 then reports 59 and the assertion fails (verified). Adding a second signature for slot 3585 at header4500 does not work: that slot is already counted through the 3700 copy, and the per-slot dedup hides the difference (verified - the test stays green when the walk collects 4500).

Comment thread consensus/XDPoS/api.go
return nil, err
}
if prevIsEpochSwitch || i == 0 {
if prevIsEpochSwitch {

@gzliudan gzliudan Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This boundary rule is the v2 reward hook's convention, but this API also serves pre-v2 epochs, where the reward hook has a different one.

  • v2 (eth/hooks/engine_v2_hooks.go): sign slots = (rewardedSwitch, bufferSwitch) - neither switch counts.
  • v1 (contracts.GetRewardForCheckpoint): startBlockNumber = prevCheckpoint+1, endBlockNumber = startBlockNumber + rCheckpoint - 1, so the slots are [prevCheckpoint+1, prevCheckpoint+rCheckpoint] - the closing checkpoint does count (mainnet/testnet/devnet RewardCheckpoint = 900 = Epoch, so v1 checkpoints and epoch switches are the same blocks).

With this break the closing boundary is dropped from mapBlkHash, so it never counts as a sign slot: for v1 epochs the API reports one slot less than the hook paid. Measured on a v1-era chain (a signature for every slot, mined in the next block), epochBlockNum = 1800:

  • v1 reward hook GetRewardForCheckpoint(engine, chain, header2700, 900, ...): 60 signings (slots 915..1800)
  • this implementation, GetSigningTxCountByEpoch(1800): 59 signings (slots 915..1785)
  • the code before this PR: 60 signings (slots 900..1785 - same number as the hook, but attributed to the previous checkpoint)

So for every epoch before the v2 switch (mainnet 80,370,000 / testnet 56,828,700) the RPC answer changes from 60 to 59 and no longer matches what was actually paid, while the goal of this PR is to report exactly the counts the reward hook pays.

Either make the slot window follow the consensus version of the epoch (v1: include the closing checkpoint; v2: exclude both switches), or state in the doc comment and the PR description that the window follows the v2 convention and is one slot short of the historical v1 rewards.


got, err := api.GetSigningTxCountByEpoch(rpc.BlockNumber(epoch * 4))
require.NoError(t, err)
require.Equal(t, uint64(59), got[signer], "the late-mined signature for slot 3585 counts")

@gzliudan gzliudan Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This assertion is satisfied even if the forward walk stops one block early: the late signature is cached in block 3700, and the epoch switch block 3600 itself is never exercised.

The hook does collect the epoch switch block: in GetSigningTxCount the epochCount == 1 branch (the buffer epoch switch, i.e. this epochBlockNum) does not break, so that block falls through to mapBlkHash[i] = h.Hash() and to the signature collection. This implementation matches it today (the forward walk starts at epochBlockNum), but nothing pins it - changing the forward walk to start at epochBlockNum+1 leaves this test green (I verified: still PASS), while the API then reports 58 and the hook 59.

Suggestion: cache the slot 3585 signature only in header3600 (instead of header3700) and keep asserting signer = 59; a forward walk that starts at epochBlockNum+1 then reports 58 and the assertion fails. Adding a second copy at header3600 while keeping the one at 3700 pins nothing: the slot is already counted through 3700, and the per-slot dedup hides the difference (verified - with both copies the test stays green even when the walk starts at epochBlockNum+1).

// the reward hook pays for it. The epoch before 3600 has the sign slots 2715..3585: the previous
// epoch switch 2700 is a multiple of MergeSignRange but not a slot, and a signature for the last
// slot that is only mined in the next epoch (block 3700) still counts.
func TestGetSigningTxCountByEpochMatchesRewardWindow(t *testing.T) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The "gather up to the head when the next epoch switch is not mined yet" behaviour described in the PR description is not covered here: the chain built by this test already has block 4500 (the next epoch switch), so the forward walk always breaks on a switch block and the head path is never taken.

The behaviour is correct today - with a chain whose tip is 4510 and no 5400 mined yet, GetSigningTxCountByEpoch(4500) returns 59 (58 mined slots plus one signature mined in the tip block) - but a rewrite of that branch (e.g. returning an error when the next header is missing) would keep this test green.

Suggestion: add a case with the tip between two switches and assert that a signature mined in the tip block counts for the latest epoch.

Comment thread consensus/XDPoS/api.go
//
// If the next epoch switch is not mined yet, signing txs are gathered up to the
// current head, so the counts can still grow until that switch.
// epochBlockNum must be an epoch-switch block number that marks the start of an epoch.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The guard and the walk disagree about the first v2 block. IsEpochSwitch returns true for V2.SwitchBlock + 1 ("if parent is last v1 block and this is first v2 block, this is treated as epoch switch"), so this call is accepted, but isBoundary below - and the reward hook it mirrors - explicitly does not treat that block as an epoch boundary.

The result is a silent empty answer. On the test chain (SwitchBlock = 1800, one signature for slot 915 mined in block 916): GetSigningTxCountByEpoch(1800) returns that signer, while GetSigningTxCountByEpoch(1801) returns an empty map with no error. The epoch preceding the one that starts at 1801 is the last v1 epoch, which the hook does pay at the first v2 switch and whose counts are reachable under 1800, so a caller that enumerates epoch switches with IsEpochSwitch silently gets zero for that epoch.

Either reject SwitchBlock + 1 with the existing "not an epoch switch block" error (i.e. use isBoundary in the guard too), or return the preceding epoch's counts for it.

require.NoError(t, err)
txs = append(txs, tx)
}
for _, h := range []*types.Header{header2700, slots[0], slots[1]} {

@gzliudan gzliudan Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The fixture only ever signs sign-slot blocks (2715..3585) plus the switch block 2700, so the slot filter in the counting loop (consensus/XDPoS/api.go:957, blockNum%common.MergeSignRange != 0) is not pinned: a mutant that drops the condition — treating every block of [2701, 3599] as a sign slot — still leaves this test green (verified), because no signature in the fixture targets a non-slot block inside that window (the one for the switch block 2700 is outside it and never looked up). An off-by-one in the modulus is a different story: it is caught, since the shifted slot set carries no signatures and the hook comparison fails (verified).

Impact: if the filter were dropped or weakened to count blocks that are not MergeSignRange boundaries, the API would tally signatures that hooks.GetSigningTxCount keeps ignoring, and this test would not notice.

Pin (verified): let acc1 also sign the in-window non-slot block epoch*3+1 (2701) next to the signatures above, keeping the existing acc1 == 2 assertion. This kills the no-filter mutant (acc1 becomes 3) while the unmodified code stays green.

// signer signs every slot, but its signature for the last one is mined in the next epoch;
// acc1 signs the previous epoch switch block and two slots.
var txs []*types.Transaction
for _, h := range slots[:len(slots)-1] {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

No (address, slot) pair occurs twice in this fixture, so the per-slot dedup in the counting loop (consensus/XDPoS/api.go:960-962, seen) is not pinned: removing the dedup — counting every signing tx instead of unique signers per slot — leaves this test green (verified: the mutant passes).

Impact: the dedup exists exactly to collapse repeated signing txs for the same slot; if it regressed, such a signer would be counted twice here but once by hooks.GetSigningTxCount, and this test would not notice.

Pin (verified): give signer a second signing tx for an already-signed slot, e.g. signingTxWithSignerFn(slots[0], 1, signer, signFn) appended to txs, keeping the existing signer == 59 assertion. The duplicate is collapsed on the unmodified code (stays green) and the no-dedup mutant is killed (signer becomes 60).

@gzliudan

Copy link
Copy Markdown
Collaborator

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Action performed

Full review finished.

This branch has not been deployed

No deployments
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.

4 participants