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

Investigating issues with ECDSA_SECP256k1 #53

Closed
wants to merge 10 commits into from

Conversation

lealobanov
Copy link
Collaborator

@lealobanov lealobanov commented May 30, 2024

Investigating reported GH issues with ECDSA_SECP256k1


For contributor use:

  • Targeted PR against master branch
  • Linked to Github issue with discussion and accepted design OR link to spec that describes this work.
  • Code follows the standards mentioned here.
  • Updated relevant documentation
  • Re-reviewed Files changed in the Github PR explorer
  • Added appropriate labels

Summary by CodeRabbit

  • New Features

    • Introduced logging support using SLF4J and Logback.
    • Added SdkConfig to allow custom logger integration.
    • Expanded cryptographic capabilities with new algorithms KECCAK256 and KMAC128.
  • Documentation

    • Updated README with instructions for integrating a custom logger.
  • Tests

    • Added extensive tests for logging and new cryptographic functionalities.
  • Enhancements

    • Improved HashAlgorithm to include KECCAK256 and KMAC128.
    • Refined cryptographic methods for better performance and flexibility.

Copy link
Contributor

coderabbitai bot commented May 30, 2024

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The updates add custom logging and expand cryptographic functionalities within the SDK for Java and Kotlin applications. This involves integrating SLF4J and Logback, adding new cryptographic algorithms, and including comprehensive tests for these features. Improvements to logging include the introduction of a custom logger through SdkConfig and an example provided in the README.

Changes

File/Directory Summary
README.md Added section on integrating custom logger
build.gradle.kts Added slf4j-api and logback-classic dependencies
src/main/kotlin/.../LoggerProvider.kt Introduced LoggerProvider singleton for managing loggers
src/main/kotlin/.../SdkConfig.kt Added SdkConfig class for setting custom loggers
src/main/kotlin/.../crypto/Crypto.kt Updated cryptographic functions and added parameters
src/main/kotlin/.../models.kt Corrected enum and added KECCAK256 and KMAC128 values
src/main/kotlin/resources/logback.xml Introduced Logback configuration
src/test/kotlin/.../LoggerProviderTest.kt Added tests for LoggerProvider
src/test/kotlin/.../SdkConfigTest.kt Added tests for SdkConfig
src/test/kotlin/.../crypto/CryptoTest.kt Added tests for cryptographic methods
src/test/kotlin/.../models/HashAlgorithmTest.kt Added tests for new hash algorithms
src/test/kotlin/.../ScriptTest.kt Minor changes to struct TestClass and main function

Poem

In the realm of code, with bytes and logs,
Where hashes mix with frogs and dogs.
A custom logger sets the scene,
With SLF4J, our apps are keen.
Crypto enhanced, so safe and sound,
In Java's land, new logs abound. 🌟🐇


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 Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

github-actions bot commented May 30, 2024

Unit Test Results

  53 files  ±0    53 suites  ±0   7s ⏱️ ±0s
292 tests +5  291 ✔️ +4  0 💤 ±0  1 ❌ +1 

For more details on these failures, see this check.

Results for commit 59feb70. ± Comparison against base commit 797007a.

♻️ This comment has been updated with latest results.

Copy link

github-actions bot commented May 30, 2024

Integration Test Results

0 files   -   7  0 suites   - 7   0s ⏱️ -27s
0 tests  - 33  0 ✔️  - 31  0 💤 ±0  0 ❌  - 2 

Results for commit 38f19fb. ± Comparison against base commit a51dee8.

This pull request removes 33 tests.
org.onflow.flow.sdk.cadence.JsonCadenceTest ‑ Can parse new JSON Cadence()
org.onflow.flow.sdk.cadence.JsonCadenceTest ‑ decodeArray()
org.onflow.flow.sdk.cadence.JsonCadenceTest ‑ decodeBoolean()
org.onflow.flow.sdk.cadence.JsonCadenceTest ‑ decodeComplexDict()
org.onflow.flow.sdk.cadence.JsonCadenceTest ‑ decodeEnum()
org.onflow.flow.sdk.cadence.JsonCadenceTest ‑ decodeOptional()
org.onflow.flow.sdk.cadence.JsonCadenceTest ‑ decodeOptional2()
org.onflow.flow.sdk.cadence.JsonCadenceTest ‑ decodeReference()
org.onflow.flow.sdk.cadence.JsonCadenceTest ‑ decodeResource()
org.onflow.flow.sdk.cadence.JsonCadenceTest ‑ decodeStruct()
…

