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

prepare initiation-2 upgrade #292

Merged
merged 17 commits into from
Oct 31, 2024
Merged

prepare initiation-2 upgrade #292

merged 17 commits into from
Oct 31, 2024

Conversation

sh-cha
Copy link
Contributor

@sh-cha sh-cha commented Oct 29, 2024

Description

Closes: #XXXX


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
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • 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.

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

@sh-cha sh-cha self-assigned this Oct 29, 2024
@sh-cha sh-cha requested a review from a team as a code owner October 29, 2024 09:58
Copy link

coderabbitai bot commented Oct 29, 2024

Warning

Rate limit exceeded

@beer-1 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 14 minutes and 56 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 84e4d54 and 88f1c1c.

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces substantial changes across multiple files, primarily enhancing the upgrade handling logic in the app/upgrade.go file. Key modifications include renaming the constant upgradeName for versioning, adding new upgrade handlers that incorporate checksum handling, and improving error handling throughout the codebase. The x/move/keeper/handler.go file sees the removal of the extractModuleIdentifier function, streamlining the PublishModuleBundle function. New methods for checksum management are added in x/move/keeper/keeper.go, while the types package receives new functions and constants related to checksums and function names. Overall, these changes reflect a more organized approach to module management and error handling.

Changes

File Path Change Summary
app/upgrade.go Updated upgradeName from "0.5.6" to "0.6.0", modified RegisterUpgradeHandlers for new upgrade process, improved error handling, and added checksum management.
x/move/keeper/handler.go Removed extractModuleIdentifier, updated PublishModuleBundle, changed functionName in ExecuteEntryFunctionJSON to FunctionNameCodePublishV2, marked several methods as deprecated.
x/move/keeper/keeper.go Added methods SetChecksum and GetChecksum for checksum handling, improved error handling in GetExecutionCounter, and updated IterateVMStore callback.
x/move/types/checksum.go Introduced ModuleBzToChecksum function for computing SHA-3 checksums.
x/move/types/connector.go Added constant FunctionNameCodePublishV2 with value "publish_v2".
x/move/types/keys.go Added ChecksumSeparator, GetChecksumPrefix, and GetChecksumKey functions for checksum handling.
api/initia/intertx/v1/tx.pulsar.go Added Ordering field to MsgRegisterAccount struct, updated serialization logic accordingly.
api/initia/move/v1/genesis.pulsar.go Replaced Resources field with Checksums in GenesisState, adjusted field order.
api/initia/move/v1/types.pulsar.go Introduced new Checksum message type with fields for address, module name, and checksum.
x/move/keeper/genesis.go Enhanced InitGenesis and ExportGenesis methods to handle checksums.
x/move/keeper/keeper_test.go Added TestGetAndSetChecksum to verify checksum functionality, modified IterateVMStore callback.
proto/initia/move/v1/genesis.proto Replaced resources field with checksums in GenesisState, updated field indices.
proto/initia/move/v1/types.proto Added new Checksum message type with fields for address, module name, and checksum.

Possibly related PRs

  • bump: opinit #278: The changes in this PR update the upgradeName constant in app/upgrade.go, which is directly related to the changes made in the main PR that also modifies the upgradeName constant in the same file.
  • fix: initialize staking at genesis #290: This PR focuses on initializing staking at genesis, which is relevant to the changes in the main PR that involve restructuring the logic for handling module updates and checksums, as both involve initialization processes within the application.

Suggested reviewers

  • beer-1

🐇 In the code where upgrades bloom,
New constants and checksums loom.
With handlers refined, errors wrapped tight,
Our modules now dance in the light.
A hop and a skip, we code with glee,
Upgrades are here, as bright as can be! 🌟


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link

github-actions bot commented Oct 29, 2024

Dependency Review

✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.

OpenSSF Scorecard

PackageVersionScoreDetails

Scanned Files

Copy link

@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: 5

🧹 Outside diff range and nitpick comments (5)
x/move/types/checksum.go (1)

7-9: Add documentation and input validation.

While the implementation is correct and secure using SHA-256, consider these improvements:

  1. Add godoc comments explaining the function's purpose and usage
  2. Add input validation for nil/empty byte slices

Consider this enhanced implementation:

+// ModuleBzToChecksum computes the SHA-256 checksum of the provided module bytes.
+// It is used to verify module integrity during the upgrade process.
 func ModuleBzToChecksum(moduleBz []byte) [32]byte {
+	if len(moduleBz) == 0 {
+		panic("empty module bytes")
+	}
 	return sha256.Sum256(moduleBz)
 }
x/move/types/keys.go (1)

90-104: LGTM! Consider adding tests for new checksum functions.

The implementation is consistent with existing patterns and maintains proper error handling. The functions follow the same security properties by using proper address validation.

Consider adding tests to verify the behavior of these new functions, particularly:

  • Key generation with various module names
  • Error handling for invalid module names
  • Collision checks with other key types

Would you like me to help generate test cases for these scenarios?

x/move/keeper/handler.go (1)

Line range hint 89-89: Enhance deprecation notices with timeline information

The deprecated functions (ExecuteEntryFunction, ExecuteScript, ExecuteViewFunction) should include:

  1. The version when they will be removed
  2. A migration guide or example of using the JSON alternatives

Consider updating the deprecation notices like this:

-// Deprecated: use ExecuteEntryFunctionJSON instead
+// Deprecated: Will be removed in v1.0.0. Use ExecuteEntryFunctionJSON instead.
+// Migration example:
+// Old: ExecuteEntryFunction(ctx, sender, moduleAddr, "module", "func", typeArgs, [][]byte{arg1, arg2})
+// New: ExecuteEntryFunctionJSON(ctx, sender, moduleAddr, "module", "func", typeArgs, []string{`"arg1"`, `"arg2"`})

Also applies to: 271-271, 516-516

app/upgrade.go (2)

68-88: Correct typographical error: 'seperator' should be 'separator'

In the comments between lines 68 and 88, the word "seperator" is misspelled. It should be "separator".


124-124: Address the TODO comment

There is a TODO comment indicating that the code needs to be checked and updated accordingly. To maintain code quality and completeness, please address this TODO or ensure it's tracked in an issue.

Would you like assistance in updating the code or creating a GitHub issue to track this task?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c8a6288 and 5fc0930.

📒 Files selected for processing (6)
  • app/upgrade.go (2 hunks)
  • x/move/keeper/handler.go (1 hunks)
  • x/move/keeper/keeper.go (1 hunks)
  • x/move/types/checksum.go (1 hunks)
  • x/move/types/connector.go (1 hunks)
  • x/move/types/keys.go (2 hunks)
🔇 Additional comments (6)
x/move/types/checksum.go (1)

1-9: Verify test coverage for checksum functionality.

The checksum calculation is a critical security feature. Please ensure comprehensive test coverage including:

  • Normal case with valid module bytes
  • Edge cases (empty/nil input)
  • Known test vectors for SHA-256

Let's check for existing test coverage:

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

68-71: Verify separator changes in upgrade handler.

The reordering of separators and introduction of ChecksumSeparator could impact existing data. Ensure the upgrade handler properly migrates existing data to use the new separator values.

✅ Verification successful

Let me analyze the provided output. I can see that:

  1. The upgrade handler for v0.6.0 is present and includes code migration logic
  2. Most importantly, there's a section that walks through the VM store and processes keys based on separators
  3. The code shows awareness of the separator changes, particularly handling ModuleSeparator

Let me verify if there's complete migration logic for all separators by checking more context around this code:


Based on the code shown, I can now generate a final response since I have clear evidence of how the separator changes are handled in the upgrade:

Separator changes are properly handled in upgrade handler

The upgrade handler correctly manages the separator changes by:

  1. Walking through all existing VM store entries
  2. Incrementing the separator value by 1 for each key (shifting all separators up by 1 to accommodate new ChecksumSeparator)
  3. Properly handling module checksums during the migration
  4. Preventing migration of any unknown separators
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify upgrade handler handles separator changes

# Test: Search for separator migration logic in upgrade handlers
rg -A 10 "upgradeName060|ChecksumSeparator" app/upgrade.go

Length of output: 10128


Script:

#!/bin/bash
# Get more context around the VM store migration logic
rg -A 20 "VMStore.Walk" app/upgrade.go

Length of output: 694

x/move/keeper/handler.go (1)

65-65: Verify backward compatibility with FunctionNameCodePublishV2

The change from FunctionNameCodePublish to FunctionNameCodePublishV2 suggests a breaking change in the module publishing protocol.

Let's verify the impact of this change:

x/move/keeper/keeper.go (2)

208-223: LGTM: Improved error handling in GetExecutionCounter

The error handling enhancement properly distinguishes between "not found" cases (returning 0) and other errors, making the behavior more explicit and robust.


208-223: Consider enhancing the SetChecksum implementation

While the basic functionality is correct, consider the following improvements:

  1. The comment indicates this should only be used during migration, but there's no enforcement mechanism.
  2. There's no validation of the checksum format or length.
  3. The error handling could be more concise.

Consider this improved implementation:

 // SetChecksum store checksum bytes
