8000 fix: sigverify to attach eip191 prefix, only it is legacy amino json mode by beer-1 · Pull Request #377 · initia-labs/initia · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

fix: sigverify to attach eip191 prefix, only it is legacy amino json mode #377

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

Merged
merged 7 commits into from
Mar 25, 2025

Conversation

beer-1
Copy link
Member
@beer-1 beer-1 commented Mar 25, 2025

Description

Closes: #XXXX


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
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • 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.

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

@beer-1 beer-1 self-assigned this Mar 25, 2025
@beer-1 beer-1 requested a review from a team as a code owner March 25, 2025 05:04
Copy link
coderabbitai bot commented Mar 25, 2025
📝 Walkthrough

Walkthrough

This pull request simplifies the signature verification process for Ethereum public keys by removing specific logic related to the "interwoven-1" chain and the EIP-191 prefix handling. It introduces a new Keyring type, modifies the command context setup to allow keyring overrides, and adds a function to remove the EIP-191 prefix. Overall, the changes streamline the verification logic and enhance the configuration of the command context.

Changes

File(s) Change Summary
app/ante/sigverify/verify.go Removed logic for verifying Ethereum public keys specific to the "interwoven-1" chain, simplifying the verification process to directly check signatures using VerifySignature.
crypto/ethsecp256k1/ethsecp256k1.go Removed EIP-191 prefix handling from Sign and VerifySignature methods, integrating the functionality of VerifySignatureWithoutEIP191 into VerifySignature. Updated comments accordingly.
cmd/initiad/root.go Added logic to create a new keyring if initClientCtx.Keyring is not nil, enhancing the flexibility of the command context setup.
crypto/keyring/keyring.go Introduced a new Keyring type with a NewKeyring function, and added a Sign method for signing messages. Implemented SignWithLedger for signing with Ledger devices, including validation for signing modes.
crypto/ledger/ledger.go Enhanced SignSECP256K1 method to format signing bytes into a readable JSON format before printing, improving user feedback during the signing process.
tx/eip191.go Added a new function RemoveEIP191Prefix to remove the EIP-191 prefix from messages, utilizing the strings package for implementation.

Sequence Diagram(s)

sequenceDiagram
    participant TX as Transaction
    participant VX as Verify.go
    participant PK as PubKey (crypto)
    
    TX->>VX: Request signature verification
    VX->>PK: Call VerifySignature (without EIP-191 prefix)
    PK-->>VX: Return verification result
    VX-->>TX: Return result to caller
Loading

Poem

I’m a rabbit, hopping through the code so bright,
With signatures verified in a fresh, new light.
EIP-191 leads the way with a clever twist,
Renamed methods and logic that simply can’t be missed.
Hop along the branches of code with a smile so wide,
Celebrating changes with each joyful stride! 🐇
Happy code trails on this adventure we ride!


🪧 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 plan to trigger planning for file edits and PR creation.
  • @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
github-actions bot commented Mar 25, 2025

Dependency Review

✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.

OpenSSF Scorecard

PackageVersionScoreDetails

Scanned Files

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

🧹 Nitpick comments (2)
crypto/ledger/ledger.go (1)

145-161: Consider limiting or securing the log output.

Pretty-printing the entire signing bytes may expose sensitive or private content (e.g., transaction details or addresses). Consider only logging when in debug mode or sanitizing the output to avoid leaking sensitive information into logs.

cmd/initiad/root.go (1)

125-134: Clarify the keyring override logic.

Overriding an already-initialized initClientCtx.Keyring may lead to confusion about which keyring is actually in use. Ensure that users and documentation are aware of this override, especially if initClientCtx.Keyring was previously modified elsewhere.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between f77a97b and 3495a76.

⛔ Files ignored due to path filters (2)
  • go.mod is excluded by !**/*.mod
  • go.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (6)
  • app/ante/sigverify/verify.go (0 hunks)
  • cmd/initiad/root.go (2 hunks)
  • crypto/ethsecp256k1/ethsecp256k1.go (1 hunks)
  • crypto/keyring/keyring.go (1 hunks)
  • crypto/ledger/ledger.go (2 hunks)
  • tx/eip191.go (2 hunks)
💤 Files with no reviewable changes (1)
  • app/ante/sigverify/verify.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • crypto/ethsecp256k1/ethsecp256k1.go
🧰 Additional context used
🧬 Code Definitions (1)
crypto/keyring/keyring.go (3)
crypto/ethsecp256k1/ethsecp256k1.go (15)
  • pubKey (173-185)
  • pubKey (188-193)
  • pubKey (196-198)
  • pubKey (201-203)
  • pubKey (206-208)
  • pubKey (211-213)
  • pubKey (216-223)
  • pubKey (226-230)
  • pubKey (233-235)
  • pubKey (241-243)
  • pubKey (246-267)
  • _ (48-48)
  • _ (49-49)
  • _ (151-151)
  • _ (152-152)
tx/eip191.go (2)
  • _ (27-27)
  • RemoveEIP191Prefix (55-57)
crypto/ledger/ledger.go (1)
  • _ (23-23)
🔇 Additional comments (8)
cmd/initiad/root.go (1)

93-94: Protobuf support for Ledger is enabled.

Attaching .WithLedgerHasProtobuf(true) is beneficial if your code requires signing or parsing Protobuf transactions directly on a Ledger device. This looks good.

crypto/keyring/keyring.go (7)

1-2: New package definition.

No issues here; the package declaration aligns with Go best practices.


3-17: Imports look appropriate.

All imports, including “errors” and “github.com/cosmos/cosmos-sdk/...”, are necessary and consistent with usage throughout the file.


19-21: Struct embedding of Keyring.

Embedding cosmoskeyring.Keyring as a field is a clean way to extend functionality.


23-30: Keyring construction is straightforward.

The NewKeyring function properly initializes and returns a wrapped Keyring.


32-44: Ledger vs. non-ledger signing logic looks correct.

Delegating to SignWithLedger when the record includes GetLedger() is clear, and otherwise falling back to the base Keyring is appropriate.


46-49: Error variables.

These specialized error variables clarify user intent for sign mode errors. No concerns here.


51-100:

❓ Verification inconclusive

Request verification of sign message matching.

This method removes the EIP-191 prefix before calling the ledger’s signing function, then verifies the signature using the original msg. To confirm correctness, ensure that the Ledger re-adds the prefix before signing internally so that verification with the original msg remains valid.

Below is a script to locate references to SignLedgerAminoJSON calls and reveal how the prefix is handled:


🏁 Script executed:

#!/bin/bash
rg -A 5 "SignLedgerAminoJSON" 

Length of output: 322


Action Required: Confirm Internal EIP-191 Prefix Re-Addition in Ledger Signing

In the SignWithLedger method in crypto/keyring/keyring.go (lines 51–100), when using an Ethereum public key the code explicitly removes the EIP-191 prefix before calling SignLedgerAminoJSON, while the signature is later verified against the original message (which includes the prefix). Please verify that the ledger’s implementation of SignLedgerAminoJSON internally re-adds the EIP-191 prefix before signing. If this behavior is confirmed—via documentation or tests—it would be helpful to add a clarifying comment or reference in the code to make this dependency explicit.

Copy link
codecov bot commented Mar 25, 2025

Codecov Report

Attention: Patch coverage is 0% with 61 lines in your changes missing coverage. Please review.

Project coverage is 39.72%. Comparing base (0f23fd7) to head (e4cb9c0).
Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
crypto/keyring/keyring.go 0.00% 55 Missing ⚠️
tx/eip191.go 0.00% 6 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #377      +/-   ##
==========================================
- Coverage   39.83%   39.72%   -0.12%     
==========================================
  Files         277      278       +1     
  Lines       26923    26968      +45     
==========================================
- Hits        10726    10713      -13     
- Misses      14539    14598      +59     
+ Partials     1658     1657       -1     
Files with missing lines Coverage Δ
app/ante/sigverify/verify.go 21.73% <ø> (+2.50%) ⬆️
crypto/ethsecp256k1/ethsecp256k1.go 70.99% <ø> (-0.64%) ⬇️
tx/eip191.go 26.08% <0.00%> (-38.62%) ⬇️
crypto/keyring/keyring.go 0.00% <0.00%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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

🧹 Nitpick comments (3)
crypto/keyring/keyring.go (3)

10-11: Redundant imports for crypto/types package

There are duplicate imports for the same package:

"github.com/cosmos/cosmos-sdk/crypto/types"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"

Choose one consistent import style to improve code clarity:

-"github.com/cosmos/cosmos-sdk/crypto/types"
-cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
+cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"

57-61: Use defined error variables for consistency

Error messages are currently hardcoded inline. For better error handling and consistency, define and use error variables similar to how other errors are handled in the codebase.

-	if isEthPubKey && signMode != signing.SignMode_SIGN_MODE_EIP_191 {
-		return nil, nil, errors.New("must use --sign-mode=eip-191 for Ethereum Ledger")
-	} else if !isEthPubKey && signMode != signing.SignMode_SIGN_MODE_LEGACY_AMINO_JSON {
-		return nil, nil, errors.New("must use --sign-mode=amino-json for Cosmos Ledger")
+	if isEthPubKey && signMode != signing.SignMode_SIGN_MODE_EIP_191 {
+		return nil, nil, ErrInvalidSignModeEthereum
+	} else if !isEthPubKey && signMode != signing.SignMode_SIGN_MODE_LEGACY_AMINO_JSON {
+		return nil, nil, ErrInvalidSignModeCosmos

Add these error variables at the package level:

var ErrInvalidSignModeEthereum = errors.New("must use --sign-mode=eip-191 for Ethereum Ledger")
var ErrInvalidSignModeCosmos = errors.New("must use --sign-mode=amino-json for Cosmos Ledger")

78-79: Explicit error return value needed

The function returns without explicitly setting an error value, which could lead to confusion. Always explicitly return the error value:

-	if err != nil {
-		return
+	if err != nil {
+		return nil, nil, err
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between ec142b9 and e75a7a1.

📒 Files selected for processing (2)
  • crypto/ethsecp256k1/ethsecp256k1.go (1 hunks)
  • crypto/keyring/keyring.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crypto/ethsecp256k1/ethsecp256k1.go
🧰 Additional context used
🧬 Code Definitions (1)
crypto/keyring/keyring.go (3)
crypto/ethsecp256k1/ethsecp256k1.go (15)
  • pubKey (173-185)
  • pubKey (188-193)
  • pubKey (196-198)
  • pubKey (201-203)
  • pubKey (206-208)
  • pubKey (211-213)
  • pubKey (216-223)
  • pubKey (226-230)
  • pubKey (233-235)
  • pubKey (241-243)
  • pubKey (246-267)
  • _ (48-48)
  • _ (49-49)
  • _ (151-151)
  • _ (152-152)
tx/eip191.go (2)
  • _ (27-27)
  • RemoveEIP191Prefix (55-62)
crypto/ledger/ledger.go (1)
  • _ (23-23)
🔇 Additional comments (3)
crypto/keyring/keyring.go (3)

64-68: LGTM: Correct handling of EIP191 prefix for Ethereum keys

The implementation correctly removes the EIP191 prefix from the message before signing with a Ledger device for Ethereum keys. This aligns with the PR objective to "fix: sigverify to attach eip191 prefix, only it is legacy amino json mode".


90-92: LGTM: Proper signature verification

Good practice to verify the signature against the original message before returning it.


32-44: LGTM: Well-designed Sign method

The Sign method correctly handles different key types, with a clear separation between Ledger and non-Ledger keys. This design makes the code more maintainable and allows for specialized handling where needed.

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

🧹 Nitpick comments (1)
crypto/keyring/keyring.go (1)

46-96: Consider adding unit tests for the SignWithLedger function.

The SignWithLedger function is central to the PR's objective and contains important logic for EIP-191 handling. Consider adding comprehensive unit tests to verify:

  1. Correct handling of different key types
  2. Proper validation of signing modes
  3. EIP-191 prefix removal for Ethereum keys
  4. Error cases for key mismatches and invalid signatures

Tests would help ensure this critical functionality remains correct through future changes.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between e75a7a1 and e4cb9c0.

⛔ Files ignored due to path filters (1)
  • go.mod is excluded by !**/*.mod
📒 Files selected for processing (1)
  • crypto/keyring/keyring.go (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
crypto/keyring/keyring.go (3)
crypto/ethsecp256k1/ethsecp256k1.go (15)
  • pubKey (173-185)
  • pubKey (188-193)
  • pubKey (196-198)
  • pubKey (201-203)
  • pubKey (206-208)
  • pubKey (211-213)
  • pubKey (216-223)
  • pubKey (226-230)
  • pubKey (233-235)
  • pubKey (241-243)
  • pubKey (246-267)
  • _ (48-48)
  • _ (49-49)
  • _ (151-151)
  • _ (152-152)
tx/eip191.go (2)
  • _ (27-27)
  • RemoveEIP191Prefix (55-62)
crypto/ledger/ledger.go (1)
  • _ (23-23)
🔇 Additional comments (7)
crypto/keyring/keyring.go (7)

19-21: Well-designed extension of the Cosmos keyring structure.

The Keyring struct extends cosmoskeyring.Keyring through embedding, which is a clean way to add custom functionality while maintaining API compatibility.


23-30: LGTM - Good error handling in the constructor.

The NewKeyring function properly initializes the keyring with context parameters and returns appropriate errors if initialization fails.


32-44: Clear separation of signing logic.

The Sign method nicely separates the signing logic between Ledger and non-Ledger keys, delegating to the appropriate implementation. This clean separation improves maintainability.


55-61: Validation of signing modes is accurate.

Correct validation enforcing EIP-191 for Ethereum keys and LEGACY_AMINO_JSON for Cosmos keys, which aligns with the PR objective to ensure proper EIP-191 handling.


63-69: EIP-191 prefix handling addresses the PR objective.

This segment properly removes the EIP-191 prefix for Ethereum keys to prevent double-prefixing, which is exactly what the PR aims to fix. The code calls tx.RemoveEIP191Prefix to handle the prefix removal.

The comment documentation clearly explains the reasoning: the Ledger device automatically adds the prefix, so removing it here prevents invalid signatures from double-prefixing.


76-84: Strong public key validation ensures security.

The code securely verifies that the public key from the keyring matches the one from the Ledger device, preventing potential key mismatches. The error message is informative and includes both keys for comparison.


91-93: Important signature verification step.

The signature verification step is crucial for ensuring the integrity of the signing process. This extra validation layer prevents returning invalid signatures.

@beer-1 beer-1 merged commit f2d2abd into main Mar 25, 2025
9 of 10 checks passed
@beer-1 beer-1 deleted the fix/sigverify branch March 25, 2025 10:24
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.

1 participant
0