♻️ This comment has been updated with latest results.

@lealobanov lealobanov marked this pull request as ready for review May 31, 2024 07:51
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: 2

Outside diff range and nitpick comments (1)
src/main/kotlin/org/onflow/flow/sdk/models.kt (1)

85-86: Add documentation for new hash algorithms KECCAK256 and KMAC128.

It would be beneficial to add documentation comments explaining the use cases and specifics of the new hash algorithms KECCAK256 and KMAC128.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a51dee8 and d249bdd.

Files selected for processing (11)
  • README.md (1 hunks)
  • build.gradle.kts (1 hunks)
  • src/main/kotlin/org/onflow/flow/sdk/LoggerProvider.kt (1 hunks)
  • src/main/kotlin/org/onflow/flow/sdk/SdkConfig.kt (1 hunks)
  • src/main/kotlin/org/onflow/flow/sdk/crypto/Crypto.kt (3 hunks)
  • src/main/kotlin/org/onflow/flow/sdk/models.kt (3 hunks)
  • src/main/kotlin/resources/logback.xml (1 hunks)
  • src/test/kotlin/org/onflow/flow/sdk/LoggerProviderTest.kt (1 hunks)
  • src/test/kotlin/org/onflow/flow/sdk/SdkConfigTest.kt (1 hunks)
  • src/test/kotlin/org/onflow/flow/sdk/crypto/CryptoTest.kt (4 hunks)
  • src/test/kotlin/org/onflow/flow/sdk/models/HashAlgorithmTest.kt (1 hunks)
Files skipped from review due to trivial changes (3)
  • src/main/kotlin/org/onflow/flow/sdk/SdkConfig.kt
  • src/main/kotlin/resources/logback.xml
  • src/test/kotlin/org/onflow/flow/sdk/LoggerProviderTest.kt
Additional context used
LanguageTool
README.md

[style] ~8-~8: For conciseness, consider replacing this expression with an adverb.
Context: ... to interact with the Flow blockchain. At the moment, this SDK includes the following featur...


