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

Refactor ECDSA implementation #71

Merged
merged 26 commits into from
Jul 30, 2024
Merged

Conversation

tarakby
Copy link

@tarakby tarakby commented Jul 27, 2024

This PR refactors the ECDSA implementation, fixes potential issues, and add proper testing (almost inexistent before the PR).

Changes:

  • update PrivateKey and PublicKey fields - in particular allow accessing the public key from the private key.
  • add a method verify to the PublicKey type. The method verifies a signature against a message using an input hashing algorithm.
  • refactor the signature generation and use the ECDSASigner class to both generate and verify signatures.
  • remove the use ecCoupleComponentSize which confuses the group order size and the prime field size.
  • fix the PublicKey serialization which did not pad the point coordinates to the prime field order. PrivateKey serialization is also padded to the group order size. Size checks are enforced in deserialization functions.
  • add checks for supported hashing and signing algos before performing operations
  • rewrite ECDSA tests, including:
    • sanity check of scalar point multiplication (through public key derivation)
    • public key derivation and encodings/decodings
    • signature verifications
  • use a Kotlin formatter in the modified files (models.kt has mainly formatting changes only).
  • remove obsolete hash tests checking for non-null outputs.

⚠️ Potential breaking changes:

  • Signer does not implement Hasher as it doesn't make sense to use a Signer to hash data.
  • PrivateKey and PublicKey fields are updated (alternatively, it is safer to make the internal fields private and allow the construction of PrivateKey and PublicKey only through functions and constructors that check the fields are compatible, but this would be a larger breaking change)
  • PrivateKey serialization is now padded to the order size. Deserializing a private key string also requires the input to be padded.
  • SignerImpl does not accept a Hasher input. The HashAlgorithm input is enough to get the hasher implementation.

Summary by CodeRabbit

  • New Features

    • Enhanced cryptographic functionalities including improved key generation, validation, and error handling for public and private keys.
    • New utility methods for algorithm compatibility checks within the cryptographic operations.
    • Expanded comprehensive testing for key pair generation and validation, enhancing robustness.
  • Bug Fixes

    • Improved the handling of invalid inputs for key decoding, ensuring proper exception raising.
  • Documentation

    • Refined test and method naming conventions for clarity and consistency.

Copy link

coderabbitai bot commented Jul 27, 2024

Walkthrough

The recent changes in the Flow SDK enhance cryptographic functionalities, improve code clarity, and strengthen testing practices. Key updates include revamped cryptographic classes, streamlined data structures, and added validation checks for key handling. The test suite has been expanded to cover new scenarios, ensuring robust verification of signature and hashing algorithms. This comprehensive set of modifications aims to bolster security, usability, and maintainability across the SDK.

Changes

Files Change Summary
sdk/src/main/kotlin/.../crypto/Crypto.kt Enhancements to cryptographic classes KeyPair, PrivateKey, and PublicKey. New utility methods added and improved key validation. Refactored signing logic using ECDSASigner.
sdk/src/main/kotlin/.../models.kt Formatting and structural improvements to enums and functions, increasing readability and consistency.
sdk/src/test/kotlin/.../crypto/HashTest.kt Renamed test function and removed several tests related to signing implementations, reducing coverage.
sdk/src/test/kotlin/.../crypto/SignTest.kt Expanded tests for key pair generation and validation, improved decoding tests, added signer compatibility checks.
sdk/src/test/kotlin/.../models/HashSigningAlgorithmTest.kt Renamed test class to reflect broader focus. Updated method names for clarity and added relevant imports.
sdk/src/test/kotlin/.../models/SignerTest.kt Simplified Signer implementation by removing overridden hasher property, streamlining test setup.

Poem

In the meadow, where the code does bloom,
A rabbit hops, dispelling gloom.
With keys and signatures, all in tune,
New tests take flight, like a bright balloon.
Oh, cryptographic dance, so spry and neat,
In the Flow SDK, we find our beat! 🐰✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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.

@tarakby tarakby self-assigned this Jul 27, 2024
Copy link

github-actions bot commented Jul 27, 2024

SDK Examples Unit Test Results

2 files  ±0  2 suites  ±0   33s ⏱️ ±0s
6 tests ±0  6 ✔️ ±0  0 💤 ±0  0 ❌ ±0 

Results for commit 0cafa2d. ± Comparison against base commit a8076ae.

♻️ This comment has been updated with latest results.

Copy link

github-actions bot commented Jul 27, 2024

Unit Test Results

0 files  ±0  0 suites  ±0   0s ⏱️ ±0s
0 tests ±0  0 ✔️ ±0  0 💤 ±0  0 ❌ ±0 

Results for commit c3f51ce. ± Comparison against base commit c3f51ce.

♻️ This comment has been updated with latest results.

Copy link

github-actions bot commented Jul 27, 2024

Integration Test Results

0 files  ±0  0 suites  ±0   0s ⏱️ ±0s
0 tests ±0  0 ✔️ ±0  0 💤 ±0  0 ❌ ±0 

Results for commit c3f51ce. ± Comparison against base commit c3f51ce.

♻️ This comment has been updated with latest results.

@tarakby tarakby changed the base branch from main to tarak/reorganize-test-files July 27, 2024 01:51
@tarakby tarakby closed this Jul 27, 2024
@tarakby tarakby deleted the tarak/review-ecdsa-rebased branch July 27, 2024 17:33
@tarakby tarakby reopened this Jul 27, 2024
@tarakby tarakby changed the title WIP - do not review Refactor ECDSA implementation Jul 30, 2024
Base automatically changed from tarak/reorganize-test-files to main July 30, 2024 16:08
@tarakby tarakby marked this pull request as ready for review July 30, 2024 16:08
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 78df08b and 0cafa2d.

Files selected for processing (6)
  • sdk/src/main/kotlin/org/onflow/flow/sdk/crypto/Crypto.kt (3 hunks)
  • sdk/src/main/kotlin/org/onflow/flow/sdk/models.kt (29 hunks)
  • sdk/src/test/kotlin/org/onflow/flow/sdk/crypto/HashTest.kt (2 hunks)
  • sdk/src/test/kotlin/org/onflow/flow/sdk/crypto/SignTest.kt (1 hunks)
  • sdk/src/test/kotlin/org/onflow/flow/sdk/models/HashSigningAlgorithmTest.kt (2 hunks)
  • sdk/src/test/kotlin/org/onflow/flow/sdk/models/SignerTest.kt (1 hunks)
Files skipped from review due to trivial changes (1)
  • sdk/src/test/kotlin/org/onflow/flow/sdk/models/SignerTest.kt
Additional comments not posted (44)
sdk/src/test/kotlin/org/onflow/flow/sdk/models/HashSigningAlgorithmTest.kt (6)

3-3: Add import statement for HashAlgorithm.

The import statement for HashAlgorithm has been added, indicating its usage in the tests.


8-8: Class renamed to SignatureAndHashingModelTest.

The class name change reflects an expanded focus on both signature and hashing algorithms.


31-31: Update test method name for clarity.

The method name has been updated to Test signature fromCode for better clarity.


38-39: Update test method name and comment for clarity.

The method name has been updated to Test signature fromCadenceIndex and the comment now references the correct documentation.


46-46: Update test method name for clarity.

The method name has been updated to Test signature fromCode with invalid code for better clarity.


51-51: Update test method name for clarity.

The method name has been updated to Test signature fromCadenceIndex with invalid index for better clarity.

sdk/src/test/kotlin/org/onflow/flow/sdk/crypto/HashTest.kt (1)

9-9: Update test method name for clarity.

The method name has been updated to Get default hasher for better clarity.

sdk/src/test/kotlin/org/onflow/flow/sdk/crypto/SignTest.kt (11)

3-3: Add import statements for SignatureAlgorithm and bytesToHex.

The import statements for SignatureAlgorithm and bytesToHex have been added, indicating their usage in the tests.


10-15: Add SupportedCurve data class.

The SupportedCurve data class encapsulates details about each curve, including the signature algorithm, private key size, public key size, and curve order.


18-28: Add supportedAlgos list.

The supportedAlgos list contains all supported curves of the library.


32-48: Update test method for key pair generation.

The method Test KeyPair generation iterates through supported algorithms and validates key pair generation and integrity.


52-73: Update test method for key decoding.

The method Can decode keys correctly validates the decoding functionality for both private and public keys.


77-101: Update test method for private key decoding exceptions.

The method Private key decoding throws exception when invalid validates that exceptions are thrown for invalid private keys.


106-134: Update test method for public key decoding exceptions.

The method Public key decoding throws exception when invalid validates that exceptions are thrown for invalid public keys.


