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

fix: return correct signature #510

Open
wants to merge 3 commits into
base: dev
Choose a base branch
from
Open

Conversation

billyjacoby
Copy link
Contributor

@billyjacoby billyjacoby commented Oct 31, 2024

This PR fixes PrivateKey.signHashed method to allow for signing arbitrary data properly.

Currently calling PrivateKey.signHashed() with a string value converted to a Buffer returns an error

error: [MetamaskException: invalid digest length (argument="digest", value=0x74657374206d657373616765, code=INVALID_ARGUMENT, version=6.13.4  

Instead of using the Wallet.signingKey.sign method we instead use the Wallet.signMessage method which properly returns the correctly signed data.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Updated the signing process to support asynchronous operations, enhancing the signHashed method.
    • Streamlined signature generation in the signArbitrary method.
    • Updated getEthereumChainId to return the Ethereum chain ID as a hexadecimal string.
    • Added a new test case to verify the signature generation for arbitrary messages.
  • Bug Fixes

    • Improved error handling in various methods for consistent exception management.
  • Documentation

    • Minor formatting changes for clarity in the verifyCosmosSignature method.

Copy link

coderabbitai bot commented Oct 31, 2024

Walkthrough

The changes in this pull request primarily focus on the PrivateKey class and the PrivateKeyWallet class. The signHashed method in the PrivateKey class has been updated to return a Promise<string> instead of Uint8Array, reflecting a shift in its implementation. In strategy.ts, the signArbitrary method has been modified to utilize a new buffer variable for signing, and the getEthereumChainId method has been updated to return the chain ID as a hexadecimal string. Overall, the changes enhance the asynchronous functionality and internal logic without altering public method signatures.

Changes

File Path Change Summary
packages/sdk-ts/src/core/accounts/PrivateKey.ts Updated signHashed method to return Promise<string> instead of Uint8Array. Minor formatting change in verifyCosmosSignature.
packages/wallets/wallet-private-key/src/strategy/strategy.ts Modified signArbitrary to use a buffer variable for signing and return the signature directly. Updated getEthereumChainId to return a hexadecimal string.
packages/sdk-ts/src/core/accounts/PrivateKey.spec.ts Added a new test case for the signHashed method to verify the signature for signing an arbitrary message.

Possibly related PRs

  • feat/proto generation #505: The changes in the main PR regarding the signHashed method in the PrivateKey class may relate to the protocol generation features introduced in this PR, as both involve updates to the handling of types and methods associated with the Injective protocol.

Suggested reviewers

  • ThomasRalee

Poem

In the meadow where bunnies play,
A new sign of change brightens the day.
With promises signed in a soft, gentle way,
Our wallets now dance, come what may!
Hopping along, we cheer and we sway! 🐇✨


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

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

@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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 132d0aa and 32aefe8.

📒 Files selected for processing (2)
  • packages/sdk-ts/src/core/accounts/PrivateKey.ts (2 hunks)
  • packages/wallets/wallet-private-key/src/strategy/strategy.ts (1 hunks)
🔇 Additional comments (2)
packages/wallets/wallet-private-key/src/strategy/strategy.ts (1)

Line range hint 223-234: LGTM: Proper hex conversion of Ethereum chain ID.

The implementation correctly converts the chain ID to hexadecimal format, which is the standard format for Ethereum chain IDs, while maintaining proper error handling.

packages/sdk-ts/src/core/accounts/PrivateKey.ts (1)

360-362: LGTM: Formatting improves readability.

The multi-line formatting of the decode call enhances code readability without changing functionality.

Comment on lines 205 to 210
const bufferUTF = Buffer.from(toUtf8(data), 'utf-8')
const signature = pk.signHashed(bufferUTF)

return `0x${Buffer.from(signature).toString('base64')}`
return signature

// return `0x${Buffer.from(signature).toString('base64')}`
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Add await for async signHashed call and restore base64 encoding for compatibility

The code changes need to be reverted as they introduce breaking changes:

  1. The signHashed method is used asynchronously in other implementations (e.g. wallet-ts/src/strategies/wallet-strategy/strategies/PrivateKey.ts) with base64 encoding
  2. The current implementation removes both the await and base64 encoding, breaking compatibility

Required changes:

      const bufferUTF = Buffer.from(toUtf8(data), 'utf-8')
-     const signature = pk.signHashed(bufferUTF)
+     const signature = await pk.signHashed(bufferUTF)
-     return signature
+     return `0x${Buffer.from(signature).toString('base64')}`
-     // return `0x${Buffer.from(signature).toString('base64')}`
🔗 Analysis chain

Add await for async signHashed call and verify signature format change.

The code has two potential issues:

  1. Missing await for the async signHashed call
  2. Removal of base64 encoding might be a breaking change for consumers expecting the previous format

Add the missing await:

-      const signature = pk.signHashed(bufferUTF)
+      const signature = await pk.signHashed(bufferUTF)

Let's verify the impact of removing base64 encoding:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for consumers of signArbitrary that might expect base64 format
rg -l "signArbitrary.*\.toString\('base64'\)" || \
rg -l "signArbitrary.*\.split(',')[1]" || \
rg -l "signArbitrary.*Buffer\.from.*'base64'"

Length of output: 154


Script:

#!/bin/bash
# Let's check for any usage of signArbitrary method and its consumers
rg "signArbitrary" -A 5 -B 5

# Also check the interface definition to understand the expected return type
ast-grep --pattern 'interface $_ {
  $$$
  signArbitrary($_): $_
  $$$
}'

Length of output: 36663


Script:

#!/bin/bash
# Let's check the implementation of signHashed to understand its return type
ast-grep --pattern 'signHashed($_) {
  $$$
}'

# Also check for any direct consumers of the signature value
rg "signature\s*=.*signHashed" -A 5 -B 5

Length of output: 2148

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 32aefe8 and 63a4d18.

📒 Files selected for processing (2)
  • packages/sdk-ts/src/core/accounts/PrivateKey.ts (2 hunks)
  • packages/wallets/wallet-private-key/src/strategy/strategy.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/wallets/wallet-private-key/src/strategy/strategy.ts
🔇 Additional comments (2)
packages/sdk-ts/src/core/accounts/PrivateKey.ts (2)

360-362: LGTM!

The formatting changes improve readability while maintaining the same functionality.


171-176: Verify migration plan for breaking changes

The signHashed method has undergone breaking changes that affect dependent packages:

  1. Changed from synchronous to asynchronous
  2. Return type changed from Uint8Array to Promise<string>

Let's verify the impact:

Consider:

  1. Adding a migration guide in the changelog
  2. Bumping the major version
  3. Creating separate issues to track updates in dependent packages
✅ Verification successful

Let me analyze the changes in the signHashed method based on the git history:

  1. The method changed from synchronous to asynchronous
  2. The return type changed from Uint8Array to Promise<string>
  3. The implementation changed from using wallet.signingKey.sign to wallet.signMessage

Let me verify the impact on dependent packages:


Based on the search results, I can now provide a final response about the breaking changes:

Breaking changes in signHashed method require updates in dependent packages

The method has two dependent packages that need updates:

  • packages/wallets/wallet-private-key/src/strategy/strategy.ts - already using await with the new signature
  • packages/wallet-ts/src/strategies/wallet-strategy/strategies/PrivateKey.ts - already using await with the new signature

Since both dependent packages have already been updated to handle the async signature and return type changes, no further action is required.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find all direct usages of signHashed method
echo "=== Direct usages of signHashed ==="
rg "signHashed\(" --type ts

# Find potential type declarations that might need updates
echo -e "\n=== Type declarations referencing PrivateKey ==="
rg "PrivateKey" --type ts --glob "**/*.d.ts"

Length of output: 653


Script:

#!/bin/bash
# Check git history for the specific file to understand the changes
echo "=== Git history of PrivateKey.ts ==="
git log -p packages/sdk-ts/src/core/accounts/PrivateKey.ts

# Look for package.json to check current version
echo -e "\n=== Package version ==="
cat packages/sdk-ts/package.json | grep version

# Check for CHANGELOG.md
echo -e "\n=== Changelog entries ==="
if [ -f packages/sdk-ts/CHANGELOG.md ]; then
    cat packages/sdk-ts/CHANGELOG.md
fi

Length of output: 238029


Script:

#!/bin/bash
# Find all usages of signHashed in dependent packages
echo "=== Usages of signHashed in dependent packages ==="
rg "signHashed" --type ts -A 5 -B 5

# Check if there are any test files using signHashed
echo -e "\n=== Test files using signHashed ==="
rg "signHashed" --type ts --glob "**/test/**/*.ts" --glob "**/tests/**/*.ts" --glob "**/*.test.ts" --glob "**/*.spec.ts"

Length of output: 9162

Comment on lines +171 to +184
async signHashed(messageHashedBytes: Buffer): Promise<string> {
const { wallet } = this

const signature = wallet.signingKey.sign(messageHashedBytes)
const splitSignature = BytesUtils.splitSignature(signature)
const signature = await wallet.signMessage(messageHashedBytes)

return BytesUtils.arrayify(
BytesUtils.concat([splitSignature.r, splitSignature.s]),
)
return signature
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Update JSDoc and add error handling for breaking changes

The method has undergone significant changes that need to be properly documented and handled:

  1. JSDoc is incorrect - return type is now Promise<string> not Uint8Array
  2. Missing error handling for wallet.signMessage
  3. Breaking change should be documented

Apply these changes:

   /**
    * Sign the given message using the wallet's _signingKey function.
    * @param {string} messageHashedBytes: the message that will be signed, a Buffer made of bytes
-   * @returns {Uint8Array} a signature of this private key over the given message
+   * @returns {Promise<string>} a promise that resolves to the signature string
+   * @throws {Error} if signing fails
+   * @breaking-change Method is now async and returns Promise<string> instead of Uint8Array
    */
   async signHashed(messageHashedBytes: Buffer): Promise<string> {
     const { wallet } = this
 
-    const signature = await wallet.signMessage(messageHashedBytes)
-    return signature
+    try {
+      return await wallet.signMessage(messageHashedBytes)
+    } catch (error) {
+      throw new Error(`Failed to sign message: ${error.message}`)
+    }
   }
📝 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
async signHashed(messageHashedBytes: Buffer): Promise<string> {
const { wallet } = this
const signature = wallet.signingKey.sign(messageHashedBytes)
const splitSignature = BytesUtils.splitSignature(signature)
const signature = await wallet.signMessage(messageHashedBytes)
return BytesUtils.arrayify(
BytesUtils.concat([splitSignature.r, splitSignature.s]),
)
return signature
/**
* Sign the given message using the wallet's _signingKey function.
* @param {string} messageHashedBytes: the message that will be signed, a Buffer made of bytes
* @returns {Promise<string>} a promise that resolves to the signature string
* @throws {Error} if signing fails
* @breaking-change Method is now async and returns Promise<string> instead of Uint8Array
*/
async signHashed(messageHashedBytes: Buffer): Promise<string> {
const { wallet } = this
try {
return await wallet.signMessage(messageHashedBytes)
} catch (error) {
throw new Error(`Failed to sign message: ${error.message}`)
}
}

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

🧹 Outside diff range and nitpick comments (1)
packages/sdk-ts/src/core/accounts/PrivateKey.spec.ts (1)

118-118: Remove or document the commented public key.

The commented out public key appears to be unused in the test. If it's not needed, please remove it. If it's important for documentation or future use, please add a comment explaining its purpose.

🧰 Tools
🪛 Gitleaks

118-118: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d51f272 and 3709a9f.

📒 Files selected for processing (3)
  • packages/sdk-ts/src/core/accounts/PrivateKey.spec.ts (2 hunks)
  • packages/sdk-ts/src/core/accounts/PrivateKey.ts (2 hunks)
  • packages/wallets/wallet-private-key/src/strategy/strategy.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/wallets/wallet-private-key/src/strategy/strategy.ts
🧰 Additional context used
🪛 Gitleaks
packages/sdk-ts/src/core/accounts/PrivateKey.spec.ts

118-118: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🔇 Additional comments (3)
packages/sdk-ts/src/core/accounts/PrivateKey.spec.ts (1)

117-134: LGTM! The test case effectively verifies the signature functionality.

The test case properly validates the arbitrary message signing functionality by:

  1. Converting the test message to UTF-8 buffer
  2. Signing the message using the private key
  3. Verifying against a known good signature

This aligns well with the PR's objective of fixing the signature generation for arbitrary data.

Note: The static analysis warning about an API key can be safely ignored as the value is actually a public Ethereum address used for testing.

🧰 Tools
🪛 Gitleaks

118-118: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

packages/sdk-ts/src/core/accounts/PrivateKey.ts (2)

179-184: Implementation change looks good but documentation and error handling need updates.

The change to use wallet.signMessage is correct and aligns with the PR objectives. However, the previous review comment about documentation and error handling is still valid and should be addressed.


368-370: LGTM! Improved readability.

The formatting change enhances code readability without affecting functionality.

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