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(x/auth/ante): allow custom verifyIsOnCurve when validate tx for public key #23128

Merged
merged 4 commits into from
Jan 2, 2025

Conversation

mmsqe
Copy link
Contributor

@mmsqe mmsqe commented Dec 30, 2024

Description

make verify with ethsecp256k1 easier

type SigVerificationDecorator struct {
	authante.SigVerificationDecorator
}

func NewSigVerificationDecorator(ak authante.AccountKeeper, signModeHandler *txsigning.HandlerMap, sigGasConsumer authante.SignatureVerificationGasConsumer, aaKeeper authante.AccountAbstractionKeeper) SigVerificationDecorator {
	return SigVerificationDecorator{
		SigVerificationDecorator: authante.NewSigVerificationDecoratorWithVerifyOnCurve(
			ak, signModeHandler, sigGasConsumer, aaKeeper,
			func(pubKey cryptotypes.PubKey) (bool, error) {
				if pubKey.Bytes() != nil {
					typedPubKey, ok := pubKey.(*ethsecp256k1.PubKey)
					if ok {
						pubKeyObject, err := secp256k1dcrd.ParsePubKey(typedPubKey.Bytes())
						if err != nil {
							if errors.Is(err, secp256k1dcrd.ErrPubKeyNotOnCurve) {
								return true, errorsmod.Wrap(sdkerrors.ErrInvalidPubKey, "secp256k1 key is not on curve")
							}
							return true, err
						}
						if !pubKeyObject.IsOnCurve() {
							return true, errorsmod.Wrap(sdkerrors.ErrInvalidPubKey, "secp256k1 key is not on curve")
						}
						return true, nil
					}
				}
				return false, nil
			},
		),
	}
}

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, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • updated the relevant documentation or specification, including comments for documenting Go code
  • 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.

Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

  • New Features

    • Added support for custom verifyIsOnCurve function when validating transactions for public keys like ethsecp256k1
    • Enhanced signature verification process with configurable public key validation
  • Improvements

    • Increased flexibility in signature verification by allowing custom verification logic

Copy link
Contributor

coderabbitai bot commented Dec 30, 2024

📝 Walkthrough

Walkthrough

This pull request introduces a new feature in the Cosmos SDK that allows for a custom verifyIsOnCurve function when validating transactions for public keys like ethsecp256k1. The changes are primarily focused on enhancing the flexibility of public key verification in the signature verification process. The modification involves updating the SigVerificationDecorator struct in the x/auth/ante/sigverify.go file and adding a new entry to the CHANGELOG.md to document the feature.

Changes

File Change Summary
CHANGELOG.md Added a new feature entry for custom verifyIsOnCurve function
x/auth/ante/sigverify.go - Added extraVerifyIsOnCurve function pointer to SigVerificationDecorator struct
- Updated NewSigVerificationDecorator method
- Added NewSigVerificationDecoratorWithVerifyOnCurve method
- Added VerifyIsOnCurve method to enhance public key verification

Possibly related PRs

Suggested labels

backport/v0.52.x

Suggested reviewers

  • sontrinh16
  • aaronc
  • tac0turtle
  • julienrbrt

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.

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.

@mmsqe mmsqe marked this pull request as ready for review December 30, 2024 14:16
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: 0

🧹 Nitpick comments (3)
x/auth/ante/sigverify.go (3)

72-76: Consider renaming or expanding comment for clarity.
Having a field named extraVerifyIsOnCurve might cause confusion as to when and how this verification is applied or bypassed. Consider adding a clarifying comment or renaming to something like customVerifyIsOnCurve to highlight its optional usage.


83-89: Ensure function pointer usage is documented.
While this constructor clearly injects the optional verification function, consider adding a doc comment explaining the expected return contract for (bool, error)—particularly how bool indicates whether the check is “handled” or should fall back to the default.


159-168: Validate behavior when the custom function partially handles the check.
This logic bypasses the built-in verifyIsOnCurve only if the custom function returns (true, err), which might be easy to misunderstand. Adding a doc comment or an explicit code comment clarifying the expected usage and meaning of handled in the returned tuple can help future maintainers.

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4f3f401 and 3f8243b.