138-151: Add test method for public key derivation.

The method Test derivePublicKey validates the derivation of public keys from private keys.


156-181: Add test method for signer compatibility with hash algorithms.

The method Test signer compatibility with hash algorithms validates that the signer can handle different hash algorithms and raises exceptions for unsupported ones.


185-209: Add test method for signer correctness.

The method Test signer correctness validates the correctness of signatures.


213-237: Add test method for signer with invalid algorithm keys.

The method Test signer with invalid algo keys validates that exceptions are thrown for invalid algorithm keys.

sdk/src/main/kotlin/org/onflow/flow/sdk/crypto/Crypto.kt (14)

5-7: Imports look good.

The new imports for cryptographic parameters and signers from Bouncy Castle are necessary and correctly used.

Also applies to: 14-15, 18-19


37-43: Changes to PrivateKey data class are approved.

The addition of algo and publicKey fields enhances the class by providing more context and usability.


47-80: Changes to PublicKey data class are approved.

The addition of the algo field and the verify method enhances the class by providing more context and functionality for signature verification.


88-94: New method checkSupportedSignAlgo is approved.

The method correctly enforces algorithm compatibility checks and handles unsupported algorithms appropriately.


95-123: Refactored generateKeyPair method is approved.

The method correctly generates key pairs with the new fields in PrivateKey and PublicKey, enhancing the integrity of key generation.


127-163: Refactored decodePrivateKey method is approved.

The method correctly decodes private keys with the new fields in PrivateKey, enhancing the integrity of key decoding.


167-198: Refactored decodePublicKey method is approved.

The method correctly decodes public keys with the new field in PublicKey, enhancing the integrity of key decoding.


204-208: Refactored getSigner and getHasher methods are approved.

The methods correctly return instances of Signer and Hasher with the new implementations, enhancing the functionality.


210-301: New and refactored methods in Crypto object are approved.

The methods correctly implement the intended functionality, enhancing the overall cryptographic capabilities of the SDK.


342-355: Updates to HasherImpl class are approved.

The class correctly implements new hashing algorithms and validation checks, enhancing the hashing capabilities.


372-397: Refactored SignerImpl class is approved.

The class correctly implements the new signing process using ECDSASigner, enhancing the signing capabilities.


292-301: New formatSignature method is approved.

The method correctly formats signatures, ensuring proper handling of the resulting signature.


249-265: New derivePublicKey method is approved.

The method correctly derives the public key from the private key, enhancing the key management capabilities.


267-273: New checkHashAlgoForSigning method is approved.

The method correctly enforces hash algorithm compatibility checks and handles unsupported algorithms appropriately.

sdk/src/main/kotlin/org/onflow/flow/sdk/models.kt (12)

19-21: Reformatted FlowTransactionStatus enum is approved.

The reformatting improves readability without altering functionality.


58-60: Reformatted SignatureAlgorithm enum is approved.

The reformatting improves readability without altering functionality.


142-147: Refactored FlowAccount data class is approved.

The refactoring simplifies the builder method definition without altering functionality.


152-161: Refactored getKeyIndex method in FlowAccount data class is approved.

The refactoring improves readability without altering functionality.


187-194: Refactored FlowAccountKey data class is approved.

The refactoring simplifies the builder method definition without altering functionality.


223-227: Refactored FlowEventResult data class is approved.

The refactoring simplifies the builder method definition without altering functionality.


Line range hint 486-530:
Refactored FlowTransaction data class is approved.

The refactoring simplifies the builder method and other method definitions without altering functionality.


576-579: Refactored FlowTransactionProposalKey data class is approved.

The refactoring simplifies the builder method definition without altering functionality.


600-603: Refactored FlowTransactionSignature data class is approved.

The refactoring simplifies the builder method definition without altering functionality.


Line range hint 621-657:
Refactored FlowBlockHeader and FlowBlock data classes are approved.

The refactoring simplifies the builder method definitions without altering functionality.


Line range hint 777-803:
Refactored FlowCollectionGuarantee and FlowBlockSeal data classes are approved.

The refactoring simplifies the builder method definitions without altering functionality.


819-821: Refactored FlowCollection data class is approved.

The refactoring simplifies the builder method definition without altering functionality.

@franklywatson franklywatson merged commit c3f51ce into main Jul 30, 2024
5 checks passed
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.

4 participants