Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(state-transition): restore state sync over boonet #2219

Merged
merged 4 commits into from
Dec 6, 2024
Merged

Conversation

abi87
Copy link
Collaborator

@abi87 abi87 commented Dec 5, 2024

Sync is currently broken on Boonet. Bysecting I found:

The latest PR breaks sync because if mistakenly changes the indexes for genesis deposits, and only those
These indexes are part of the beacon state that is hashed into blocks. So state sync was broken because:

  • Genesis state is subtly modified
  • Block 1, already finalized and downloaded from a peer, fails verification because AppHash reported by the block does not match the AppHash generated by the local state.

The fix is to preserve the way we set indexes over genesis

MOREOVER

We need to properly drop uselass BeaconState ops to preserve appHash

@abi87 abi87 self-assigned this Dec 5, 2024
Copy link
Contributor

coderabbitai bot commented Dec 5, 2024

Walkthrough

The changes in this pull request modify the processDeposit method in the state_processor_staking.go file, refining the condition for deposit processing by ensuring the slot value is greater than zero and less than BoonetFork2Height. Additionally, a comment was added to the createValidator method to highlight the need for improved error handling, specifically in distinguishing between ErrNotFound and other errors. These adjustments aim to enhance the logic for deposit handling and clarify error management.

Changes

File Path Change Summary
state-transition/core/state_processor_staking.go Modified processDeposit method to check that the slot is greater than zero and less than BoonetFork2Height. Added comment for improved error handling in createValidator method.
config/spec/special_cases.go Added import for "math" package and introduced new constant BoonetFork3Height as math.MaxUint64.
state-transition/core/state_processor.go Added hollowProcessRewardsAndPenalties method for processing rewards and penalties without balance changes; modified processEpoch to include new logic for reward processing.

Possibly related PRs

Suggested labels

Ready for Review, Merge me daddy

Suggested reviewers

  • itsdevbear
  • calbera
  • fridrik01

🐇 In the meadow, hops a little hare,
With changes made, it dances in the air.
Deposits refined, with care we tread,
Error handling clearer, no more dread.
Hooray for logic, so bright and bold,
In the world of code, new tales unfold! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Dec 5, 2024

Codecov Report

Attention: Patch coverage is 6.97674% with 40 lines in your changes missing coverage. Please review.

Project coverage is 29.75%. Comparing base (d7e65c4) to head (4e99f74).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
state-transition/core/state_processor.go 7.14% 35 Missing and 4 partials ⚠️
state-transition/core/state_processor_staking.go 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2219      +/-   ##
==========================================
- Coverage   29.85%   29.75%   -0.10%     
==========================================
  Files         350      350              
  Lines       15871    15908      +37     
  Branches       13       13              
==========================================
- Hits         4738     4734       -4     
- Misses      10825    10865      +40     
- Partials      308      309       +1     
Files with missing lines Coverage Δ
state-transition/core/state_processor_staking.go 66.51% <0.00%> (-2.33%) ⬇️
state-transition/core/state_processor.go 36.29% <7.14%> (-5.34%) ⬇️

@abi87 abi87 marked this pull request as ready for review December 5, 2024 19:00
@abi87 abi87 requested a review from itsdevbear as a code owner December 5, 2024 19:00
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range comments (1)
state-transition/core/state_processor_staking.go (1)

Line range hint 124-125: Improve error handling in validator lookup.

The current implementation doesn't distinguish between ErrNotFound (expected for new validators) and other errors (potential system issues). This could mask serious problems.