📒 Files selected for processing (2)
  • CHANGELOG.md (1 hunks)
  • x/auth/ante/sigverify.go (3 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
x/auth/ante/sigverify.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

CHANGELOG.md (1)

Pattern **/*.md: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"

🔇 Additional comments (3)
x/auth/ante/sigverify.go (2)

80-82: Reusing the new constructor is good.
This approach avoids code duplication by simply redirecting to the more general constructor. No issues found here.


436-436: Good to see centralized curve verification.
Invoking svd.VerifyIsOnCurve(txPubKey) ensures all relevant checks, including any custom logic, are properly applied. This approach is consistent with the single-responsibility principle.

CHANGELOG.md (1)

Line range hint 1-2000: LGTM! The CHANGELOG.md follows best practices

The changelog is well-structured and follows best practices:

  • Clear categorization of changes (Features, Improvements, Bug Fixes etc.)
  • Consistent formatting throughout
  • Proper linking to PRs and issues
  • Detailed descriptions of changes
  • Good organization by version numbers

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

🧹 Nitpick comments (1)
x/auth/ante/sigverify.go (1)

79-90: Consider adding validation for the verifyFn parameter.

While the implementation is correct, it would be beneficial to add validation for the verifyFn parameter to ensure it behaves consistently when called.

 func NewSigVerificationDecoratorWithVerifyOnCurve(ak AccountKeeper, signModeHandler *txsigning.HandlerMap, sigGasConsumer SignatureVerificationGasConsumer, aaKeeper AccountAbstractionKeeper, verifyFn func(pubKey cryptotypes.PubKey) (bool, error)) SigVerificationDecorator {
+    if verifyFn != nil {
+        // Validate the function with a nil pubkey to ensure it handles edge cases
+        if _, err := verifyFn(nil); err != nil && !errors.Is(err, sdkerrors.ErrInvalidPubKey) {
+            panic(fmt.Sprintf("verifyFn must handle nil pubkey gracefully: %v", err))
+        }
+    }
     return SigVerificationDecorator{
         aaKeeper:             aaKeeper,
         ak:                   ak,
         signModeHandler:      signModeHandler,
         sigGasConsumer:       sigGasConsumer,
         extraVerifyIsOnCurve: verifyFn,
     }
 }
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3f8243b and 8c5f74e.

📒 Files selected for processing (2)
  • CHANGELOG.md (1 hunks)
  • x/auth/ante/sigverify.go (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG.md
🧰 Additional context used
📓 Path-based instructions (1)
x/auth/ante/sigverify.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

🔇 Additional comments (3)
x/auth/ante/sigverify.go (3)

72-76: LGTM! Well-structured decorator with clear field declarations.

The addition of extraVerifyIsOnCurve as an optional function field provides good flexibility for custom curve verification while maintaining backward compatibility.


Line range hint 432-436: LGTM! Proper integration of curve verification in setPubKey.

The VerifyIsOnCurve check is correctly placed before setting the public key in the account.


Line range hint 114-163: Verify error handling in recursive multisig verification.

The implementation of VerifyIsOnCurve is thorough, but there's a potential issue in the multisig handling where we break early on the first error without collecting all validation errors.

Consider collecting all validation errors for better debugging:

 case multisig.PubKey:
     pubKeysObjects := typedPubKey.GetPubKeys()
-    ok := true
+    var errs []error
     for _, pubKeyObject := range pubKeysObjects {
         if err := svd.VerifyIsOnCurve(pubKeyObject); err != nil {
-            ok = false
-            break
+            errs = append(errs, err)
         }
     }
-    if !ok {
-        return errorsmod.Wrap(sdkerrors.ErrInvalidPubKey, "some keys are not on curve")
+    if len(errs) > 0 {
+        return errorsmod.Wrap(sdkerrors.ErrInvalidPubKey, fmt.Sprintf("invalid keys: %v", errs))
     }

@tac0turtle tac0turtle added this pull request to the merge queue Jan 2, 2025
Merged via the queue into cosmos:main with commit 57a1437 Jan 2, 2025
70 of 73 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants