Skip to content

Conversation

jns-ps
Copy link
Contributor

@jns-ps jns-ps commented Feb 25, 2025

Summary by CodeRabbit

  • New Features

    • Added support for Ethereum (EIP-191) and Cosmos (ADR-36) signature standards, enabling new signing and verification methods.
    • Introduced a module for handling Cosmos signing documents with enhanced message hashing and serialization.
    • Integrated Bech32 encoding/decoding for improved data formatting.
  • Chores

    • Expanded cryptographic dependencies to bolster overall functionality and stability.

@jns-ps jns-ps self-assigned this Feb 25, 2025
Copy link

vercel bot commented Feb 25, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
prism ⬜️ Ignored (Inspect) Visit Preview Feb 26, 2025 11:26am

Copy link
Contributor

coderabbitai bot commented Feb 25, 2025

Walkthrough

This pull request expands the cryptographic capabilities of the project by adding new dependencies and introducing support for additional signing and verification algorithms. It adds new Cargo dependency declarations across several packages, introduces new enum variants and modules (including Cosmos-related signing and Bech32 conversion), and updates function implementations to handle the added algorithms. The changes also adjust signature verification calls to work directly with hash digest types.

Changes

File(s) Change Summary
Cargo.toml, crates/keys/Cargo.toml, crates/serde/Cargo.toml Added new dependencies: bech32, alloy-primitives, ripemd and workspace flags for serde_json, alloy-primitives, ripemd, and bech32.
crates/keys/src/algorithm.rs Added new enum variants Eip191 and CosmosAdr36 to CryptoAlgorithm with updated string matching logic.
crates/keys/src/cosmos.rs New file introducing Cosmos signing document structures and functions for hashing, serialization, and address derivation.
crates/keys/src/lib.rs Added the new cosmos module.
crates/keys/src/signatures.rs Updated error handling in signature methods to account for unsupported EIP-191 and Cosmos ADR-36 signatures.
crates/keys/src/signing_keys.rs Added new variants (Eip191, CosmosAdr36) with corresponding constructors, serialization/deserialization, and signing logic.
crates/keys/src/verifying_keys.rs Added new variants (Eip191, CosmosAdr36) and updated verification logic, including adapting the method signature to accept generic byte slices.
crates/serde/src/bech32.rs, crates/serde/src/lib.rs Introduced Bech32 encoding/decoding traits (ToBech32 and FromBech32) and implemented them, along with adding the new bech32 module.
crates/tree/src/proofs.rs, crates/tree/src/snarkable_tree.rs Modified calls to verify_signature to pass a Digest directly instead of converting it to bytes.
crates/keys/src/tests.rs Added new tests for EIP-191 and Cosmos ADR-36 signing and verification, ensuring functionality and integrity of cryptographic operations.

Possibly related PRs

  • feat: test all available curves #186: The changes in the main PR, which involve adding new dependencies related to cryptographic operations, are related to the retrieved PR as both involve modifications to the handling of cryptographic algorithms and keys, specifically the CryptoAlgorithm type and its usage in signing and verifying keys.
  • feat: http client and request builders #235: The changes in the main PR are related to the addition of the alloy-primitives and ripemd dependencies, which are also included in the retrieved PR's Cargo.toml file, indicating a shared focus on cryptographic functionalities.
  • feature(keys): crypto algorithm as enum #188: The changes in the main PR, which involve adding dependencies related to cryptographic operations, are related to the retrieved PR as both involve modifications to the CryptoAlgorithm enum and its usage in the codebase, specifically in the context of cryptographic algorithms.

Suggested reviewers

  • distractedm1nd
  • sebasti810

Poem

I'm a rabbit with a curious pace,
Hopping through bytes and cryptographic space.
New keys, new codes, a signing delight,
Cosmos and Bech32 — oh what a sight!
With each little hop, I cheer "hip hooray!" 🐇
For these changes make our code brighter each day!
~ Hop on, keep coding! ~

Tip

CodeRabbit's docstrings feature is now available as part of our Pro Plan! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
  • @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
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: 1

🔭 Outside diff range comments (2)
crates/keys/src/signatures.rs (1)

76-82: ⚠️ Potential issue

Update algorithm() method to handle new variants.

The algorithm() method needs to be updated to handle the new Eip191 and CosmosAdr36 variants, even if they're not implemented yet. This ensures the method remains exhaustive for all variants.

     pub fn algorithm(&self) -> CryptoAlgorithm {
         match self {
             Signature::Ed25519(_) => CryptoAlgorithm::Ed25519,
             Signature::Secp256k1(_) => CryptoAlgorithm::Secp256k1,
             Signature::Secp256r1(_) => CryptoAlgorithm::Secp256r1,
+            // These variants are not yet implemented
+            _ => unreachable!("Eip191 and CosmosAdr36 signatures are not implemented"),
         }
     }
crates/keys/src/signing_keys.rs (1)

144-153: ⚠️ Potential issue

Update PartialEq implementation to handle new key types

The PartialEq implementation doesn't handle the new Eip191 and CosmosAdr36 variants, which means equality checks for these types will always return false. This could lead to subtle bugs when comparing keys.

Consider updating the implementation to include the new variants:

impl PartialEq for SigningKey {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (SigningKey::Ed25519(a), SigningKey::Ed25519(b)) => a.as_bytes() == b.as_bytes(),
            (SigningKey::Secp256k1(a), SigningKey::Secp256k1(b)) => a == b,
            (SigningKey::Secp256r1(a), SigningKey::Secp256r1(b)) => a == b,
+           (SigningKey::Eip191(a), SigningKey::Eip191(b)) => a == b,
+           (SigningKey::CosmosAdr36(a), SigningKey::CosmosAdr36(b)) => a == b,
            _ => false,
        }
    }
}
🧹 Nitpick comments (10)
crates/keys/src/signatures.rs (1)

69-73: Improve error messages to be more descriptive.

The error messages could be more informative about why these signatures are not implemented and what alternatives are available.

-            CryptoAlgorithm::Eip191 => bail!("No EIP-191 specific signatures implemented"),
-            CryptoAlgorithm::CosmosAdr36 => {
-                bail!("No cosmos ADR-36 specific signatures implemented")
-            }
+            CryptoAlgorithm::Eip191 => bail!("EIP-191 specific signatures are not yet implemented. Use Secp256k1 signatures instead."),
+            CryptoAlgorithm::CosmosAdr36 => {
+                bail!("Cosmos ADR-36 specific signatures are not yet implemented. Use Secp256k1 signatures instead.")
+            }
crates/keys/src/algorithm.rs (1)

14-17: Consider adding references to official EIP-191/ADR-36 documentation.
It can be helpful to mention or link to the official specs in the doc comments to guide maintainers and users.

crates/serde/src/bech32.rs (1)

3-18: Add trait usage examples.
Providing usage samples or doc tests for the ToBech32 trait would help new contributors understand how to integrate it.

crates/keys/src/cosmos.rs (4)

8-16: Document each field for clarity.
Adding doc comments that explain each field in CosmosSignDoc would make the structure more maintainable.


38-54: Allow setting chain ID in the constructor.
Currently, it defaults to an empty string. If chain ID is vital, consider a constructor parameter or builder pattern.


57-71: Replace or remove the debug print.
println!("Signer: {}", signer); can clutter logs in production or libraries. Consider a structured logging macro or removing it.

-    println!("Signer: {}", signer);

83-90: Support for other prefixes.
The TODO indicates future prefix customization. If a variable prefix is necessary soon, consider a wrapper or parameter for signer_from_key.

crates/keys/src/verifying_keys.rs (3)

92-95: Unsupported DER format.
Explicitly failing early for EIP-191 and Cosmos ADR-36 is fine, but consider clarifying error messages or implementing these later.


129-132: DER parsing unimplemented.
Like before, these placeholders are acceptable, but plan to either remove or implement them if needed.


146-191: Extended verification logic.
EIP-191 and Cosmos ADR-36 verification uses prehash flows. Consider additional signature-length checks before verifying.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 16de9a4 and 79fd8a1.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (13)
  • Cargo.toml (2 hunks)
  • crates/keys/Cargo.toml (2 hunks)
  • crates/keys/src/algorithm.rs (2 hunks)
  • crates/keys/src/cosmos.rs (1 hunks)
  • crates/keys/src/lib.rs (1 hunks)
  • crates/keys/src/signatures.rs (2 hunks)
  • crates/keys/src/signing_keys.rs (7 hunks)
  • crates/keys/src/verifying_keys.rs (11 hunks)
  • crates/serde/Cargo.toml (1 hunks)
  • crates/serde/src/bech32.rs (1 hunks)
  • crates/serde/src/lib.rs (1 hunks)
  • crates/tree/src/proofs.rs (1 hunks)
  • crates/tree/src/snarkable_tree.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: unused dependencies
  • GitHub Check: unit-test
  • GitHub Check: clippy
  • GitHub Check: integration-test
  • GitHub Check: build-and-push-image
🔇 Additional comments (23)
crates/keys/src/lib.rs (1)

2-2: LGTM! Clean addition of the Cosmos module.

The new cosmos module is well-placed among other cryptographic modules and follows Rust's module visibility best practices.

crates/serde/src/lib.rs (1)

2-2: LGTM! Clean addition of the Bech32 module.

The new bech32 module is appropriately made public and maintains the alphabetical ordering of modules.

crates/serde/Cargo.toml (1)

14-14: LGTM! Clean addition of the Bech32 dependency.

The bech32 dependency is correctly specified using workspace version and appropriately placed in the serde section.

crates/keys/src/signatures.rs (1)

53-57: Inconsistency with PR objectives.

The PR title suggests that Cosmos ADR-36 and EIP-191 signatures can be verified, but the implementation returns "not implemented" errors. Please clarify if this is intentional or if the implementation is missing.

Likely an incorrect or invalid review comment.

crates/tree/src/snarkable_tree.rs (1)

142-142: Signature verification now using Digest directly

The signature verification now accepts the hash parameter directly as a Digest type instead of converting it to bytes first with &hash.to_bytes(). This change aligns with the PR objective to support additional signature verification algorithms.

crates/keys/Cargo.toml (2)

13-13: Added serde_json dependency

Adding serde_json as a workspace dependency is appropriate for JSON serialization/deserialization needs.


23-25: Added new signature dependencies

The added dependencies (alloy-primitives and ripemd) are necessary for implementing the new signature verification algorithms (Cosmos ADR-36 and EIP-191) mentioned in the PR objectives.

Cargo.toml (2)

59-59: Added bech32 dependency

The bech32 dependency is necessary for Cosmos address encoding/decoding, which supports the Cosmos ADR-36 signature verification mentioned in the PR objectives.


109-114: Added new signature verification dependencies

The added dependencies (alloy-primitives with k256 feature and ripemd) provide the necessary functionality for implementing the EIP-191 and Cosmos ADR-36 signature verification algorithms.

It's good that you've specified a restricted feature set for alloy-primitives with just the k256 feature to minimize dependencies.

crates/tree/src/proofs.rs (1)

144-144: Signature verification now using Digest directly

Similar to the change in snarkable_tree.rs, the signature verification now accepts the hash parameter directly as a Digest type instead of converting it to bytes first. This creates a consistent approach to signature verification across the codebase.

crates/keys/src/algorithm.rs (1)

28-29: New match arms look correct.
The new variants for EIP-191 and Cosmos ADR-36 are properly handled in the from_str implementation.

crates/serde/src/bech32.rs (1)

20-34: Implementation looks solid.
Decoding logic using bech32::decode is straightforward and consistent with the trait design.

crates/keys/src/cosmos.rs (4)

18-22: Confirm string-based amounts.
Using String for numeric fields like gas and amount is common in Cosmos code, but ensure you handle potential parsing or localization issues.


24-29: No immediate concerns.
The CosmosMessage structure is succinct and follows standard naming.


31-36: Field-level serializing logic appears correct.
The usage of raw_or_b64 is a neat approach to handle raw/b64-encoded data.


73-81: Double-check special-character escaping.
Replacing <, >, and & in JSON is sometimes done for HTML safety, but verify if it’s a required step in ADR-36.

crates/keys/src/verifying_keys.rs (6)

40-45: Additional variants are well integrated.
EIP-191 and Cosmos ADR-36 variants align with the existing scheme.


63-70: Proper hashing approach for new variants.
Including unique hash identifiers (3 and 4) for EIP-191 and Cosmos ADR-36 ensures correctness in hashing.


82-83: Consistent byte retrieval.
Returning sec1 bytes for EIP-191 and Cosmos ADR-36 keeps the approach uniform.


111-116: Variant handling for from_algorithm_and_bytes is correct.
The logic matches the newly introduced algorithms without any obvious issues.


141-142: Enum to algorithm mapping is straightforward.
The new variants map directly to the correct CryptoAlgorithm.


255-256: Consistent with other From impls.
Automatically converting a SigningKey variant to the corresponding VerifyingKey variant remains consistent.

crates/keys/src/signing_keys.rs (1)

36-37: Implementation of new signing algorithms looks good

The implementation approach for the new signing algorithms is well-structured. Both new variants reuse the Secp256k1SigningKey type since they use the same underlying key format but with different signature algorithms.

The construction, serialization, and deserialization methods are properly implemented to support the new key types.

Also applies to: 53-59, 66-67, 80-81, 96-101, 110-111

@distractedm1nd
Copy link
Contributor

This is good.

For the next iteration we should add EIP-712, which is more common and UX friendly in the eth ecosystem. Will show users even more transparently what they are signing!

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

♻️ Duplicate comments (1)
crates/keys/src/signing_keys.rs (1)

130-139: ⚠️ Potential issue

Improve error handling in signature generation

The current implementation uses unwrap() which will panic if an error occurs during signing. This doesn't follow the error handling pattern used elsewhere in the code.

Consider using proper error handling instead of unwrap():

SigningKey::Eip191(sk) => {
    let message = eip191_hash_message(message);
-   let sig: Secp256k1Signature = sk.sign_prehash(message.as_slice()).unwrap();
+   let sig: Secp256k1Signature = sk.sign_prehash(message.as_slice())
+       .map_err(|e| anyhow::anyhow!("Failed to sign EIP-191 message: {}", e))?;
    Signature::Secp256k1(sig)
}
SigningKey::CosmosAdr36(sk) => {
-   let message = cosmos_adr36_hash_message(message, sk.verifying_key()).unwrap();
-   let sig: Secp256k1Signature = sk.sign_prehash(message.as_slice()).unwrap();
+   let message = cosmos_adr36_hash_message(message, sk.verifying_key())
+       .map_err(|e| anyhow::anyhow!("Failed to hash Cosmos ADR-36 message: {}", e))?;
+   let sig: Secp256k1Signature = sk.sign_prehash(message.as_slice())
+       .map_err(|e| anyhow::anyhow!("Failed to sign Cosmos ADR-36 message: {}", e))?;
    Signature::Secp256k1(sig)
}

Note that this would require changing the return type of the sign method to Result<Signature, anyhow::Error>.

🧹 Nitpick comments (5)
crates/keys/src/tests.rs (2)

54-54: Skipping DER for select algorithms
A comment clarifies why EIP-191 and Cosmos ADR-36 lack DER support. If future requirements change, adding DER handling would be beneficial.


144-144: Note on omitted EIP-191 and Cosmos signatures
Suggests these signatures rely on secp256k1 logic. Consider adding explicit tests if advanced handling is needed later.

crates/keys/src/cosmos.rs (2)

18-22: CosmosFee type
Representing fee values as strings might invite parsing overhead elsewhere—still acceptable if usage remains minimal.


38-54: Constructor for CosmosSignDoc
new() supplies default chain, account, and sequence values. If future expansions require them, consider making them configurable.

crates/keys/src/signing_keys.rs (1)

5-6: Consider importing K256DigestSigner for consistency.

You're using the PrehashSigner trait but might want to also import K256DigestSigner for a more complete and consistent import set.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 79fd8a1 and 609e2a5.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (9)
  • Cargo.toml (2 hunks)
  • crates/keys/Cargo.toml (2 hunks)
  • crates/keys/src/algorithm.rs (2 hunks)
  • crates/keys/src/cosmos.rs (1 hunks)
  • crates/keys/src/lib.rs (1 hunks)
  • crates/keys/src/signatures.rs (2 hunks)
  • crates/keys/src/signing_keys.rs (8 hunks)
  • crates/keys/src/tests.rs (6 hunks)
  • crates/keys/src/verifying_keys.rs (11 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • crates/keys/src/lib.rs
  • crates/keys/src/signatures.rs
  • crates/keys/Cargo.toml
  • Cargo.toml
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: clippy
  • GitHub Check: unit-test
  • GitHub Check: unused dependencies
  • GitHub Check: build-and-push-image
  • GitHub Check: integration-test
🔇 Additional comments (26)
crates/keys/src/algorithm.rs (3)

14-18: Well-structured new enum variants
No issues stand out; introducing Eip191 and CosmosAdr36 cleanly expands the supported algorithms.


20-30: Comprehensive method for enumerating all algorithms
Providing a dedicated all() method to return every variant is a neat approach that helps ensure future expansions remain testable.


41-42: Consistent string matching
Matching "eip191" and "cosmos_adr36" aligns well with the existing pattern, maintaining clarity and consistency.

crates/keys/src/tests.rs (10)

4-4: New imports for cryptographic structures
Importing CryptoAlgorithm, Signature, SigningKey, and VerifyingKey is appropriately aligned with the extended test coverage.


6-6: Base64 conversion utility
Adopting FromBase64 and ToBase64 is a straightforward solution for handling the signature key material in a test environment.


34-49: Extended coverage for verifying keys
Verifying that EIP-191 and Cosmos ADR-36 keys round-trip correctly via from_algorithm_and_bytes strengthens confidence in the new features.


64-70: Secp256k1 re-parsing from DER
Good consistency with other curves; ensuring test coverage for DER path fosters interoperability.


99-105: EIP-191 signing key round-trip
Adding a re-parsing test for EIP-191 helps ensure serialization and deserialization correctness.


107-113: Cosmos ADR-36 signing key test
Clear demonstration of round-tripping Cosmos ADR-36 signing keys. Strengthens confidence in the approach.


167-168: Duplicate comment
Repeated note about EIP-191 and Cosmos ADR-36 using secp256k1 signatures.


170-199: Robust multi-algorithm verification
Iterating over CryptoAlgorithm::all() enhances coverage, ensuring each variant (old or new) undergoes end-to-end testing.


201-232: Real-world EIP-191 interoperability test
Using an actual Metamask-generated signature validates cross-environment compatibility for EIP-191. Nicely handled.


234-258: Integration test for Cosmos ADR-36
Ensures Keplr wallet signatures are recognized, confirming practical support for ADR-36.

crates/keys/src/cosmos.rs (7)

1-7: Appropriate usage of cryptographic crates
Using k256 for secp256k1, Ripemd160, and sha2 is standard and ensures reliable Cosmos address derivation.


8-16: Structured CosmosSignDoc
Cleanly captures all relevant fields for ADR-36. This design is straightforward and easy to extend.


24-29: CosmosMessage structure
Renaming type to msg_type avoids collisions with Rust keywords and clarifies the intended field.


31-36: CosmosMessageValue handling
Good use of raw_or_b64 for binary data. This preserves flexibility in how payloads are provided.


57-81: cosmos_adr36_hash_message function
Follows the ADR-36 flow: build sign doc, serialize, then hash with SHA-256. Straightforward and secure.


83-103: Escaping JSON
Using string replacements for <, >, and & is a known approach for mitigating potential JSON injection. Verify no partial overlap or double-escaping occurs in edge cases.


105-127: Bech32 address derivation
Adheres to the classic 4-step process (SHA-256 → RIPEMD160 → bech32). Implementation looks correct and robust.

crates/keys/src/verifying_keys.rs (4)

43-45: Clean implementation of new verification key variants.

The addition of Eip191 and CosmosAdr36 variants to the VerifyingKey enum is well-designed and clearly documented with appropriate comments that explain their purpose.


146-146: Improved method signature for better flexibility.

Changing the signature from &[u8] to impl AsRef<[u8]> is a good improvement that allows for more flexible usage without any performance impact.


176-183: Well-implemented EIP-191 verification logic.

The implementation correctly uses the eip191_hash_message function to prehash the message before verification and includes proper error handling and informative error messages.


184-191: Comprehensive Cosmos ADR-36 verification with proper error handling.

The implementation correctly uses the cosmos_adr36_hash_message function with appropriate error propagation and informative error messages.

crates/keys/src/signing_keys.rs (2)

36-37: Well-structured implementation of new signing key variants.

The addition of Eip191 and CosmosAdr36 variants to the SigningKey enum maintains consistency with the corresponding VerifyingKey variants.


53-59: Well-implemented constructor methods.

The implementation of new_eip191 and new_cosmos_adr36 follows the pattern established by other constructors in the codebase.

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)
crates/common/src/builder.rs (1)

108-109: Consider preserving the underlying error context.

Currently, the map_err call discards the underlying signing error details. It might be beneficial to include the original error message or context to aid with debugging. For example:

-service_signing_key.sign(hash).map_err(|_| TransactionError::SigningFailed)?;
+service_signing_key.sign(hash).map_err(|e| {
+    TransactionError::SigningFailed(format!("Signing failed: {}", e))
+})?;
crates/keys/src/tests.rs (1)

54-54: Consider adding DER coverage for additional algorithms.

Currently, EIP-191 and Cosmos ADR-36 verification steps are skipped for DER-based testing. While they may not rely on DER encoding, any partial coverage or explicit tests could further strengthen reliability.

crates/keys/src/cosmos.rs (1)

83-103: Ensuring ADR-36 compliance by escaping HTML characters.

The escaping of <, >, and & is useful for reducing injection risks. For broader coverage, consider escaping additional characters if the environment is untrusted.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 609e2a5 and abcfa54.

📒 Files selected for processing (11)
  • crates/common/src/builder.rs (1 hunks)
  • crates/common/src/test_transaction_builder.rs (8 hunks)
  • crates/common/src/transaction.rs (1 hunks)
  • crates/da/src/lib.rs (1 hunks)
  • crates/keys/src/algorithm.rs (2 hunks)
  • crates/keys/src/cosmos.rs (1 hunks)
  • crates/keys/src/signing_keys.rs (7 hunks)
  • crates/keys/src/tests.rs (4 hunks)
  • crates/keys/src/verifying_keys.rs (11 hunks)
  • crates/node_types/prover/src/prover/mod.rs (1 hunks)
  • crates/tree/src/tests.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/keys/src/algorithm.rs
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: unit-test
  • GitHub Check: unused dependencies
  • GitHub Check: build-and-push-image
  • GitHub Check: integration-test
🔇 Additional comments (47)
crates/tree/src/tests.rs (1)

231-231: Improved error handling by explicitly unwrapping the sign result.

This change makes the error handling more explicit by unwrapping the Result returned by the sign method. This is appropriate in a test context where we want immediate failure if the signing operation fails.

crates/common/src/transaction.rs (1)

27-27: Improved error handling for signing operation.

The change now maps any error from the signing operation to a specific TransactionError::SigningFailed type, providing clearer error information to callers.

crates/common/src/test_transaction_builder.rs (2)

190-190: Now explicitly handling sign operation errors.

This change ensures that the code will fail fast with a clear error message if signing fails.


344-344: Consistent error handling added for all sign operations.

All sign method calls now use unwrap() to handle potential errors, which aligns with the changes in the signing API. This ensures that any signing failures will be immediately apparent.

Also applies to: 357-357, 389-390, 406-407, 489-490, 504-505, 517-518

crates/da/src/lib.rs (1)

40-44: Enhanced error handling in insert_signature method.

The method signature has been updated to return a Result<()> instead of void, and now properly propagates errors from the signing operation. This change improves the robustness of the cryptographic operations by allowing callers to handle signing failures.

crates/node_types/prover/src/prover/mod.rs (1)

433-433: Now propagating errors from signature insertion.

This change properly handles potential errors during signature insertion by using the ? operator, which aligns with the updated insert_signature method signature that now returns a Result.

crates/keys/src/tests.rs (10)

3-4: Good addition of new cryptographic enums and types.

The newly added import references CryptoAlgorithm, which is essential for handling multiple cryptographic variants in the tests. This integration looks appropriate.


6-6: Nice usage of base64 conversions.

This ensures that we can parse base64-encoded crypto material in test scenarios without reinventing the wheel.


35-49: Expanded coverage for EIP-191 and Cosmos ADR-36 verifying keys.

These lines ensure that verifying keys for EIP-191 and ADR-36 are correctly re-parsed from raw bytes. This coverage is crucial for guaranteeing compatibility.


64-70: Verifying secp256k1 DER parsing.

Ensuring that DER-encoded secp256k1 verifying keys match their non-DER equivalents is essential for seamless interoperability with external tools.


99-113: Excellent coverage for EIP-191 and Cosmos ADR-36 signing keys.

These lines confirm that the new signing keys can be serialized and re-parsed accurately, retaining their cryptographic properties.


120-144: Comprehensive signature re-parsing for multiple algorithms.

This test covers Ed25519, secp256k1, and secp256r1. A note explains that EIP-191 and Cosmos ADR-36 also use secp256k1-based signatures, hence no separate coverage is provided here.


151-168: DER-based signature tests for secp256k1 and secp256r1.

These blocks confirm that DER decoding for secp256k1 and secp256r1 signatures is consistent. EIP-191 and Cosmos ADR-36 are excluded due to raw signature usage.


170-199: Broad coverage for signature creation and verification.

Verifying all supported algorithms in a loop is an effective strategy for ensuring consistent behavior across different cryptographic backends.


201-232: Integration test with EIP-191 wallet signatures.

These lines confirm real-world compatibility by verifying a wallet-generated signature. This is critical for production readiness within Ethereum-based workflows.


234-258: Integration test with Cosmos ADR-36 wallet signatures.

Testing with Keplr-generated signatures ensures correctness in actual Cosmos environments. This helps validate end-to-end functionality.

crates/keys/src/cosmos.rs (8)

1-7: Sensible crates for Cosmos-based signing logic.

sha2 and ripemd are standard for generating Cosmos addresses, and the included bech32 utility further ensures overall compatibility.


8-16: Well-structured sign doc.

CosmosSignDoc includes essential fields (msgs, fee, chain_id, etc.), aligning with ADR-36 expectations for message signing on Cosmos.


18-22: Flexible design for fees.

Representing fee amounts as Vec<String> accommodates various token denominations. Numeric types could be considered for stricter type safety, but this is a solid approach.


24-29: Correct usage of #[serde(rename = "type"].

This ensures JSON compatibility with the typical Cosmos message structure, preserving the type field naming convention.


31-36: Using #[serde(with = "raw_or_b64")] for message data.

Handling binary data with either raw bytes or base64 encoding helps interoperate smoothly with standard Cosmos message formats.


38-55: Constructor with sensible defaults.

Users can quickly create a CosmosSignDoc by providing just the signer and data, while other fields default to typical ADR-36 placeholders.


57-81: Well-documented ADR-36 hashing function.

Returning a Result<Vec<u8>> is a good practice, allowing upper layers to handle any cryptographic or serialization errors gracefully.


105-126: Standard Cosmos address derivation procedure.

Sequential SHA-256 followed by RIPEMD160, plus bech32 encoding, matches Cosmos norms. This ensures compatibility with major Cosmos wallets.

crates/keys/src/verifying_keys.rs (12)

1-1: LGTM: Appropriate imports added for the new signature verification schemes

The imports for eip191_hash_message from alloy_primitives and the updated imports from the crate including cosmos_adr36_hash_message are correctly added to support the new functionality.

Also applies to: 26-29


42-45: LGTM: New VerifyingKey variants properly documented

The two new variants Eip191 and CosmosAdr36 are added with appropriate documentation comments explaining their purpose. This makes it clear that these variants are used specifically for verifying signatures according to EIP-191 and Cosmos ADR-36 standards.


63-70: LGTM: Hash implementation properly updated for new variants

The Hash implementation is correctly extended to include the new VerifyingKey variants, with unique identifiers (3 and 4) assigned to each variant.


82-83: LGTM: Byte representation for new variants implemented

The to_bytes method is properly extended to handle the new variants, correctly reusing the SEC1 byte representation of the Secp256k1 key.


92-95: LGTM: Proper error handling for unsupported DER format

The to_der method is appropriately updated to handle the new variants with clear error messages stating that DER format is not supported for these verification key types.


111-116: LGTM: Key creation from bytes implemented for new variants

The from_algorithm_and_bytes method is correctly updated to support the new variants, properly creating the appropriate VerifyingKey type based on the algorithm and byte data.


129-132: LGTM: Error handling for unsupported DER format in key creation

The from_algorithm_and_der method is properly updated with clear error messages for the new algorithms when attempting to create keys from DER format.


141-142: LGTM: Algorithm mapping for new variants

The algorithm method is properly updated to return the correct CryptoAlgorithm for the new variants.


146-146: LGTM: Improved function signature for verify_signature method

The signature verification method now accepts impl AsRef<[u8]> instead of &[u8], which provides more flexibility in the types of message inputs that can be verified.


176-183: LGTM: EIP-191 signature verification properly implemented

The verification logic for EIP-191 signatures is implemented correctly:

  1. It ensures the signature type is compatible (Secp256k1)
  2. It properly hashes the message using eip191_hash_message
  3. It verifies the signature against the prehashed message
  4. It provides clear error messages if verification fails

184-191: LGTM: Cosmos ADR-36 signature verification properly implemented

The verification logic for Cosmos ADR-36 signatures is implemented correctly:

  1. It ensures the signature type is compatible (Secp256k1)
  2. It properly hashes the message using cosmos_adr36_hash_message
  3. It verifies the signature against the prehashed message
  4. It provides clear error messages if verification fails

219-220: LGTM: SigningKey to VerifyingKey conversion updated for new variants

The From implementation is correctly updated to support converting the new SigningKey variants to their corresponding VerifyingKey variants.

crates/keys/src/signing_keys.rs (11)

1-1: LGTM: Appropriate imports added for the new signing schemes

The imports for eip191_hash_message, signature-related traits, and crate modules including cosmos_adr36_hash_message are correctly added to support the new signing functionality.

Also applies to: 5-6, 12-15


36-37: LGTM: New SigningKey variants added

The two new variants Eip191 and CosmosAdr36 are properly added to the SigningKey enum, both using Secp256k1SigningKey as their underlying implementation.


53-59: LGTM: Constructor methods added for new key types

The new methods new_eip191() and new_cosmos_adr36() are properly implemented to create random signing keys for the new variants using secure random number generation.


66-67: LGTM: Algorithm-based key creation updated

The new_with_algorithm method is correctly updated to handle the new CryptoAlgorithm variants.


80-81: LGTM: Byte representation for new variants implemented

The to_bytes method is properly extended to handle the new variants, correctly reusing the byte representation of the Secp256k1 key.


96-101: LGTM: Key creation from bytes implemented for new variants

The from_algorithm_and_bytes method is correctly updated to support the new variants, properly creating the appropriate SigningKey type based on the algorithm and byte data.


110-111: LGTM: Algorithm mapping for new variants

The algorithm method is properly updated to return the correct CryptoAlgorithm for the new variants.


115-115: LGTM: Improved function signature and return type for sign method

The signing method now:

  1. Returns Result<Signature> to properly handle errors
  2. Accepts impl AsRef<[u8]> instead of &[u8], which provides more flexibility

130-134: LGTM: EIP-191 signing properly implemented

The signing logic for EIP-191 is implemented correctly:

  1. It properly hashes the message using eip191_hash_message
  2. It signs the prehashed message using the Secp256k1 key
  3. It correctly handles errors through the Result type

135-139: LGTM: Cosmos ADR-36 signing properly implemented

The signing logic for Cosmos ADR-36 is implemented correctly:

  1. It properly hashes the message using cosmos_adr36_hash_message with the verifying key
  2. It signs the prehashed message using the Secp256k1 key
  3. It correctly handles errors through the Result type

The implementation properly addresses the error handling concerns raised in previous reviews by using ? instead of unwrap().


150-151: LGTM: PartialEq implementation updated for new variants

The PartialEq implementation is correctly extended to include equality comparison for the new SigningKey variants.

@jns-ps jns-ps merged commit cefe27a into main Feb 27, 2025
8 of 10 checks passed
@jns-ps jns-ps deleted the wallet-signatures branch February 27, 2025 05:36
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.

2 participants