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!: Add BlocksUntilNextEpoch query #2106

Merged
merged 11 commits into from
Jul 30, 2024
Merged

Conversation

p-offtermatt
Copy link
Contributor

@p-offtermatt p-offtermatt commented Jul 26, 2024

Description

Closes: #1940

Adds a new query that returns the blocks until the next epoch starts.

Slightly refactors the condition for sending VSCPackets in relay.go to achieve this


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
  • Added ! to the type prefix if the change is state-machine breaking
  • Confirmed this PR does not introduce changes requiring state migrations, OR migration code has been added to consumer and/or provider modules
  • Targeted the correct branch (see PR Targeting)
  • Provided a link to the relevant issue or specification
  • Followed the guidelines for building SDK modules
  • Included the necessary unit and integration tests
  • Added a changelog entry to CHANGELOG.md
  • Included comments for documenting Go code
  • Updated the relevant documentation or specification
  • Reviewed "Files changed" and left comments if necessary
  • Confirmed all CI checks have passed
  • If this PR is library API breaking, bump the go.mod version string of the repo, and follow through on a new major release

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 ! the type prefix if the change is state-machine breaking
  • confirmed this PR does not introduce changes requiring state migrations, OR confirmed migration code has been added to consumer and/or provider modules
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic
  • reviewed API design and naming
  • reviewed documentation is accurate
  • reviewed tests and test coverage

Summary by CodeRabbit

  • New Features

    • Introduced a new method to query the number of blocks until the next epoch begins, enhancing blockchain interaction for applications relying on epoch timing.
    • Added a command to the CLI for users to easily retrieve block count until the next epoch.
  • Documentation

    • Updated the FAQ section to include information on the timing of validator updates and how to query blocks until the next epoch.
  • Tests

    • Added tests to validate the functionality of blocks until the next epoch calculations, ensuring accuracy under various scenarios.

@github-actions github-actions bot added the C:x/provider Assigned automatically by the PR labeler label Jul 26, 2024
@p-offtermatt p-offtermatt marked this pull request as ready for review July 26, 2024 15:12
@p-offtermatt p-offtermatt requested a review from a team as a code owner July 26, 2024 15:12
Copy link
Contributor

coderabbitai bot commented Jul 26, 2024

Walkthrough

Walkthrough

The recent changes introduce a feature that allows users to query the number of blocks remaining until the next epoch in the Cosmos interchain security framework. This enhancement includes the addition of a new RPC method, related request and response messages, and a CLI command, aimed at improving usability and efficiency of blockchain interactions regarding epoch transitions.

Changes

Files Change Summary
.changelog/unreleased/features/provider/... Added a feature to query for blocks until the next epoch, including new RPC methods and CLI command.
docs/docs/frequently-asked-questions.md Updated FAQ to include timing of validator updates and how to query remaining blocks until the next epoch.
x/ccv/provider/keeper/relay_test.go Introduced a new test function to validate the BlocksUntilNextEpoch method, improving test coverage.

Assessment against linked issues

Objective Addressed Explanation
Query for blocks until next epoch (#1940)
Improve validator awareness of epoch transitions (#1940)

Recent review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 23cf6bf and cdef43d.

Files selected for processing (2)
  • x/ccv/provider/keeper/relay.go (2 hunks)
  • x/ccv/provider/keeper/relay_test.go (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • x/ccv/provider/keeper/relay.go
Additional context used
Path-based instructions (1)
x/ccv/provider/keeper/relay_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations. Only report issues that you have a high degree of confidence in.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request. Only report issues that you have a high degree of confidence in."

Additional comments not posted (1)
x/ccv/provider/keeper/relay_test.go (1)

928-962: LGTM! Verify the function usage in the codebase.

The code changes are approved. The test cases cover various scenarios effectively.

However, ensure that the BlocksUntilNextEpoch method is used correctly in the codebase.

Verification successful

Function usage verified and consistent across the codebase.

The BlocksUntilNextEpoch function is used correctly in various contexts, including tests, relay logic, gRPC queries, CLI commands, and protobuf files. The test cases effectively cover different scenarios to validate the behavior of the function.

  • x/ccv/provider/keeper/relay_test.go
  • x/ccv/provider/keeper/relay.go
  • x/ccv/provider/keeper/grpc_query.go
  • x/ccv/provider/client/cli/query.go
  • x/ccv/provider/types/query.pb.gw.go
  • x/ccv/provider/types/query.pb.go
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `BlocksUntilNextEpoch` match the expected usage.

# Test: Search for the function usage. Expect: Correct usage of the function.
rg --type go -A 5 $'BlocksUntilNextEpoch'

Length of output: 27557


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.

@github-actions github-actions bot added the C:Docs Assigned automatically by the PR labeler label Jul 26, 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 (4)
.changelog/unreleased/features/provider/2106-query-blocks-until-next-epoch.md (1)

1-1: Ensure consistency in changelog entries.

Consider adding a period at the end of the sentence for consistency with other changelog entries.

docs/docs/frequently-asked-questions.md (2)

143-143: Surround fenced code blocks with blank lines.

According to Markdownlint, fenced code blocks should be surrounded by blank lines.

- ```bash
+ 
+ ```bash
Tools
Markdownlint

143-143: null
Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


145-145: Ensure the file ends with a single newline character.

According to Markdownlint, files should end with a single newline character.

- interchain-security-pd query provider blocks-until-next-epoch
+ interchain-security-pd query provider blocks-until-next-epoch
+
Tools
Markdownlint

145-145: null
Files should end with a single newline character

(MD047, single-trailing-newline)

x/ccv/provider/keeper/relay.go (1)

Line range hint 152-161: Simplify the condition for better readability.

The condition can be simplified to improve readability.

if k.BlocksUntilNextEpoch(ctx) == 0 {
	// only queue and send VSCPackets at the boundaries of an epoch

	// collect validator updates
	k.QueueVSCPackets(ctx)

	// try sending VSC packets to all registered consumer chains;
	// if the CCV channel is not established for a consumer chain,
	// the updates will remain queued until the channel is established
	k.SendVSCPackets(ctx)
}

docs/docs/frequently-asked-questions.md Outdated Show resolved Hide resolved
Comment on lines +492 to +499
// QueryBlocksUntilNextEpoch returns the number of blocks until the next epoch
func (k Keeper) QueryBlocksUntilNextEpoch(goCtx context.Context, req *types.QueryBlocksUntilNextEpochRequest) (*types.QueryBlocksUntilNextEpochResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)

// Calculate the blocks until the next epoch
blocksUntilNextEpoch := k.BlocksUntilNextEpoch(ctx)

return &types.QueryBlocksUntilNextEpochResponse{BlocksUntilNextEpoch: uint64(blocksUntilNextEpoch)}, nil
Copy link
Contributor

Choose a reason for hiding this comment

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

Add error handling for null requests.

The function should handle potential null requests to prevent unexpected errors.

func (k Keeper) QueryBlocksUntilNextEpoch(goCtx context.Context, req *types.QueryBlocksUntilNextEpochRequest) (*types.QueryBlocksUntilNextEpochResponse, error) {
+	if req == nil {
+		return nil, status.Error(codes.InvalidArgument, "empty request")
+	}
	ctx := sdk.UnwrapSDKContext(goCtx)

	// Calculate the blocks until the next epoch
	blocksUntilNextEpoch := k.BlocksUntilNextEpoch(ctx)

	return &types.QueryBlocksUntilNextEpochResponse{BlocksUntilNextEpoch: uint64(blocksUntilNextEpoch)}, nil
}
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
// QueryBlocksUntilNextEpoch returns the number of blocks until the next epoch
func (k Keeper) QueryBlocksUntilNextEpoch(goCtx context.Context, req *types.QueryBlocksUntilNextEpochRequest) (*types.QueryBlocksUntilNextEpochResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)
// Calculate the blocks until the next epoch
blocksUntilNextEpoch := k.BlocksUntilNextEpoch(ctx)
return &types.QueryBlocksUntilNextEpochResponse{BlocksUntilNextEpoch: uint64(blocksUntilNextEpoch)}, nil
// QueryBlocksUntilNextEpoch returns the number of blocks until the next epoch
func (k Keeper) QueryBlocksUntilNextEpoch(goCtx context.Context, req *types.QueryBlocksUntilNextEpochRequest) (*types.QueryBlocksUntilNextEpochResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
ctx := sdk.UnwrapSDKContext(goCtx)
// Calculate the blocks until the next epoch
blocksUntilNextEpoch := k.BlocksUntilNextEpoch(ctx)
return &types.QueryBlocksUntilNextEpochResponse{BlocksUntilNextEpoch: uint64(blocksUntilNextEpoch)}, nil
}

Comment on lines +601 to +625
func CmdBlocksUntilNextEpoch() *cobra.Command {
cmd := &cobra.Command{
Use: "blocks-until-next-epoch",
Short: "Query the number of blocks until the next epoch begins and validator updates are sent to consumer chains",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
queryClient := types.NewQueryClient(clientCtx)

req := &types.QueryBlocksUntilNextEpochRequest{}
res, err := queryClient.QueryBlocksUntilNextEpoch(cmd.Context(), req)
if err != nil {
return err
}

return clientCtx.PrintProto(res)
},
}

flags.AddQueryFlagsToCmd(cmd)

return cmd
Copy link
Contributor

Choose a reason for hiding this comment

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

Add error handling for null responses.

The function should handle potential null responses to prevent unexpected errors.

func CmdBlocksUntilNextEpoch() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "blocks-until-next-epoch",
		Short: "Query the number of blocks until the next epoch begins and validator updates are sent to consumer chains",
		Args:  cobra.ExactArgs(0),
		RunE: func(cmd *cobra.Command, args []string) error {
			clientCtx, err := client.GetClientQueryContext(cmd)
			if err != nil {
				return err
			}
			queryClient := types.NewQueryClient(clientCtx)

			req := &types.QueryBlocksUntilNextEpochRequest{}
			res, err := queryClient.QueryBlocksUntilNextEpoch(cmd.Context(), req)
			if err != nil {
				return err
			}
+			if res == nil {
+				return fmt.Errorf("received empty response")
+			}
			return clientCtx.PrintProto(res)
		},
	}

	flags.AddQueryFlagsToCmd(cmd)

	return cmd
}
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
func CmdBlocksUntilNextEpoch() *cobra.Command {
cmd := &cobra.Command{
Use: "blocks-until-next-epoch",
Short: "Query the number of blocks until the next epoch begins and validator updates are sent to consumer chains",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
queryClient := types.NewQueryClient(clientCtx)
req := &types.QueryBlocksUntilNextEpochRequest{}
res, err := queryClient.QueryBlocksUntilNextEpoch(cmd.Context(), req)
if err != nil {
return err
}
return clientCtx.PrintProto(res)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
func CmdBlocksUntilNextEpoch() *cobra.Command {
cmd := &cobra.Command{
Use: "blocks-until-next-epoch",
Short: "Query the number of blocks until the next epoch begins and validator updates are sent to consumer chains",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
queryClient := types.NewQueryClient(clientCtx)
req := &types.QueryBlocksUntilNextEpochRequest{}
res, err := queryClient.QueryBlocksUntilNextEpoch(cmd.Context(), req)
if err != nil {
return err
}
if res == nil {
return fmt.Errorf("received empty response")
}
return clientCtx.PrintProto(res)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}

@@ -162,6 +162,13 @@ func (k Keeper) EndBlockVSU(ctx sdk.Context) {
}
}

// BlocksUntilNextEpoch returns the number of blocks until the next epoch starts
// Returns 0 if the current block is the last block of the epoch
func (k Keeper) BlocksUntilNextEpoch(ctx sdk.Context) int64 {
Copy link
Contributor

Choose a reason for hiding this comment

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

It seems you could easily move the logic inside the query itself without having to create the BlocksUntilNextEpoch method. Was this added to make testing easier? Couldn't we test the logic from inside grpc_query_test.go?

Copy link
Contributor Author

@p-offtermatt p-offtermatt Jul 26, 2024

Choose a reason for hiding this comment

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

To make tests easier and to make the query logic and the logic in relay.go more closely connected with the query. I dont see a downside, do you think this is worse now?

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

To query how many blocks are left until the next epoch starts,
run the following command:
```bash
Copy link
Contributor

@coderabbitai coderabbitai bot Jul 29, 2024

Choose a reason for hiding this comment

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

Surround fenced code block with blank lines.

Fenced code blocks should be surrounded by blank lines for better readability.

+ 
```bash
interchain-security-pd query provider blocks-until-next-epoch

<details>
<summary>Tools</summary>

<details>
<summary>Markdownlint</summary><blockquote>

146-146: null
Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)

</blockquote></details>

</details>

<!-- This is an auto-generated reply by CodeRabbit -->

Copy link
Contributor

Choose a reason for hiding this comment

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

@p-offtermatt Is it expected that coderabbitai still looks at markdown files?

Copy link
Contributor

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This was branched off of main before the config change got in, so on this PR, yes it is

docs/docs/frequently-asked-questions.md Show resolved Hide resolved
docs/docs/frequently-asked-questions.md Show resolved Hide resolved
docs/docs/frequently-asked-questions.md Show resolved Hide resolved
@p-offtermatt p-offtermatt added this pull request to the merge queue Jul 30, 2024
Merged via the queue into main with commit e5c567e Jul 30, 2024
17 of 18 checks passed
@p-offtermatt p-offtermatt deleted the ph/blocks-until-epoch-end branch July 30, 2024 14:35
@p-offtermatt p-offtermatt linked an issue Aug 5, 2024 that may be closed by this pull request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C:Docs 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.

[Feature]: Query for blocks until next epoch Add query for epoch info
4 participants