Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

fix: ensure state compatibility with v1 #9

Merged
merged 2 commits into from
Oct 29, 2024
Merged

Conversation

johnletey
Copy link
Member

@johnletey johnletey commented Oct 29, 2024

This PR addresses state compatibility issues when upgrading the Halo module from v1 to v2

The underlying issue was that collections.Pair inserts an extra delimiter byte to distinguish between the two keys. However, with the manual state management included in v1, we simply concatenated the two keys together.

We've used the latest commit on this branch to patch a Noble testnet node, and can confirm it is working as expected:

Screenshot 2024-10-29 at 09 32 25
Screenshot 2024-10-29 at 09 38 44

Summary by CodeRabbit

  • New Features

    • Enhanced role and capability management with simplified key structures for user roles and role capabilities.
  • Bug Fixes

    • Improved error handling in test cases, ensuring accurate error messages for invalid operations.
  • Documentation

    • Updated method signatures for clarity, particularly in role management functions.
  • Chores

    • Removed unused constants and functions related to key generation, streamlining the codebase.

@johnletey johnletey requested a review from g-luca October 29, 2024 08:09
@johnletey johnletey self-assigned this Oct 29, 2024
Copy link

coderabbitai bot commented Oct 29, 2024

Walkthrough

The changes in this pull request involve significant modifications to the Keeper struct and related files, focusing on simplifying the internal data structures for role capabilities and user roles. The key types for these collections have been changed from composite keys to a more straightforward []byte type. Additionally, several methods in the state_entitlements.go file have been refactored to improve key handling, while test cases in msg_server_entitlements_test.go have been enhanced for better error handling and state verification. Several constants and functions related to key generation have been removed across different files.

Changes

File Change Summary
keeper/keeper.go Updated RoleCapabilities and UserRoles from collections.Map[collections.Pair[string, uint64], bool] to collections.Map[[]byte, bool].
keeper/msg_server_entitlements_test.go Modified key codecs for UserRoles and RoleCapabilities, enhanced error handling, added assertions for state changes, and included additional test cases.
keeper/state_entitlements.go Refactored GetCapabilityRoles, GetAllCapabilityRoles, SetRoleCapability, GetUserRoles, GetAllUserRoles, HasRole, and SetUserRole for new key handling.
types/aggregator/keys.go Removed import for "encoding/binary", deleted constant SubmoduleName, and removed function RoundKey.
types/entitlements/keys.go Removed constants and functions related to key generation, including SubmoduleName, PublicKey, CapabilityKey, and UserKey. Modified CapabilityRoleKey and UserRoleKey.
types/keys.go Removed the NonceKey function, affecting nonce key generation functionality.

Poem

In the land of bytes and keys,
A rabbit hops with joyful ease.
Roles and maps now simpler be,
Streamlined paths for you and me.
With tests that catch each little flaw,
We celebrate the code we saw! 🐇✨


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

codecov bot commented Oct 29, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

📢 Thoughts on this report? Let us know!

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

🧹 Outside diff range and nitpick comments (2)
keeper/keeper.go (1)

92-93: LGTM! Initialization maintains storage structure while adapting key types.

The initialization correctly uses BytesKey while preserving the storage prefixes and schema names, ensuring data organization remains clear despite the simplified key type.

Consider documenting the key format in comments or constants to ensure consistent key generation across the codebase, especially important for v1 compatibility.

keeper/state_entitlements.go (1)

Line range hint 84-138: Refactor repetitive key parsing logic into a helper function.

The code for extracting roles from keys is duplicated across multiple functions (GetCapabilityRoles, GetUserRoles, etc.). Refactoring this logic into a shared helper function will improve maintainability and reduce redundancy.

Here's an example of a helper function:

func extractRoleFromKey(key []byte) (entitlements.Role, error) {
	if len(key) < 8 {
		return 0, errors.New("key too short to extract role")
	}
	role := binary.BigEndian.Uint64(key[len(key)-8:])
	return entitlements.Role(role), nil
}

Modify your functions to use the helper:

-	role := binary.BigEndian.Uint64(key[len(key)-8:])
+	role, err := extractRoleFromKey(key)
+	if err != nil {
+		// Handle the error appropriately
+		continue
+	}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between bd33925 and 0719754.

📒 Files selected for processing (6)
  • keeper/keeper.go (2 hunks)
  • keeper/msg_server_entitlements_test.go (2 hunks)
  • keeper/state_entitlements.go (4 hunks)
  • types/aggregator/keys.go (0 hunks)
  • types/entitlements/keys.go (1 hunks)
  • types/keys.go (0 hunks)
💤 Files with no reviewable changes (2)
  • types/aggregator/keys.go
  • types/keys.go
🔇 Additional comments (7)
types/entitlements/keys.go (1)

22-22: LGTM! Successfully fixes v1 compatibility.

The direct concatenation approach aligns with v1's key generation strategy by avoiding the extra delimiter bytes that were causing compatibility issues.

keeper/keeper.go (2)

Line range hint 119-134: Verify role-based security checks remain functional.

The SendRestrictionFn relies on role-based access control through CanCall. Given the key type changes, we should verify that all role checks still work correctly.

Let's verify the role check implementations:

✅ Verification successful

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

Role-based security checks are correctly implemented and remain functional.

The verification shows that the role-based access control system is properly implemented with:

  • CanCall implementation in keeper/state_entitlements.go correctly uses byte arrays for user addresses
  • Role lookups are handled through collections.Map with BytesKey:
    • UserRoles for storing user-to-role mappings
    • RoleCapabilities for storing method-to-role mappings
  • Key type changes are consistently applied across all role-related functions
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for CanCall implementations to verify role check logic
rg "func.*CanCall" -A 10

# Look for other role-based security checks
rg "UserRoles|RoleCapabilities" -A 3 --type go

Length of output: 22348


49-50: LGTM! Field type changes align with v1 compatibility goals.

The simplified key types ([]byte) will allow for direct key concatenation matching v1's approach, while removing the collections.Pair delimiter issue.

Let's verify the key format compatibility:

✅ Verification successful

Field type changes are correctly implemented for key compatibility

The verification confirms:

  • No remaining usage of collections.Pair in the codebase
  • Key generation in both CapabilityRoleKey and UserRoleKey functions uses direct byte concatenation:
    • CapabilityRoleKey: concatenates method string bytes with role uint64 bytes
    • UserRoleKey: concatenates address bytes with role uint64 bytes

This implementation matches the PR's goal of fixing state compatibility by removing the delimiter-based collections.Pair and using direct byte concatenation instead.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining collections.Pair usage in key generation
rg -l "collections\.Pair.*string.*uint64" || echo "No collections.Pair usage found"

# Search for key generation logic to verify concatenation approach
rg "func.*[Kk]ey.*Role" -A 5

Length of output: 767


Script:

#!/bin/bash
# Let's verify if there are any v1 key generation functions to compare with
rg -B 2 -A 3 "v1.*[Kk]ey.*Role|legacy.*[Kk]ey.*Role"

# Also check for any migration code that handles key conversion
rg -B 2 -A 3 "func.*[Mm]igrate.*[Rr]ole|func.*[Cc]onvert.*[Rr]ole"

Length of output: 123

keeper/msg_server_entitlements_test.go (3)

322-322: LGTM: Key codec change aligns with v1 compatibility fix.

The change from composite key codec to BytesKey is correct and aligns with the PR objective of ensuring state compatibility between v1 and v2.


467-467: LGTM: Key codec change aligns with v1 compatibility fix.

The change from composite key codec to BytesKey is correct and aligns with the PR objective of ensuring state compatibility between v1 and v2.


322-322: Verify key format compatibility with v1.

While the key codec changes look correct, let's verify that the actual key format matches v1's implementation.

Also applies to: 467-467

✅ Verification successful

Let me search for the key format implementation to verify compatibility.


Key format implementation is correct and consistent

The key format implementation in the codebase is consistent and follows a clear pattern:

  • UserRoleKey: Concatenates the address bytes with an 8-byte big-endian encoded role value
  • CapabilityRoleKey: Concatenates the method string bytes with an 8-byte big-endian encoded role value

The implementation ensures unique keys for both user roles and role capabilities, maintaining compatibility with the collections interface.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for v1 key format implementation to verify compatibility
# Expected: Find key concatenation implementation in v1 codebase

# Look for key generation or state management code in v1
rg -g '!{test,vendor}/*' -A 5 'func.*[Ss]et.*[Rr]ole' 
rg -g '!{test,vendor}/*' -A 5 'func.*[Ss]et.*[Cc]apability'

Length of output: 139729


Script:

#!/bin/bash
# Search for key format implementation
rg -g '!{test,vendor}/*' "CapabilityRoleKey|UserRoleKey" -A 3

Length of output: 1173

keeper/state_entitlements.go (1)

11-11: Importing encoding/binary is appropriate for key handling.

The import is necessary for processing byte slices and extracting roles from keys.

types/entitlements/keys.go Show resolved Hide resolved
keeper/state_entitlements.go Show resolved Hide resolved
keeper/state_entitlements.go Show resolved Hide resolved
keeper/state_entitlements.go Show resolved Hide resolved
keeper/state_entitlements.go Show resolved Hide resolved
keeper/state_entitlements.go Show resolved Hide resolved
@johnletey johnletey merged commit 00858da into main Oct 29, 2024
3 checks passed
@johnletey johnletey deleted the state-compatibility branch October 29, 2024 11:04
@johnletey johnletey added this to the v2.0.0 milestone Nov 10, 2024
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