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(server/v2/store): Add ModuleHashByHeightQuery command #23479

Merged
merged 2 commits into from
Jan 22, 2025

Conversation

julienrbrt
Copy link
Member

@julienrbrt julienrbrt commented Jan 22, 2025

Description

Closes: #23019


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

  • New Features

    • Added a new CLI command to retrieve module hashes at a specific height.
    • Introduced a debugging tool for verifying application state through module hash queries.
  • Improvements

    • Enhanced command-line interface with additional query functionality.
    • Implemented JSON output for module hash information.

The new feature allows users to inspect module hashes at a specific blockchain height, providing improved debugging and state verification capabilities.

@julienrbrt julienrbrt requested a review from a team as a code owner January 22, 2025 14:15
@julienrbrt julienrbrt changed the title feat(server/v2/store): Add ModuleHashByHeightQuery feat(server/v2/store): Add ModuleHashByHeightQuery command Jan 22, 2025
Copy link
Contributor

coderabbitai bot commented Jan 22, 2025

📝 Walkthrough

Walkthrough

This pull request adds a new command ModuleHashByHeightQuery to the server's command-line interface, enabling users to retrieve module hashes at a specific blockchain height. The implementation involves creating a new method in the Server[T] struct that allows querying module hash information, with support for converting height to an integer, fetching state commitment, and outputting the results in JSON format. Additionally, a modification is made to the ExportSnapshotCmd method to streamline height handling.

Changes

File Change Summary
server/v2/store/commands.go - Added ModuleHashByHeightQuery() method
- Implemented getModuleHashesAtHeight() function
- Added new imports for hex, JSON, sorting, and string conversions
server/v2/store/server.go - Updated CLICommands() to include new ModuleHashByHeightQuery() method
server/v2/store/snapshot.go - Modified height assignment in ExportSnapshotCmd to retain type as uint64

Possibly related PRs

Suggested Labels

C:server/v2 appmanager, C:server/v2 cometbft, C:Store

Suggested Reviewers

  • kocubinski
  • facundomedica
  • testinginprod
  • sontrinh16
  • tac0turtle
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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.

@github-actions github-actions bot added the C:server/v2 Issues related to server/v2 label Jan 22, 2025
Copy link
Contributor

@julienrbrt your pull request is missing a changelog!

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

🧹 Nitpick comments (1)
server/v2/store/commands.go (1)

124-165: Optimize memory usage and improve documentation.

Several improvements can be made to this function:

  1. The hex-encoded hash is unnecessarily converted back to bytes
  2. Memory allocation can be optimized
  3. Missing documentation for exported function

Here's the suggested implementation:

+// getModuleHashesAtHeight retrieves the commit info at the specified height and
+// returns it with hex-encoded hashes sorted by store name.
 func getModuleHashesAtHeight(vp *viper.Viper, logger log.Logger, height uint64) (*proof.CommitInfo, error) {
     rootStore, _, err := createRootStore(vp, logger)
     if err != nil {
         return nil, fmt.Errorf("can not create root store %w", err)
     }

     commitInfoForHeight, err := rootStore.GetStateCommitment().GetCommitInfo(height)
     if err != nil {
         return nil, err
     }

-    // Create a new slice of StoreInfos for storing the modified hashes.
-    storeInfos := make([]*proof.StoreInfo, len(commitInfoForHeight.StoreInfos))
+    // Modify the existing StoreInfos slice in-place
+    storeInfos := commitInfoForHeight.StoreInfos
     for i, storeInfo := range commitInfoForHeight.StoreInfos {
-        // Convert the hash to a hexadecimal string.
         hash := strings.ToUpper(hex.EncodeToString(storeInfo.CommitId.Hash))
-
-        // Create a new StoreInfo with the modified hash.
-        storeInfos[i] = &proof.StoreInfo{
-            Name: storeInfo.Name,
-            CommitId: &proof.CommitID{
-                Version: storeInfo.CommitId.Version,
-                Hash:    []byte(hash),
-            },
-        }
+        storeInfo.CommitId.Hash = []byte(hash)
+        storeInfos[i] = storeInfo
     }

     // Sort the storeInfos slice based on the module name.
     sort.Slice(storeInfos, func(i, j int) bool {
         return storeInfos[i].Name < storeInfos[j].Name
     })

-    // Create a new CommitInfo with the modified StoreInfos.
-    commitInfoForHeight = &proof.CommitInfo{
-        Version:    commitInfoForHeight.Version,
-        StoreInfos: storeInfos,
-        Timestamp:  commitInfoForHeight.Timestamp,
-    }

     return commitInfoForHeight, nil
 }
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 39b0244 and ef5466b.