[style] ~210-~210: Style-wise, it’s not ideal to insert an adverb (‘automatically’) in the middle of an infinitive construction (‘to create’). Try moving the adverb to avoid split infinitives.
Context: ...ount credentials - @FlowTestAccount - used to automatically create an account in the emulator and inject a `TestAccou...


[misspelling] ~218-~218: Although the phrase ‘are welcomed’ is grammatically correct, possibly, the meaning is not correct in this context. Did you mean “welcome”?
Context: ...very early phase; all contributions are welcomed. Read the [contributing guide](https:/...

Markdownlint
README.md

111-111: Expected: h3; Actual: h4
Heading levels should only increment by one level at a time


229-229: Expected: dash; Actual: asterisk
Unordered list style


230-230: Expected: dash; Actual: asterisk
Unordered list style


231-231: Expected: dash; Actual: asterisk
Unordered list style


232-232: Expected: dash; Actual: asterisk
Unordered list style


233-233: Expected: dash; Actual: asterisk
Unordered list style


230-230: Expected: 2; Actual: 3
Unordered list indentation


231-231: Expected: 2; Actual: 3
Unordered list indentation


233-233: Expected: 2; Actual: 3
Unordered list indentation


3-3: Expected: 0 or 2; Actual: 1
Trailing spaces


10-10: Expected: 0 or 2; Actual: 1
Trailing spaces


18-18: Expected: 0 or 2; Actual: 1
Trailing spaces


231-231: Expected: 0 or 2; Actual: 1
Trailing spaces


234-234: Expected: 0 or 2; Actual: 1
Trailing spaces


235-235: Expected: 0 or 2; Actual: 5
Trailing spaces


235-235: Expected: 1; Actual: 2
Multiple consecutive blank lines


236-236: Expected: 1; Actual: 3
Multiple consecutive blank lines


141-141: null
Fenced code blocks should be surrounded by blank lines


163-163: null
Fenced code blocks should be surrounded by blank lines


10-10: null
Lists should be surrounded by blank lines


229-229: null
Lists should be surrounded by blank lines

Additional comments not posted (8)
src/main/kotlin/org/onflow/flow/sdk/LoggerProvider.kt (2)

7-7: Initialization of the logger with a default name "DefaultLogger" is appropriate and follows standard practices.


9-13: The implementation of the getter and setter for the logger is correct and provides necessary flexibility for changing the logger at runtime.

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

7-14: The test testSetLogger correctly verifies the functionality of setting a custom logger through SdkConfig. It uses appropriate assertions to ensure that the logger is set correctly.

src/test/kotlin/org/onflow/flow/sdk/models/HashAlgorithmTest.kt (1)

22-23: The tests for KECCAK256 and KMAC128 correctly verify the mapping from Cadence indices to HashAlgorithm values. This ensures that the enum mappings are accurate and functional.

build.gradle.kts (1)

65-66: The addition of slf4j-api and logback-classic dependencies is appropriate for enabling logging capabilities within the SDK. These dependencies are correctly configured in the implementation scope.

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

66-71: The tests for ECDSA_SECP256k1 correctly verify the signing and normalization of signatures. These tests are crucial for ensuring the cryptographic integrity and functionality of the SDK.

Also applies to: 95-110, 130-136

README.md (1)

89-130: The added documentation on integrating a custom logger with the SDK is comprehensive and clear. It provides valuable guidance for developers on how to customize the logging functionality of the SDK.

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

60-60: Ensure the id for ECDSA_SECP256k1 is consistent with standards.

Verification successful

The id values for ECDSA_SECP256k1 (3 and 2) appear to be used consistently across the codebase. However, to ensure these values are correct and align with the standards, we need to verify their correctness.


The id values for ECDSA_SECP256k1 (3 and 2) are used consistently in the codebase, particularly in the SignatureAlgorithmTest.kt file, where they are tested for correctness. This indicates that the values are correctly implemented and align with the expected standards.

  • SignatureAlgorithm.fromCode(3) returns SignatureAlgorithm.ECDSA_SECP256k1.
  • SignatureAlgorithm.fromCadenceIndex(2) returns SignatureAlgorithm.ECDSA_SECP256k1.

These tests confirm that the id values are correctly mapped and used.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the `id` for `ECDSA_SECP256k1` across different standards.

# Test: Search for the `id` usage. Expect: Consistent usage across the codebase.
rg --type kotlin $'ECDSA_SECP256k1'

Length of output: 1984



Script:

#!/bin/bash
# Description: Verify the correctness of the `id` values for `ECDSA_SECP256k1`.

# Test: Search for the `id` values (3 and 2) usage in the codebase.
rg --type kotlin '3' | rg 'SignatureAlgorithm'
rg --type kotlin '2' | rg 'SignatureAlgorithm'

Length of output: 5934

Comment on lines 196 to 221
val signature: ByteArray
val ecdsaSign: Signature

if (privateKey.key.algorithm == "EC" && privateKey.key is ECPrivateKey) {
// Use Bouncy Castle for secp256k1
ecdsaSign = Signature.getInstance("ECDSA", "BC")
} else {
// Use default provider for other algorithms
ecdsaSign = Signature.getInstance(hashAlgo.id)
}

ecdsaSign.initSign(privateKey.key)
ecdsaSign.update(bytes)

val signature = ecdsaSign.sign()
if (hashAlgo == HashAlgorithm.KECCAK256 || hashAlgo == HashAlgorithm.KMAC128) {
// Handle Keccak-256 and KMAC128 separately
val hash = hasher.hash(bytes)
val noneEcdsaSign = Signature.getInstance("NONEwithECDSA", "BC")
noneEcdsaSign.initSign(privateKey.key)
noneEcdsaSign.update(hash)
signature = noneEcdsaSign.sign()
} else {
// Handle other algorithms with valid IDs
ecdsaSign.update(bytes)
signature = ecdsaSign.sign()
}

Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor to simplify the conditional logic in the signing process.

- if (privateKey.key.algorithm == "EC" && privateKey.key is ECPrivateKey) {
-     ecdsaSign = Signature.getInstance("ECDSA", "BC")
- } else {
-     ecdsaSign = Signature.getInstance(hashAlgo.id)
- }
+ ecdsaSign = Signature.getInstance(privateKey.key.algorithm, "BC")

This change simplifies the conditional logic by directly using the algorithm specified in the private key.

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.

Suggested change
val signature: ByteArray
val ecdsaSign: Signature
if (privateKey.key.algorithm == "EC" && privateKey.key is ECPrivateKey) {
// Use Bouncy Castle for secp256k1
ecdsaSign = Signature.getInstance("ECDSA", "BC")
} else {
// Use default provider for other algorithms
ecdsaSign = Signature.getInstance(hashAlgo.id)
}
ecdsaSign.initSign(privateKey.key)
ecdsaSign.update(bytes)
val signature = ecdsaSign.sign()
if (hashAlgo == HashAlgorithm.KECCAK256 || hashAlgo == HashAlgorithm.KMAC128) {
// Handle Keccak-256 and KMAC128 separately
val hash = hasher.hash(bytes)
val noneEcdsaSign = Signature.getInstance("NONEwithECDSA", "BC")
noneEcdsaSign.initSign(privateKey.key)
noneEcdsaSign.update(hash)
signature = noneEcdsaSign.sign()
} else {
// Handle other algorithms with valid IDs
ecdsaSign.update(bytes)
signature = ecdsaSign.sign()
}
val signature: ByteArray
val ecdsaSign: Signature
ecdsaSign = Signature.getInstance(privateKey.key.algorithm, "BC")
ecdsaSign.initSign(privateKey.key)
if (hashAlgo == HashAlgorithm.KECCAK256 || hashAlgo == HashAlgorithm.KMAC128) {
// Handle Keccak-256 and KMAC128 separately
val hash = hasher.hash(bytes)
val noneEcdsaSign = Signature.getInstance("NONEwithECDSA", "BC")
noneEcdsaSign.initSign(privateKey.key)
noneEcdsaSign.update(hash)
signature = noneEcdsaSign.sign()
} else {
// Handle other algorithms with valid IDs
ecdsaSign.update(bytes)
signature = ecdsaSign.sign()
}

src/main/kotlin/org/onflow/flow/sdk/crypto/Crypto.kt Outdated Show resolved Hide resolved
@tarakby tarakby self-requested a review June 21, 2024 05:31
@tarakby
Copy link
Contributor

tarakby commented Jun 24, 2024

I'll also review this PR, but it seems to have changes from #52 too, so I'll wait for #52 to be merged to see the specific changes of #53 clearer.

@lealobanov lealobanov changed the base branch from main to hashing-algorithms July 4, 2024 13:09
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: 3

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d249bdd and 38f19fb.

Files selected for processing (3)
  • src/main/kotlin/org/onflow/flow/sdk/crypto/Crypto.kt (3 hunks)
  • src/test/kotlin/org/onflow/flow/sdk/ScriptTest.kt (1 hunks)
  • src/test/kotlin/org/onflow/flow/sdk/crypto/CryptoTest.kt (4 hunks)
Additional context used
Learnings (2)
src/main/kotlin/org/onflow/flow/sdk/crypto/Crypto.kt (1)
Learnt from: lealobanov
PR: onflow/flow-jvm-sdk#52
File: src/test/kotlin/org/onflow/flow/sdk/crypto/CryptoTest.kt:116-122
Timestamp: 2024-07-04T12:45:26.335Z
Learning: The "Sanity check KMAC128" test in `CryptoTest.kt` covers various key and customizer combinations and verifies the hash output against known good values.
src/test/kotlin/org/onflow/flow/sdk/crypto/CryptoTest.kt (1)
Learnt from: lealobanov
PR: onflow/flow-jvm-sdk#52
File: src/test/kotlin/org/onflow/flow/sdk/crypto/CryptoTest.kt:109-114
Timestamp: 2024-07-04T12:44:06.833Z
Learning: The "Sanity check Keccak_256" test in `CryptoTest.kt` verifies the correctness of the Keccak-256 hash output against known good values.
Gitleaks
src/test/kotlin/org/onflow/flow/sdk/crypto/CryptoTest.kt

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

(generic-api-key)


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

(generic-api-key)

Additional comments not posted (5)
src/test/kotlin/org/onflow/flow/sdk/ScriptTest.kt (2)

88-96: Verify the relocation of the main function.

The main function has been moved inside the script block. Ensure that this change is consistent with the rest of the codebase and does not introduce any issues.

Verification successful

Verified the relocation of the main function.

The main function has been correctly moved inside the script block in ScriptTest.kt. All occurrences of pub fun main within ScriptTest.kt are within script blocks, maintaining consistency.

  • src/test/kotlin/org/onflow/flow/sdk/ScriptTest.kt
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistency of the `main` function relocation.

# Test: Search for the usage of `main` function inside script blocks. Expect: All occurrences should be inside script blocks.
rg --type cadence $'pub fun main'

Length of output: 66


Script:

#!/bin/bash
# Description: Verify consistency of the `main` function relocation.

# Test: Search for the usage of `main` function inside Kotlin files. Expect: All occurrences should be inside script blocks.
rg --type kotlin 'pub fun main'

Length of output: 1392


Script:

#!/bin/bash
# Description: Verify that all occurrences of `pub fun main` in `ScriptTest.kt` are within script blocks.

# Extract and display 5 lines before and after each occurrence of `pub fun main` in `ScriptTest.kt` to verify the context.
rg --type kotlin 'pub fun main' -C 5 src/test/kotlin/org/onflow/flow/sdk/ScriptTest.kt

Length of output: 1198


74-96: Ensure consistency with struct naming conventions and initialization.

The TestClass struct's constructor has been renamed to init. Ensure that this change is consistent with the rest of the codebase and adheres to the naming conventions for initializers in Cadence scripts.

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

201-208: Ensure proper finalization of KMAC hashing.

The doFinal method properly finalizes the KMAC hashing. Ensure that the output size is correctly handled.

src/test/kotlin/org/onflow/flow/sdk/crypto/CryptoTest.kt (2)

210-217: Ensure comprehensive test coverage for KECCAK256.

The tests for KECCAK256 should cover all relevant cases, including edge cases.


220-251: Ensure comprehensive test coverage for KMAC128.

The tests for KMAC128 should cover all relevant cases, including edge cases.

@tarakby
Copy link
Contributor

tarakby commented Jul 12, 2024

Thanks for rebasing the changes to the hashing branch 👌🏼
The PR title mentions ECDSA issues with secp256k1, is there a reference to where those issues are described? This is to help with the review. Thanks

@lealobanov
Copy link
Collaborator Author

@tarakby , yes the related issue is: the-nft-company/flow-jvm-sdk#24 which links to 2 more follow-up issues. Will follow up on latest comments for hashing PR tomorrow as well. Thanks!

@@ -60,6 +63,13 @@ internal class CryptoTest {
assertNotNull(signer)
}

@Test
fun `Get signer for ECDSA_SECP256k1`() {
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

While we are looking at the signer class I think it makes sense to improve the quality of these tests because they follow the same paradigm as the old hasher tests... will have a look at sanity checks Go SDK is currently using

Base automatically changed from hashing-algorithms to main July 25, 2024 17:22
@tarakby
Copy link
Contributor

tarakby commented Aug 1, 2024

I think #71 covered the same issues addressed by this current PR, so it should be fine to close this PR.

@lealobanov lealobanov closed this Aug 3, 2024
@lealobanov lealobanov deleted the validate-ECDSA_SECP256k1 branch August 18, 2024 19:59
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