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): fix deposit index upon genesis processing #2116

Merged
merged 2 commits into from
Oct 31, 2024

Conversation

abi87
Copy link
Collaborator

@abi87 abi87 commented Oct 31, 2024

Fixes #1538

The more general cleanup to drop Eth1Data is deferred to a future PR

Summary by CodeRabbit

Release Notes

  • New Features

    • Added a new package for mock generation to facilitate testing.
    • Introduced a new interface for managing withdrawals, enhancing clarity in the execution engine.
  • Bug Fixes

    • Improved error handling in deposit processing and withdrawal functions.
  • Tests

    • Added a test suite for validating the initialization of the state processor from Ethereum 1.0 data.
  • Documentation

    • Enhanced comments and organization for better code clarity and maintainability.

@abi87 abi87 self-assigned this Oct 31, 2024
Copy link
Contributor

coderabbitai bot commented Oct 31, 2024

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

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

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

Walkthrough

The pull request introduces several changes across multiple files, focusing on enhancing mock generation, testing capabilities, and state processing in the blockchain environment. Key updates include the addition of a new package in the .mockery.yaml for generating mocks of the ExecutionEngine, the creation of a testing setup in helpers_test.go, and modifications to the StateProcessor struct to track genesis processing. Furthermore, new interfaces and error handling improvements are implemented to refine the state transition logic.

Changes

File Path Change Summary
.mockery.yaml Added package github.com/berachain/beacon-kit/mod/state-transition/pkg/core with specific configuration.
mod/state-transition/pkg/core/helpers_test.go Introduced testing types and functions for state transitions, including TestKVStoreService and initTestStore.
mod/state-transition/pkg/core/mocks/execution_engine.mock.go Added mock implementation for ExecutionEngine with methods for simulating behavior during tests.
mod/state-transition/pkg/core/state_processor.go Added processingGenesis boolean field to StateProcessor struct for genesis initialization tracking.
mod/state-transition/pkg/core/state_processor_genesis.go Updated InitializePreminedBeaconStateFromEth1 to include processingGenesis logic.
mod/state-transition/pkg/core/state_processor_genesis_test.go Created test suite for validating state processor functionality with Ethereum 1.0 data.
mod/state-transition/pkg/core/state_processor_staking.go Enhanced error handling and control flow in deposit processing functions.
mod/state-transition/pkg/core/types.go Introduced new Withdrawals interface and updated ExecutionEngine to reference it.

Assessment against linked issues

Objective Addressed Explanation
Fix eth1 deposit index to start at 0 (1538)

Possibly related PRs

Suggested reviewers

  • itsdevbear
  • ocnc
  • nidhi-singh02

Poem

🐇 In the land of code where bunnies hop,
New mocks and tests, we never stop!
With states and transitions, we play all day,
Building a future in a blockchain way.
So here’s to the changes, both big and small,
Together we code, together we stand tall! 🌟


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.

@abi87 abi87 changed the base branch from main to state-transition-add-UTs October 31, 2024 11:32
Copy link

codecov bot commented Oct 31, 2024

Codecov Report

Attention: Patch coverage is 80.00000% with 6 lines in your changes missing coverage. Please review.

Project coverage is 24.81%. Comparing base (4a9fe1c) to head (f4c7519).
Report is 3 commits behind head on state-transition-add-UTs.

Files with missing lines Patch % Lines
...ate-transition/pkg/core/state_processor_staking.go 63.63% 3 Missing and 1 partial ⚠️
...ate-transition/pkg/core/state_processor_genesis.go 89.47% 0 Missing and 2 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@                     Coverage Diff                      @@
##           state-transition-add-UTs    #2116      +/-   ##
============================================================
+ Coverage                     24.75%   24.81%   +0.06%     
============================================================
  Files                           357      357              
  Lines                         16047    16057      +10     
  Branches                         12       12              