📒 Files selected for processing (2)
  • server/v2/store/commands.go (2 hunks)
  • server/v2/store/server.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
server/v2/store/server.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/store/commands.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: tests (03)
  • GitHub Check: tests (02)
  • GitHub Check: tests (01)
  • GitHub Check: tests (00)
  • GitHub Check: test-simapp-v2
  • GitHub Check: test-sim-nondeterminism
  • GitHub Check: test-system-v2
  • GitHub Check: build (arm64)
  • GitHub Check: test-integration
  • GitHub Check: build (amd64)
  • GitHub Check: Analyze
  • GitHub Check: Summary
🔇 Additional comments (2)
server/v2/store/server.go (1)

63-63: LGTM! Command registration follows established patterns.

The addition of ModuleHashByHeightQuery to the CLI commands is consistent with the existing command registration pattern.

server/v2/store/commands.go (1)

4-9: LGTM! Import organization follows style guide.

The new imports are properly grouped and all are necessary for the new functionality.

Comment on lines +83 to +122
// ModuleHashByHeightQuery retrieves the module hashes at a given height.
func (s *Server[T]) ModuleHashByHeightQuery() *cobra.Command {
cmd := &cobra.Command{
Use: "module-hash-by-height <height>",
Short: "Get module hashes at a given height",
Long: "Get module hashes at a given height. This command is useful for debugging and verifying the state of the application at a given height. Daemon should not be running when calling this command.",
Example: "<appd module-hash-by-height 16841115",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
vp := serverv2.GetViperFromCmd(cmd)
if err := vp.BindPFlags(cmd.Flags()); err != nil {
return err
}
if err := vp.BindPFlags(cmd.PersistentFlags()); err != nil {
return err
}

heightToRetrieveString := args[0]
height, err := strconv.ParseInt(heightToRetrieveString, 10, 64)
if err != nil {
return fmt.Errorf("invalid height: %w", err)
}

commitInfoForHeight, err := getModuleHashesAtHeight(vp, serverv2.GetLoggerFromCmd(cmd), uint64(height))
if err != nil {
return err
}

bytes, err := json.Marshal(commitInfoForHeight)
if err != nil {
return fmt.Errorf("failed to marshal commit info: %w", err)
}

cmd.Println(string(bytes))
return nil
},
}

return cmd
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add height validation checks.

The height parameter needs additional validation:

  1. Check for negative values after parsing
  2. Verify the height doesn't exceed the latest height
  3. Improve error messages to be more descriptive

