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(common): secp256r1 support #152

Merged
merged 1 commit into from
Nov 25, 2024
Merged

feat(common): secp256r1 support #152

merged 1 commit into from
Nov 25, 2024

Conversation

distractedm1nd
Copy link
Contributor

@distractedm1nd distractedm1nd commented Oct 31, 2024

This PR adds secp256r1 support.

It also removes verifying_key method from SigningKey, instead opting for a From<SigningKey> impl for VerifyingKey.

Secp256k1Signature also now uses der format, like Secp256r1Signature

Summary by CodeRabbit

  • New Features

    • Added support for the Secp256r1 signature scheme, enhancing cryptographic capabilities.
    • Introduced a new dependency, p256, to improve functionality.
  • Bug Fixes

    • Updated key handling methods to streamline conversions and improve clarity in transaction processing.
  • Refactor

    • Simplified conversion logic across various methods to consistently use the into() method for key management.
    • Enhanced TransactionBuilder methods to utilize VerifyingKey directly for better maintainability.

Copy link
Contributor

coderabbitai bot commented Oct 31, 2024

Walkthrough

The pull request introduces several modifications to the Cargo.toml files across different crates, adding a new dependency p256 and updating the workspace structure to include a new member crate crates/zk/sp1. Additionally, enhancements are made to the keys.rs file to support the Secp256r1 signature scheme, along with changes in various modules to streamline the conversion from SigningKey to VerifyingKey. Test cases are updated to reflect these changes, ensuring that the overall functionality remains intact.

Changes

File Change Summary
Cargo.toml Added dependency p256 = { version = "0.13.2", features = ["serde", "ecdsa"] }, updated workspace members to include crates/zk/sp1.
crates/common/Cargo.toml Introduced dependency p256.workspace = true.
crates/common/src/keys.rs Added variants for Secp256r1 in enums Signature, VerifyingKey, and SigningKey; updated methods to support Secp256r1 logic.
crates/common/src/operation.rs Updated From<SigningKey> implementation for ServiceChallenge to simplify conversion logic.
crates/common/src/test_utils.rs Replaced verifying_key() method calls with into() for type conversion consistency.
crates/node_types/prover/src/prover/tests.rs Modified key handling in tests to utilize into() for VerifyingKey.
crates/common/src/transaction_builder.rs Updated methods to use VerifyingKey directly instead of calling signing_key.verifying_key().

Possibly related PRs

Suggested reviewers

  • sebasti810

🐰 In the code's green fields, we hop and play,
New keys and features brighten the day.
With p256 in tow, we leap and bound,
In the world of cryptography, joy is found!
So let’s celebrate this code's fine dance,
For every change brings a new chance! 🎉


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

🧹 Outside diff range and nitpick comments (5)
crates/common/Cargo.toml (1)

Line range hint 27-29: Consider adding a secp256r1 feature flag

Similar to how secp256k1 has its own feature flag, consider adding a feature flag for secp256r1 to maintain consistency and allow optional compilation.

 [features]
 default = []
 test_utils = []
 secp256k1 = ["secp256k1/global-context", "secp256k1/rand-std"]
+secp256r1 = ["p256/ecdsa"]
crates/node_types/prover/src/prover/tests.rs (1)

87-88: LGTM: Clear separation of signing and verifying keys.

The explicit type annotation and separate variables improve code clarity. Consider adding a comment explaining why we need both keys in this test scenario.

 let new_signing_key = create_mock_signing_key();
+// Create verifying key for validation, while keeping signing key for later operations
 let new_verifying_key: VerifyingKey = new_signing_key.clone().into();
crates/common/src/test_ops.rs (1)

Line range hint 1-300: Consider adding test coverage for secp256r1.

Since this PR adds secp256r1 support, consider extending the test utilities to explicitly verify operations with both secp256k1 and secp256r1 keys. This would help ensure the new key type works correctly throughout the operation lifecycle.

Would you like me to help create additional test cases that exercise secp256r1 keys?

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

140-140: LGTM! Consider documenting the key conversion behavior.

The change to use into() is correct and consistent with the new conversion pattern. The clone() is necessary as the signing key is borrowed.

Consider adding a doc comment explaining the key conversion behavior:

/// Creates a new CreateAccount operation.
/// The signing key is converted to a verifying key using the From<SigningKey> implementation.
pub fn new_create_account(...)
crates/common/src/keys.rs (1)

33-33: Add documentation for the Secp256r1 variant.

Consider adding a doc comment to the Secp256r1 variant for consistency and clarity.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 46f19a8 and 4a62ab7.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (8)
  • Cargo.toml (1 hunks)
  • crates/common/Cargo.toml (1 hunks)
  • crates/common/src/keys.rs (7 hunks)
  • crates/common/src/operation.rs (2 hunks)
  • crates/common/src/test_ops.rs (1 hunks)
  • crates/common/src/test_utils.rs (4 hunks)
  • crates/node_types/prover/src/prover/tests.rs (3 hunks)
  • crates/tests/src/lib.rs (2 hunks)
🔇 Additional comments (16)
crates/common/Cargo.toml (1)

23-23: LGTM: p256 dependency addition

The addition of the p256 crate with workspace inheritance aligns with the PR objective of adding secp256r1 support.

Cargo.toml (1)

102-102: LGTM! The p256 dependency is correctly configured.

The p256 crate version 0.13.2 with "serde" and "ecdsa" features is appropriate for implementing secp256r1 support.

crates/tests/src/lib.rs (2)

12-12: LGTM: Import addition aligns with new key handling approach

The explicit import of VerifyingKey supports the PR's transition to using type conversions instead of method calls.


48-48: LGTM: Key conversion change follows new pattern

The change from verifying_key() to explicit into() conversion aligns with the PR's objective of streamlining key type conversions.

Let's verify the conversion implementation exists:

✅ Verification successful

Conversion implementation verified and correctly handles all key types

The From<SigningKey> implementation for VerifyingKey exists in crates/common/src/keys.rs and properly handles conversions for all supported key types (Ed25519, Secp256k1, Secp256r1) using their respective verification/public key derivation methods.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify From<SigningKey> for VerifyingKey implementation exists
# Expected: Find the implementation in the keys module

ast-grep --pattern 'impl From<SigningKey> for VerifyingKey'

Length of output: 703

crates/node_types/prover/src/prover/tests.rs (4)

2-2: LGTM: Import aligns with the new key handling approach.

The explicit import of VerifyingKey supports the transition from using verifying_key() method to using Into trait implementations.


62-62: LGTM: Correctly updated to use the new key conversion approach.

The change from verifying_key() to into() aligns with the PR's objective of streamlining key type conversions.


94-99: LGTM: Operations correctly use appropriate key types.

The operations are properly updated to use the new key handling approach while maintaining the test's original purpose of validating the handling of conflicting operations in the same block.


2-2: Verify consistent key handling across test files.

Let's ensure all test files have been updated to use the new key conversion approach.

✅ Verification successful

Based on the results, I can now generate the final response:

Key handling is consistent across test files

The codebase shows a consistent pattern:

  • All test files correctly use the Into trait for key conversions
  • The only remaining verifying_key() calls are in keys.rs where they are part of the implementation, not test code
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining uses of verifying_key() method in test files
# and verify consistent usage of Into trait for key conversions

echo "Checking for any remaining verifying_key() calls:"
rg "verifying_key\(\)" --type rust

echo -e "\nVerifying consistent key conversion patterns in tests:"
rg "into\(\)" --type rust -g "*test*.rs"

Length of output: 1332

crates/common/src/test_utils.rs (4)

111-111: LGTM! Clear and explicit type conversion.

The explicit type annotation with into() improves code clarity while maintaining the intended functionality.


216-216: LGTM! Clear type conversion in test utility.

The explicit type annotation with into() maintains consistency with the new conversion pattern while improving code clarity.


148-148: LGTM! Verify signature validation.

The key conversion change is correct. Since this affects signature creation, ensure the signature validation still works correctly with the converted keys.

Let's verify the signature validation tests:

#!/bin/bash
# Description: Verify signature validation tests
# Test: Search for signature validation test cases
rg -A 5 'test.*signature.*valid'

64-64: LGTM! Verify the key conversion behavior.

The change to use into() aligns with the new From<SigningKey> implementation for VerifyingKey.

Let's verify the key conversion implementation:

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

7-11: LGTM!

The imports for p256::ecdsa are appropriate for adding Secp256r1 support.


17-17: LGTM!

Importing sha2::Sha256 is necessary for computing SHA-256 digests.


36-52: LGTM!

The Hash implementation correctly handles the new Secp256r1 variant.


61-61: LGTM!

The as_bytes method correctly serializes the Secp256r1 verifying key using to_sec1_bytes().

Cargo.toml Show resolved Hide resolved
crates/common/src/test_ops.rs Outdated Show resolved Hide resolved
crates/common/src/operation.rs Show resolved Hide resolved
crates/common/src/keys.rs Outdated Show resolved Hide resolved
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 and nitpick comments (3)
crates/common/src/keys.rs (2)

Line range hint 233-254: Add test coverage for secp256r1 operations

While the existing tests were properly updated, we should add specific test cases for secp256r1:

  • Signing and verification
  • Key conversion
  • String serialization/deserialization

Would you like me to provide the implementation for these test cases?


Line range hint 154-190: Add secp256r1 support to TryFrom implementation

The current implementation only handles Ed25519 (32 bytes) and Secp256k1 (33/65 bytes) keys. It should be extended to support secp256r1 keys as well.

Here's a suggested implementation:

 match bytes.len() {
     32 => {
         let vk = Ed25519VerifyingKey::try_from(bytes.as_slice())
             .map_err(|e| anyhow!("Invalid Ed25519 key: {}", e))?;
         Ok(VerifyingKey::Ed25519(vk))
     }
     33 | 65 => {
-        let vk = Secp256k1VerifyingKey::from_slice(bytes.as_slice())
-            .map_err(|e| anyhow!("Invalid Secp256k1 key: {}", e))?;
-        Ok(VerifyingKey::Secp256k1(vk))
+        // Try parsing as Secp256k1 first
+        if let Ok(vk) = Secp256k1VerifyingKey::from_slice(bytes.as_slice()) {
+            return Ok(VerifyingKey::Secp256k1(vk));
+        }
+        // Try parsing as Secp256r1
+        let vk = Secp256r1VerifyingKey::from_sec1_bytes(bytes.as_slice())
+            .map_err(|e| anyhow!("Invalid key: neither Secp256k1 nor Secp256r1: {}", e))?;
+        Ok(VerifyingKey::Secp256r1(vk))
     }
     _ => Err(anyhow!("Invalid public key length")),
 }
crates/common/src/transaction_builder.rs (1)

134-143: Consider removing unnecessary clone.

The conversion to VerifyingKey and its usage in hash computation is correct. However, vk.clone() on line 143 appears unnecessary since vk is already owned and not used after this point.

Consider this optimization:

-            vk.clone(),
+            vk,
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4a62ab7 and 96b7343.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (7)
  • Cargo.toml (1 hunks)
  • crates/common/Cargo.toml (1 hunks)
  • crates/common/src/keys.rs (8 hunks)
  • crates/common/src/operation.rs (1 hunks)
  • crates/common/src/test_utils.rs (9 hunks)
  • crates/common/src/transaction_builder.rs (3 hunks)
  • crates/node_types/prover/src/prover/tests.rs (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • Cargo.toml
  • crates/common/Cargo.toml
  • crates/common/src/operation.rs
  • crates/node_types/prover/src/prover/tests.rs
🔇 Additional comments (11)
crates/common/src/test_utils.rs (6)

57-57: LGTM: Idiomatic type conversion using into()

The changes properly implement the transition from verifying_key() to into() for SigningKey to VerifyingKey conversion, making the code more idiomatic.

Also applies to: 65-65, 76-76


87-87: LGTM: Consistent type conversion in account creation

The changes maintain consistency in using into() for type conversion while preserving the original functionality.

Also applies to: 91-91, 100-100


152-152: LGTM: Clear and consistent type conversion

The change maintains consistency with the new pattern while using clear variable naming.


185-185: LGTM: Proper type conversion in SignatureBundle

The change correctly implements the type conversion while maintaining necessary ownership semantics.


218-219: LGTM: Consistent updates in random insert logic

The changes maintain consistency in type conversion while preserving good code formatting and readability.

Also applies to: 224-224, 236-236


265-265: LGTM: Clean type conversion in update logic

The change maintains consistency with the new pattern while using clear variable naming.

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

7-11: LGTM: Clean integration of secp256r1 dependencies

The p256 ECDSA imports and Signature enum extension are well-structured and maintain consistency with the existing implementation.

Also applies to: 29-29


41-42: LGTM: Well-documented secp256r1 support with proper Hash implementation

The documentation clearly indicates the use cases for secp256r1 (TLS, X.509 PKI, Passkeys), and the Hash implementation correctly maintains uniqueness with a distinct discriminator.

Also applies to: 45-61


108-118: LGTM: Consistent implementation of secp256r1 signing operations

The SigningKey implementation maintains consistency with the verification side:

  • Proper SHA-256 digest usage
  • Clean conversion implementations
  • Consistent error handling

Also applies to: 203-203, 216-221


93-103: Verify DER signature format handling across the codebase

The implementation correctly uses DER format for secp256r1 signatures. Let's verify this is handled consistently across the codebase.

✅ Verification successful

Let me gather more context about signature handling in the codebase.


Based on the comprehensive search results, I can now provide the final response:

DER signature format is consistently handled for secp256r1 signatures

The codebase shows consistent and correct handling of signature formats:

  • In keys.rs, secp256r1 signatures are properly converted to DER format during verification
  • Other signature types (Ed25519, Secp256k1) use their appropriate formats
  • No raw byte manipulation of secp256r1 signatures was found that could bypass DER encoding
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other signature format conversions to ensure consistency
rg -l "to_der|from_der" --type rust

# Search for any direct byte manipulation of signatures that might need DER handling
ast-grep --pattern 'signature.$$$bytes$$$'

Length of output: 108


Script:

#!/bin/bash
# Look for all signature-related code with context
rg "Signature" -A 5 -B 5 --type rust

# Look specifically for signature verification implementations
ast-grep --pattern 'verify$$$signature$$$'

# Search for any signature encoding/decoding
rg "encode|decode|serialize|deserialize" --type rust -A 3 -B 3 | grep -i "signature"

Length of output: 22682

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

171-171: LGTM! Efficient chaining of operations.

The direct conversion of the mock signing key to VerifyingKey using method chaining is clean and efficient.

crates/common/src/transaction_builder.rs Show resolved Hide resolved
crates/common/src/keys.rs Show resolved Hide resolved
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.

3 participants