-// This function should be used only when Migration
+// This function should be used only during Migration.
+// Expected checksum format: SHA-256 hash (32 bytes)
 func (k Keeper) SetChecksum(
 	ctx context.Context,
 	addr vmtypes.AccountAddress,
 	moduleName string,
 	checksum []byte,
 ) error {
+	if len(checksum) != 32 {
+		return fmt.Errorf("invalid checksum length: expected 32 bytes, got %d", len(checksum))
+	}
+
 	checksumKey, err := types.GetChecksumKey(addr, moduleName)
-	if err != nil {
-		return err
-	}
-	if err := k.VMStore.Set(ctx, checksumKey, checksum); err != nil {
+	if err != nil {
 		return err
 	}
-	return nil
+	
+	return k.VMStore.Set(ctx, checksumKey, checksum)
 }

Let's verify if there are any existing checksum validations in the codebase:

x/move/types/connector.go (1)

66-66: LGTM! Consider documenting the migration strategy.

The new constant follows the established naming convention. However, since this introduces a v2 version of the publish functionality:

Let's verify the migration strategy and usage:

app/upgrade.go Outdated Show resolved Hide resolved
app/upgrade.go Outdated Show resolved Hide resolved
app/upgrade.go Outdated Show resolved Hide resolved
app/upgrade.go Outdated Show resolved Hide resolved
app/upgrade.go Outdated Show resolved Hide resolved
Copy link

@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 and nitpick comments (2)
app/upgrade.go (2)

Line range hint 27-35: Consider externalizing large base64 encoded module data.

Large base64 encoded strings in code reduce readability and make maintenance difficult. Consider moving these to separate configuration files.

// Example: Load from config file
func loadModuleCodes() ([]string, error) {
    return config.LoadModuleCodes("upgrade_056_modules.json")
}

126-130: Consider adding progress logging for module updates.

For complex operations involving multiple modules, adding progress logs would improve observability during upgrades.

Apply this diff:

 			modules := make([]vmtypes.Module, len(codesBz))
 			for i, codeBz := range codesBz {
+				app.Logger().Info("Processing module", "index", i, "total", len(codesBz))
 				modules[i] = vmtypes.NewModule(codeBz)
 			}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 5fc0930 and b64b12d.

📒 Files selected for processing (1)
  • app/upgrade.go (2 hunks)
🔇 Additional comments (5)
app/upgrade.go (5)

4-19: LGTM! Clear version management with descriptive constants.

The renaming of upgrade constants and addition of necessary imports improves code clarity and maintainability.


37-38: LGTM! Proper error handling with SDK error wrapping.

The error handling follows SDK best practices by using sdkerrors.Wrap.


53-55: LGTM! Consistent upgrade handler setup.

The setup follows the established pattern for upgrade handlers.


95-97: ⚠️ Potential issue

Use consistent error handling with sdkerrors.

Direct use of errors.New breaks consistency with SDK error handling pattern.

Apply this diff:

-					return true, errors.New("unknown prefix")
+					return true, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "unknown separator prefix")

Likely invalid or redundant comment.


89-91: ⚠️ Potential issue

Add bounds checking before accessing key index.

The code accesses key[cursor] without verifying the key length, which could cause a panic.

Apply this diff to add safety check:

 				cursor := movetypes.AddressBytesLength
+				if len(key) <= cursor {
+					return true, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "key length is insufficient")
+				}
 				separator := key[cursor]

Likely invalid or redundant comment.

app/upgrade.go Outdated Show resolved Hide resolved
app/upgrade.go Outdated Show resolved Hide resolved
app/upgrade.go Outdated Show resolved Hide resolved
Copy link
Contributor

@beer-1 beer-1 left a comment

Choose a reason for hiding this comment

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

Also seems we missed to update genesis export and import too

Copy link

@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: 3

🧹 Outside diff range and nitpick comments (8)
app/upgrade.go (2)

44-56: Add documentation for the separator changes.

The comments explain the previous and current separator structure, but it would be helpful to document why this change was made and its implications.


68-70: Improve error message for unknown separator.

The error message "unknown prefix" could be more descriptive to help with debugging.

Apply this diff:

-					return true, errors.New("unknown prefix")
+					return true, fmt.Errorf("unknown separator value: %d", separator)
proto/initia/move/v1/types.proto (1)

75-80: LGTM with suggestions for improved documentation and validation.

The new Checksum message structure is well-organized and follows the existing patterns. However, consider these improvements:

  1. Add field validation and constraints
  2. Document the checksum generation method
  3. Indicate required fields

Apply this diff to enhance the message definition:

 // Checksum is checksum of the uploaded contract move code
+// It stores the verification hash for a specific module's bytecode to ensure integrity
 message Checksum {
-  string address = 1;
-  string module_name = 2;
-  bytes checksum = 3;
+  string address = 1 [(gogoproto.moretags) = "yaml:\"address\"", (gogoproto.nullable) = false];
+  string module_name = 2 [(gogoproto.moretags) = "yaml:\"module_name\"", (gogoproto.nullable) = false];
+  // checksum is a SHA-256 hash of the module's bytecode
+  bytes checksum = 3 [(gogoproto.moretags) = "yaml:\"checksum\"", (gogoproto.nullable) = false];
 }
x/move/keeper/genesis.go (1)

154-154: Consider grouping related fields together.

The changes look good, but consider grouping the checksum-related fields closer to the module-related fields in both the iteration callback parameters and the genState assignments, since they are conceptually related.

Apply this organization to improve readability:

 var modules []types.Module
+var checksums []types.Checksum
 var resources []types.Resource
 var tableEntries []types.TableEntry
 var tableInfos []types.TableInfo
-var checksums []types.Checksum

 err = k.IterateVMStore(ctx, func(
   module *types.Module,
+  checksum *types.Checksum,
   resource *types.Resource,
   tableInfo *types.TableInfo,
   tableEntry *types.TableEntry,
-  checksum *types.Checksum,
 ) {

Also applies to: 160-160, 169-171, 202-202

x/move/keeper/keeper_test.go (1)

56-76: Enhance test coverage with additional test cases.

While the basic checksum functionality is tested, consider adding the following test cases for robustness:

  • Negative test case for non-existent module
  • Validation of checksum computation correctness
  • Test for updating/overwriting checksums

Would you like me to help generate these additional test cases?

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

208-222: Add parameter validation and improve documentation for SetChecksum.

The method needs additional validation and documentation improvements:

  1. Add validation for checksum bytes (e.g., length, format)
  2. Document the expected checksum format and validation rules
  3. Consider adding a migration-only guard if this method should only be used during migration

Example improvements:

 // SetChecksum store checksum bytes
 // This function should be used only when Migration
+//
+// Parameters:
+// - ctx: The context for the operation
+// - addr: The account address associated with the module
+// - moduleName: The name of the module
+// - checksum: The checksum bytes (expected to be SHA-256 hash, 32 bytes)
 func (k Keeper) SetChecksum(
 	ctx context.Context,
 	addr vmtypes.AccountAddress,
 	moduleName string,
 	checksum []byte,
 ) error {
+	if len(checksum) != 32 {
+		return fmt.Errorf("invalid checksum length: got %d, want 32", len(checksum))
+	}
+	if len(moduleName) == 0 {
+		return errors.New("empty module name")
+	}
 	if checksumKey, err := types.GetChecksumKey(addr, moduleName); err != nil {
 		return err
 	} else if err := k.VMStore.Set(ctx, checksumKey, checksum); err != nil {

224-245: Improve error handling and documentation for GetChecksum.

The method needs documentation improvements and consistent error handling:

Example improvements:

 // GetChecksum return checksum of module of the given account address and name
+//
+// Parameters:
+// - ctx: The context for the operation
+// - addr: The account address associated with the module
+// - moduleName: The name of the module
+//
+// Returns:
+// - types.Checksum: The checksum information
+// - error: Returns collections.ErrNotFound if the checksum doesn't exist
 func (k Keeper) GetChecksum(
 	ctx context.Context,
 	addr vmtypes.AccountAddress,
 	moduleName string,
 ) (types.Checksum, error) {
+	if len(moduleName) == 0 {
+		return types.Checksum{}, errors.New("empty module name")
+	}
 	bz, err := types.GetChecksumKey(addr, moduleName)
 	if err != nil {
 		return types.Checksum{}, err

Line range hint 552-644: Consider refactoring IterateVMStore for better maintainability.

The method has grown complex with the addition of checksum handling. Consider breaking it down into smaller, focused methods:

Example refactoring:

 func (k Keeper) IterateVMStore(ctx context.Context, cb func(*types.Module, *types.Checksum, *types.Resource, *types.TableInfo, *types.TableEntry)) error {
+	return k.iterateStore(ctx, func(key, value []byte) (bool, error) {
+		return k.handleStoreEntry(ctx, key, value, cb)
+	})
+}
+
+func (k Keeper) handleStoreEntry(ctx context.Context, key, value []byte, cb func(*types.Module, *types.Checksum, *types.Resource, *types.TableInfo, *types.TableEntry)) (bool, error) {
+	cursor := types.AddressBytesLength
+	addrBytes := key[:cursor]
+	separator := key[cursor]
+
+	vmAddr, err := vmtypes.NewAccountAddressFromBytes(addrBytes)
+	if err != nil {
+		return true, err
+	}
+
+	cursor += 1
+	switch separator {
+	case types.ModuleSeparator:
+		return k.handleModule(ctx, vmAddr, key[cursor:], value, cb)
+	case types.ChecksumSeparator:
+		return k.handleChecksum(vmAddr, key[cursor:], value, cb)
+	case types.ResourceSeparator:
+		return k.handleResource(vmAddr, key[cursor:], value, cb)
+	case types.TableInfoSeparator:
+		return k.handleTableInfo(vmAddr, value, cb)
+	case types.TableEntrySeparator:
+		return k.handleTableEntry(vmAddr, key[cursor:], value, cb)
+	default:
+		return true, fmt.Errorf("unknown separator: %d", separator)
+	}
+}

This refactoring would:

  1. Improve readability by separating concerns
  2. Make the code more maintainable
  3. Make it easier to add new entry types in the future
  4. Reduce cognitive complexity
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0d03d73 and 0d8f917.

⛔ Files ignored due to path filters (3)
  • api/initia/tx/v1/query_grpc.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • x/move/types/genesis.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • x/move/types/types.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
📒 Files selected for processing (10)
  • api/initia/intertx/v1/tx.pulsar.go (17 hunks)
  • api/initia/move/v1/genesis.pulsar.go (34 hunks)
  • api/initia/move/v1/types.pulsar.go (29 hunks)
  • api/initia/tx/v1/query.pulsar.go (1 hunks)
  • app/upgrade.go (1 hunks)
  • proto/initia/move/v1/genesis.proto (1 hunks)
  • proto/initia/move/v1/types.proto (1 hunks)
  • x/move/keeper/genesis.go (4 hunks)
  • x/move/keeper/keeper.go (5 hunks)
  • x/move/keeper/keeper_test.go (4 hunks)
🔇 Additional comments (39)
proto/initia/move/v1/genesis.proto (1)

23-27: Verify the impact of adding the new checksums field.

The addition of the checksums field enhances the genesis state with checksum tracking capabilities. However, we need to ensure this change is properly handled in migration scripts.

Please ensure that:

  1. Migration scripts are in place to handle existing genesis states
  2. The checksum validation logic is implemented in the keeper layer
  3. Documentation is updated to reflect this new field's purpose and usage
✅ Verification successful

Based on the search results, I can now generate the final response:

The addition of the checksums field is properly handled in the Move module

The implementation shows that:

  1. The Checksum type is properly defined with address, module name, and checksum fields
  2. Genesis state handling is implemented in the keeper to properly export and store checksums
  3. The field is integrated with the VM store iteration logic

Since this is a new field being added (not renumbered) and the implementation shows proper handling in both the type definition and genesis state management, this change is safe.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for migration scripts and keeper implementations

# Look for migration scripts
echo "Checking for migration scripts..."
rg -l "genesis.*migration|upgrade.*genesis" -g "*.go"

# Look for checksum validation in keeper
echo "Checking for checksum validation implementation..."
rg -l "checksum.*valid|valid.*checksum" -g "*/keeper/*.go"

Length of output: 453


Script:

#!/bin/bash
# Let's try a more comprehensive search approach

# 1. First, let's find all Go files in the repository
echo "=== Finding all Go files ==="
fd -e go

# 2. Look for migration and upgrade related files
echo -e "\n=== Searching for migration and upgrade patterns ==="
rg -l "upgrade|migration" -t go

# 3. Look specifically for checksum-related code
echo -e "\n=== Searching for checksum-related code ==="
rg -l "checksum" -t go

# 4. Search for Move module keeper implementation
echo -e "\n=== Searching for Move module keeper ==="
fd "keeper" -t d

Length of output: 20221


Script:

#!/bin/bash
# Let's examine the checksum-related code implementation and migration handling

# 1. Check the checksum implementation in Move module
echo "=== Checking checksum implementation ==="
rg -A 10 "type.*Checksum" x/move/types/

# 2. Look for checksum handling in genesis
echo -e "\n=== Checking genesis handling of checksums ==="
rg -A 10 "checksums" x/move/keeper/genesis.go

# 3. Check upgrade handler for checksum migration
echo -e "\n=== Checking upgrade handler ==="
rg -A 10 "initiation-2" app/upgrade.go

# 4. Look for any validation logic
echo -e "\n=== Checking validation logic ==="
rg "Valid.*Checksum|checksum.*valid" x/move/

Length of output: 2177

app/upgrade.go (3)

4-18: LGTM: Imports and version constant look good.

The imports are appropriate for the added functionality, and the version follows semantic versioning.


26-34: Maintain consistent error handling pattern.

Error handling at line 29 directly returns the error without wrapping, breaking consistency with the established pattern.

Apply this diff to maintain consistency:

-				return nil, err
+				return nil, sdkerrors.Wrap(err, "failed to read stdlib")

95-98: Document module deployment order and consider configuration-driven approach.

The hardcoded list of module files makes the code less flexible and maintainable. Consider:

  1. Documenting the required order of module deployment, if any
  2. Moving the module list to a configuration file

Let's verify the module dependencies:

proto/initia/move/v1/types.proto (1)

75-80: Verify integration with upgrade handlers and genesis.

The new Checksum message appears to be part of a larger upgrade handling enhancement. Let's verify its integration:

✅ Verification successful

Checksum message is properly integrated across the system

The verification shows comprehensive integration:

  • Genesis handling: Proper export/import of checksums in genesis state
  • Keeper implementation: Complete CRUD operations with SetChecksum and GetChecksum methods
  • Tests: Thorough test coverage including checksum operations and store iteration
  • Upgrade handling: Proper checksum conversion during upgrades
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the integration of the Checksum message

# Test 1: Check for proper genesis handling
echo "Checking genesis integration..."
rg -l "Checksum" --type go | grep "genesis"

# Test 2: Check for keeper methods using Checksum
echo "Checking keeper integration..."
rg -l "Checksum" --type go | grep "keeper"

# Test 3: Check for upgrade handler integration
echo "Checking upgrade handler integration..."
rg -l "Checksum" --type go | grep "upgrade"

Length of output: 539


Script:

#!/bin/bash
# Let's examine the actual integration in these files

# Check genesis integration
echo "=== Genesis Integration ==="
rg "Checksum" x/move/keeper/genesis.go -B 2 -A 2

# Check keeper implementation
echo -e "\n=== Keeper Implementation ==="
rg "Checksum" x/move/keeper/keeper.go -B 2 -A 2

# Check upgrade handler
echo -e "\n=== Upgrade Handler ==="
rg "Checksum" app/upgrade.go -B 2 -A 2

# Check if there are any tests
echo -e "\n=== Tests ==="
rg "Checksum" x/move/keeper/keeper_test.go -B 2 -A 2

Length of output: 4325

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

93-102: Verify upgrade compatibility for existing chains.

Since this PR is preparing for an upgrade (initiation-2), ensure that existing chains can handle the new checksum fields during the upgrade process. Consider adding upgrade handlers to initialize checksums for existing modules if necessary.

Let's check for upgrade handlers:

#!/bin/bash
# Description: Look for upgrade handlers that might need to handle checksum initialization

# Test: Search for upgrade handlers
rg -A 10 "func.*Upgrade.*Handler"

# Test: Search for any migration code
rg -A 10 "func.*Migrate"

Also applies to: 154-202


93-102: LGTM! Verify checksum initialization order.

The checksum initialization logic is well-implemented with proper error handling. The implementation follows the existing patterns used for modules and resources.

Let's verify the initialization order dependencies:

x/move/keeper/keeper_test.go (1)

Line range hint 194-210: Verify the intended upgrade policy.

There's an inconsistency in the upgrade policies used across tests:

  • TestGetAndSetChecksum uses UpgradePolicy_IMMUTABLE
  • TestIterateVMStore uses UpgradePolicy_COMPATIBLE

This might indicate confusion about the expected behavior. Please verify the correct upgrade policy and update tests accordingly.

✅ Verification successful

Let me analyze the results from the rg search to understand the upgrade policy usage patterns:

  1. The codebase defines three upgrade policies:

    • UNSPECIFIED (0): Invalid/unset state
    • COMPATIBLE (1): Allows upgrades with compatibility checks
    • IMMUTABLE (2): No upgrades allowed
  2. Looking at the test files:

    • Most test cases use COMPATIBLE as the default policy
    • TestGetAndSetChecksum specifically tests the IMMUTABLE policy
    • TestIterateVMStore uses COMPATIBLE policy
  3. The default policy in CLI flags is set to COMPATIBLE:

    FlagUpgradePolicy, types.UpgradePolicy_name[int32(types.UpgradePolicy_COMPATIBLE)]
  4. Production code in app/upgrade.go also uses COMPATIBLE as the policy.

The upgrade policy usage in TestIterateVMStore is correct.

The use of UpgradePolicy_COMPATIBLE in TestIterateVMStore aligns with the codebase's default behavior. The IMMUTABLE policy in TestGetAndSetChecksum is intentionally different as it specifically tests the immutable policy scenario. This is not an inconsistency but rather proper test coverage of different upgrade policies.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all upgrade policy usages to verify consistency
rg -A 2 "UpgradePolicy_" 

Length of output: 11305

api/initia/intertx/v1/tx.pulsar.go (5)

10-10: LGTM: Import of IBC channel types.

The addition of the IBC channel types import is appropriate for supporting the new Ordering field.


1910-1913: LGTM: Addition of Ordering field to MsgRegisterAccount struct.

The new Ordering field is properly added to the MsgRegisterAccount struct with appropriate protobuf tags and JSON annotations. The field type types.Order is correctly used from the IBC channel package.


1957-1962: LGTM: GetOrdering accessor method implementation.

The GetOrdering method is correctly implemented with proper nil checks and default value handling.


2160-2174: LGTM: Updated type dependencies.

The type dependencies are correctly updated to include both the IBC Order type and maintain existing dependencies.


2081-2095: Verify protobuf message compatibility.

The protobuf message definition has been updated to include the new ordering field with tag number 4. While the change looks correct, we should verify that this change maintains backward compatibility with existing clients.

✅ Verification successful

Let me gather more specific information about the protobuf message usage.


Let me try one more search to find the original proto definition and any existing implementations.


Based on the search results, I can now generate the final response since I have enough information about the protobuf message usage and implementation.

The protobuf change maintains backward compatibility

The addition of the ordering field with tag number 4 follows protobuf's backward compatibility rules:

  • It's an optional field (not required)
  • Uses a new field number that wasn't previously used
  • The field has a default value (Order(0))
  • Existing code in x/intertx/types/msgs.go and keeper implementation handles the field appropriately

The implementation shows proper handling in tests and message server, with the ordering field being properly initialized when needed:

msg := types.NewMsgRegisterAccount(owner, path.EndpointA.ConnectionID, path.EndpointA.ChannelConfig.Version)
msg.Ordering = channeltypes.ORDERED
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any existing protobuf message usage that might be affected by the field addition

# Search for any direct protobuf message usage
rg -l "MsgRegisterAccount.*{" --type go

# Search for any gRPC client implementations that might need updates
rg -l "MsgClient" --type go

Length of output: 759


Script:

#!/bin/bash
# Search for MsgRegisterAccount usage with proper regex
rg "MsgRegisterAccount\s*{" -A 5 --type go

# Check the proto file for any existing MsgRegisterAccount definitions
fd -e proto | xargs rg "message\s+MsgRegisterAccount\s*{"  -A 10

# Look for any tests involving MsgRegisterAccount
rg "MsgRegisterAccount" --type go -g "*_test.go"

Length of output: 1231


Script:

#!/bin/bash
# Search for proto file containing MsgRegisterAccount without regex
rg -l "MsgRegisterAccount" --type proto

# Search for the implementation file
rg -l "func.*MsgRegisterAccount" --type go

# Check the keeper implementation
rg "RegisterAccount" -A 5 --type go

Length of output: 68102

api/initia/move/v1/genesis.pulsar.go (20)

Line range hint 117-157: Addition of _GenesisState_5_list for Checksum type

The new list type _GenesisState_5_list has been correctly implemented to handle the Checksum type. Methods like Set, Append, AppendMutable, and NewElement are appropriately updated to work with *Checksum pointers.


Line range hint 168-208: Update _GenesisState_6_list for Resource type

The _GenesisState_6_list struct and its associated methods have been updated to handle *Resource pointers. The implementation aligns with the expected structure and functionality.


Line range hint 219-259: Introduction of _GenesisState_7_list for TableInfo type

The new list type _GenesisState_7_list for *TableInfo pointers appears to be correctly implemented. All associated methods handle the TableInfo type as expected.


Line range hint 270-310: Addition of _GenesisState_8_list for TableEntry type

The _GenesisState_8_list struct has been introduced to manage *TableEntry pointers. The methods are correctly implemented and consistent with other list types.


318-368: Implementation of _GenesisState_9_list for DexPair type

A new list type _GenesisState_9_list has been added for handling *DexPair pointers. The struct and its methods (Len, Get, Set, Append, AppendMutable, Truncate, NewElement, IsValid) are properly defined.


Line range hint 375-390: Update field descriptors to include Checksums

The field descriptor fd_GenesisState_checksums has been added and initialized. This ensures that the Checksums field is correctly integrated into the GenesisState message descriptor.


485-490: Handle Checksums in the Range method

The Range method in fastReflection_GenesisState now includes logic to iterate over the Checksums field when it's populated. This addition ensures that Checksums are properly reflected during message iteration.


538-539: Implement Has method for Checksums field

The Has method now checks for the presence of the Checksums field in GenesisState. This allows for correct reporting on whether the Checksums field is populated.


572-573: Include Checksums in the Clear method

The Clear method has been updated to handle the Checksums field, ensuring that it can be reset to its zero value when needed.


616-621: Update Get method to retrieve Checksums

The Get method in fastReflection_GenesisState now includes logic to retrieve the Checksums field. This ensures proper access to the Checksums list via reflection.


678-681: Modify Set method to assign Checksums field

The Set method has been updated to handle assignment to the Checksums field. This allows for correct setting of the Checksums list through reflection.


735-740: Enhance Mutable method for Checksums

The Mutable method now supports the Checksums field, allowing for obtaining a mutable reference to modify the Checksums list.


791-793: Initialize Checksums in NewField method

The NewField method includes initialization for the Checksums field, returning a new, empty list. This ensures that new instances of GenesisState have the Checksums field properly set up.


894-899: Include Checksums in size calculation

The Size method now accounts for the Checksums field in the overall size calculation of the GenesisState message. This ensures accurate sizing for serialization purposes.


1014-1029: Handle Checksums in the Marshal method

The Marshal method has been updated to serialize the Checksums field. This addition ensures that all Checksums data is properly included during message serialization.


1248-1281: Update Unmarshal method to parse Checksums

The Unmarshal method now includes logic to deserialize the Checksums field from the input data. This guarantees that incoming data correctly populates the Checksums list.


1475-1479: Add Checksums field to GenesisState struct

The Checksums field has been added to the GenesisState struct with appropriate protobuf annotations. This expansion of the struct allows for the storage of checksum data associated with modules.


1530-1535: Introduce GetChecksums method

A getter method GetChecksums has been implemented to access the Checksums field. This provides a standard way to retrieve checksum data from a GenesisState instance.


Line range hint 1575-1633: Update protobuf definitions to include Checksums

The protobuf definition in genesis.proto has been updated to include the checksums field with field number 5. Ensure that this change is reflected across all dependent services and that backward compatibility is maintained.


1653-1671: Adjust Go types and dependencies for Checksum

The Go types and dependency indexes have been updated to include the new Checksum type. This change ensures that the generated code aligns with the updated protobuf definitions.

api/initia/tx/v1/query.pulsar.go (4)

1737-1741: Definition of QueryGasPricesRequest is appropriate

The QueryGasPricesRequest message is correctly defined for the Query/GasPrices RPC method, with necessary proto message state fields.


1764-1770: Definition of QueryGasPricesResponse is appropriate

The QueryGasPricesResponse message appropriately includes the GasPrices field as a repeated DecCoin, which is suitable for returning multiple gas prices.


1800-1807: Definition of QueryGasPriceRequest is appropriate

The QueryGasPriceRequest message includes the Denom field to specify the denomination, which is suitable for querying a specific gas price.


1837-1843: Definition of QueryGasPriceResponse is appropriate

The QueryGasPriceResponse message correctly contains the GasPrice field of type DecCoin, fitting for returning a specific gas price.

api/initia/move/v1/types.pulsar.go (2)

2007-2020: Addition of 'Checksum' message and descriptors

The Checksum message and its field descriptors have been correctly defined and initialized. The code follows the established patterns for adding new message types.


2022-2555: Implementation of 'Checksum' message methods

The methods associated with the Checksum message properly implement the protoreflect.Message interface and adhere to the conventions used in existing message types. This ensures consistency and correct behavior within the protobuf reflection system.

proto/initia/move/v1/genesis.proto Show resolved Hide resolved
x/move/keeper/keeper.go Show resolved Hide resolved
api/initia/move/v1/types.pulsar.go Show resolved Hide resolved
sh-cha and others added 4 commits October 31, 2024 16:38
* connect movevm with loaderv2 and introduce module & script cache

* use cache context before query

* disable unstable

* update movevm to latest

* add toml description

---------

Co-authored-by: beer-1 <[email protected]>
Copy link

@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: 10

🧹 Outside diff range and nitpick comments (9)
x/move/keeper/vm_msg_stargate.go (1)

Line range hint 17-45: Consider adding debug logging for better observability.

For better operational visibility, consider adding debug logging at key points:

  • Before message unmarshal
  • After successful validation
  • When signer verification fails
 func (k Keeper) HandleVMStargateMsg(ctx context.Context, req *vmtypes.CosmosMessage) (proto.Message, error) {
+    k.Logger(ctx).Debug("handling cosmos message", "data", string(req.Data))
     var sdkMsg sdk.Msg
     err := k.cdc.UnmarshalInterfaceJSON(req.Data, &sdkMsg)
     if err != nil {
+        k.Logger(ctx).Debug("failed to unmarshal message", "error", err)
         return nil, err
     }

     if m, ok := sdkMsg.(sdk.HasValidateBasic); ok {
         if err := m.ValidateBasic(); err != nil {
+            k.Logger(ctx).Debug("message validation failed", "error", err)
             return nil, err
         }
     }
+    k.Logger(ctx).Debug("message validated successfully", "type", sdk.MsgTypeURL(sdkMsg))
x/move/keeper/vm_query.go (1)

Line range hint 28-50: Consider extracting cache context handling into middleware

The duplicate cache context creation pattern in both query handlers suggests an opportunity for improvement. Consider implementing a middleware approach that automatically wraps query operations in a cache context with proper error handling and cleanup.

This would:

  1. Centralize the cache context lifecycle management
  2. Ensure consistent error handling
  3. Reduce code duplication
  4. Make it easier to modify caching behavior in the future

Example approach:

func withCacheContext(ctx sdk.Context, fn func(sdk.Context) ([]byte, error)) ([]byte, error) {
    cacheCtx, err := ctx.CacheContext()
    if err != nil {
        return nil, fmt.Errorf("failed to create cache context: %w", err)
    }
    defer cacheCtx.CacheContext().Delete()
    
    return fn(cacheCtx)
}
x/move/config/config.go (1)

49-50: Enhance flag descriptions with units and constraints.

The flag descriptions would be more helpful if they included:

  1. The unit of measurement for cache capacity
  2. Any minimum/maximum constraints
  3. Performance implications of different values
-	startCmd.Flags().Uint64(flagScriptCacheCapacity, DefaultScriptCacheCapacity, "Set the script cache capacity")
-	startCmd.Flags().Uint64(flagModuleCacheCapacity, DefaultModuleCacheCapacity, "Set the module cache capacity")
+	startCmd.Flags().Uint64(flagScriptCacheCapacity, DefaultScriptCacheCapacity, "Set the script cache capacity (number of entries, default: 100)")
+	startCmd.Flags().Uint64(flagModuleCacheCapacity, DefaultModuleCacheCapacity, "Set the module cache capacity (number of entries, default: 500)")
app/upgrade.go (4)

49-61: Document the breaking changes in separator values.

The migration introduces significant changes to separator values. This should be clearly documented in the upgrade guide to ensure proper migration planning.

Consider adding detailed comments explaining the separator value changes and their implications.


64-98: Add detailed logging for migration progress.

The migration process would benefit from more detailed logging to help track progress and debug issues in production.

Consider adding structured logging at key points:

  • Before/after each module processing
  • Number of records processed
  • Checksum calculations

116-127: Add validation and rollback handling for module upgrades.

While the module publishing looks correct, consider these improvements:

  1. Validate each module's successful deployment
  2. Implement rollback mechanism for failed upgrades
  3. Add health checks post-deployment

Consider implementing a validation step:

func validateModuleDeployment(ctx context.Context, keeper *MoveKeeper, modules []vmtypes.Module) error {
    // Verify each module is properly deployed
    // Check critical functions are accessible
    // Validate state consistency
}

Line range hint 22-133: Consider implementing a phased upgrade approach.

Given the complexity of this upgrade (separator changes, module updates, and data migration), consider implementing a phased approach:

  1. Pre-upgrade validation phase
  2. Data backup phase
  3. Migration execution phase
  4. Post-upgrade verification phase

This would make the upgrade process more robust and easier to troubleshoot if issues occur.

Would you like assistance in designing this phased approach?

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

107-116: Ensure deterministic checksum initialization.

While the checksum handling looks correct, consider sorting the checksums before initialization to ensure deterministic genesis state across all nodes in the network.

Consider sorting checksums by address and module name:

+ sort.Slice(genState.GetChecksums(), func(i, j int) bool {
+     if genState.Checksums[i].Address == genState.Checksums[j].Address {
+         return genState.Checksums[i].ModuleName < genState.Checksums[j].ModuleName
+     }
+     return genState.Checksums[i].Address < genState.Checksums[j].Address
+ })
 for _, checksum := range genState.GetChecksums() {
x/move/keeper/keeper.go (1)

201-215: Enhance the migration-related documentation.

The comment "This function should be used only when Migration" could be more descriptive. Consider adding:

  • What type of migration this is for
  • Potential risks of using it outside migration
  • Example usage in migration context
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0d8f917 and fb9993c.

⛔ Files ignored due to path filters (2)
  • go.mod is excluded by !**/*.mod
  • go.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (22)
  • Dockerfile (1 hunks)
  • app/upgrade.go (1 hunks)
  • x/bank/keeper/common_test.go (1 hunks)
  • x/distribution/keeper/common_test.go (1 hunks)
  • x/gov/keeper/common_test.go (1 hunks)
  • x/ibc-hooks/keeper/common_test.go (1 hunks)
  • x/ibc-hooks/move-hooks/common_test.go (1 hunks)
  • x/move/config/config.go (2 hunks)
  • x/move/keeper/common_test.go (3 hunks)
  • x/move/keeper/genesis.go (7 hunks)
  • x/move/keeper/handler.go (6 hunks)
  • x/move/keeper/keeper.go (8 hunks)
  • x/move/keeper/staking_test.go (1 hunks)
  • x/move/keeper/vm_msg_stargate.go (1 hunks)
  • x/move/keeper/vm_msg_stargate_test.go (1 hunks)
  • x/move/keeper/vm_query.go (2 hunks)
  • x/move/keeper/vmpool.go (0 hunks)
  • x/move/types/checksum.go (1 hunks)
  • x/move/types/cosmos_message.go (0 hunks)
  • x/mstaking/keeper/common_test.go (1 hunks)
  • x/reward/keeper/common_test.go (1 hunks)
  • x/slashing/keeper/common_test.go (1 hunks)
💤 Files with no reviewable changes (2)
  • x/move/keeper/vmpool.go
  • x/move/types/cosmos_message.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • x/move/types/checksum.go
🔇 Additional comments (34)
x/move/keeper/vm_msg_stargate.go (1)

17-17: Verify the impact of changing from StargateMessage to CosmosMessage.

The parameter type change looks good, but let's verify that all callers have been updated accordingly.

✅ Verification successful

Let me try a different search strategy to verify this change more thoroughly.


Based on the search results, I can now generate the final response:

Parameter type change from StargateMessage to CosmosMessage is correctly implemented

The verification shows that:

  • All references to HandleVMStargateMsg consistently use *vmtypes.CosmosMessage
  • The function is called from handler.go and tested in vm_msg_stargate_test.go
  • No legacy StargateMessage references remain in the codebase
  • The change aligns with the module's message handling system, as evidenced by related CosmosMessage usage in DispatchMessages and error definitions
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to StargateMessage
# and verify all callers are using CosmosMessage

# Search for any remaining StargateMessage references
echo "Checking for remaining StargateMessage references:"
rg "StargateMessage" 

# Search for HandleVMStargateMsg callers
echo -e "\nChecking HandleVMStargateMsg callers:"
ast-grep --pattern 'HandleVMStargateMsg($$$)'

Length of output: 270


Script:

#!/bin/bash
# Search for any references to HandleVMStargateMsg using ripgrep with context
echo "Searching for HandleVMStargateMsg references with context:"
rg -A 5 -B 5 "HandleVMStargateMsg"

# Search for CosmosMessage type references
echo -e "\nSearching for CosmosMessage type references:"
rg "CosmosMessage"

# Search for any message type definitions in vmtypes
echo -e "\nSearching for message type definitions in vmtypes:"
fd -e go -e proto "vmtypes" --exec cat {}

Length of output: 4762

x/move/keeper/vm_msg_stargate_test.go (2)

Line range hint 41-49: LGTM! Valid access test case properly updated.

The test case correctly validates the successful handling of a governance vote message using the new CosmosMessage type. The response validation remains thorough and appropriate.


34-37: LGTM! Unauthorized access test case properly updated.

The test case correctly validates that unauthorized access is prevented when using the new CosmosMessage type.

Let's verify the consistent usage of the new message type across the codebase:

✅ Verification successful

Type migration from StargateMessage to CosmosMessage is complete and consistent

The verification confirms:

  • No remaining references to the old StargateMessage type in the codebase
  • CosmosMessage is consistently used across all relevant files:
    • Message handling in vm_msg_stargate.go
    • Error definitions in types/errors.go
    • Test cases in vm_msg_stargate_test.go
    • Message dispatching in handler.go
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that StargateMessage has been completely replaced with CosmosMessage
# and there are no lingering references to the old type.

# Test 1: Check for any remaining StargateMessage references
echo "Checking for remaining StargateMessage references..."
rg "StargateMessage"

# Test 2: Verify CosmosMessage usage in related files
echo "Verifying CosmosMessage usage..."
rg "CosmosMessage" -A 3

Length of output: 2771

x/move/keeper/vm_query.go (1)

49-50: ⚠️ Potential issue

Improve error handling for Stargate query cache context

Similar to the custom query handler, the cache context creation needs proper error handling and lifecycle management.

Apply the same fix pattern:

-	ctx, _ = ctx.CacheContext()
+	cacheCtx, err := ctx.CacheContext()
+	if err != nil {
+		return nil, fmt.Errorf("failed to create cache context: %w", err)
+	}
+	// Use cacheCtx for the query operation
+	defer cacheCtx.CacheContext().Delete()

Let's verify if this change affects upgrade handling:

Dockerfile (1)

9-9: Verify compatibility with v0.6.0.

The major version bump from v0.5.1 to v0.6.0 could introduce breaking changes. Please ensure this version is compatible with the changes in app/upgrade.go and other dependent components.

✅ Verification successful

Let me gather more specific information about the upgrade handlers and version dependencies.


Let me check one more aspect to verify the upgrade compatibility.


Version update is aligned with codebase upgrade plan

The LIBMOVEVM version bump to v0.6.0 is verified to be part of a coordinated upgrade:

  • The upgrade handler in app/upgrade.go defines the same version 0.6.0 as the upgrade name
  • The change includes Move VM module updates and redeployment logic
  • A comment in go.mod explicitly links the LIBMOVEVM_VERSION update to this upgrade
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any version-specific code or dependencies in the codebase

# Test: Look for any hardcoded version references that might need updating
rg -g '!Dockerfile' 'v0.5' 

# Test: Check upgrade handlers that might need to handle version-specific logic
ast-grep --pattern 'func RegisterUpgradeHandlers'

Length of output: 7202


Script:

#!/bin/bash
# Check for upgrade-related code and version dependencies
# Look for upgrade handlers and version-specific logic
rg -g '!{*.sum,*.mod}' -A 5 'initiation-2'

# Check for any Move VM version references
rg -g '!Dockerfile' 'LIBMOVEVM'

# Look for upgrade-related constants or version definitions
ast-grep --pattern 'const $_ = "initiation-2"'

Length of output: 909


Script:

#!/bin/bash
# Check the upgrade handler implementation and version-specific changes
rg -A 10 'func (app \*App) BeginBlocker' app/

# Look for any Move VM related configurations or dependencies
rg -A 5 'move' app/upgrade.go

Length of output: 1526

x/move/config/config.go (5)

17-18: LGTM!

The new flag definitions follow the established naming convention and maintain consistency with the config field names.


24-25: LGTM!

The new fields are properly typed and tagged, following the existing struct field patterns.


32-33: LGTM!

The default configuration properly initializes the new cache capacity fields with their respective constants.


12-13: Consider documenting cache capacity units and rationale.

The default cache capacities (100 and 500) would benefit from:

  1. Documentation specifying the unit of measurement (bytes, entries, etc.)
  2. Explanation of how these values were determined
  3. Consider using powers of 2 for optimal memory allocation if these represent byte sizes

Line range hint 1-65: Verify upgrade handler implementation.

Since these configuration changes are part of an upgrade preparation, we should verify that the upgrade handler properly handles these new configuration values.

app/upgrade.go (1)

4-19: LGTM: Import changes and version update look good.

The new imports support the enhanced functionality, and the version update to "0.6.0" aligns with the upgrade objectives.

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

168-168: Verify genesis state compatibility.

The addition of checksums to the genesis state looks correct. However, please ensure:

  1. The exported genesis state is compatible with nodes running older versions
  2. The genesis export properly handles the case when no checksums exist

Let's verify the genesis state structure and compatibility:

Also applies to: 174-174, 183-186, 216-216

✅ Verification successful

Let me gather more information about the genesis state handling to verify backward compatibility.


Let me check one more aspect about the checksum handling in the genesis state.


Based on the gathered information, I can now provide the final response:

Genesis state changes are backward compatible

The addition of checksums to the genesis state is safe because:

  1. The checksums field is marked with omitempty in protobuf definition, making it optional
  2. The default genesis state is properly handled in DefaultGenesisState()
  3. Genesis validation through ValidateGenesis() only validates params, not checksums
  4. Older nodes can safely ignore the new checksums field during state import
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check genesis state structure and usage
rg -A 10 "type GenesisState struct"
rg "UnmarshalJSON.*GenesisState"

Length of output: 16799


Script:

#!/bin/bash
# Check genesis state validation and initialization
rg -A 5 "ValidateGenesis|InitGenesis|DefaultGenesis" x/move/

Length of output: 3976


Script:

#!/bin/bash
# Check checksum handling in genesis
rg -A 5 "Checksum.*omitempty" x/move/
rg -A 10 "ExportGenesis" x/move/

Length of output: 2436


59-69: Verify staking initialization prerequisites.

The staking initialization is a critical operation. Please ensure:

  1. The order of operations is correct (coin initialization before staking)
  2. The impact of failed initialization on the system state

Let's verify the staking keeper implementation:

✅ Verification successful

Let me gather more information about the initialization process and error handling.


Let me check one more aspect to understand the implementation details and error handling in the bank keeper.


Based on the gathered information, I can now provide the final response:

Staking initialization sequence is correctly implemented

The code follows a proper initialization sequence:

  1. The null check on StakingKeeper ensures safe conditional initialization
  2. Coin initialization precedes staking initialization as required
  3. Error handling is properly implemented with immediate returns on failures, preventing partial initializations
  4. The handleExecuteResponse ensures proper event emission and state management
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check staking keeper interface and initialization
rg -A 5 "type StakingKeeper interface" 
rg -A 5 "InitializeStaking.*baseDenom"

Length of output: 2984


Script:

#!/bin/bash
# Check InitializeStaking implementation and MoveBankKeeper interface
ast-grep --pattern 'func (k Keeper) InitializeStaking(ctx $_, baseDenom $_) error {
  $$$
}'

rg -A 5 "type MoveBankKeeper interface"
rg -A 5 "InitializeCoin.*ctx"

Length of output: 1847


Script:

#!/bin/bash
# Check bank keeper implementation and error handling
ast-grep --pattern 'func (k $keeper) InitializeCoin(ctx $_, denom $_) error {
  $$$
}'

rg -B 5 -A 10 "func \(k.*Keeper\) handleExecuteResponse"

Length of output: 1020

x/reward/keeper/common_test.go (1)

378-378: LGTM! Verify Initialize method signature.

The addition of bondDenom parameter to moveKeeper.Initialize is consistent with the move parameters setup where moveParams.BaseDenom is set to the same value.

Let's verify the Initialize method signature across the codebase:

✅ Verification successful

Let me generate one more verification script to check the complete method signature in the keeper implementation:


Initialize method signature is consistent across the codebase

The verification confirms that:

  • The Initialize method in x/move/keeper/genesis.go correctly accepts baseDenom as the fourth parameter
  • All test files across different modules consistently pass bondDenom as the fourth argument
  • The implementation properly uses baseDenom to initialize the move staking module and coin
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the Initialize method signature is consistent
# Test: Search for Initialize method definition and usage
# Expect: All Initialize calls include bondDenom parameter

# Find Initialize method definition
ast-grep --pattern 'func (k *Keeper) Initialize($$$) $$ {'

# Find Initialize method calls
rg -A 2 'Initialize\(' 

Length of output: 2720


Script:

#!/bin/bash
# Get the full Initialize method implementation from the keeper
ast-grep --pattern 'func (k Keeper) Initialize(ctx context.Context, moduleBytes [][]byte, $$$) error {
  $$$
}'

Length of output: 3256

x/ibc-hooks/move-hooks/common_test.go (1)

312-312: LGTM! Verify test coverage across the codebase.

The update to moveKeeper.Initialize correctly includes the new bondDenom parameter. However, let's ensure consistent test coverage across the codebase.

Let's verify that all test files have been updated with the new Initialize signature:

✅ Verification successful

All test files have been properly updated with the new Initialize signature

The verification shows that all test files consistently use the updated moveKeeper.Initialize signature with the bondDenom parameter. Each occurrence follows the same pattern:

moveKeeper.Initialize(ctx, moduleBytes/stdlib, moveParams.AllowedPublishers, bondDenom)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential missing updates to moveKeeper.Initialize calls in test files
# Test: Search for Initialize calls in test files. Expect: All calls include bondDenom parameter

# Search for moveKeeper.Initialize calls in test files
rg -t go --multiline 'moveKeeper\.Initialize\([^)]+\)' -g '*_test.go'

# Search for potential test files that might need updates
fd -e go -g '*_test.go' --exec grep -l 'moveKeeper'

Length of output: 1569

x/move/keeper/handler.go (5)

Line range hint 407-445: LGTM! Improved error handling in message dispatch

The enhanced error handling with AllowFailure flag and proper message validation through HandleVMStargateMsg provides better control and safety.


600-606: LGTM! Consistent VM execution pattern

The view function execution follows the same pattern of direct VM access while maintaining proper context and gas handling.


425-434: Verify callback execution with JSON arguments

The callback handling has been updated to use JSON arguments. Please ensure that all callback implementations support the new JSON format.

Let's check callback implementations:

#!/bin/bash
# Search for callback implementations
ast-grep --pattern 'function $name($$$) {
  $$$
  $callback($$$)
  $$$
}'

65-65: Verify upgrade compatibility for FunctionNameCodePublishV2

The change from FunctionNameCodePublish to FunctionNameCodePublishV2 indicates a breaking change in the API.

Let's verify the upgrade path and usage:

#!/bin/bash
# Check for any remaining references to the old function name
rg "FunctionNameCodePublish[^V]" 

# Check for upgrade handling code
rg -A 5 "upgrade.*handler.*publish"

173-180: Verify deadlock prevention after removing execVM wrapper

The code now directly uses k.initiaMoveVM instead of the previous execVM wrapper that handled deadlock prevention. Please ensure that deadlock prevention is maintained in the new implementation.

Let's check for any deadlock prevention mechanisms:

x/ibc-hooks/keeper/common_test.go (1)

399-399: LGTM: Consistent bond denomination handling

The addition of bondDenom parameter to moveKeeper.Initialize is consistent with its usage throughout the test setup, where it's properly configured in staking, reward, distribution, and move parameters.

x/bank/keeper/common_test.go (1)

397-397: LGTM! Consider adding test cases for different bond denominations.

The addition of bondDenom parameter to Initialize aligns with the consistent usage of bond denomination throughout the test setup. The parameter is properly sourced from the constant and matches its usage in staking, reward, distribution, and move parameters.

Let's verify that we have test coverage for different bond denominations:

x/mstaking/keeper/common_test.go (1)

423-423: Verify bond denomination consistency.

The bondDenom parameter is passed to Initialize after setting it as BaseDenom in moveParams. Consider adding a test case to verify the initialization behavior when these values differ, ensuring proper validation or synchronization between them.

Consider adding a test case:

func TestMoveKeeperInitializeWithDifferentBondDenom(t *testing.T) {
    // Test initialization with mismatched BaseDenom and bondDenom
    // to verify expected behavior
}
x/gov/keeper/common_test.go (1)

409-409: LGTM! Consistent bond denomination usage across modules.

The addition of bondDenom parameter to moveKeeper.Initialize aligns with the module-wide standardization of bond denomination usage, maintaining consistency with other module configurations (staking, reward, distribution, and governance parameters).

x/slashing/keeper/common_test.go (1)

392-393: LGTM: Proper initialization with bond denomination.

The update to include bondDenom in moveKeeper.Initialize is correct and consistent with similar changes across other test files.

x/move/keeper/keeper.go (4)

93-107: LGTM: VM configuration and initialization looks good!

The code properly handles default values for cache capacities and initializes the VM with appropriate error handling.


Line range hint 545-585: Previous suggestion about builder pattern still applies.

The callback signature with 5 nullable parameters could benefit from the builder pattern as suggested in the previous review.


Line range hint 1-238: Verify upgrade implications.

As this PR prepares for "initiation-2 upgrade", please ensure:

  1. The new checksum functionality has a migration path
  2. The VM configuration changes won't affect existing deployments
  3. The changes to IterateVMStore won't break existing consumers

Consider adding upgrade documentation that covers these changes.

#!/bin/bash
# Check for existing upgrade handlers and docs
echo "Checking for upgrade handlers..."
rg -l 'upgrade.*handler.*initiation-2'

echo "Checking for upgrade documentation..."
fd -g '*UPGRADE*.md'

50-50: Verify the field naming convention.

The field name initiaMoveVM contains the product name. Consider if this should be more generic, like moveVM, to maintain better abstraction.

✅ Verification successful

Let me gather more information about naming patterns in the codebase to make a better assessment.


Let me search for more context about the naming patterns and VM-related fields in the codebase.


Based on the search results, I can now provide a final response about the field naming convention:

The field name initiaMoveVM follows established naming patterns in the codebase

The field name is appropriate because:

  1. It implements the VMEngine interface which is a core abstraction
  2. The initia prefix is used consistently in the codebase for VM-related components (e.g., InitiaVMConfig)
  3. The field represents the specific Move VM implementation for the Initia blockchain, so the prefix helps distinguish it from potential alternative VM implementations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if similar naming patterns exist in the codebase
rg -l 'initia.*VM' 

Length of output: 223


Script:

#!/bin/bash
# Search for VM-related field declarations and usages
rg -g '*.go' 'VM\s+\w+' -A 2

# Search for Move-related types and fields
rg -g '*.go' 'Move[A-Z]\w+' -A 2

# Look for other engine/VM interfaces and implementations
ast-grep --pattern 'type $_ interface {
  $$$
}'

Length of output: 283307


Script:

#!/bin/bash
# Search for VM-related fields and their naming patterns
rg -g '*.go' 'type.*Keeper.*struct.*{[\s\S]*VM.*}' -A 5

# Search for VM-related interfaces and their implementations
ast-grep --pattern 'type VMEngine interface {
  $$$
}'

# Look for other VM-related type definitions
rg -g '*.go' 'type.*VM.*'

Length of output: 7324

x/distribution/keeper/common_test.go (1)

381-381: LGTM! The Initialize method call is properly updated.

The addition of bondDenom parameter is consistent with the test setup, where bondDenom is already properly defined as a constant and used throughout the test utilities for various keeper configurations.

x/move/keeper/common_test.go (3)

52-54: LGTM! IBC module imports are properly organized.

The new IBC-related imports are logically grouped and follow the project's import organization pattern.


97-99: LGTM! IBC modules are properly registered.

The new IBC modules are correctly added to the ModuleBasics manager, which is necessary for their integration into the test environment.


429-429: Verify the impact of the bondDenom parameter addition.

The Initialize method now includes bondDenom as a parameter. While this change looks correct, ensure that all test cases using this setup function are updated accordingly.

✅ Verification successful

Based on the search results, I can generate the final response as we have comprehensive information about all the Initialize calls in the codebase.

All test cases are properly updated with the bondDenom parameter

The search results show that all test cases across different modules (slashing, reward, mstaking, move, ibc-hooks, distribution, gov, bank) are consistently using the bondDenom parameter in their Initialize calls. No outdated calls were found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other Initialize calls that might need updating
rg -A 2 "moveKeeper\.Initialize\(" --type go

Length of output: 1960

x/move/keeper/staking_test.go (1)

236-276: Test TestApplyStakingDeltas_BaseDenom is correctly implemented

The test function is well-structured and effectively verifies the delegation logic for the base denomination. Error handling and assertions are appropriately used.

Dockerfile Outdated Show resolved Hide resolved
Comment on lines 62 to 65
# The capacity of the script cache in (MiB).
script-cache-capacity = "{{ .MoveConfig.ScriptCacheCapacity }}"
# The capacity of the module cache in (MiB).
module-cache-capacity = "{{ .MoveConfig.ModuleCacheCapacity }}"
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Resolve unit inconsistency in documentation.

The config template suggests the cache capacities are in MiB, but this unit isn't mentioned in:

  1. The constant definitions
  2. The flag descriptions
  3. The struct field documentation

Please ensure consistency in unit specification across all documentation.

x/move/config/config.go Outdated Show resolved Hide resolved
app/upgrade.go Outdated
Comment on lines 92 to 97
key[cursor] = key[cursor] + 1
kvs = append(kvs, KV{
key: bytes.Clone(key),
value: bytes.Clone(value),
})
return false, nil
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add bounds check before key modification.

The key modification at line 92 could cause a panic if cursor is out of bounds.

Add a safety check:

+				if len(key) <= cursor {
+					return true, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "invalid key length for separator increment")
+				}
				key[cursor] = key[cursor] + 1
📝 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
key[cursor] = key[cursor] + 1
kvs = append(kvs, KV{
key: bytes.Clone(key),
value: bytes.Clone(value),
})
return false, nil
if len(key) <= cursor {
return true, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "invalid key length for separator increment")
}
key[cursor] = key[cursor] + 1
kvs = append(kvs, KV{
key: bytes.Clone(key),
value: bytes.Clone(value),
})
return false, nil

app/upgrade.go Outdated
Comment on lines 30 to 37
codeModuleBz, err := vmprecompile.ReadStdlib("code.mv")
if err != nil {
return nil, err
}
err = app.MoveKeeper.SetModule(ctx, vmtypes.StdAddress, movetypes.MoveModuleNameCode, codeModuleBz[0])
if err != nil {
return nil, err
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve error handling consistency.

The error handling should follow the established pattern of using sdkerrors.Wrap to provide context.

Apply this diff:

-				return nil, err
+				return nil, sdkerrors.Wrap(err, "failed to read code.mv stdlib")
📝 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
codeModuleBz, err := vmprecompile.ReadStdlib("code.mv")
if err != nil {
return nil, err
}
err = app.MoveKeeper.SetModule(ctx, vmtypes.StdAddress, movetypes.MoveModuleNameCode, codeModuleBz[0])
if err != nil {
return nil, err
}
codeModuleBz, err := vmprecompile.ReadStdlib("code.mv")
if err != nil {
return nil, sdkerrors.Wrap(err, "failed to read code.mv stdlib")
}
err = app.MoveKeeper.SetModule(ctx, vmtypes.StdAddress, movetypes.MoveModuleNameCode, codeModuleBz[0])
if err != nil {
return nil, err
}

Comment on lines 55 to 57
if err = k.handleExecuteResponse(sdkCtx, sdkCtx.GasMeter(), execRes); err != nil {
return err
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove duplicate error handling.

The error handling for execRes appears twice - once immediately after the VM initialization and again at the end of the function. This is redundant and could lead to confusion.

Remove the first error handling block:

 execRes, err := k.initiaMoveVM.Initialize(vmStore, api, env, vmtypes.NewModuleBundle(modules...), _allowedPublishers)
 if err != nil {
     return err
 }
-if err = k.handleExecuteResponse(sdkCtx, sdkCtx.GasMeter(), execRes); err != nil {
-    return err
-}

 // if staking keeper is available...

Also applies to: 71-71

@@ -15,6 +15,7 @@ func (k Keeper) Initialize(
ctx context.Context,
moduleBytes [][]byte,
allowedPublishers []string,
baseDenom string,
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add baseDenom validation.

The baseDenom parameter is used for critical initialization but lacks validation. Consider validating the denomination format to prevent issues during coin and staking initialization.

Add validation before usage:

 baseDenom string,
) error {
+    if err := sdk.ValidateDenom(baseDenom); err != nil {
+        return fmt.Errorf("invalid base denomination: %w", err)
+    }
     sdkCtx := sdk.UnwrapSDKContext(ctx)

Also applies to: 61-61

Comment on lines 239 to 241
// add second BondDenom to staking keeper
input.StakingKeeper.SetBondDenoms(ctx, []string{bondDenom})

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Inconsistent comment: Only one BondDenom added

The comment suggests adding a second BondDenom to the staking keeper, but the code only includes a single bondDenom. If the test is intended to use only the base denomination, consider updating the comment to reflect that.

Apply this diff to correct the comment:

-	// add second BondDenom to staking keeper
+	// set BondDenoms to staking keeper with base denom

Alternatively, if you intend to add a second bond denomination, include it in the slice:

input.StakingKeeper.SetBondDenoms(ctx, []string{bondDenom, secondBondDenom})

Committable suggestion was skipped due to low confidence.

@initia-labs initia-labs deleted a comment from coderabbitai bot Oct 31, 2024
Copy link

@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 and nitpick comments (4)
app/upgrade.go (3)

27-27: Consider using structured logging instead of fmt.Println

The progress messages are helpful for debugging, but using a structured logger would be more consistent with production practices and provide better observability.

Consider using the application's logger:

-fmt.Println("upgrade to 0.6.0")
+app.Logger().Info("starting upgrade process", "version", upgradeName)

Also applies to: 39-39, 64-64, 102-102, 120-120


66-70: Improve error message for invalid key length

The error message should include more context about the expected length.

-return true, fmt.Errorf("invalid key length: %d", len(key))
+return true, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "key length %d is less than required address length %d", len(key), movetypes.AddressBytesLength)

122-125: Consider making the module list configurable

The list of stdlib modules is hardcoded. Consider moving it to a configuration file or parameter to make it more maintainable and flexible for future upgrades.

x/move/types/checksum_test.go (1)

10-12: Consider improving test data management and coverage.

While the test is functional, consider these improvements for better maintainability and coverage:

  1. Move the large hex string to a separate test data file
  2. Add documentation explaining the source/significance of this test data
  3. Implement table-driven tests with multiple test cases
  4. Include negative test cases (e.g., invalid bytecode)

Example table-driven test structure:

func TestModuleBzToChecksum(t *testing.T) {
    tests := []struct {
        name        string
        codeBzStr   string
        wantErr     bool
        wantChecksum string
    }{
        {
            name:         "valid module bytecode",
            codeBzStr:    "a11ceb0b...", // current test case
            wantChecksum: "16324a588e78ed4452ef4d9d4d57be38b581a1438e86cd9d891626b856b27d3b",
        },
        {
            name:      "invalid hex string",
            codeBzStr: "invalid",
            wantErr:   true,
        },
        // Add more test cases
    }
    
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            // Test implementation
        })
    }
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between fb9993c and 82a3de4.

📒 Files selected for processing (2)
  • app/upgrade.go (1 hunks)
  • x/move/types/checksum_test.go (1 hunks)
🔇 Additional comments (6)
app/upgrade.go (3)

19-19: LGTM: Version upgrade to 0.6.0

The version bump is appropriate given the significant changes in module handling and checksum implementation.


131-133: Verify upgrade policy implications

The use of UpgradePolicy_COMPATIBLE needs verification to ensure it won't break existing module references.

#!/bin/bash
# Search for existing module references that might be affected
rg -A 2 "PublishModuleBundle.*UpgradePolicy" --type go

82-83: Add error handling for checksum calculation

The checksum calculation result should be validated before logging.

x/move/types/checksum_test.go (3)

3-8: LGTM: Clean and minimal imports.

The imports are well-organized and include only the necessary packages for testing and hex encoding/decoding.


12-14: LGTM: Proper error handling for hex decoding.

The code correctly handles potential errors from hex decoding using require.NoError.


15-17: Verify the checksum calculation implementation.

The test verifies a specific checksum, but we should ensure the ModuleBzToChecksum implementation is consistent with Move's checksum calculation specification.

app/upgrade.go Show resolved Hide resolved
Copy link

@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 and nitpick comments (1)
app/upgrade.go (1)

Line range hint 22-122: Consider adding transaction safety.

The upgrade handler is well-structured but could benefit from transaction safety. Consider wrapping the entire upgrade process in a transaction to ensure atomicity. If any step fails, all changes should be rolled back to maintain data consistency.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 82a3de4 and df6576e.

📒 Files selected for processing (1)
  • app/upgrade.go (1 hunks)
🔇 Additional comments (4)
app/upgrade.go (4)

4-18: LGTM: Imports and version update look good.

The imports are appropriate for the required functionality, and the version update to "0.6.0" aligns with the upgrade purpose.


36-58: LGTM: Clear documentation and appropriate data structures.

The comment block clearly documents the separator changes, and the KV structure is well-designed for the migration process.


26-34: ⚠️ Potential issue

Improve error handling consistency.

The error handling should provide more context using sdkerrors.Wrap.

Apply these changes:

-				return nil, err
+				return nil, sdkerrors.Wrap(err, "failed to read code.mv stdlib")

Likely invalid or redundant comment.


104-117: Verify module dependencies and add validation.

The module publishing logic looks good, but consider:

  1. Validating that each module bytecode is not empty
  2. Verifying module dependencies are correctly ordered

Let's verify the module dependencies:

app/upgrade.go Outdated
Comment on lines 59 to 102
err = app.MoveKeeper.VMStore.Walk(ctx, nil, func(key, value []byte) (stop bool, err error) {
key = bytes.Clone(key)
value = bytes.Clone(value)

cursor := movetypes.AddressBytesLength
if len(key) <= cursor {
return true, fmt.Errorf("invalid key length: %d", len(key))
}

separator := key[cursor]

modules := make([]vmtypes.Module, len(codes))
for i, code := range codes {
codeBz, err := base64.StdEncoding.DecodeString(code)
if separator == movetypes.ModuleSeparator {
checksum := movetypes.ModuleBzToChecksum(value)
value = checksum[:]
} else if separator >= movetypes.TableInfoSeparator {
return true, errors.New("unknown prefix")
} else {
rmKeys = append(rmKeys, bytes.Clone(key))
}

key[cursor] = key[cursor] + 1
kvs = append(kvs, KV{
key: key,
value: value,
})
return false, nil
})
if err != nil {
return nil, err
}

for _, key := range rmKeys {
err = app.MoveKeeper.VMStore.Remove(ctx, key)
if err != nil {
return nil, errors.Wrap(err, "failed to decode module code")
return nil, err
}
}

for _, kv := range kvs {
err = app.MoveKeeper.VMStore.Set(ctx, kv.key, kv.value)
if err != nil {
return nil, err
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add validation and improve error handling.

  1. The error handling at line 74 should use sdkerrors.Wrap for consistency.
  2. Consider adding validation for the value length before checksum calculation.

Apply these changes:

-					return true, errors.New("unknown prefix")
+					return true, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "unknown separator prefix")

-					checksum := movetypes.ModuleBzToChecksum(value)
+					if len(value) == 0 {
+						return true, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "empty module bytecode")
+					}
+					checksum := movetypes.ModuleBzToChecksum(value)
📝 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
err = app.MoveKeeper.VMStore.Walk(ctx, nil, func(key, value []byte) (stop bool, err error) {
key = bytes.Clone(key)
value = bytes.Clone(value)
cursor := movetypes.AddressBytesLength
if len(key) <= cursor {
return true, fmt.Errorf("invalid key length: %d", len(key))
}
separator := key[cursor]
modules := make([]vmtypes.Module, len(codes))
for i, code := range codes {
codeBz, err := base64.StdEncoding.DecodeString(code)
if separator == movetypes.ModuleSeparator {
checksum := movetypes.ModuleBzToChecksum(value)
value = checksum[:]
} else if separator >= movetypes.TableInfoSeparator {
return true, errors.New("unknown prefix")
} else {
rmKeys = append(rmKeys, bytes.Clone(key))
}
key[cursor] = key[cursor] + 1
kvs = append(kvs, KV{
key: key,
value: value,
})
return false, nil
})
if err != nil {
return nil, err
}
for _, key := range rmKeys {
err = app.MoveKeeper.VMStore.Remove(ctx, key)
if err != nil {
return nil, errors.Wrap(err, "failed to decode module code")
return nil, err
}
}
for _, kv := range kvs {
err = app.MoveKeeper.VMStore.Set(ctx, kv.key, kv.value)
if err != nil {
return nil, err
}
}
err = app.MoveKeeper.VMStore.Walk(ctx, nil, func(key, value []byte) (stop bool, err error) {
key = bytes.Clone(key)
value = bytes.Clone(value)
cursor := movetypes.AddressBytesLength
if len(key) <= cursor {
return true, fmt.Errorf("invalid key length: %d", len(key))
}
separator := key[cursor]
if separator == movetypes.ModuleSeparator {
if len(value) == 0 {
return true, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "empty module bytecode")
}
checksum := movetypes.ModuleBzToChecksum(value)
value = checksum[:]
} else if separator >= movetypes.TableInfoSeparator {
return true, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "unknown separator prefix")
} else {
rmKeys = append(rmKeys, bytes.Clone(key))
}
key[cursor] = key[cursor] + 1
kvs = append(kvs, KV{
key: key,
value: value,
})
return false, nil
})
if err != nil {
return nil, err
}
for _, key := range rmKeys {
err = app.MoveKeeper.VMStore.Remove(ctx, key)
if err != nil {
return nil, err
}
}
for _, kv := range kvs {
err = app.MoveKeeper.VMStore.Set(ctx, kv.key, kv.value)
if err != nil {
return nil, err
}
}

Copy link

@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

🧹 Outside diff range and nitpick comments (5)
app/upgrade.go (1)

37-51: Document separator changes in code.

While the comments explain the separator changes, consider adding constants for the new separator values to make the code more maintainable.

+const (
+    OldTableInfoSeparator = byte(3)
+    NewTableInfoSeparator = byte(4)
+)
x/move/keeper/keeper_test.go (3)

56-76: Consider adding more test cases for checksum handling.

While the basic happy path is covered, consider adding test cases for:

  • Invalid module names
  • Non-existent modules
  • Error scenarios

Line range hint 196-249: Consider using a more robust verification approach.

Instead of using a simple counter, consider:

  1. Creating a map of expected items
  2. Marking items as seen during iteration
  3. Verifying all expected items were seen exactly once

This would make the test more maintainable and less dependent on iteration order.

Example approach:

type ItemType int
const (
    ModuleItem ItemType = iota
    ChecksumItem
    ResourceItem
    TableEntryItem
    TableInfoItem
)

expected := map[ItemType]bool{
    ModuleItem: false,
    ChecksumItem: false,
    ResourceItem: false,
    TableEntryItem: false,
    TableInfoItem: false,
}

input.MoveKeeper.IterateVMStore(ctx, func(module *types.Module, checksum *types.Checksum, resource *types.Resource, tableInfo *types.TableInfo, tableEntry *types.TableEntry) {
    if module != nil && module.ModuleName == "BasicCoin" {
        require.False(t, expected[ModuleItem], "Module seen multiple times")
        // ... existing assertions ...
        expected[ModuleItem] = true
    }
    // ... similar for other items ...
})

for itemType, seen := range expected {
    require.True(t, seen, "Item type %v was not seen during iteration", itemType)
}

Line range hint 252-334: Reduce code duplication with test helpers.

The setup code is duplicated from TestIterateVMStore. Consider:

  1. Creating a helper function for common setup
  2. Using table-driven tests for both forward and reverse iteration

Example approach:

func setupIterationTest(t *testing.T, ctx sdk.Context, k keeper.Keeper) {
    // Common setup code here
}

func TestVMStoreIteration(t *testing.T) {
    tests := []struct {
        name string
        iterFn func(k keeper.Keeper, callback func(*types.Module, *types.Checksum, *types.Resource, *types.TableInfo, *types.TableEntry))
        expectedOrder []ItemType
    }{
        {
            name: "forward iteration",
            iterFn: keeper.IterateVMStore,
            expectedOrder: []ItemType{ModuleItem, ChecksumItem, ResourceItem, TableEntryItem, TableInfoItem},
        },
        {
            name: "reverse iteration",
            iterFn: keeper.ReverseIterateVMStore,
            expectedOrder: []ItemType{TableInfoItem, TableEntryItem, ResourceItem, ChecksumItem, ModuleItem},
        },
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            ctx, input := createDefaultTestInput(t)
            setupIterationTest(t, ctx, input.MoveKeeper)
            // Test implementation
        })
    }
}
x/move/keeper/keeper.go (1)

201-238: Please clarify the Migration context in the comment.

The implementation looks good, but the comment "This function should be used only when Migration" could be more specific about:

  1. Which migration scenario this applies to
  2. What could go wrong if used outside migration
  3. Whether there are any validation requirements during migration
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between df6576e and 84e4d54.

📒 Files selected for processing (3)
  • app/upgrade.go (1 hunks)
  • x/move/keeper/keeper.go (8 hunks)
  • x/move/keeper/keeper_test.go (5 hunks)
🔇 Additional comments (5)
app/upgrade.go (3)

4-19: LGTM! Imports and version constant look good.

The imports are appropriate for the required functionality, and the version bump follows semantic versioning.


91-94: ⚠️ Potential issue

Add validation for module bytecode.

Validate that each module's bytecode is not empty before creating the module.

 modules := make([]vmtypes.Module, len(codesBz))
 for i, codeBz := range codesBz {
+    if len(codeBz) == 0 {
+        return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "empty bytecode for module %s", stdlibModules[i])
+    }
     modules[i] = vmtypes.NewModule(codeBz)
 }

Likely invalid or redundant comment.


Line range hint 22-103: Verify upgrade atomicity.

The upgrade process involves multiple steps. We should verify that if any step fails, the entire upgrade is rolled back to prevent partial upgrades.

✅ Verification successful

Based on the search results, I can now provide a final response about the upgrade atomicity concern:

The upgrade process is atomic through Cosmos SDK's context caching mechanism

The upgrade handler operates within Cosmos SDK's context system, which provides built-in atomicity guarantees:

  • All state changes during the upgrade are performed through the VMStore operations (Set/Remove/Walk)
  • These operations are executed within the main SDK context that's passed to the upgrade handler
  • If any operation fails (indicated by returned errors), the entire upgrade transaction is automatically rolled back since the changes haven't been committed to the main context
  • The error handling pattern shows proper error propagation at each step:
    • Module publishing errors are returned directly
    • VMStore operations errors are checked and propagated
    • All state modifications are properly wrapped in error checks
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for transaction handling and rollback mechanisms in the upgrade process

# Check for transaction handling in upgrade-related code
rg -A 5 "BeginTx|CommitTx|RollbackTx" --type go

# Look for error handling patterns in upgrade handlers
rg -A 5 "SetUpgradeHandler.*func.*error" --type go

Length of output: 102


Script:

#!/bin/bash
# Let's check how the upgrade process is handled at a lower level

# Check for store/state management in the upgrade process
rg -A 10 "VMStore\.(Set|Remove|Walk)" --type go

# Look for any transaction or state management patterns
rg -A 10 "CacheContext|MustGetCache|WithCache" --type go

# Check for any error handling patterns in the Move keeper
rg -A 10 "MoveKeeper.*error" --type go

Length of output: 17578

x/move/keeper/keeper.go (2)

50-50: LGTM: Improved VM configuration and initialization.

The changes properly consolidate VM-related fields and ensure robust initialization with proper default values.

Also applies to: 93-105


545-552: ⚠️ Potential issue

Consider adding null checks in the callback invocations.

The callback is invoked with multiple nullable parameters, but there are no explicit checks to ensure the callback can handle null values safely. While the current implementation ensures only one parameter is non-null at a time, this contract isn't explicitly documented or enforced.

Let's verify the callback usage:

Consider adding:

  1. Documentation about the callback contract
  2. Runtime assertions to validate the contract
  3. Example callback implementation in tests

Also applies to: 583-584, 591-594, 608-610, 630-633, 637-640

app/upgrade.go Outdated Show resolved Hide resolved
app/upgrade.go Show resolved Hide resolved
app/upgrade.go Show resolved Hide resolved
app/upgrade.go Show resolved Hide resolved
Copy link
Contributor

@beer-1 beer-1 left a comment

Choose a reason for hiding this comment

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

LGTM

@initia-labs initia-labs deleted a comment from coderabbitai bot Oct 31, 2024
@beer-1 beer-1 merged commit edef2a5 into main Oct 31, 2024
2 of 6 checks passed
@beer-1 beer-1 deleted the feat/update-handler-for-0.6.0 branch October 31, 2024 09:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants