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

imp: add flat fee for queries to VerifyMembership #5927

Conversation

charleenfei
Copy link
Contributor

@charleenfei charleenfei commented Mar 5, 2024

Description

see cosmos/cosmos-sdk#9995 for similar flat gas consumption fee logic.

closes: #5902

i elected to consume the gas outside of the defer func as we are not operating on the cached context in this case, and simply consuming gas for the read on consensus state from the store...but open to other opinions if people have any!

Commit Message / Changelog Entry

type: commit message

see the guidelines for commit messages. (view raw markdown for examples)


Before we can merge this PR, please make sure that all the following items have been
checked off. If any of the checklist items are not applicable, please leave them but
write a little note why.

  • Targeted PR against the correct branch (see CONTRIBUTING.md).
  • Linked to Github issue with discussion and accepted design OR link to spec that describes this work.
  • Code follows the module structure standards and Go style guide.
  • Wrote unit and integration tests.
  • Updated relevant documentation (docs/) or specification (x/<module>/spec/).
  • Added relevant godoc comments.
  • Provide a commit message to be used for the changelog entry in the PR description for review.
  • Re-reviewed Files changed in the Github PR explorer.
  • Review Codecov Report in the comment section below once CI passes.

Summary by CodeRabbit

  • Refactor
    • Improved gas consumption logic for proof verification queries to ensure proper gas handling.

Copy link
Contributor

coderabbitai bot commented Mar 7, 2024

Walkthrough

The update introduces a new gas consumption logic in the VerifyMembership function of the grpc_query.go file. This logic ensures that a flat gas fee is consumed for proof verification queries based on the length of the proof before the actual clientState.VerifyMembership call is made. This change aims to provide a basic defense mechanism against potential abuse by preventing endless client calls through gas exhaustion.

Changes

File Path Change Summary
.../02-client/keeper/grpc_query.go Added gas consumption logic to VerifyMembership for proof verification queries.

Assessment against linked issues

Objective Addressed Explanation
Consume flat gas fee on VerifyMembership rpc (#5902)

Poem

In the realm of code, where logic intertwines,
A rabbit hopped, leaving bugs behind.
🐰 With every leap, a fix in place,
🌟 For gas and proofs, a steady pace.

"No endless calls," it said with glee,
🛡️ A defense built, for you and me.
With wisdom shared, in bytes and bits,
🎉 A rabbit's touch, the code now fits.

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-tests 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 tests 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 tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

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 a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

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

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

@charleenfei charleenfei marked this pull request as ready for review March 7, 2024 10:27
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.

Review Status

Actionable comments generated: 1

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 3c4f037 and dda366b.
Files selected for processing (1)
  • modules/core/02-client/keeper/grpc_query.go (2 hunks)

Comment on lines 387 to 398
return nil, status.Error(codes.FailedPrecondition, errorsmod.Wrapf(types.ErrClientNotActive, "cannot verify membership using client (%s) with status %s", req.ClientId, clientStatus).Error())
}

// consume flat gas fee for proof verification queries
ctx.GasMeter().ConsumeGas(
3*ctx.KVGasConfig().ReadCostPerByte*uint64(len(req.Proof)),
"verify membership query",
)

if err := clientState.VerifyMembership(cachedCtx, k.ClientStore(cachedCtx, req.ClientId), k.cdc, req.ProofHeight, req.TimeDelay, req.BlockDelay, req.Proof, req.MerklePath, req.Value); err != nil {
k.Logger(ctx).Debug("proof verification failed", "key", req.MerklePath, "error", err)
return &types.QueryVerifyMembershipResponse{
Copy link
Contributor

Choose a reason for hiding this comment

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

📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [372-395]

The addition of a flat gas fee consumption mechanism based on the length of req.Proof in the VerifyMembership function is a significant change aimed at preventing potential abuse scenarios. However, there are a few points to consider for refinement:

  1. Gas Consumption Calculation: The formula 3*ctx.KVGasConfig().ReadCostPerByte*uint64(len(req.Proof)) is used to calculate the gas consumed. It's crucial to ensure that the multiplier 3 and the usage of ReadCostPerByte accurately reflect the intended gas consumption model for proof verification. If the constants and multipliers are derived from empirical data or specific reasoning, documenting this within the code or in the PR description would enhance clarity and maintainability.

  2. Error Handling and Logging: The function correctly handles errors and logs the failure of proof verification. However, it might be beneficial to also log the gas consumption for successful and unsuccessful queries to aid in debugging and monitoring the system's behavior under different load conditions.

  3. Performance Considerations: While the focus is on security and preventing abuse, it's also important to consider the performance implications of the new gas consumption logic, especially in high-throughput scenarios. Ensuring that the gas metering does not introduce significant overhead or latency in the VerifyMembership query processing is crucial. Performance testing or benchmarking results, if available, should be discussed in the PR to validate the impact of these changes.

  4. Documentation and Comments: Adding more detailed comments explaining the rationale behind the chosen gas consumption formula and any potential edge cases or limitations of the current implementation would be helpful. This documentation can assist future maintainers in understanding the context and reasoning behind these changes.

Overall, the implementation aligns with the PR's objectives to introduce a flat fee for proof verification queries, enhancing the system's resilience against potential abuse. Further refinement and documentation could improve the clarity, maintainability, and performance of this feature.

Copy link

sonarcloud bot commented Mar 7, 2024

Quality Gate Passed Quality Gate passed

Issues
0 New issues
0 Accepted issues

Measures
0 Security Hotspots
No data about Coverage
0.0% Duplication on New Code

See analysis details on SonarCloud

Copy link
Contributor

@crodriguezvega crodriguezvega left a comment

Choose a reason for hiding this comment

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

🙏

Copy link
Contributor

@DimitrisJim DimitrisJim left a comment

Choose a reason for hiding this comment

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

this lgtm, not consuming in defer makes sense to me too, we don't want to consume this gas in the cases where the previous if clauses return an error, yea?

@@ -386,6 +387,12 @@ func (k Keeper) VerifyMembership(c context.Context, req *types.QueryVerifyMember
return nil, status.Error(codes.FailedPrecondition, errorsmod.Wrapf(types.ErrClientNotActive, "cannot verify membership using client (%s) with status %s", req.ClientId, clientStatus).Error())
}

// consume flat gas fee for proof verification queries
Copy link
Contributor

Choose a reason for hiding this comment

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

do we want to mention the reasoning here? (protection against clients recursively calling each other)

Copy link
Member

Choose a reason for hiding this comment

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

Personally I think its fine to just state that we're consuming a flat fee for proof verification, as its cpu intensive and not based around IOPS, which is the main gas consumption factor in the cosmos sdk.

Pretty sure all VerifyMembership calls within the client state will have to look up a root to prove against based on the provided height, so there would be gas consumed on the cacheCtx for that store access which should also protection against recursive client calls, but this just adds an extra bit of gas consumption which is definitely no harm and the right call imo!

Copy link
Contributor

Choose a reason for hiding this comment

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

but wouldn't that gas on the cached context only be consumed when function returns, i.e in defer? (which, in the recursive case, is what doesn't happen)

I don't want to appear waaay too nitty though 😅, fine w/o it if you agree!

Copy link
Member

Choose a reason for hiding this comment

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

You're 100% correct! Great point!

Happy to add a note if others agree too, maybe something like:

Suggested change
// consume flat gas fee for proof verification queries
// consume flat gas fee for proof verification queries.
// NOTE: consuming gas prior to method invocation also provides protection against recursive calls reaching stack overflow

Copy link
Contributor Author

Choose a reason for hiding this comment

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

great suggestion! ill update this, thanks for the reviews and reasonings @damiannolan @DimitrisJim

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.

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between dda366b and e57aa4a.
Files selected for processing (1)
  • modules/core/02-client/keeper/grpc_query.go (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • modules/core/02-client/keeper/grpc_query.go

Copy link

sonarcloud bot commented Mar 12, 2024

Quality Gate Passed Quality Gate passed for 'ibc-go'

Issues
0 New issues
0 Accepted issues

Measures
0 Security Hotspots
No data about Coverage
No data about Duplication

See analysis details on SonarCloud

@charleenfei charleenfei merged commit 9aa7151 into main Mar 12, 2024
78 of 81 checks passed
@charleenfei charleenfei deleted the charly/issue#5902-consume-flat-gas-fee-on-verifymembership-rpc branch March 12, 2024 11:04
mergify bot pushed a commit that referenced this pull request Mar 12, 2024
Co-authored-by: Damian Nolan <[email protected]>
(cherry picked from commit 9aa7151)
crodriguezvega pushed a commit that referenced this pull request Mar 12, 2024
Co-authored-by: Damian Nolan <[email protected]>
(cherry picked from commit 9aa7151)

Co-authored-by: Charly <[email protected]>
mergify bot pushed a commit that referenced this pull request Apr 8, 2024
Co-authored-by: Damian Nolan <[email protected]>
(cherry picked from commit 9aa7151)

# Conflicts:
#	modules/core/02-client/keeper/grpc_query.go
crodriguezvega added a commit that referenced this pull request Apr 8, 2024
Co-authored-by: Damian Nolan <[email protected]>
(cherry picked from commit 9aa7151)

# Conflicts:
#	modules/core/02-client/keeper/grpc_query.go

Co-authored-by: Charly <[email protected]>
Co-authored-by: Damian Nolan <[email protected]>
Co-authored-by: Carlos Rodriguez <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Consume flat gas fee on VerifyMembership rpc
4 participants