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

feat(epochs): backport the module from SDK #102

Merged
merged 22 commits into from
Jul 11, 2024

Conversation

MaxMustermann2
Copy link
Contributor

@MaxMustermann2 MaxMustermann2 commented Jun 14, 2024

This PR is a backport of the Cosmos SDK's epochs module. The backport allows us the flexibility to define our own epochs as default epochs and fixes a bug wherein the first epoch in the hook was always 2.

Summary by CodeRabbit

  • New Features

    • Introduced CLI query commands for the epochs module.
    • Added functionality for initializing and exporting genesis state for epochs.
    • Introduced new test helpers for setting up epoch-related queries and clients.
  • Bug Fixes

    • Fixed import path issues related to the epochs package across multiple files.
  • Documentation

    • Updated x/epochs/README.md to reflect new functionalities and changes.
  • Refactor

    • Modified various import paths and package names to align with the new repository structure.
  • Tests

    • Added new test cases to validate epoch increments, chain downtime handling, and querying epoch information.
  • Chores

    • Updated workflow configurations to include necessary tokens and conditional setups.
    • Added exclusion patterns in .semgrepignore for specific simulation directories.

Copy link
Contributor

coderabbitai bot commented Jun 14, 2024

Walkthrough

This update primarily involves a series of enhancements and modifications across several components of the Exocore project. Key changes include integrating GitHub tokens in workflow configurations, adopting the new Exocore namespace for the epochs package, and adding various functionalities and tests for epochs in the blockchain system. New CLI commands and the ability to manage epoch information are also introduced.

Changes

Files Change Summary
.github/workflows/proto.yml Added github_token for buf-setup-action in job configurations.
.github/workflows/super-linter.yml Added conditional configurations for running with act.
.semgrepignore Added exclusion pattern for x/*/simulation/ directory.
app/app.go Updated import paths from evmos to ExocoreNetwork/exocore.
local_node.sh Modified epoch parameters and added custom epoch definitions.
proto/exocore/epochs/v1/*.proto Introduced EpochInfo and GenesisState messages, updated package names and endpoints.
testutil/utils.go Added InitTime field and new functions for managing block commits.
x/dogfood/keeper/*.go Updated import path for epochstypes.
x/dogfood/keeper/keeper.go Updated Hooks function to check for k.dogfoodHooks being nil.
x/dogfood/types/*.go Changed import path for epochstypes, updated comments.
x/epochs/*.md Added AfterEpochEnd and BeforeEpochStart functions, updated queries.
x/epochs/client/cli/query.go Introduced new CLI query commands for epochs.
x/epochs/keeper/*.go Added methods for managing epochs, initializing/exporting genesis state, and querying epoch information.
x/epochs/keeper/*_test.go Added test cases for epoch increments, chain downtime, and querying epoch information.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant EpochsModule
    participant Blockchain

    User ->> CLI: Query Epoch Info
    CLI ->> EpochsModule: GetEpochInfo
    EpochsModule ->> Blockchain: Retrieve Epoch Data
    Blockchain -->> EpochsModule: Epoch Data
    EpochsModule -->> CLI: Epoch Info
    CLI -->> User: Display Epoch Info

    User ->> CLI: Query Current Epoch
    CLI ->> EpochsModule: GetCurrentEpoch
    EpochsModule ->> Blockchain: Retrieve Current Epoch
    Blockchain -->> EpochsModule: Current Epoch
    EpochsModule -->> CLI: Current Epoch Info
    CLI -->> User: Display Current Epoch
Loading

Poem

In the world of code so bright,
Epochs tick with all their might.
Changes made with tokens new,
Exocore's journey we pursue.
Queries dance, commands now sing,
Blockchain's heart, a rhythmic ring.
Cheers to all, let's celebrate,
For new features, we await!


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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
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: 9

Outside diff range and nitpick comments (2)
x/epochs/simulation/genesis.go (1)

20-31: Consider adding a comment explaining why the maximum number of epochs is set to 10 for clarity.

x/epochs/keeper/keeper.go (1)

40-50: The method SetHooks correctly prevents setting the hooks more than once and checks for nil, which are good security practices. However, consider adding a comment to explain why setting hooks twice is prohibited, as it might not be immediately clear to other developers.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 324070f and a60e577.

Files ignored due to path filters (3)
  • x/epochs/types/genesis.pb.go is excluded by !**/*.pb.go
  • x/epochs/types/query.pb.go is excluded by !**/*.pb.go
  • x/epochs/types/query.pb.gw.go is excluded by !**/*.pb.gw.go
Files selected for processing (31)
  • app/app.go (1 hunks)
  • go.mod (4 hunks)
  • local_node.sh (1 hunks)
  • proto/exocore/epochs/v1/genesis.proto (1 hunks)
  • proto/exocore/epochs/v1/query.proto (2 hunks)
  • testutil/utils.go (4 hunks)
  • x/dogfood/keeper/impl_epochs_hooks.go (1 hunks)
  • x/dogfood/types/expected_keepers.go (1 hunks)
  • x/dogfood/types/params.go (2 hunks)
  • x/epochs/README.md (1 hunks)
  • x/epochs/client/cli/query.go (1 hunks)
  • x/epochs/keeper/abci.go (1 hunks)
  • x/epochs/keeper/abci_test.go (1 hunks)
  • x/epochs/keeper/epoch_infos.go (1 hunks)
  • x/epochs/keeper/epoch_infos_test.go (1 hunks)
  • x/epochs/keeper/genesis.go (1 hunks)
  • x/epochs/keeper/grpc_query.go (1 hunks)
  • x/epochs/keeper/grpc_query_test.go (1 hunks)
  • x/epochs/keeper/keeper.go (1 hunks)
  • x/epochs/keeper/setup_test.go (1 hunks)
  • x/epochs/keeper/utils_test.go (1 hunks)
  • x/epochs/module.go (1 hunks)
  • x/epochs/simulation/genesis.go (1 hunks)
  • x/epochs/types/codec.go (1 hunks)
  • x/epochs/types/errors.go (1 hunks)
  • x/epochs/types/events.go (1 hunks)
  • x/epochs/types/genesis.go (1 hunks)
  • x/epochs/types/genesis_test.go (1 hunks)
  • x/epochs/types/hooks.go (1 hunks)
  • x/epochs/types/identifier.go (1 hunks)
  • x/epochs/types/keys.go (1 hunks)
Files not reviewed due to errors (3)
  • local_node.sh (Error: Server error. Please try again later.)
  • testutil/utils.go (Error: Server error. Please try again later.)
  • app/app.go (Error: Server error. Please try again later.)
Files skipped from review due to trivial changes (3)
  • x/dogfood/types/params.go
  • x/epochs/types/events.go
  • x/epochs/types/identifier.go
Additional context used
LanguageTool
x/epochs/README.md

[grammar] ~46-~46: The word ‘begin’ is not a noun. Did you mean “beginning” or “start”? (PREPOSITION_VERB)
Context: ...logic, and are only modified during the begin blocker. ## Hooks ```go // the firs...

Markdownlint
x/epochs/README.md

36-36: Expected: asterisk; Actual: underscore (MD049, emphasis-style)
Emphasis style


36-36: Expected: asterisk; Actual: underscore (MD049, emphasis-style)
Emphasis style

Additional comments not posted (45)
x/epochs/keeper/utils_test.go (1)

9-15: The setup for query helpers and registration of the query server in PostSetup looks well-implemented.

x/epochs/types/errors.go (2)

15-17: The error registration for ErrInvalidGenesisData is clear and follows standard practices.


18-20: The error registration for ErrDuplicateEpochInfo is clear and follows standard practices.

x/epochs/types/keys.go (2)

3-14: The constants for module identification and key management are clearly defined and follow naming conventions.


19-22: The implementation of KeyEpoch is correct and efficiently combines the prefix with the identifier.

x/epochs/keeper/genesis.go (2)