Consider implementing explicit error handling:

 idx, err := st.ValidatorIndexByPubkey(dep.GetPubkey())
 if err != nil {
-    // If the validator does not exist, we add the validator.
-    // TODO: improve error handling by distinguishing
-    // ErrNotFound from other kind of errors
-    return sp.createValidator(st, dep)
+    if errors.Is(err, ErrNotFound) {
+        return sp.createValidator(st, dep)
+    }
+    return errors.Wrap(err, "failed to lookup validator")
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 3ca00bc and 4a4cb28.

📒 Files selected for processing (1)
  • state-transition/core/state_processor_staking.go (1 hunks)
🔇 Additional comments (1)
state-transition/core/state_processor_staking.go (1)

87-87: LGTM, but verify genesis slot handling.

The additional check slot != 0 for Boonet chain is correct and aligns with fixing state sync. This prevents incorrect deposit index increments at genesis while maintaining backward compatibility for non-zero slots.

Let's verify the genesis slot handling across the codebase:

✅ Verification successful

Based on the search results, I can now make a definitive assessment of the genesis slot handling across the codebase. The search revealed comprehensive and consistent special handling of slot 0 (genesis) across multiple components:

Special genesis slot handling verified across codebase

The additional check slot != 0 in the Boonet chain condition is consistent with the codebase's overall genesis slot handling pattern. Key evidence:

  • State processor has proper genesis handling:

    • state_processor_staking.go: Empty root at genesis, special handling for validators root
    • state_processor_validators.go: Special epoch handling for genesis slot
    • state_processor_genesis.go: Dedicated genesis state initialization
  • Storage layer validates genesis:

    • store.go: Explicit check preventing parent slot lookup for genesis
    • beacondb: Special genesis validators root storage
  • Validation layer has genesis-specific logic:

    • validation_deposits.go: Special validation rules for genesis deposits
    • Explicit checks for deposit index at genesis

The change is safe and properly maintains backward compatibility while fixing state sync by preventing deposit index increment at genesis slot.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for special genesis slot (0) handling in state processing
# Expected: Find other places where slot 0 has special handling to ensure consistency

# Search for slot zero checks in state processing
rg -A 3 "slot\s*(==|!=)\s*0" 

# Search for genesis-related handling
rg -A 3 "genesis" 

Length of output: 66398

Copy link
Contributor

@calbera calbera left a comment

Choose a reason for hiding this comment

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

LGTM

@abi87 abi87 requested a review from calbera December 6, 2024 13:54
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 4a4cb28 and bc45673.

📒 Files selected for processing (2)
  • config/spec/special_cases.go (2 hunks)
  • state-transition/core/state_processor.go (3 hunks)
🔇 Additional comments (1)
config/spec/special_cases.go (1)

23-24: Addition of 'math' import and 'BoonetFork3Height' constant

The import of the "math" package and the definition of BoonetFork3Height using math.MaxUint64 are appropriate for handling numerical constants.

Also applies to: 40-40

Comment on lines +495 to +525
func (sp *StateProcessor[
_, _, _, BeaconStateT, _, _, _, _, _, _, _, _, _, _, _, _, _,
]) hollowProcessRewardsAndPenalties(st BeaconStateT) error {
slot, err := st.GetSlot()
if err != nil {
return err
}

if sp.cs.SlotToEpoch(slot) == math.U64(constants.GenesisEpoch) {
return nil
}

// this has been simplified to make clear that
// we are not really doing anything here
valCount, err := st.GetTotalValidators()
if err != nil {
return err
}

for i := range valCount {
// Increase the balance of the validator.
if err = st.IncreaseBalance(math.ValidatorIndex(i), 0); err != nil {
return err
}

// Decrease the balance of the validator.
if err = st.DecreaseBalance(math.ValidatorIndex(i), 0); err != nil {
return err
}
}

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the incorrect loop iteration over validators in 'hollowProcessRewardsAndPenalties'

The loop for i := range valCount is incorrect because valCount is a numeric value representing the total number of validators, not a slice or array. Using range on an integer will result in a compilation error.

Apply this diff to fix the loop:

func (sp *StateProcessor[
    _, _, _, BeaconStateT, _, _, _, _, _, _, _, _, _, _, _, _, _,
]) hollowProcessRewardsAndPenalties(st BeaconStateT) error {
    slot, err := st.GetSlot()
    if err != nil {
        return err
    }

    if sp.cs.SlotToEpoch(slot) == math.U64(constants.GenesisEpoch) {
        return nil
    }

    // this has been simplified to make clear that
    // we are not really doing anything here
    valCount, err := st.GetTotalValidators()
    if err != nil {
        return err
    }

-   for i := range valCount {
+   for i := uint64(0); i < valCount; i++ {
        // Increase the balance of the validator.
        if err = st.IncreaseBalance(math.ValidatorIndex(i), 0); err != nil {
            return err
        }

        // Decrease the balance of the validator.
        if err = st.DecreaseBalance(math.ValidatorIndex(i), 0); err != nil {
            return err
        }
    }

    return nil
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (sp *StateProcessor[
_, _, _, BeaconStateT, _, _, _, _, _, _, _, _, _, _, _, _, _,
]) hollowProcessRewardsAndPenalties(st BeaconStateT) error {
slot, err := st.GetSlot()
if err != nil {
return err
}
if sp.cs.SlotToEpoch(slot) == math.U64(constants.GenesisEpoch) {
return nil
}
// this has been simplified to make clear that
// we are not really doing anything here
valCount, err := st.GetTotalValidators()
if err != nil {
return err
}
for i := range valCount {
// Increase the balance of the validator.
if err = st.IncreaseBalance(math.ValidatorIndex(i), 0); err != nil {
return err
}
// Decrease the balance of the validator.
if err = st.DecreaseBalance(math.ValidatorIndex(i), 0); err != nil {
return err
}
}
func (sp *StateProcessor[
_, _, _, BeaconStateT, _, _, _, _, _, _, _, _, _, _, _, _, _,
]) hollowProcessRewardsAndPenalties(st BeaconStateT) error {
slot, err := st.GetSlot()
if err != nil {
return err
}
if sp.cs.SlotToEpoch(slot) == math.U64(constants.GenesisEpoch) {
return nil
}
// this has been simplified to make clear that
// we are not really doing anything here
valCount, err := st.GetTotalValidators()
if err != nil {
return err
}
for i := uint64(0); i < valCount; i++ {
// Increase the balance of the validator.
if err = st.IncreaseBalance(math.ValidatorIndex(i), 0); err != nil {
return err
}
// Decrease the balance of the validator.
if err = st.DecreaseBalance(math.ValidatorIndex(i), 0); err != nil {
return err
}
}

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between bc45673 and 4e99f74.

📒 Files selected for processing (1)
  • state-transition/core/state_processor.go (3 hunks)
🔇 Additional comments (5)
state-transition/core/state_processor.go (5)

33-33: Import statement addition is appropriate

The addition of the constants package is necessary for accessing constant values like GenesisEpoch.


378-381: Slot retrieval and error handling are correct

The retrieval of slot and the handling of potential errors are properly implemented.


383-400: Switch statement logic is correctly structured

The switch cases handle different DepositEth1ChainID conditions appropriately, calling hollowProcessRewardsAndPenalties when necessary.


401-407: Error handling in epoch processing functions is sound

The sequential calls to processEffectiveBalanceUpdates, processSlashingsReset, and processRandaoMixesReset with proper error checks ensure robustness.


495-525: ⚠️ Potential issue

Fix the incorrect loop iteration in 'hollowProcessRewardsAndPenalties'

The loop for i := range valCount is incorrect because valCount is a numeric value representing the total number of validators, not a slice or array. Using range on an integer will result in a compilation error.

Apply this diff to correct the loop:

-	for i := range valCount {
+	for i := uint64(0); i < valCount; i++ {

Comment on lines +495 to +527
func (sp *StateProcessor[
_, _, _, BeaconStateT, _, _, _, _, _, _, _, _, _, _, _, _, _,
]) hollowProcessRewardsAndPenalties(st BeaconStateT) error {
slot, err := st.GetSlot()
if err != nil {
return err
}

if sp.cs.SlotToEpoch(slot) == math.U64(constants.GenesisEpoch) {
return nil
}

// this has been simplified to make clear that
// we are not really doing anything here
valCount, err := st.GetTotalValidators()
if err != nil {
return err
}

for i := range valCount {
// Increase the balance of the validator.
if err = st.IncreaseBalance(math.ValidatorIndex(i), 0); err != nil {
return err
}

// Decrease the balance of the validator.
if err = st.DecreaseBalance(math.ValidatorIndex(i), 0); err != nil {
return err
}
}

return nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider adding unit tests for 'hollowProcessRewardsAndPenalties'

Adding unit tests for the new hollowProcessRewardsAndPenalties function will ensure its correctness across different scenarios.

@@ -84,7 +84,7 @@ func (sp *StateProcessor[
// We keep it for backward compatibility.
depositIndex++
case sp.cs.DepositEth1ChainID() == spec.BoonetEth1ChainID &&
slot < math.U64(spec.BoonetFork2Height):
slot != 0 && slot < math.U64(spec.BoonetFork2Height):
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

genesis indexes were set right, so we don't correct them.

@@ -470,6 +492,40 @@ func (sp *StateProcessor[
return st.SetLatestBlockHeader(lbh)
}

func (sp *StateProcessor[
_, _, _, BeaconStateT, _, _, _, _, _, _, _, _, _, _, _, _, _,
]) hollowProcessRewardsAndPenalties(st BeaconStateT) error {
Copy link
Contributor

Choose a reason for hiding this comment

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

would just add a comment above this function explaining it came from getAttestationDeltas which was just returning 0s for rewards and 0s for penalties.

Copy link
Contributor

@calbera calbera left a comment

Choose a reason for hiding this comment

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

add one comment then LGTM

@abi87 abi87 merged commit cf624db into main Dec 6, 2024
16 checks passed
@abi87 abi87 deleted the fix-boonet-sync branch December 6, 2024 16:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants