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

refactor: change byte prefixing scheme for provider #2061

Merged
merged 7 commits into from
Jul 24, 2024

Conversation

mpoke
Copy link
Contributor

@mpoke mpoke commented Jul 18, 2024

Description

Closes: #939

TODO:

  • do the same on consumer

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
  • Targeted the correct branch (see PR Targeting)
  • Provided a link to the relevant issue or specification
  • Reviewed "Files changed" and left comments if necessary
  • 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
  • Confirmed that this PR does not change production code

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of key prefixes to ensure correct retrieval and storage of data.
  • Refactor

    • Updated key prefix logic across various functions for greater consistency and maintainability.
    • Refactored key management structure to enhance clarity and organization.
  • Tests

    • Added new test functions to validate key prefix handling and ensure no prefix overlaps.
    • Enhanced existing tests for accuracy and better coverage of key prefix validations.

@mpoke mpoke requested a review from a team as a code owner July 18, 2024 12:59
@github-actions github-actions bot added C:x/provider Assigned automatically by the PR labeler C:Docs Assigned automatically by the PR labeler C:ADR Assigned automatically by the PR labeler labels Jul 18, 2024
Copy link
Contributor

coderabbitai bot commented Jul 18, 2024

Caution

Review failed

The head commit changed during the review from ede5f86 to 133e705.

Walkthrough

Walkthrough

The changes involve refactoring key prefix handling in the Cosmos Interchain Security module. The main goal is to shift from using brittle byte prefixes defined with Go's iota operator to a more robust method using MustGetKeyPrefix for key generation. This change enhances consistency and maintainability of key prefixes across the codebase, reducing the risk of accidental prefix reuse and the need for database migrations when keys are reordered.

Changes

Files/Groups Change Summary
x/ccv/provider/keeper/... Modified functions to use MustGetKeyPrefix instead of direct byte prefix references for key management, improving clarity and consistency.
x/ccv/provider/types/keys.go Refactored key prefix handling by introducing a mapping for key prefixes and dynamic key retrieval functions, enhancing maintainability.
x/ccv/provider/types/keys_test.go Updated test cases to validate new key prefix handling methods using MustGetKeyPrefix. Added tests for prefix overlap, preservation of byte prefixes, and correct key parsing.

Assessment against linked issues

Objective Addressed Explanation
Rethink byte prefixing scheme (#939)

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

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (invoked as PR comments)

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

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

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

Comment on lines 215 to 217
for _, prefix := range prefixMap {
prefixList = append(prefixList, prefix)
}

Check warning

Code scanning / CodeQL

Iteration over map Warning

Iteration over map may be a possible source of non-determinism
func MustGetKeyPrefix(index string) byte {
keyPrefixes := getKeyPrefixes()
if prefix, found := keyPrefixes[index]; !found {
panic(fmt.Sprintf("could not find key prefix for index %s", index))

Check warning

Code scanning / CodeQL

Panic in BeginBock or EndBlock consensus methods Warning

Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Outside diff range, codebase verification and nitpick comments (1)
x/ccv/provider/keeper/validator_set_update.go (1)

56-56: Issue Found: Missing Key Prefix

The key prefix for "ConsumerValidatorKey" is missing in the getKeyPrefixes function, which will cause a runtime error when MustGetKeyPrefix("ConsumerValidatorKey") is called.

  • File: x/ccv/provider/types/keys.go
  • Function: getKeyPrefixes

Please add the key prefix for "ConsumerValidatorKey" to the map returned by getKeyPrefixes.

Analysis chain

Verify the correctness of the new key prefix usage.

Ensure that types.MustGetKeyPrefix("ConsumerValidatorKey") returns the correct and expected key prefix.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correctness of the new key prefix usage.

# Test: Search for the MustGetKeyPrefix function definition and its usage.
# Expect: Correct key prefix for "ConsumerValidatorKey".
rg --type go --pattern 'MustGetKeyPrefix("ConsumerValidatorKey")'

Length of output: 479


Script:

#!/bin/bash
# Description: Verify the correctness of the new key prefix usage.

# Test: Search for the MustGetKeyPrefix function definition and its usage.
# Expect: Correct key prefix for "ConsumerValidatorKey".
rg 'MustGetKeyPrefix("ConsumerValidatorKey")' --type go

Length of output: 57


Script:

#!/bin/bash
# Description: Search for the MustGetKeyPrefix function definition and inspect its implementation.

# Search for the MustGetKeyPrefix function definition.
rg 'func MustGetKeyPrefix' --type go -A 10

Length of output: 667


Script:

#!/bin/bash
# Description: Search for the getKeyPrefixes function definition and inspect its implementation.

# Search for the getKeyPrefixes function definition.
rg 'func getKeyPrefixes' --type go -A 10

Length of output: 837


Script:

#!/bin/bash
# Description: Display the full implementation of the getKeyPrefixes function to verify if "ConsumerValidatorKey" is included.

# Display the full implementation of the getKeyPrefixes function.
rg 'func getKeyPrefixes' --type go -A 50

Length of output: 3732

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

x/ccv/provider/types/keys.go Outdated Show resolved Hide resolved
x/ccv/provider/types/keys.go Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

x/ccv/provider/types/keys.go Outdated Show resolved Hide resolved
x/ccv/provider/types/keys.go Outdated Show resolved Hide resolved
x/ccv/provider/types/keys.go Dismissed Show dismissed Hide dismissed
x/ccv/provider/types/keys.go Dismissed Show dismissed Hide dismissed
func MustGetKeyPrefix(key string) byte {
keyPrefixes := getKeyPrefixes()
if prefix, found := keyPrefixes[key]; !found {
panic(fmt.Sprintf("could not find key prefix for index %s", key))

Check warning

Code scanning / CodeQL

Panic in BeginBock or EndBlock consensus methods Warning

Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Outside diff range, codebase verification and nitpick comments (3)
x/ccv/provider/types/keys.go (3)

Line range hint 325-637:
Update key retrieval functions to handle errors from MustGetKeyPrefix.

The key retrieval functions use MustGetKeyPrefix, which can panic if the key is not found. Consider updating these functions to handle errors from MustGetKeyPrefix instead.

- func ParametersKey() []byte {
- 	return []byte{MustGetKeyPrefix(ParametersKeyName)}
- }

+ func ParametersKey() ([]byte, error) {
+ 	prefix, err := MustGetKeyPrefix(ParametersKeyName)
+ 	if err != nil {
+ 		return nil, err
+ 	}
+ 	return []byte{prefix}, nil
+ }

# Repeat similar changes for other key retrieval functions.
Tools
golangci-lint

532-532: File is not gofumpt-ed with -extra

(gofumpt)


Line range hint 477-482:
Avoid using panic in consensus methods.

Using panic in MustParseThrottledPacketDataKey can cause a chain halt if used in consensus methods. Consider returning an error instead.

- func MustParseThrottledPacketDataKey(key []byte) (string, uint64) {
- 	chainId, ibcSeqNum, err := ParseThrottledPacketDataKey(key)
- 	if err != nil {
- 		panic(fmt.Sprintf("failed to parse throttled packet data key: %s", err.Error()))
- 	}
- 	return chainId, ibcSeqNum
- }

+ func MustParseThrottledPacketDataKey(key []byte) (string, uint64, error) {
+ 	chainId, ibcSeqNum, err := ParseThrottledPacketDataKey(key)
+ 	if err != nil {
+ 		return "", 0, fmt.Errorf("failed to parse throttled packet data key: %s", err.Error())
+ 	}
+ 	return chainId, ibcSeqNum, nil
+ }
Tools
golangci-lint

362-362: File is not gofumpt-ed with -extra

(gofumpt)

GitHub Check: CodeQL

[warning] 303-305: Iteration over map
Iteration over map may be a possible source of non-determinism


[warning] 314-316: Iteration over map
Iteration over map may be a possible source of non-determinism


[warning] 292-292: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt


Line range hint 502-517:
Avoid using panic in consensus methods.

Using panic in MustParseGlobalSlashEntryKey can cause a chain halt if used in consensus methods. Consider returning an error instead.

- func MustParseGlobalSlashEntryKey(bz []byte) (
- 	recvTime time.Time, consumerChainID string, ibcSeqNum uint64,
- ) {
- 	// Prefix is in first byte
- 	expectedPrefix := []byte{MustGetKeyPrefix(GlobalSlashEntryKeyName)}
- 	if prefix := bz[:1]; !bytes.Equal(prefix, expectedPrefix) {
- 		panic(fmt.Sprintf("invalid prefix; expected: %X, got: %X", expectedPrefix, prefix))
- 	}
- 	// 8 bytes for uint64 storing time bytes
- 	timeBz := sdk.BigEndianToUint64(bz[1:9])
- 	recvTime = time.Unix(0, int64(timeBz)).UTC()
- 	// 8 bytes for uint64 storing ibc seq num
- 	ibcSeqNum = sdk.BigEndianToUint64(bz[9:17])
- 	// ChainID is stored after 8 byte ibc seq num
- 	chainID := string(bz[17:])
- 	return recvTime, chainID, ibcSeqNum
- }

+ func MustParseGlobalSlashEntryKey(bz []byte) (
+ 	recvTime time.Time, consumerChainID string, ibcSeqNum uint64, error,
+ ) {
+ 	// Prefix is in first byte
+ 	expectedPrefix := []byte{MustGetKeyPrefix(GlobalSlashEntryKeyName)}
+ 	if prefix := bz[:1]; !bytes.Equal(prefix, expectedPrefix) {
+ 		return time.Time{}, "", 0, fmt.Errorf("invalid prefix; expected: %X, got: %X", expectedPrefix, prefix)
+ 	}
+ 	// 8 bytes for uint64 storing time bytes
+ 	timeBz := sdk.BigEndianToUint64(bz[1:9])
+ 	recvTime = time.Unix(0, int64(timeBz)).UTC()
+ 	// 8 bytes for uint64 storing ibc seq num
+ 	ibcSeqNum = sdk.BigEndianToUint64(bz[9:17])
+ 	// ChainID is stored after 8 byte ibc seq num
+ 	chainID := string(bz[17:])
+ 	return recvTime, chainID, ibcSeqNum, nil
+ }

x/ccv/provider/types/keys.go Outdated Show resolved Hide resolved
x/ccv/provider/types/keys.go Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

x/ccv/provider/types/keys.go Outdated Show resolved Hide resolved
x/ccv/provider/types/keys.go Show resolved Hide resolved
@github-actions github-actions bot added the C:x/consumer Assigned automatically by the PR labeler label Jul 19, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Outside diff range, codebase verification and nitpick comments (1)
x/ccv/provider/types/keys.go (1)

125-286: Missing Key Prefixes in getKeyPrefixes Function

The following key prefixes are used in the codebase but are missing from the getKeyPrefixes function:

  • x/ccv/provider/types/keys.go:AllowlistKeyName
  • x/ccv/provider/types/keys.go:ChainToChannelKeyName
  • x/ccv/provider/types/keys.go:ChainToClientKeyName
  • x/ccv/provider/types/keys.go:ChannelToChainKeyName
  • x/ccv/provider/types/keys.go:ConsumerAddrsToPruneKeyName
  • x/ccv/provider/types/keys.go:ConsumerCommissionRateKeyName
  • x/ccv/provider/types/keys.go:ConsumerGenesisKeyName
  • x/ccv/provider/types/keys.go:ConsumerRewardDenomsKeyName
  • x/ccv/provider/types/keys.go:ConsumerRewardsAllocationKeyName
  • x/ccv/provider/types/keys.go:ConsumerValidatorKeyName
  • x/ccv/provider/types/keys.go:ConsumerValidatorsKeyName
  • x/ccv/provider/types/keys.go:DenylistKeyName
  • x/ccv/provider/types/keys.go:EquivocationEvidenceMinHeightKeyName
  • x/ccv/provider/types/keys.go:GlobalSlashEntryKeyName
  • x/ccv/provider/types/keys.go:InitChainHeightKeyName
  • x/ccv/provider/types/keys.go:InitTimeoutTimestampKeyName
  • x/ccv/provider/types/keys.go:KeyAssignmentReplacementsKeyName
  • x/ccv/provider/types/keys.go:MaturedUnbondingOpsKeyName
  • x/ccv/provider/types/keys.go:MinimumPowerInTopNKeyName
  • x/ccv/provider/types/keys.go:OptedInKeyName
  • x/ccv/provider/types/keys.go:ParametersKeyName
  • x/ccv/provider/types/keys.go:PendingCAPKeyName
  • x/ccv/provider/types/keys.go:PendingCRPKeyName
  • x/ccv/provider/types/keys.go:PendingVSCsKeyName
  • x/ccv/provider/types/keys.go:PortKeyName
  • x/ccv/provider/types/keys.go:ProposedConsumerChainKeyName
  • x/ccv/provider/types/keys.go:SlashAcksKeyName
  • x/ccv/provider/types/keys.go:SlashLogKeyName
  • x/ccv/provider/types/keys.go:SlashMeterKeyName
  • x/ccv/provider/types/keys.go:SlashMeterReplenishTimeCandidateKeyName
  • x/ccv/provider/types/keys.go:ThrottledPacketDataKeyName
  • x/ccv/provider/types/keys.go:ThrottledPacketDataSizeKeyName
  • x/ccv/provider/types/keys.go:TopNKeyName
  • x/ccv/provider/types/keys.go:UnbondingOpIndexKeyName
  • x/ccv/provider/types/keys.go:UnbondingOpKeyName
  • x/ccv/provider/types/keys.go:VSCMaturedHandledThisBlockKeyName
  • x/ccv/provider/types/keys.go:ValidatorSetCapKeyName
  • x/ccv/provider/types/keys.go:ValidatorSetUpdateIdKeyName
  • x/ccv/provider/types/keys.go:ValidatorsByConsumerAddrKeyName
  • x/ccv/provider/types/keys.go:ValidatorsPowerCapKeyName
  • x/ccv/provider/types/keys.go:ValsetUpdateBlockHeightKeyName
  • x/ccv/provider/types/keys.go:VscSendTimestampKeyName

Please ensure these keys are included in the getKeyPrefixes function.

Analysis chain

LGTM! Verify the completeness of key prefixes.

The function getKeyPrefixes is well-defined and improves maintainability by centralizing key prefixes.

However, ensure that all necessary key prefixes are included.


To ensure the completeness of key prefixes, we need to gather all key names used in the codebase and compare them with the keys defined in the getKeyPrefixes function.


To verify the completeness of key prefixes, we will use the diff command to compare the key names extracted from the codebase with those in the getKeyPrefixes function.


To verify the completeness of key prefixes, we will write the key names to temporary files and then use the diff command to compare them.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the completeness of key prefixes.

# Test: Ensure all key prefixes are included in `getKeyPrefixes`.
rg --type go -A 5 $'getKeyPrefixes'

Length of output: 1907


Script:

#!/bin/bash
# Description: Verify the completeness of key prefixes by comparing all key names used in the codebase with those in `getKeyPrefixes`.

# Step 1: Extract all key names from the codebase.
key_names=$(rg --type go -o '\b[A-Za-z]+KeyName\b' | sort | uniq)

# Step 2: Extract all key names from the `getKeyPrefixes` function.
prefix_keys=$(rg --type go -o '\b[A-Za-z]+KeyName\b' x/ccv/provider/types/keys.go | sort | uniq)

# Step 3: Compare the lists and find any missing keys.
echo "Key names in codebase:"
echo "$key_names"
echo
echo "Key names in getKeyPrefixes:"
echo "$prefix_keys"
echo
echo "Missing keys in getKeyPrefixes:"
comm -23 <(echo "$key_names") <(echo "$prefix_keys")

Length of output: 13561


Script:

#!/bin/bash
# Description: Verify the completeness of key prefixes by comparing all key names used in the codebase with those in `getKeyPrefixes`.

# Step 1: Extract all key names from the codebase.
key_names=$(rg --type go -o '\b[A-Za-z]+KeyName\b' | sort | uniq)

# Step 2: Extract all key names from the `getKeyPrefixes` function.
prefix_keys=$(rg --type go -o '\b[A-Za-z]+KeyName\b' x/ccv/provider/types/keys.go | sort | uniq)

# Step 3: Compare the lists and find any missing keys using `diff`.
echo "Key names in codebase:"
echo "$key_names"
echo
echo "Key names in getKeyPrefixes:"
echo "$prefix_keys"
echo
echo "Missing keys in getKeyPrefixes:"
diff <(echo "$key_names") <(echo "$prefix_keys") | grep '<'

Length of output: 13583


Script:

#!/bin/bash
# Description: Verify the completeness of key prefixes by comparing all key names used in the codebase with those in `getKeyPrefixes`.

# Step 1: Extract all key names from the codebase.
key_names=$(rg --type go -o '\b[A-Za-z]+KeyName\b' | sort | uniq)

# Step 2: Extract all key names from the `getKeyPrefixes` function.
prefix_keys=$(rg --type go -o '\b[A-Za-z]+KeyName\b' x/ccv/provider/types/keys.go | sort | uniq)

# Step 3: Write the lists to temporary files.
echo "$key_names" > /tmp/key_names.txt
echo "$prefix_keys" > /tmp/prefix_keys.txt

# Step 4: Compare the lists and find any missing keys using `diff`.
echo "Key names in codebase:"
cat /tmp/key_names.txt
echo
echo "Key names in getKeyPrefixes:"
cat /tmp/prefix_keys.txt
echo
echo "Missing keys in getKeyPrefixes:"
diff /tmp/key_names.txt /tmp/prefix_keys.txt | grep '<'

Length of output: 12609

x/ccv/provider/types/keys.go Show resolved Hide resolved
x/ccv/provider/types/keys.go Show resolved Hide resolved
x/ccv/provider/types/keys.go Show resolved Hide resolved
@p-offtermatt
Copy link
Contributor

Just to double-check, this doesn't need a migration, since the actual keys remain the same, correct?

Copy link
Contributor

@p-offtermatt p-offtermatt left a comment

Choose a reason for hiding this comment

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

LGTM!

keyPrefixes := getKeyPrefixes()
if prefix, found := keyPrefixes[key]; !found {
panic(fmt.Sprintf("could not find key prefix for index %s", key))
} else {
Copy link
Contributor

Choose a reason for hiding this comment

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

very nit: else statement is unnecessary here.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

without the else I need to define prefix outside the if.

@sainoe
Copy link
Contributor

sainoe commented Jul 24, 2024

LGTM. Thanks for the refactor!

@sainoe sainoe self-requested a review July 24, 2024 09:05
Merged via the queue into main with commit dbaf024 Jul 24, 2024
13 of 14 checks passed
@mpoke mpoke deleted the marius/939-prefixing-scheme branch July 24, 2024 09:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C:ADR Assigned automatically by the PR labeler C:Docs Assigned automatically by the PR labeler C:x/consumer Assigned automatically by the PR labeler C:x/provider Assigned automatically by the PR labeler
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Rethink byte prefixing scheme
3 participants