19-24: The implementation of ExportGenesis is clean and adheres to the single responsibility principle by delegating data fetching to AllEpochInfos.


10-17: Ensure validation of epoch data before adding to keeper to prevent potential security issues. Consider documenting where and how the epochs are validated.

Verification successful

The AddEpochInfo function in epoch_infos.go does indeed include validation logic through the epochInfo.Validate() call. This confirms that the epochs are validated before being added, addressing the security concern mentioned in the review comment.

  • epoch_infos.go:13: if err := epochInfo.Validate(); err != nil {

This validation ensures that the epoch data is checked for correctness before being processed further.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that epoch data is validated before being used in InitGenesis.

# Test: Search for validation logic.
rg --type go 'validate.*epoch' x/epochs/keeper/

Length of output: 258



Script:

#!/bin/bash
# Description: Find and inspect the validation function in epoch_infos.go.

# Locate the validation function.
rg --type go 'func .*validate.*epoch' x/epochs/keeper/epoch_infos.go

Length of output: 70



Script:

#!/bin/bash
# Description: Broaden search to locate validation logic for epochs across the entire codebase.

# Search for validation functions related to epochs.
rg --type go 'func .*validate.*epoch'

Length of output: 39



Script:

#!/bin/bash
# Description: Search for references to AddEpochInfo to trace validation logic.

# Find references to AddEpochInfo across the codebase.
rg 'AddEpochInfo'

Length of output: 448



Script:

#!/bin/bash
# Description: Extract and review the AddEpochInfo function from epoch_infos.go.

# Extract the AddEpochInfo function.
ast-grep --lang go --pattern $'func (k Keeper) AddEpochInfo(ctx sdk.Context, epochInfo types.EpochInfo) error {
  $$$
}' x/epochs/keeper/epoch_infos.go

Length of output: 1434

x/epochs/keeper/setup_test.go (2)

14-17: The KeeperTestSuite structure is well set up for unit testing with necessary fields and inheritance from BaseTestSuite.


24-35: The SetupTest method effectively prepares the test environment by ensuring all configured epochs are correctly initialized and meet expected conditions.

x/epochs/simulation/genesis.go (2)

15-18: GenDuration is correctly implemented for generating a random duration between 1 hour and 1 week, suitable for simulation testing.


33-46: RandomizedGenState is well-implemented for simulation purposes, with appropriate error handling and use of json.MarshalIndent for enhanced log readability.

x/epochs/types/hooks.go (2)

7-12: The EpochHooks interface is clearly defined, appropriately capturing the necessary methods for epoch event handling.


16-37: MultiEpochHooks is well-designed for combining multiple epoch hooks, allowing modular management and sequential execution of hook methods.

x/epochs/keeper/keeper.go (1)

35-38: The use of fmt.Sprintf in the Logger method is efficient for constructing the module-specific logger. This is a good use of contextual logging.

x/epochs/keeper/epoch_infos_test.go (1)

9-34: The test is well-organized and checks the persistence and ordering of epochs effectively. The use of alphabetical order for validation is a smart way to ensure consistency in the data retrieved.

proto/exocore/epochs/v1/query.proto (2)

14-20: The endpoint changes in the rpc EpochInfos and rpc CurrentEpoch methods are correctly updated to reflect the new namespace. This adheres to the best practices of maintaining clear and consistent endpoint naming conventions.


34-36: The response message for QueryEpochsInfoResponse now correctly specifies that the pagination is for the response, not the request. This change improves the clarity of the API documentation.

x/epochs/keeper/grpc_query.go (1)

49-68: The CurrentEpoch method is well-implemented with clear error handling for not found cases. This method ensures that users will receive a meaningful error message if an epoch is not found, which enhances the user experience.
[APROVED]

x/epochs/types/genesis.go (5)

10-12: The function NewGenesisState correctly initializes a GenesisState with a provided slice of EpochInfo. This is a straightforward factory function.


14-24: The DefaultGenesis function provides a sensible set of default epochs. The use of time constants (e.g., time.Hour*24) is clear and correct. It's good practice to comment that epochs are in alphabetical order, which aids in maintainability.


26-40: The Validate method for GenesisState checks for unique epoch identifiers and validates each EpochInfo. Using a map to check for uniqueness is efficient. The error handling with errorsmod.Wrapf is appropriate, providing clear error messages.


42-58: The Validate method for EpochInfo correctly checks for required conditions such as non-empty identifiers and non-zero duration. The use of plain errors.New for error messages is consistent and clear.


60-70: The NewGenesisEpochInfo function initializes EpochInfo with sensible defaults and parameters. Setting the start times and flags to their zero values is a good default behavior, ensuring that there are no uninitialized properties.
[APROVED]

x/dogfood/keeper/impl_epochs_hooks.go (3)

7-7: The import path has been correctly updated to reflect the new location of the epochs/types. This is part of the transition from evmos to ExocoreNetwork.


Line range hint 52-53: The BeforeEpochStart method is correctly implemented as a no-op for this context. This is a clear and minimalistic approach when no action is required.


Line range hint 1-51: The AfterEpochEnd method handles various lifecycle events at the end of an epoch. The logic within the method is complex but appears well-structured and handles multiple aspects of state transition. Ensure that all methods called (MarkEpochEnd, GetOptOutsToFinish, etc.) are correctly implemented and tested, as they are crucial for the correct functioning of the epoch transitions.

Verification successful

All the methods called within the AfterEpochEnd function (MarkEpochEnd, GetOptOutsToFinish, SetPendingOptOuts, DeleteOperatorOptOutFinishEpoch, ClearOptOutsToFinish, GetConsensusAddrsToPrune, SetPendingConsensusAddrs, and ClearConsensusAddrsToPrune) are implemented in the codebase. This confirms that the logic within the AfterEpochEnd method is supported by the necessary implementations.

  • MarkEpochEnd: Implemented in x/dogfood/keeper/keeper.go
  • GetOptOutsToFinish: Implemented in x/dogfood/keeper/opt_out.go
  • SetPendingOptOuts: Implemented in x/dogfood/keeper/pending.go
  • DeleteOperatorOptOutFinishEpoch: Implemented in x/dogfood/keeper/opt_out.go
  • ClearOptOutsToFinish: Implemented in x/dogfood/keeper/opt_out.go
  • GetConsensusAddrsToPrune: Implemented in x/dogfood/keeper/opt_out.go
  • SetPendingConsensusAddrs: Implemented in x/dogfood/keeper/pending.go
  • ClearConsensusAddrsToPrune: Implemented in x/dogfood/keeper/opt_out.go
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the implementation and test coverage for methods called in AfterEpochEnd.

# Test: Search for the implementation and tests for MarkEpochEnd, GetOptOutsToFinish, etc.
rg --type go $'MarkEpochEnd\\(\\)|GetOptOutsToFinish\\(\\)'

Length of output: 56



Script:

#!/bin/bash
# Description: Verify the implementation and test coverage for methods called in AfterEpochEnd.

# Test: Search for the implementation and tests for MarkEpochEnd
echo "Searching for MarkEpochEnd implementation and tests..."
rg --type go 'func MarkEpochEnd'

# Test: Search for the implementation and tests for GetOptOutsToFinish
echo "Searching for GetOptOutsToFinish implementation and tests..."
rg --type go 'func GetOptOutsToFinish'

# Test: Search for the implementation and tests for SetPendingOptOuts
echo "Searching for SetPendingOptOuts implementation and tests..."
rg --type go 'func SetPendingOptOuts'

# Test: Search for the implementation and tests for DeleteOperatorOptOutFinishEpoch
echo "Searching for DeleteOperatorOptOutFinishEpoch implementation and tests..."
rg --type go 'func DeleteOperatorOptOutFinishEpoch'

# Test: Search for the implementation and tests for ClearOptOutsToFinish
echo "Searching for ClearOptOutsToFinish implementation and tests..."
rg --type go 'func ClearOptOutsToFinish'

# Test: Search for the implementation and tests for GetConsensusAddrsToPrune
echo "Searching for GetConsensusAddrsToPrune implementation and tests..."
rg --type go 'func GetConsensusAddrsToPrune'

# Test: Search for the implementation and tests for SetPendingConsensusAddrs
echo "Searching for SetPendingConsensusAddrs implementation and tests..."
rg --type go 'func SetPendingConsensusAddrs'

# Test: Search for the implementation and tests for ClearConsensusAddrsToPrune
echo "Searching for ClearConsensusAddrsToPrune implementation and tests..."
rg --type go 'func ClearConsensusAddrsToPrune'

Length of output: 1459



Script:

#!/bin/bash
# Description: Verify the implementation and test coverage for methods called in AfterEpochEnd.

# Test: Search for the methods without the 'func' keyword to check for their presence in the codebase.

# Search for MarkEpochEnd
echo "Searching for MarkEpochEnd in the codebase..."
rg --type go 'MarkEpochEnd'

# Search for GetOptOutsToFinish
echo "Searching for GetOptOutsToFinish in the codebase..."
rg --type go 'GetOptOutsToFinish'

# Search for SetPendingOptOuts
echo "Searching for SetPendingOptOuts in the codebase..."
rg --type go 'SetPendingOptOuts'

# Search for DeleteOperatorOptOutFinishEpoch
echo "Searching for DeleteOperatorOptOutFinishEpoch in the codebase..."
rg --type go 'DeleteOperatorOptOutFinishEpoch'

# Search for ClearOptOutsToFinish
echo "Searching for ClearOptOutsToFinish in the codebase..."
rg --type go 'ClearOptOutsToFinish'

# Search for GetConsensusAddrsToPrune
echo "Searching for GetConsensusAddrsToPrune in the codebase..."
rg --type go 'GetConsensusAddrsToPrune'

# Search for SetPendingConsensusAddrs
echo "Searching for SetPendingConsensusAddrs in the codebase..."
rg --type go 'SetPendingConsensusAddrs'

# Search for ClearConsensusAddrsToPrune
echo "Searching for ClearConsensusAddrsToPrune in the codebase..."
rg --type go 'ClearConsensusAddrsToPrune'

Length of output: 4004

x/dogfood/types/expected_keepers.go (2)

5-5: The import for epochsTypes has been updated correctly to the new ExocoreNetwork namespace. This change is essential for ensuring that all types are correctly referenced after the namespace transition.


Line range hint 1-44: The interfaces defined in this file, such as EpochsKeeper, DogfoodHooks, and OperatorKeeper, are well-documented and clearly specify the expected behavior of their respective implementations. This is crucial for maintainability and understanding the module's architecture.

x/epochs/client/cli/query.go (2)

13-33: The GetQueryCmd function sets up the root command for epoch queries. The use of types.ModuleName for dynamic command construction is a good practice, ensuring that the command adapts to changes in the module name.


76-108: The GetCmdCurrentEpoch command is correctly implemented with precise argument handling and error management. The use of clientCtx.PrintProto for output is consistent with modern Cosmos SDK practices.

x/epochs/keeper/epoch_infos.go (4)

12-30: The method AddEpochInfo handles adding new epoch information to the store. It includes checks for duplicate identifiers and initializes start times and start heights if they are not set. This logic appears robust and correctly implements the necessary validations and initializations for epoch data. The error handling and use of store operations are appropriate, ensuring data integrity and consistency.


33-46: The GetEpochInfo function retrieves epoch information based on an identifier. It correctly handles cases where the epoch does not exist by returning false for the found flag. The use of MustUnmarshal ensures that the data integrity is maintained, throwing an error if the data cannot be unmarshalled into the expected structure.


58-81: The IterateEpochInfos function efficiently iterates over all epoch information in the store, applying a provided function to each. This method is well-implemented, providing a flexible way to process all epochs. The use of a closure function as a parameter adds to the method's versatility.


83-91: The AllEpochInfos method aggregates all epoch information into a slice. This method leverages the IterateEpochInfos function to collect all epochs, which is an efficient use of existing functionality. The implementation is straightforward and correctly handles the aggregation of data.
[APROVED]

x/epochs/types/genesis_test.go (1)

22-121: The TestValidateGenesis function in the GenesisTestSuite thoroughly tests various scenarios for the validation of genesis state, including handling of duplicate identifiers, blank identifiers, zero duration, and negative values for current epoch and start height. The use of a table-driven test structure enhances the clarity and maintainability of the test cases. Each test case is well-documented with expected outcomes, making it easy to understand the purpose of each test.

x/epochs/keeper/abci.go (1)

13-104: The BeginBlocker function handles the logic to start or end epochs based on the block time. It includes checks for the start and end of epochs and appropriately manages state transitions with detailed logging and event emissions. The use of telemetry and structured logging adds to the observability of the epoch transitions. The function is well-structured and contains comprehensive logic to handle various scenarios of epoch management.

proto/exocore/epochs/v1/genesis.proto (2)

11-60: The EpochInfo message is well-documented and structured. It provides a comprehensive set of fields that are crucial for managing epoch information in a blockchain context. The use of gogoproto options to handle Go-specific features like stdtime and stdduration is appropriate and ensures that the protobuf fields are correctly handled in Go without additional transformation logic. This is crucial for both performance and correctness.


63-66: The GenesisState message definition is concise and clear. It appropriately uses the repeated keyword for the epochs field to handle multiple EpochInfo instances, which is essential for initializing the state of the epochs module during the genesis block of a blockchain.

x/epochs/keeper/grpc_query_test.go (2)

11-81: The test cases in TestEpochInfos are well-constructed and cover a variety of scenarios, including a default case with all genesis epochs. The use of structured test cases with expected results ensures that any discrepancies in the epoch information retrieval can be caught during testing. This is crucial for maintaining the reliability of the epoch querying functionality.
[APROVED]


84-130: The test cases in TestCurrentEpoch handle different scenarios effectively, including edge cases like unknown or blank epoch identifiers. This thorough testing is important to ensure robust error handling and correct responses in the querying of current epoch information.

x/epochs/keeper/abci_test.go (1)

20-100: The detailed comments and test scenarios provided in the TestEpochsIncreaseByOne, TestTwoEpochIncreases, and TestChainDowntime functions are excellent. They not only test the functionality but also explain the expected behavior and the conditions under which different tests are executed. This clarity in testing is crucial for ensuring the correct implementation of epoch transitions in response to blockchain time advancements.

x/epochs/module.go (2)

32-90: The AppModuleBasic struct and its methods are well-implemented. Methods like RegisterLegacyAminoCodec, RegisterInterfaces, and DefaultGenesis are crucial for module setup and integration within the larger Cosmos SDK framework. The use of a clear and concise coding style in these foundational methods facilitates easy maintenance and understanding of the module's basic functionalities.


109-170: The AppModule struct and its associated methods effectively encapsulate the functionalities related to block processing, genesis initialization, and state export. The clear separation of concerns and the detailed method implementations ensure that the module's operations are transparent and maintainable. The inclusion of BeginBlock and EndBlock methods aligns well with the Cosmos SDK's architecture, allowing for custom logic at the start and end of each block.

go.mod (2)

34-34: Direct dependencies on github.com/spf13/pflag v1.0.5 and google.golang.org/protobuf v1.33.0 have been added. Ensure these versions are compatible with other modules and meet the specific needs of the project.

Also applies to: 44-44


Line range hint 34-44: The replace section addresses various issues including security advisories and broken dependencies. Verify that each replacement aligns with the project's goals and resolves the issues effectively.

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: CHILL

Commits

Files that changed from the base of the PR and between a60e577 and 1d5d257.

Files selected for processing (3)
  • .semgrepignore (1 hunks)
  • proto/exocore/epochs/v1/genesis.proto (1 hunks)
  • x/epochs/README.md (1 hunks)
Files skipped from review due to trivial changes (1)
  • .semgrepignore
Additional context used
LanguageTool
x/epochs/README.md

[grammar] ~44-~44: The word ‘begin’ is not a noun. Did you mean “beginning” or “start”? (PREPOSITION_VERB)
Context: ...logic, and are only modified during the begin blocker. ## Hooks ```go // the firs...

Additional comments not posted (4)
x/epochs/README.md (2)

44-44: Duplicate comment regarding grammatical correction.

Tools
LanguageTool

[grammar] ~44-~44: The word ‘begin’ is not a noun. Did you mean “beginning” or “start”? (PREPOSITION_VERB)
Context: ...logic, and are only modified during the begin blocker. ## Hooks ```go // the firs...


36-36: Duplicate comment regarding Markdown style.

proto/exocore/epochs/v1/genesis.proto (2)

11-60: The EpochInfo message is well-structured and clearly defines each field with appropriate protobuf options.


63-67: The GenesisState message is correctly defined to include a list of epochs, ensuring data integrity with the non-nullable option.

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: 4

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a60e577 and e8f735c.

Files selected for processing (8)
  • .semgrepignore (1 hunks)
  • proto/exocore/epochs/v1/genesis.proto (1 hunks)
  • x/dogfood/keeper/keeper.go (1 hunks)
  • x/epochs/README.md (1 hunks)
  • x/epochs/client/cli/query.go (1 hunks)
  • x/epochs/keeper/epoch_infos_test.go (1 hunks)
  • x/epochs/keeper/grpc_query.go (1 hunks)
  • x/epochs/keeper/keeper.go (1 hunks)
Files skipped from review due to trivial changes (1)
  • .semgrepignore
Additional context used
LanguageTool
x/epochs/README.md

[uncategorized] ~11-~11: You might be missing the article “the” here. (AI_EN_LECTOR_MISSING_DETERMINER_THE)
Context: ...ain code every-so often. The purpose of epochs module is to allow other modules...


[grammar] ~44-~44: The word ‘begin’ is not a noun. Did you mean “beginning” or “start”? (PREPOSITION_VERB)
Context: ...logic, and are only modified during the begin blocker. ## Hooks ```go // the firs...

Additional comments not posted (7)
x/epochs/keeper/keeper.go (2)

40-50: LGTM! Using panic to enforce hook constraints ensures robustness in critical blockchain operations.


52-57: Well-implemented! Providing a default no-op implementation for hooks when none are set enhances safety and robustness.

x/epochs/keeper/epoch_infos_test.go (1)

9-37: Excellent work on the test coverage for epoch information handling! Including both positive and negative scenarios provides a robust test suite.

x/epochs/keeper/grpc_query.go (2)

18-51: Well-implemented GRPC method for epoch information retrieval. Proper use of pagination and detailed error messages enhance usability and debuggability.


53-72: Excellent error handling in the CurrentEpoch query method. Clear error messages aid in troubleshooting and ensure a good user experience.

x/epochs/client/cli/query.go (1)

76-108: Well-designed CLI command for querying the current epoch. Detailed examples and robust error handling make it user-friendly and reliable.

x/dogfood/keeper/keeper.go (1)

80-83: Ensure proper handling of nil dogfoodHooks.

This implementation correctly returns an empty MultiDogfoodHooks when dogfoodHooks is nil, ensuring stability and preventing potential null pointer dereferences.

MaxMustermann2 and others added 2 commits June 14, 2024 14:08
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between e8f735c and bd8c2bb.

Files selected for processing (1)
  • x/epochs/README.md (1 hunks)
Files not reviewed due to errors (1)
  • x/epochs/README.md (Error: Server error. Please try again later.)
Additional context used
Learnings (1)
x/epochs/README.md (1)
User: MaxMustermann2
PR: ExocoreNetwork/exocore#102
File: x/epochs/README.md:44-44
Timestamp: 2024-06-14T08:40:13.568Z
Learning: The term "begin blocker" is a standard terminology within the Cosmos SDK, used to describe the beginning of block processing.
LanguageTool
x/epochs/README.md

[grammar] ~44-~44: The word ‘begin’ is not a noun. Did you mean “beginning” or “start”? (PREPOSITION_VERB)
Context: ...logic, and are only modified during the begin blocker. ## Hooks ```go // the firs...

),
)
// NOTE: this hook is called BEFORE the new epoch info is saved.
k.Hooks().AfterEpochEnd(ctx, epochInfo.Identifier, epochInfo.CurrentEpoch)
Copy link
Contributor Author

Choose a reason for hiding this comment

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

In the previously imported implementation, the AfterEpochEnd function was called after incrementing the epochInfo.CurrentEpoch, resulting in the same epoch (bearing the increased number) ending and then starting immediately afterwards

Copy link
Contributor Author

@MaxMustermann2 MaxMustermann2 Jun 16, 2024

Choose a reason for hiding this comment

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

As a result of this bug, the effective opt-out completion epoch was reduced by 1.

For example, with the number of unbonding epochs set to 2, if an operator opts out during epoch 5, they will stop validating at the end of epoch 5 and complete the opt out at the end of epoch 7. This is accurately scheduled with or without the bug being present in the x/epochs module, because the currently running epoch number is accurately fetched during the time of opt out.

With the bug, however, the epoch reported in the AfterEpochEnd hook is 7 even though the epoch currently ending is 6. The hook then finds all the opt-outs completing at epoch 7 (instead of epoch 6) and schedules them to be removed at the end of the block.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Of course, we can work around this bug by first decrementing the currentEpoch variable within each hook. But I felt that it's better to bring ownership of this code under our primary repository, given that a lot of our design depends on the epochs system.

@cloud8little
Copy link
Contributor

Query the epoch information with two successive command exocored q epochs epoch-infos, look into the minute epoch information, the current_epoch increase by 1 while the time latency for two successive command is obivioulyless than one minute. and the current_epoch_start_time in the minute identifier is incorrect.

NOTE: the genesis_time is "2024-06-14T08:34:18.95676475Z"

[root@testnet-exochain testscript]# exocored q epochs epoch-infos
epochs:
- current_epoch: "3"
  current_epoch_start_height: "3"
  current_epoch_start_time: "2024-06-16T08:34:18.956764750Z"
  duration: 86400s
  epoch_counting_started: true
  identifier: day
  start_time: "2024-06-14T08:34:18.956764750Z"
- current_epoch: "68"
  current_epoch_start_height: "68"
  current_epoch_start_time: "2024-06-17T03:34:18.956764750Z"
  duration: 3600s
  epoch_counting_started: true
  identifier: hour
  start_time: "2024-06-14T08:34:18.956764750Z"
- current_epoch: "423"
  current_epoch_start_height: "423"
  current_epoch_start_time: "2024-06-14T15:36:18.956764750Z"
  duration: 60s
  epoch_counting_started: true
  identifier: minute
  start_time: "2024-06-14T08:34:18.956764750Z"
- current_epoch: "1"
  current_epoch_start_height: "1"
  current_epoch_start_time: "2024-06-14T08:34:18.956764750Z"
  duration: 604800s
  epoch_counting_started: true
  identifier: week
  start_time: "2024-06-14T08:34:18.956764750Z"
pagination:
  next_key: null
  total: "4"
[root@testnet-exochain testscript]# exocored q epochs epoch-infos
epochs:
- current_epoch: "3"
  current_epoch_start_height: "3"
  current_epoch_start_time: "2024-06-16T08:34:18.956764750Z"
  duration: 86400s
  epoch_counting_started: true
  identifier: day
  start_time: "2024-06-14T08:34:18.956764750Z"
- current_epoch: "68"
  current_epoch_start_height: "68"
  current_epoch_start_time: "2024-06-17T03:34:18.956764750Z"
  duration: 3600s
  epoch_counting_started: true
  identifier: hour
  start_time: "2024-06-14T08:34:18.956764750Z"
- current_epoch: "424"
  current_epoch_start_height: "424"
  current_epoch_start_time: "2024-06-14T15:37:18.956764750Z"
  duration: 60s
  epoch_counting_started: true
  identifier: minute
  start_time: "2024-06-14T08:34:18.956764750Z"
