Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat: merkle_root bundles migration #236

Merged
merged 17 commits into from
Feb 11, 2025
Merged

Conversation

christopherbrumm
Copy link
Member

@christopherbrumm christopherbrumm commented Jan 30, 2025

This PR implements the bundle migration for the upcoming v2 release. It adds the Merkle roots computed using the following script: https://github.com/KYVENetwork/merkle-script

Summary by CodeRabbit

  • New Features

    • Enhanced upgrade process for bundles management.
    • Added migration support for Merkle Roots in bundles.
    • Integrated migration step into block processing logic.
    • New section in documentation detailing the bundles migration process.
  • Chores

    • Updated upgrade handler to include bundles keeper.
    • Added migration-related utility functions in keeper and module.
  • Bug Fixes

    • Improved bundle migration process with more robust handling of upgrade heights.
    • Added a new key for managing migration heights related to bundles.

Copy link

coderabbitai bot commented Jan 30, 2025

Walkthrough

This pull request introduces modifications to enhance the upgrade mechanism for the Bundles module in the KYVE Network chain. Key changes include the addition of the BundlesKeeper to the upgrade handler, updates to the CreateUpgradeHandler function, and the introduction of methods for managing migration heights. A new migration package is implemented to handle the integration of Bundles Merkle Roots during the upgrade process, ensuring that finalized bundles are updated accordingly. Additionally, the block processing logic is modified to trigger the migration at the beginning of each block.

Changes

File Change Summary
app/app.go Added BundlesKeeper to upgrade handler parameters.
app/upgrades/v2_0/upgrade.go Updated CreateUpgradeHandler to include bundlesKeeper parameter.
x/bundles/keeper/getters_migration.go Added methods to get and set bundles migration upgrade height.
x/bundles/keeper/keeper.go Added temporary migration-related methods.
x/bundles/migration/migration.go New migration package for handling Bundles Merkle Roots migration.
x/bundles/module.go Updated BeginBlock to trigger migration process.
x/bundles/types/keys.go Added BundlesMigrationHeightKey constant.
x/bundles/migration/README.md Added documentation for the Bundles migration process.

Possibly related PRs

  • chore: v1.5 migration #200: The changes in the main PR, which involve adding the BundlesKeeper to the SetUpgradeHandler method in the New function of the App struct, are related to the modifications in the retrieved PR that also involve changes to the CreateUpgradeHandler function by adding a new parameter for bundlesKeeper, indicating both PRs are enhancing the upgrade handling process for bundles.
  • chore: multiple coins migration #187: The changes in the main PR are related to the modifications in the CreateUpgradeHandler function in the retrieved PR, as both involve adding parameters to upgrade handling functions, specifically including the BundlesKeeper.

Suggested reviewers

  • shifty11
  • mbreithecker
  • troykessler

Poem

🐰 Bundles hop, migration's dance,
Merkle roots find their new stance,
Upgrades flow with rabbit's grace,
Code evolves at lightning pace,
KYVE's network leaps and prances! 🚀


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

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

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
x/bundles/migration/migration.go (2)

22-25: Use consistent type specifications for all constants in this block.

Static analysis reports a warning that only the first constant in this group has an explicit type. To resolve “SA9004,” specify types for all or none consistently.

 const (
-	BundlesMigrationStepSizePerPool uint64 = 100
-	WaitingBlockPeriod                     = 1
+	BundlesMigrationStepSizePerPool uint64 = 100
+	WaitingBlockPeriod              uint64 = 1
 )
🧰 Tools
🪛 GitHub Check: lint / golangci

[failure] 23-23:
SA9004: only the first constant in this group has an explicit type (staticcheck)


94-95: Merge variable declaration and assignment into a single statement.

The pipeline flagged an S1021 warning (gosimple) recommending you adopt a short variable declaration.

-	var iterator storeTypes.Iterator
-	iterator = store.Iterator(util.GetByteKey(offset), util.GetByteKey(offset+BundlesMigrationStepSizePerPool))
+	iterator := store.Iterator(util.GetByteKey(offset), util.GetByteKey(offset+BundlesMigrationStepSizePerPool))
🧰 Tools
🪛 GitHub Check: lint / golangci

[failure] 94-94:
S1021: should merge variable declaration with assignment on next line (gosimple)

🪛 GitHub Actions: run all jobs

[error] 94-94: Variable declaration should be merged with assignment on next line (gosimple S1021)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6a10c14 and 82c17d2.

📒 Files selected for processing (7)
  • app/app.go (1 hunks)
  • app/upgrades/v2_0/upgrade.go (3 hunks)
  • x/bundles/keeper/getters_migration.go (1 hunks)
  • x/bundles/keeper/keeper.go (2 hunks)
  • x/bundles/migration/migration.go (1 hunks)
  • x/bundles/module.go (2 hunks)
  • x/bundles/types/keys.go (1 hunks)
🧰 Additional context used
🪛 GitHub Check: lint / golangci
x/bundles/migration/migration.go

[failure] 94-94:
S1021: should merge variable declaration with assignment on next line (gosimple)


[failure] 23-23:
SA9004: only the first constant in this group has an explicit type (staticcheck)

🪛 GitHub Actions: run all jobs
x/bundles/migration/migration.go

[error] 94-94: Variable declaration should be merged with assignment on next line (gosimple S1021)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Summary
🔇 Additional comments (11)
x/bundles/migration/migration.go (1)

109-111: Verify safe indexing when slicing merkleRoots.

This line slices merkleRoots with rawFinalizedBundle.Id * 32 as a start index. Although there’s an upper bound check at line 105, please verify that the maxBundleId consistently matches the length of merkleRoots to avoid potential out-of-bounds errors if data is corrupt or inconsistent.

x/bundles/keeper/getters_migration.go (1)

13-13: Confirm nil handling for the returned byte slice.

binary.BigEndian.Uint64(storeAdapter.Get(...)) will return 0 if the store value is nil. Ensure this default of 0 is an intended behavior. If not, consider adding a check.

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

30-31: Looks good!

This key aligns with the rest of the module’s structure, providing clear semantics for tracking migration heights.

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

8-8: LGTM!

The import statement is correctly positioned.


94-102: Ensure temporary migration methods are removed post-migration.

These methods expose internal fields for migration purposes. While this is acceptable for a migration, it's crucial to:

  1. Document when these methods will be removed
  2. Create a follow-up task to remove them post-migration
  3. Ensure they are only used within the migration context
app/upgrades/v2_0/upgrade.go (3)

6-6: LGTM!

The import is correctly added for the bundles keeper.


37-37: LGTM!

The bundlesKeeper parameter is properly added to the CreateUpgradeHandler function.


50-51: LGTM!

The migration height is correctly set using the current block height. This ensures the migration process starts at the right block during the upgrade.

x/bundles/module.go (2)

7-7: LGTM!

The migration package is correctly imported.


180-181: Verify migration trigger conditions.

The migration is integrated into BeginBlock and triggered based on the upgrade height. Please ensure:

  1. The migration is idempotent
  2. There are proper error handling mechanisms
  3. The migration can handle chain halts and restarts
✅ Verification successful

Migration implementation verified successfully

The migration implementation includes proper safeguards:

  • Idempotent execution through block height checks and offset-based processing
  • Error handling at both critical (panic) and data processing (returns) levels
  • Chain halt/restart safety via block height-based progress tracking and state-based continuation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify migration implementation details

# Test: Check migration implementation for error handling and idempotency
ast-grep --pattern 'func MigrateBundlesModule($ctx, $keeper, $height) {
  $$$
}'

Length of output: 82


Script:

#!/bin/bash
# First locate the migration implementation
rg -l "MigrateBundlesModule"

# Then show the content of files containing this function
rg -A 20 "func MigrateBundlesModule"

Length of output: 1599


Script:

#!/bin/bash
# Get the constants and bundlesMigration variable
rg -B 10 "var bundlesMigration" x/bundles/migration/migration.go

# Get the migrateFinalizedBundles implementation
rg -A 20 "func migrateFinalizedBundles" x/bundles/migration/migration.go

# Get any other migration-related constants
rg "const.*Bundle.*" x/bundles/migration/migration.go

Length of output: 1479

app/app.go (1)

412-412: LGTM!

The BundlesKeeper is correctly added to the upgrade handler setup, enabling bundle migrations during the v2 upgrade.

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

🧹 Nitpick comments (3)
x/bundles/keeper/getters_migration.go (3)

11-18: Improve error handling and add documentation.

The function would benefit from the following improvements:

  1. The error message could be more descriptive, e.g., "bundles migration height not found" instead of "upgrade height can't be zero".
  2. Consider adding validation for the retrieved value.
  3. Add godoc-style documentation explaining the function's purpose and return values.

Apply this diff to implement the suggested improvements:

+// GetBundlesMigrationUpgradeHeight retrieves the upgrade height for the v2.0 bundles migration
+// from the KV store.
+// Returns the upgrade height and nil if found, or 0 and an error if not found.
 func (k Keeper) GetBundlesMigrationUpgradeHeight(ctx sdk.Context) (uint64, error) {
 	storeAdapter := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
 
 	if storeAdapter.Has(types.BundlesMigrationHeightKey) {
-		return binary.BigEndian.Uint64(storeAdapter.Get(types.BundlesMigrationHeightKey)), nil
+		height := binary.BigEndian.Uint64(storeAdapter.Get(types.BundlesMigrationHeightKey))
+		if height == 0 {
+			return 0, errors.New("invalid bundles migration height: height cannot be zero")
+		}
+		return height, nil
 	}
-	return 0, errors.New("upgrade height can't be zero")
+	return 0, errors.New("bundles migration height not found")
 }

20-29: Add input validation and improve error handling.

The function would benefit from the following improvements:

  1. Validate that upgradeHeight is not zero.
  2. Add error handling for potential store failures.
  3. Enhance the documentation with parameter details.

Apply this diff to implement the suggested improvements:

 // SetBundlesMigrationUpgradeHeight stores the upgrade height of the v2.0 bundles migration
-// upgrade in the KV-Store.
-func (k Keeper) SetBundlesMigrationUpgradeHeight(ctx sdk.Context, upgradeHeight uint64) {
+// upgrade in the KV-Store. The upgrade height must be greater than zero.
+// Returns an error if the height is invalid or if the store operation fails.
+func (k Keeper) SetBundlesMigrationUpgradeHeight(ctx sdk.Context, upgradeHeight uint64) error {
+	if upgradeHeight == 0 {
+		return errors.New("invalid bundles migration height: height cannot be zero")
+	}
+
 	storeAdapter := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
 
 	bz := make([]byte, 8)
 	binary.BigEndian.PutUint64(bz, upgradeHeight)
 
 	storeAdapter.Set(types.BundlesMigrationHeightKey, bz)
+	return nil
 }

1-29: Consider architectural improvements for future migrations.

The current implementation assumes a single migration height, which might limit future migrations. Consider the following architectural improvements:

  1. Use a more generic approach that supports multiple migrations.
  2. Define constants for error messages to ensure consistency.

Here's a suggested approach for supporting multiple migrations:

// Define in types/keys.go
const (
    BundlesMigrationHeightKeyPrefix = "bundles_migration_height_"
    ErrMigrationHeightNotFound     = "bundles migration height not found for version %s"
    ErrInvalidMigrationHeight      = "invalid bundles migration height: height cannot be zero"
)

// Function to generate key for specific version
func GetBundlesMigrationHeightKey(version string) []byte {
    return []byte(BundlesMigrationHeightKeyPrefix + version)
}

// Updated getter function
func (k Keeper) GetBundlesMigrationUpgradeHeight(ctx sdk.Context, version string) (uint64, error) {
    storeAdapter := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
    key := GetBundlesMigrationHeightKey(version)
    
    if storeAdapter.Has(key) {
        height := binary.BigEndian.Uint64(storeAdapter.Get(key))
        if height == 0 {
            return 0, errors.New(ErrInvalidMigrationHeight)
        }
        return height, nil
    }
    return 0, fmt.Errorf(ErrMigrationHeightNotFound, version)
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 82c17d2 and 992f9c1.

📒 Files selected for processing (2)
  • x/bundles/keeper/getters_migration.go (1 hunks)
  • x/bundles/module.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • x/bundles/module.go
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Summary
🔇 Additional comments (1)
x/bundles/keeper/getters_migration.go (1)

1-10: LGTM!

The package declaration and imports are appropriate for the functionality being implemented.

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

🧹 Nitpick comments (4)
x/bundles/migration/README.md (4)

9-11: Add details about binary files format and location.

The documentation mentions binary files but could benefit from additional information.

Consider adding:

  • Format/structure of the binary files
  • Expected file size ranges
  • Location of these files in the repository structure
  • Instructions for regenerating these files if needed

12-33: Add language specification to code block and clarify pool numbering.

The hash listings could be improved for better clarity and documentation standards.

Apply this diff to specify the language and improve formatting:

-```
+```text
 merkle_roots_pool_0
 da4bb9bf0a60c5c79e399d8bb54ae4cf916f6c1dbdd5cdae45cb991f4e56158f

Also consider:

  • Explaining why certain pool numbers (4, 6, 8) are missing
  • Adding a note about the hash format (SHA-256, etc.)
  • Including a timestamp or version identifier for when these hashes were generated
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

12-12: Fenced code blocks should have a language specified
null

(MD040, fenced-code-language)


1-33: Consider adding practical sections to enhance documentation.

The documentation provides good technical information but could benefit from additional sections.

Consider adding:

  • Prerequisites section
  • Step-by-step migration procedure
  • Troubleshooting guide
  • Verification steps to confirm successful migration
  • Rollback procedure if needed
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

12-12: Fenced code blocks should have a language specified
null

(MD040, fenced-code-language)


1-8: Verify external links and consider adding version information.

The documentation clearly explains the purpose and implementation. Let's verify the referenced links:

Consider adding:

  • Version information for the Go and Python implementations
  • Link to the TypeScript runtime implementation mentioned
✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Verify the existence and accessibility of referenced links

# Check Trustless API documentation
curl -I "https://docs.kyve.network/access-data-sets/trustless-api/overview"

# Check merkle-script repository
curl -I "https://github.com/KYVENetwork/merkle-script"

Length of output: 5889


External links verified – consider version and reference improvements.

Both the Trustless API documentation and the merkle-script repository URLs return a successful (HTTP 200) response, confirming they are accessible. As noted, the current markdown snippet is accurate but might benefit from these enhancements:

  • Add explicit language identifiers to code blocks if applicable.
  • Include version information for the Go and Python implementations.
  • Provide a direct link to the TypeScript runtime implementation for completeness.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d6c771f and 2219300.

📒 Files selected for processing (1)
  • x/bundles/migration/README.md (1 hunks)
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
x/bundles/migration/README.md

12-12: Fenced code blocks should have a language specified
null

(MD040, fenced-code-language)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: lint / golangci
  • GitHub Check: test / test
  • GitHub Check: Summary

@mbreithecker mbreithecker merged commit 1e322bb into main Feb 11, 2025
5 checks passed
@mbreithecker mbreithecker deleted the cbrumm/merkle-bundles-migration branch February 11, 2025 12:27
@coderabbitai coderabbitai bot mentioned this pull request Feb 13, 2025
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