Here's the suggested implementation:

 func (s *Server[T]) ModuleHashByHeightQuery() *cobra.Command {
     cmd := &cobra.Command{
         Use:     "module-hash-by-height <height>",
         Short:   "Get module hashes at a given height",
         Long:    "Get module hashes at a given height. This command is useful for debugging and verifying the state of the application at a given height. Daemon should not be running when calling this command.",
         Example: "<appd module-hash-by-height 16841115",
         Args:    cobra.ExactArgs(1),
         RunE: func(cmd *cobra.Command, args []string) error {
             vp := serverv2.GetViperFromCmd(cmd)
             if err := vp.BindPFlags(cmd.Flags()); err != nil {
                 return err
             }
             if err := vp.BindPFlags(cmd.PersistentFlags()); err != nil {
                 return err
             }

             heightToRetrieveString := args[0]
             height, err := strconv.ParseInt(heightToRetrieveString, 10, 64)
             if err != nil {
-                return fmt.Errorf("invalid height: %w", err)
+                return fmt.Errorf("failed to parse height %q: %w", heightToRetrieveString, err)
             }
+            if height < 0 {
+                return fmt.Errorf("height cannot be negative: %d", height)
+            }
+
+            rootStore, _, err := createRootStore(vp, serverv2.GetLoggerFromCmd(cmd))
+            if err != nil {
+                return fmt.Errorf("failed to create root store: %w", err)
+            }
+
+            latestHeight, err := rootStore.GetLatestVersion()
+            if err != nil {
+                return fmt.Errorf("failed to get latest height: %w", err)
+            }
+
+            if uint64(height) > latestHeight {
+                return fmt.Errorf("height %d is greater than latest height %d", height, latestHeight)
+            }

             commitInfoForHeight, err := getModuleHashesAtHeight(vp, serverv2.GetLoggerFromCmd(cmd), uint64(height))
             if err != nil {
                 return err
             }

             bytes, err := json.Marshal(commitInfoForHeight)
             if err != nil {
                 return fmt.Errorf("failed to marshal commit info: %w", err)
             }

             cmd.Println(string(bytes))
             return nil
         },
     }

     return cmd
 }

Committable suggestion skipped: line range outside the PR's diff.

@julienrbrt julienrbrt enabled auto-merge January 22, 2025 19:47
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

🔭 Outside diff range comments (1)
server/v2/store/snapshot.go (1)

Line range hint 36-51: Add overflow checks for height conversions.

The code should validate height values when converting between signed and unsigned integers to prevent silent overflow issues. This includes both the command-line input and the lastCommitId.Version.

Apply this diff to add overflow checks:

 			height, err := cmd.Flags().GetInt64("height")
 			if err != nil {
 				return err
 			}
+			if height < 0 {
+				return fmt.Errorf("height cannot be negative: %d", height)
+			}
 
 			logger := serverv2.GetLoggerFromCmd(cmd)
 			rootStore, _, err := createRootStore(v, logger)
 			if err != nil {
 				return err
 			}
 			if height == 0 {
 				lastCommitId, err := rootStore.LastCommitID()
 				if err != nil {
 					return err
 				}
+				if lastCommitId.Version > uint64(math.MaxInt64) {
+					return fmt.Errorf("height %d exceeds maximum allowed value", lastCommitId.Version)
+				}
 				height = int64(lastCommitId.Version)
 			}
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ef5466b and 07e5912.

📒 Files selected for processing (1)
  • server/v2/store/snapshot.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
server/v2/store/snapshot.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: tests (03)
  • GitHub Check: tests (02)
  • GitHub Check: tests (01)
  • GitHub Check: tests (00)
  • GitHub Check: test-simapp-v2
  • GitHub Check: test-system-v2
  • GitHub Check: test-sim-nondeterminism
  • GitHub Check: test-integration
  • GitHub Check: build (arm64)
  • GitHub Check: build (amd64)
  • GitHub Check: Analyze
  • GitHub Check: golangci-lint
  • GitHub Check: Summary

@@ -48,7 +48,7 @@ func (s *Server[T]) ExportSnapshotCmd() *cobra.Command {
if err != nil {
return err
}
height = int64(lastCommitId.Version)
height = lastCommitId.Version
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Restore the explicit type conversion for type safety.

The removal of the explicit type conversion from uint64 to int64 could lead to compilation errors and potential data loss for heights greater than MaxInt64. The height variable is declared as int64 from flag parsing, so we should maintain consistent type handling.

Apply this diff to restore type safety:

-				height = lastCommitId.Version
+				height = int64(lastCommitId.Version)
📝 Committable suggestion

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

Suggested change
height = lastCommitId.Version
height = int64(lastCommitId.Version)

@julienrbrt julienrbrt added this pull request to the merge queue Jan 22, 2025
Merged via the queue into main with commit 3860b2b Jan 22, 2025
73 of 74 checks passed
@julienrbrt julienrbrt deleted the julien/add-cmds branch January 22, 2025 20:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C:server/v2 Issues related to server/v2
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add ModuleHashByHeightQuery command in server/v2/store
2 participants