- current_epoch: "1"
  current_epoch_start_height: "1"
  current_epoch_start_time: "2024-06-14T08:34:18.956764750Z"
  duration: 604800s
  epoch_counting_started: true
  identifier: week
  start_time: "2024-06-14T08:34:18.956764750Z"
pagination:
  next_key: null
  total: "4"
[root@testnet-exochain testscript]# date
Mon Jun 17 04:09:16 UTC 2024
[root@testnet-exochain testscript]# date
Mon Jun 17 04:09:18 UTC 2024
[root@testnet-exochain testscript]# date
Mon Jun 17 04:09:20 UTC 2024

The returned block time can be used to determine whether any of the
epochs are about to change.
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between bd8c2bb and a71e4db.

Files ignored due to path filters (1)
  • x/epochs/types/query.pb.go is excluded by !**/*.pb.go
Files selected for processing (3)
  • proto/exocore/epochs/v1/query.proto (2 hunks)
  • x/epochs/keeper/grpc_query.go (1 hunks)
  • x/epochs/keeper/grpc_query_test.go (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • x/epochs/keeper/grpc_query.go
Additional comments not posted (4)
proto/exocore/epochs/v1/query.proto (2)

15-17: Updated endpoint URLs and comments enhance clarity and reflect the new package structure.

Also applies to: 19-21


35-41: The modifications in the comments and structure fields are clear and align with the intended functionality of the query responses. The use of pagination and timestamp fields is appropriate for the context.

Also applies to: 47-47

x/epochs/keeper/grpc_query_test.go (2)

12-92: The test case for EpochInfos is comprehensive, covering various scenarios including default genesis values and pagination. It correctly asserts the expected results, ensuring the functionality aligns with the specifications.


94-141: The test case for CurrentEpoch adequately handles different scenarios, including error cases for unknown and blank identifiers, and a success case for a known identifier. This ensures robust error handling and correct functionality.

@MaxMustermann2
Copy link
Contributor Author

MaxMustermann2 commented Jun 17, 2024

NOTE: the genesis_time is "2024-06-14T08:34:18.95676475Z"

Given that is the case, this behavior is expected. It is the same functionality as the one implemented in the Cosmos SDK and the previously imported module.

The current epoch, given any identifier, indicates the number of periods of that epoch since the epoch counting start time (which defaults to the genesis time, if not set). For example, if the day epoch is reported as 3, it means that the 3rd day (since counting started) is ongoing.

However, the number is incremented only once during a block. This is an intentional design, since doing otherwise would result in epochs being skipped. This is the cause for the deviation that you observed.

Starting a chain with a genesis time in the past causes each produced block to increase the current epoch number by 1 until the epoch's scheduled end time (= current start time + duration) < block time.

In the provided example, the chain's genesis time was 2 days, 19 hours, 32 minutes and ~16 seconds ago. The start_time for each epoch is set to the genesis time.

Since the start_time, the 3rd day has started, which is accurately reflected in your query.
Similarly, it is the 68th hour that is currently ongoing, which is also correctly reported.
The week is the first week since the genesis time, which is again accurate.

The minute, however, is increasing by 1 at each block. 4052.3 minutes have completed between the genesis time and now, so it will increase till 4053 blocks (+ some extra for the time it takes for block production to get there) and then continue on its regular minute-wise schedule.

The comments in the code describe this detail as well.
https://github.com/ExocoreNetwork/exocore/blob/91a9681fd5448474b76229e6ef3b7193107fcc32/proto/exocore/epochs/v1/genesis.proto#L33-L51

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a71e4db and 059d839.

Files selected for processing (2)
  • x/epochs/keeper/abci.go (1 hunks)
  • x/epochs/keeper/epoch_infos.go (1 hunks)
Additional context used
Learnings (1)
x/epochs/keeper/abci.go (1)
User: MaxMustermann2
PR: ExocoreNetwork/exocore#102
File: x/epochs/README.md:44-44
Timestamp: 2024-06-14T08:40:13.568Z
Learning: The term "begin blocker" is a standard terminology within the Cosmos SDK, used to describe the beginning of block processing.
Additional comments not posted (5)
x/epochs/keeper/epoch_infos.go (4)

8-32: The AddEpochInfo function is well-implemented with appropriate validations and checks for duplicates before adding new epoch information.


34-47: The GetEpochInfo function correctly implements the logic to retrieve epoch information based on an identifier, including handling cases where the information does not exist.


59-82: The IterateEpochInfos function correctly implements the iteration over all epoch information, managing the iterator lifecycle properly.


84-92: The AllEpochInfos function is efficiently implemented, leveraging the IterateEpochInfos function to gather all epoch information.

x/epochs/keeper/abci.go (1)

13-113: The BeginBlocker function is well-structured and effectively handles the logic of starting or ending epochs based on the current block time and epoch configurations. It uses telemetry to monitor performance and logs significant actions, enhancing maintainability and observability.

Example usage:
act --workflows .github/workflows/super-linter.yml pull_request
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 059d839 and 89627e2.

Files selected for processing (2)
  • .github/workflows/proto.yml (2 hunks)
  • .github/workflows/super-linter.yml (1 hunks)
Files skipped from review due to trivial changes (2)
  • .github/workflows/proto.yml
  • .github/workflows/super-linter.yml

@MaxMustermann2
Copy link
Contributor Author

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Jun 28, 2024

Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Contributor

coderabbitai bot commented Jun 28, 2024

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

Commits

Files that changed from the base of the PR and between 002d277 and 5386343.

Files ignored due to path filters (4)
  • SAFU.pdf is excluded by !**/*.pdf
  • x/epochs/types/genesis.pb.go is excluded by !**/*.pb.go
  • x/epochs/types/query.pb.go is excluded by !**/*.pb.go
  • x/epochs/types/query.pb.gw.go is excluded by !**/*.pb.gw.go
Files selected for processing (34)
  • .github/workflows/proto.yml (2 hunks)
  • .github/workflows/super-linter.yml (1 hunks)
  • .semgrepignore (1 hunks)
  • app/app.go (1 hunks)
  • local_node.sh (1 hunks)
  • proto/exocore/epochs/v1/genesis.proto (1 hunks)
  • proto/exocore/epochs/v1/query.proto (2 hunks)
  • testutil/utils.go (4 hunks)
  • x/dogfood/keeper/impl_epochs_hooks.go (1 hunks)
  • x/dogfood/keeper/keeper.go (1 hunks)
  • x/dogfood/types/expected_keepers.go (1 hunks)
  • x/dogfood/types/params.go (2 hunks)
  • x/epochs/README.md (1 hunks)
  • x/epochs/client/cli/query.go (1 hunks)
  • x/epochs/keeper/abci.go (1 hunks)
  • x/epochs/keeper/abci_test.go (1 hunks)
  • x/epochs/keeper/epoch_infos.go (1 hunks)
  • x/epochs/keeper/epoch_infos_test.go (1 hunks)
  • x/epochs/keeper/genesis.go (1 hunks)
  • x/epochs/keeper/grpc_query.go (1 hunks)
  • x/epochs/keeper/grpc_query_test.go (1 hunks)
  • x/epochs/keeper/keeper.go (1 hunks)
  • x/epochs/keeper/setup_test.go (1 hunks)
  • x/epochs/keeper/utils_test.go (1 hunks)
  • x/epochs/module.go (1 hunks)
  • x/epochs/simulation/genesis.go (1 hunks)
  • x/epochs/types/codec.go (1 hunks)
  • x/epochs/types/errors.go (1 hunks)
  • x/epochs/types/events.go (1 hunks)
  • x/epochs/types/genesis.go (1 hunks)
  • x/epochs/types/genesis_test.go (1 hunks)
  • x/epochs/types/hooks.go (1 hunks)
  • x/epochs/types/identifier.go (1 hunks)
  • x/epochs/types/keys.go (1 hunks)
 _________________________________________________________________________________________________________________
< Estimate the order of your algorithms. Get a feel for how long things are likely to take before you write code. >
 -----------------------------------------------------------------------------------------------------------------
  \
   \   \
        \ /\
        ( )
      .( o ).

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 002d277 and 5386343.

Files ignored due to path filters (4)
  • SAFU.pdf is excluded by !**/*.pdf
  • x/epochs/types/genesis.pb.go is excluded by !**/*.pb.go
  • x/epochs/types/query.pb.go is excluded by !**/*.pb.go
  • x/epochs/types/query.pb.gw.go is excluded by !**/*.pb.gw.go
Files selected for processing (34)
  • .github/workflows/proto.yml (2 hunks)
  • .github/workflows/super-linter.yml (1 hunks)
  • .semgrepignore (1 hunks)
  • app/app.go (1 hunks)
  • local_node.sh (1 hunks)
  • proto/exocore/epochs/v1/genesis.proto (1 hunks)
  • proto/exocore/epochs/v1/query.proto (2 hunks)
  • testutil/utils.go (4 hunks)
  • x/dogfood/keeper/impl_epochs_hooks.go (1 hunks)
  • x/dogfood/keeper/keeper.go (1 hunks)
  • x/dogfood/types/expected_keepers.go (1 hunks)
  • x/dogfood/types/params.go (2 hunks)
  • x/epochs/README.md (1 hunks)
  • x/epochs/client/cli/query.go (1 hunks)
  • x/epochs/keeper/abci.go (1 hunks)
  • x/epochs/keeper/abci_test.go (1 hunks)
  • x/epochs/keeper/epoch_infos.go (1 hunks)
  • x/epochs/keeper/epoch_infos_test.go (1 hunks)
  • x/epochs/keeper/genesis.go (1 hunks)
  • x/epochs/keeper/grpc_query.go (1 hunks)
  • x/epochs/keeper/grpc_query_test.go (1 hunks)
  • x/epochs/keeper/keeper.go (1 hunks)
  • x/epochs/keeper/setup_test.go (1 hunks)
  • x/epochs/keeper/utils_test.go (1 hunks)
  • x/epochs/module.go (1 hunks)
  • x/epochs/simulation/genesis.go (1 hunks)
  • x/epochs/types/codec.go (1 hunks)
  • x/epochs/types/errors.go (1 hunks)
  • x/epochs/types/events.go (1 hunks)
  • x/epochs/types/genesis.go (1 hunks)
  • x/epochs/types/genesis_test.go (1 hunks)
  • x/epochs/types/hooks.go (1 hunks)
  • x/epochs/types/identifier.go (1 hunks)
  • x/epochs/types/keys.go (1 hunks)
Files skipped from review due to trivial changes (7)
  • .github/workflows/proto.yml
  • .github/workflows/super-linter.yml
  • .semgrepignore
  • app/app.go
  • local_node.sh
  • x/dogfood/types/params.go
  • x/epochs/types/events.go
Additional context used
Learnings (4)
x/epochs/client/cli/query.go (1)
User: MaxMustermann2
PR: ExocoreNetwork/exocore#102
File: x/epochs/client/cli/query.go:35-73
Timestamp: 2024-06-14T08:37:38.019Z
Learning: `PrintProtoLegacy` was replaced with `PrintProto` in the `x/epochs/client/cli/query.go` as part of aligning with newer SDK standards, and this change has been confirmed and approved by MaxMustermann2.
x/epochs/README.md (1)
User: MaxMustermann2
PR: ExocoreNetwork/exocore#102
File: x/epochs/README.md:44-44
Timestamp: 2024-06-14T08:40:13.568Z
Learning: The term "begin blocker" is a standard terminology within the Cosmos SDK, used to describe the beginning of block processing.
proto/exocore/epochs/v1/genesis.proto (1)
User: MaxMustermann2
PR: ExocoreNetwork/exocore#102
File: proto/exocore/epochs/v1/genesis.proto:19-19
Timestamp: 2024-06-14T08:45:34.340Z
Learning: In protobuf files, a field declaration line can continue beyond one line if it includes additional options, and the semicolon appears at the end of the complete declaration.
x/epochs/keeper/abci.go (1)
User: MaxMustermann2
PR: ExocoreNetwork/exocore#102
File: x/epochs/README.md:44-44
Timestamp: 2024-06-14T08:40:13.568Z
Learning: The term "begin blocker" is a standard terminology within the Cosmos SDK, used to describe the beginning of block processing.
LanguageTool
x/epochs/README.md

[grammar] ~44-~44: The word ‘begin’ is not a noun. Did you mean “beginning” or “start”?
Context: ...logic, and are only modified during the begin blocker. ## Hooks ```go // the firs...

(PREPOSITION_VERB)

Additional comments not posted (62)
x/epochs/types/codec.go (3)

8-9: Implement or document the purpose of RegisterCodec.

This function is currently empty. Depending on your architecture, either implement its intended functionality or provide documentation explaining why it's left empty.


11-12: Implement or document the purpose of RegisterInterfaces.

Similar to RegisterCodec, this function is also empty. It's crucial to either implement the necessary functionality or document its purpose clearly.


15-16: Variable declarations are standard and correct.

x/epochs/keeper/utils_test.go (1)

9-15: Proper setup for testing environment.

The PostSetup function correctly sets up query helpers, which is essential for testing the keeper functionalities. This setup follows best practices for modular and maintainable test code.

x/epochs/types/errors.go (1)

15-20: Proper definition of custom errors.

The custom error types ErrInvalidGenesisData and ErrDuplicateEpochInfo are well-defined and correctly registered, making error handling more descriptive and traceable.

x/epochs/types/keys.go (1)

16-22: Correct implementation of key management functionalities.

KeyEpoch function and KeyPrefixEpoch constant are implemented correctly, ensuring efficient and error-free data retrieval from the store.

x/epochs/keeper/genesis.go (1)

10-24: Correct handling of genesis state.

The InitGenesis and ExportGenesis functions are implemented correctly, ensuring proper module initialization and state export, which are essential for the module's lifecycle management.

x/epochs/keeper/setup_test.go (2)

14-17: Code Review: Struct Definition for KeeperTestSuite

The struct KeeperTestSuite inherits from testutil.BaseTestSuite and includes a queryClient of type types.QueryClient. This struct is well-defined for its purpose, encapsulating the necessary components for testing the Keeper functionalities.


24-35: Code Review: SetupTest Method

The SetupTest method initializes test conditions for Keeper functionalities. It correctly retrieves and validates epoch information for various identifiers. This setup ensures that each epoch is properly initialized before tests run, which is crucial for the integrity of subsequent tests.

x/epochs/simulation/genesis.go (3)

15-18: Code Review: Function GenDuration

The function GenDuration generates a random duration between 1 hour and 1 week. It effectively uses the rand package to ensure variability in simulation tests. This function is well-implemented for its intended use in testing.


20-31: Code Review: Function RandomizedEpochs

This function generates a list of randomized epoch configurations for testing. It correctly uses GenDuration to ensure varied epoch durations. This implementation aids in creating diverse test scenarios, which is essential for robust simulation testing.


33-46: Code Review: Function RandomizedGenState

The function RandomizedGenState effectively integrates the randomized epochs into the simulation state. It properly handles JSON marshaling and error scenarios. This function is crucial for setting up initial states in simulations and is implemented correctly.

x/epochs/types/hooks.go (2)

7-12: Code Review: EpochHooks Interface

The EpochHooks interface is well-defined, covering methods for handling events at the start and end of epochs. This interface is crucial for extending functionality via hooks, allowing custom actions at epoch boundaries.


16-37: Code Review: MultiEpochHooks Type and Methods

The MultiEpochHooks type allows combining multiple hook implementations. The methods AfterEpochEnd and BeforeEpochStart are implemented to iterate over all hooks, ensuring that all registered hooks are executed. This design promotes modularity and extensibility in handling epoch events.

x/epochs/types/identifier.go (2)

8-17: Code Review: Constants for Epoch Identifiers

The constants defined for various epoch durations (day, hour, minute, week) are clear and appropriately named. These identifiers are essential for referencing specific epochs throughout the codebase.


19-43: Code Review: Epoch Identifier Validation Functions

The functions ValidateEpochIdentifierInterface and ValidateEpochIdentifierString are well-implemented to ensure that epoch identifiers are correctly formatted. These validation mechanisms are crucial for maintaining data integrity across the system.

x/epochs/keeper/keeper.go (3)

22-32: Code Review: NewKeeper Function

The NewKeeper function is correctly implemented to initialize the Keeper struct. It ensures that all necessary components are set up for managing epochs. This function adheres to best practices in Go for struct initialization.


35-38: Code Review: Logger Method

The Logger method provides a logging interface specifically configured for the epochs module. This method correctly utilizes the Cosmos SDK's logging facilities, enhancing the debuggability of the module.


40-58: Code Review: SetHooks and Hooks Methods

The SetHooks method correctly handles setting hooks with appropriate error checks, preventing multiple initializations and nil assignments. The Hooks method provides a safe way to retrieve hooks, using lazy initialization to return a default if none are set. These implementations ensure robustness and flexibility in the module's hook management.

x/epochs/keeper/epoch_infos_test.go (1)

9-37: Comprehensive testing of epoch information addition and retrieval.

The test method TestEpochInfoAddition effectively checks various aspects of epoch information management. The addition of the negative test case for non-existent epoch info retrieval, as suggested in the previous review, has been correctly implemented. This enhances the robustness of the test suite.

x/epochs/keeper/grpc_query.go (2)

19-45: Enhanced error handling in gRPC queries.

The error message enhancement in the EpochInfos method improves debugging capabilities and provides more context when errors occur during pagination. This change, as suggested in a previous review, has been implemented correctly.


54-73: Proper error handling for non-existent epoch queries.

The CurrentEpoch method correctly handles cases where the requested epoch does not exist, returning an appropriate error message. This is crucial for robustness and user experience in production environments.

proto/exocore/epochs/v1/query.proto (2)

3-21: Well-defined gRPC service for epoch queries.

The Query service and its methods EpochInfos and CurrentEpoch are clearly defined, with appropriate HTTP GET paths and pagination support. This setup ensures that the API is both functional and user-friendly.


35-41: Clear and precise message definitions for epoch queries.

The QueryEpochsInfoResponse message includes well-defined fields with appropriate annotations for handling null values and time formats, which is crucial for data integrity and ease of use in client applications.

x/epochs/types/genesis.go (2)

10-40: Robust genesis state management and validation.

The functions for managing the genesis state, including DefaultGenesis and Validate, are well-implemented. The validation logic is comprehensive, ensuring that all epochs are unique and correctly configured.


42-58: Effective validation logic for individual epoch information.

The Validate method for EpochInfo includes thorough checks for the identifier, duration, and epoch start conditions. This ensures that the epoch data is always valid and prevents potential runtime errors.

x/dogfood/keeper/impl_epochs_hooks.go (2)

Line range hint 1-50: Well-implemented epoch hooks with detailed state management.

The AfterEpochEnd method in EpochsHooksWrapper effectively handles various state transitions at the epoch end, such as updating opt-outs and pruning consensus addresses. This method ensures that state changes are correctly applied at the correct times, enhancing the robustness of the system.


Line range hint 52-58: Placeholder implementation for BeforeEpochStart.

The BeforeEpochStart method is currently a no-op. If future requirements specify actions to be taken before an epoch starts, this method will need to be implemented accordingly.

Consider adding a comment or a TODO note to indicate potential future implementations or enhancements.

x/epochs/client/cli/query.go (3)

16-33: Review of GetQueryCmd Function:

The GetQueryCmd function is well-structured and follows best practices by dynamically building the command structure and adding sub-commands. The use of client.ValidateCmd ensures that the command validation is delegated to a standard handler, which is good for consistency.


35-73: Review of GetCmdEpochsInfos Function:

This function constructs the command for querying all epoch information. It uses pagination and error handling correctly. The change from PrintProtoLegacy to PrintProto aligns with newer SDK standards and has been previously approved.


76-109: Review of GetCmdCurrentEpoch Function:

The GetCmdCurrentEpoch command is implemented correctly, with appropriate error handling and use of PrintProto for output. The command structure is clear, and the use of exact argument matching (cobra.ExactArgs(1)) is appropriate for the command's purpose.

x/epochs/keeper/epoch_infos.go (4)

8-32: Review of AddEpochInfo Function:

The AddEpochInfo function correctly validates the epoch information before adding it to the store, which prevents corrupt or invalid data from being saved. The checks for existing epoch identifiers and the setting of default values for unset fields are correctly implemented. This function follows best practices for error handling and data integrity.


34-47: Review of GetEpochInfo Function:

This function retrieves epoch information based on an identifier. The use of the store's Get method and the handling of non-existent entries are correctly implemented. The function is straightforward and follows best practices for data retrieval.


49-57: Review of setEpochInfoUnchecked Method:

The method directly sets epoch information in the store without validation, as noted in the previous comments. The existing documentation clearly states that the caller must ensure data validity, which is a reasonable approach given this method's internal use. No further action is needed here since the context in which this method is used is controlled.


59-92: Review of Iteration Functions:

The IterateEpochInfos and AllEpochInfos functions are implemented to iterate through all epoch information stored. They use the standard Cosmos SDK iteration patterns and correctly handle the unmarshalling of data. These functions are essential for data access patterns in the keeper and are implemented correctly.

x/dogfood/types/expected_keepers.go (1)

Line range hint 1-47: Review of Keeper Interfaces:

The interfaces defined in this file (EpochsKeeper, DogfoodHooks, OperatorKeeper, DelegationKeeper, AssetsKeeper) provide a clear contract for the functionality expected from the corresponding keeper implementations. These interfaces are essential for modular design and ensure that the dogfood module can interact with other modules securely and predictably.

x/epochs/types/genesis_test.go (1)

11-121: Review of Genesis State Validation Tests:

The test suite GenesisTestSuite effectively covers various scenarios for validating the genesis state of the epochs module. The tests check for unique epoch identifiers, non-empty identifiers, valid epoch durations, and non-negative values for epoch numbers and start heights. These tests are well-structured and provide comprehensive coverage of the genesis state validation logic.

x/dogfood/keeper/keeper.go (1)

Line range hint 1-83: Review of Dogfood Keeper Implementation:

The Keeper struct in this file is well-designed, encapsulating all necessary dependencies and providing methods to interact with these dependencies. The use of panic for error handling in the SetHooks method is appropriate given the context (initialization phase). The methods for marking and checking epoch ends are implemented correctly and follow best practices for state management within the Cosmos SDK framework.

x/epochs/README.md (3)

1-1: Document Title Formatting

Consider using a more descriptive title for the README to enhance clarity and SEO.

- # Epochs
+ # Exocore Epochs Module Overview

5-7: External Link Formatting

Ensure that the Markdown link is correctly formatted without unnecessary spaces to ensure it works as expected.

- from Osmosis. Much of the documentation below is sourced from the [README in that pull request.]( https://github.com/cosmos/cosmos-sdk/blob/8b171c5a4300fb3287ab591b5e6cf221019ddb07/x/epochs/README.md)
+ from Osmosis. Much of the documentation below is sourced from the [README in that pull request.](https://github.com/cosmos/cosmos-sdk/blob/8b171c5a4300fb3287ab591b5e6cf221019ddb07/x/epochs/README.md)

44-44: Use of 'Begin Blocker'

The term "begin blocker" is accurately used here as per the Cosmos SDK terminology.

Tools
LanguageTool

[grammar] ~44-~44: The word ‘begin’ is not a noun. Did you mean “beginning” or “start”?
Context: ...logic, and are only modified during the begin blocker. ## Hooks ```go // the firs...

(PREPOSITION_VERB)

proto/exocore/epochs/v1/genesis.proto (1)

19-20: Field Options Formatting

The field options for start_time are correctly formatted and the continuation onto the next line is appropriate as per protobuf standards.

x/epochs/keeper/abci.go (1)

15-113: Comprehensive Epoch Management Logic

The BeginBlocker function is well-implemented with clear logic for handling epoch starts and ends based on block times. The use of telemetry and logging is appropriate, and the handling of first ticks and epoch transitions is robust.

x/epochs/keeper/grpc_query_test.go (1)

12-92: Comprehensive Testing of Epoch Queries

The test cases for querying epoch information are thoroughly implemented, covering various scenarios and ensuring the integrity of epoch data. The use of the KeeperTestSuite to maintain test isolation is commendable.

x/epochs/keeper/abci_test.go (1)

20-100: Epoch Transition Testing with Chain Downtime

The test cases effectively simulate various scenarios including chain downtime, ensuring that the epoch logic handles time jumps and block intervals correctly. This robust testing is crucial for the reliability of the epoch management system.

x/epochs/module.go (14)

32-40: Initialization of AppModuleBasic looks correct.

The constructor NewAppModuleBasic correctly initializes the AppModuleBasic with a codec, which is essential for data serialization and deserialization in Cosmos SDK modules.


47-51: Legacy Amino Codec Registration is correctly implemented.

The method RegisterLegacyAminoCodec uses the RegisterCodec function from the types package to register necessary types for the Amino codec. This ensures backward compatibility with Cosmos SDK's legacy encoding system.


53-57: Interface registration is implemented correctly.

RegisterInterfaces method properly registers module's concrete types as proto.Message, which is crucial for gRPC and other inter-module communication.


59-64: Default genesis state provision is properly implemented.

DefaultGenesis method correctly provides a marshaled default genesis state, which is essential for module initialization and tests.


66-76: Genesis state validation method is implemented with proper error handling.

The ValidateGenesis method correctly unmarshals the genesis state and validates it, providing detailed error information if the unmarshaling fails. This is crucial for ensuring the integrity of the genesis state at startup.


79-90: Proper error handling in gRPC Gateway route registration.

The method RegisterGRPCGatewayRoutes correctly handles potential errors during the registration process by panicking, which is acceptable here since a failure to register routes is a critical startup error.


92-103: Query command setup is correctly implemented.

The GetQueryCmd method correctly sets up the root query command for the module, enabling end-users to perform state queries defined by the module.


109-125: AppModule initialization is correctly implemented.

The NewAppModule constructor correctly sets up the AppModule with both a codec and a keeper, ensuring that all necessary dependencies are provided for the module's operations.


127-130: Service registration is correctly implemented.

The RegisterServices method correctly registers a gRPC query service, allowing the module to respond to specific gRPC queries.


138-148: Genesis initialization logic is properly implemented.

InitGenesis method correctly handles the genesis state initialization, ensuring that the module's state is set up according to the provided genesis data.


151-155: Genesis state export functionality is correctly implemented.

ExportGenesis method correctly serializes the module's state into a genesis format, ensuring that the state can be exported and reused, for instance, during blockchain upgrades.


157-160: Module versioning is handled correctly.

The ConsensusVersion method correctly provides a version number for the module, which is important for handling state-breaking changes.


162-165: BeginBlock logic is correctly implemented.

The BeginBlock method correctly triggers the BeginBlocker logic of the keeper, which is essential for processing beginning-of-block actions like updating epoch states.


167-170: EndBlock logic is correctly implemented.

The EndBlock method correctly handles the logic that needs to be triggered at the end of each block, ensuring that any necessary updates or checks are performed.

testutil/utils.go (3)

67-68: Initialization of InitTime in the test suite is appropriate.

Adding InitTime to BaseTestSuite allows for better control and testing of time-dependent features in the blockchain environment.


Line range hint 76-305: Comprehensive test setup function is well-implemented.

The SetupWithGenesisValSet function is well-structured and covers a wide range of initializations, from setting up genesis accounts to configuring modules like assets, oracle, and operators. This thorough setup is crucial for conducting meaningful and comprehensive tests.


387-401: Block transition utility functions are correctly implemented.

Functions NextBlock, Commit, and CommitAfter provide essential utilities for moving the test blockchain through different states, allowing for the testing of block-by-block transitions and state changes.

@MaxMustermann2
Copy link
Contributor Author

Test object: 3cda16e

Results for minute epoch

$ exocored query epochs current-epoch minute --output json | jq -r .current_epoch && sleep 60 && exocored query epochs current-epoch minute --output json | jq -r .current_epoch
2
3

Associated logs

2:07PM INF ending epoch identifier=minute module=x/epochs number=2

@MaxMustermann2 MaxMustermann2 requested a review from bwhour July 11, 2024 05:22
Copy link
Contributor

@bwhour bwhour left a comment

Choose a reason for hiding this comment

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

it looks good.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5386343 and ef3026c.

Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
Files selected for processing (9)
  • app/app.go (1 hunks)
  • go.mod (1 hunks)
  • local_node.sh (1 hunks)
  • precompiles/avs/avs_test.go (1 hunks)
  • precompiles/avsTask/task_test.go (1 hunks)
  • x/avs/keeper/avs_test.go (1 hunks)
  • x/avs/types/expected_keepers.go (1 hunks)
  • x/epochs/keeper/abci.go (1 hunks)
  • x/epochs/keeper/epoch_infos.go (1 hunks)
Files skipped from review due to trivial changes (4)
  • app/app.go
  • go.mod
  • local_node.sh
  • precompiles/avs/avs_test.go
Additional context used
Learnings (1)
x/epochs/keeper/abci.go (1)
Learnt from: MaxMustermann2
PR: ExocoreNetwork/exocore#102
File: x/epochs/README.md:44-44
Timestamp: 2024-06-14T08:40:13.568Z
Learning: The term "begin blocker" is a standard terminology within the Cosmos SDK, used to describe the beginning of block processing.
Additional comments not posted (9)
x/avs/types/expected_keepers.go (1)

4-4: LGTM! Import path change is correct.

The import path for epochs types has been updated to github.com/ExocoreNetwork/exocore/x/epochs/types, which aligns with the PR objectives.

x/epochs/keeper/epoch_infos.go (5)

9-33: LGTM! The function is well-structured.

The AddEpochInfo function appropriately validates the epoch information, checks for duplicates, and sets the start time and height if not provided.


35-47: LGTM! The function is correctly implemented.

The GetEpochInfo function correctly retrieves epoch information from the store and handles the unmarshalling process.


49-56: LGTM! Ensure safe usage contexts.

The setEpochInfoUnchecked function is correctly implemented. Ensure that it is only called in contexts where data integrity is guaranteed, as indicated by the comments.


58-81: LGTM! The function is correctly implemented.

The IterateEpochInfos function correctly iterates through all epoch information in the store, with proper handling of the store and iterator.


83-91: LGTM! The function is correctly implemented.

The AllEpochInfos function correctly gathers all epoch information by utilizing the IterateEpochInfos function.

x/epochs/keeper/abci.go (1)

13-124: LGTM! The function is well-structured.

The BeginBlocker function appropriately handles the start and end of epochs, with proper validation, logging, event emission, and hook calls.

precompiles/avsTask/task_test.go (1)

9-9: LGTM! Import path change is correct.

The import path for epochs types has been updated to github.com/ExocoreNetwork/exocore/x/epochs/types, which aligns with the PR objectives.

x/avs/keeper/avs_test.go (1)

8-8: Import path update is correct.

The import path change for epochstypes is consistent with the backporting of the epochs module to Exocore.

@MaxMustermann2 MaxMustermann2 merged commit 06fd123 into imua-xyz:develop Jul 11, 2024
21 of 22 checks passed
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.

4 participants