============================================================
+ Hits                           3972     3985      +13     
+ Misses                        11879    11878       -1     
+ Partials                        196      194       -2     
Files with missing lines Coverage Δ
mod/state-transition/pkg/core/state_processor.go 4.72% <ø> (ø)
...ate-transition/pkg/core/state_processor_genesis.go 48.95% <89.47%> (+6.73%) ⬆️
...ate-transition/pkg/core/state_processor_staking.go 25.43% <63.63%> (+1.76%) ⬆️

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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 7

🧹 Outside diff range comments (2)
mod/state-transition/pkg/core/state_processor_genesis.go (1)

Line range hint 50-96: Consider documenting the genesis state handling design

The refactoring moves deposit index handling to processDeposit while using a flag to differentiate genesis processing. This is a good separation of concerns, but consider adding documentation to explain:

  1. Why the deposit index handling is special during genesis
  2. How processDeposit behaves differently during genesis
  3. The relationship between these changes and issue fix(eth1): deposit index is incorrect #1538

This will help future maintainers understand the design decisions.

mod/state-transition/pkg/core/state_processor.go (1)

Line range hint 171-177: Consider explicit initialization of processingGenesis.

While the default false value is correct, consider explicitly initializing processingGenesis in the constructor for better clarity:

 return &StateProcessor[
   BeaconBlockT, BeaconBlockBodyT, BeaconBlockHeaderT,
   BeaconStateT, ContextT, DepositT, Eth1DataT, ExecutionPayloadT,
   ExecutionPayloadHeaderT, ForkT, ForkDataT, KVStoreT, ValidatorT,
   ValidatorsT, WithdrawalT, WithdrawalsT, WithdrawalCredentialsT,
 ]{
   cs:              cs,
   executionEngine: executionEngine,
   signer:          signer,
+  processingGenesis: false,
 }
🛑 Comments failed to post (7)
mod/state-transition/pkg/core/helpers_test.go (2)

43-78: 🧹 Nitpick (assertive)

Add documentation for the test type aliases.

These type aliases are complex and their purpose isn't immediately clear. Consider adding documentation comments explaining:

  • The purpose of each type alias
  • How they relate to the production types they're based on
  • Example usage in tests

96-138: 🧹 Nitpick (assertive)

Improve readability of function signature using type alias.

The function signature is quite verbose due to the generic type parameters. Consider using the TestKVStoreT type alias that was defined earlier to simplify it:

-func initTestStore() (
-	*beacondb.KVStore[
-		*types.BeaconBlockHeader,
-		*types.Eth1Data,
-		*types.ExecutionPayloadHeader,
-		*types.Fork,
-		*types.Validator,
-		types.Validators,
-	], error) {
+func initTestStore() (*TestKVStoreT, error) {

Committable suggestion was skipped due to low confidence.

mod/state-transition/pkg/core/mocks/execution_engine.mock.go (1)

74-86: 🧹 Nitpick (assertive)

Consider adding nil check for testing interface.

While the implementation is correct, consider adding a defensive nil check for the testing interface to prevent potential panics.

 func NewExecutionEngine[ExecutionPayloadT core.ExecutionPayload[ExecutionPayloadT, ExecutionPayloadHeaderT, WithdrawalsT], ExecutionPayloadHeaderT any, WithdrawalsT core.Withdrawals](t interface {
 	mock.TestingT
 	Cleanup(func())
 }) *ExecutionEngine[ExecutionPayloadT, ExecutionPayloadHeaderT, WithdrawalsT] {
+	if t == nil {
+		panic("testing interface cannot be nil")
+	}
 	mock := &ExecutionEngine[ExecutionPayloadT, ExecutionPayloadHeaderT, WithdrawalsT]{}
 	mock.Mock.Test(t)
📝 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.

// NewExecutionEngine creates a new instance of ExecutionEngine. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewExecutionEngine[ExecutionPayloadT core.ExecutionPayload[ExecutionPayloadT, ExecutionPayloadHeaderT, WithdrawalsT], ExecutionPayloadHeaderT any, WithdrawalsT core.Withdrawals](t interface {
	mock.TestingT
	Cleanup(func())
}) *ExecutionEngine[ExecutionPayloadT, ExecutionPayloadHeaderT, WithdrawalsT] {
	if t == nil {
		panic("testing interface cannot be nil")
	}
	mock := &ExecutionEngine[ExecutionPayloadT, ExecutionPayloadHeaderT, WithdrawalsT]{}
	mock.Mock.Test(t)

	t.Cleanup(func() { mock.AssertExpectations(t) })

	return mock
}
mod/state-transition/pkg/core/state_processor_genesis_test.go (2)

81-97: 🧹 Nitpick (assertive)

Consider adding edge cases to test deposits.

The current test cases cover basic scenarios with different deposit amounts. Consider adding edge cases such as:

  • Maximum number of validators
  • Zero amount deposits
  • Duplicate public keys

102-106: ⚠️ Potential issue

Strengthen mock expectations for signature verification.

The current mock setup accepts any arguments and always returns nil. Consider:

  1. Verifying the actual signature parameters being passed
  2. Testing failure scenarios where signature verification fails
// Example of stronger mock expectations
mocksSigner.On(
    "VerifySignature",
    mock.MatchedBy(func(msg []byte) bool {
        // Add specific message validation
        return len(msg) > 0
    }),
    mock.MatchedBy(func(sig []byte) bool {
        // Add specific signature validation
        return len(sig) == 96
    }),
    mock.Anything,
).Return(nil)
mod/state-transition/pkg/core/state_processor.go (1)

88-91: 🧹 Nitpick (assertive)

Enhance field documentation for better context.

The field addition aligns with the PR objective. Consider enhancing the comment to better explain the specific issue it addresses:

-	// processingGenesis allows initializing correctly
-	// eth1 deposit index upon genesis
+	// processingGenesis tracks whether we are processing genesis state to ensure
+	// eth1 deposit index starts at zero and does not account for genesis validators.
📝 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.

	// processingGenesis tracks whether we are processing genesis state to ensure
	// eth1 deposit index starts at zero and does not account for genesis validators.
	processingGenesis bool
mod/state-transition/pkg/core/state_processor_staking.go (1)

88-100: 🛠️ Refactor suggestion

Use errors.Wrapf instead of fmt.Errorf for consistent error handling

The code uses fmt.Errorf to wrap errors, but elsewhere in the codebase, errors.Wrapf is used. For consistency, consider replacing fmt.Errorf with errors.Wrapf.

Apply this diff to make the change:

- return fmt.Errorf("failed retrieving eth1 deposit index: %w", err)
+ return errors.Wrapf(err, "failed retrieving eth1 deposit index")
📝 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.

	var nextDepositIndex uint64
	switch depositIndex, err := st.GetEth1DepositIndex(); {
	case err == nil:
		nextDepositIndex = depositIndex + 1
	case sp.processingGenesis && err != nil:
		// Eth1DepositIndex may have not been set yet
		nextDepositIndex = 0
	default:
		// Failed retrieving Eth1DepositIndex outside genesis is an error
		return errors.Wrapf(err, "failed retrieving eth1 deposit index")
	}

	if err := st.SetEth1DepositIndex(nextDepositIndex); err != nil {
```

Note: The suggestion assumes that the `errors` package is already imported in the file. If it's not, an additional import statement would need to be added to the file's import block:
```go
import "github.com/pkg/errors"

// check that validator index is duly set
latestValIdx, err := beaconState.GetEth1DepositIndex()
require.NoError(t, err)
require.Equal(t, uint64(len(deposits)-1), latestValIdx)
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

deposits should be zero-indexed, not 1-indexed as they currently are

@itsdevbear itsdevbear merged commit d90a95a into state-transition-add-UTs Oct 31, 2024
16 checks passed
@itsdevbear itsdevbear deleted the fix-deposit-index branch October 31, 2024 14:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

fix(eth1): deposit index is incorrect
2 participants