Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: avoid double hashing JMT keys #170

Merged
merged 1 commit into from
Dec 12, 2024
Merged

fix: avoid double hashing JMT keys #170

merged 1 commit into from
Dec 12, 2024

Conversation

jns-ps
Copy link
Contributor

@jns-ps jns-ps commented Dec 11, 2024

Summary by CodeRabbit

  • New Features
    • Simplified key hash generation process by using identifiers directly instead of hashed versions across various components.
  • Bug Fixes
    • Adjusted the get_hashchain method to improve how hash chains are retrieved, enhancing its interaction with the underlying data structure.
  • Documentation
    • Updated method signature for get_hashchain in the Prover struct to reflect changes in key hash generation.

@jns-ps jns-ps self-assigned this Dec 11, 2024
Copy link
Contributor

coderabbitai bot commented Dec 11, 2024

Walkthrough

The changes in this pull request primarily focus on modifying how KeyHash is generated across several components in the codebase. The updates involve replacing the previous method of creating KeyHash using hashed versions of identifiers with a direct use of the identifier strings themselves. This alteration affects methods in TestTreeState, TransactionBuilder, SnarkableTree, and Prover, streamlining the process of key generation by removing the intermediate hashing step while maintaining existing functionality.

Changes

File Path Change Summary
crates/common/src/test_utils.rs Updated TestTreeState methods to generate KeyHash directly from service and account IDs.
crates/common/src/transaction_builder.rs Modified TransactionBuilder methods to use direct IDs for generating KeyHash.
crates/common/src/tree/snarkable_tree.rs Altered SnarkableTree implementation to create KeyHash from transaction and service IDs directly.
crates/node_types/prover/src/prover/mod.rs Changed get_hashchain method in Prover to generate key_hash using the ID string directly.

Possibly related PRs

Suggested reviewers

  • distractedm1nd
  • sebasti810

🐰 In the code where hashes did dwell,
A change was made, oh can you tell?
From hashed to plain, the keys now shine,
Simplifying paths, making them fine.
With every tweak, the logic flows,
In rabbit's hop, the progress shows! 🐇✨


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. (Experiment)
  • @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: 0

🧹 Outside diff range and nitpick comments (2)
crates/common/src/test_utils.rs (2)

63-63: Add test cases for edge-case IDs.

With the change to use raw IDs for key generation, ensure test coverage for:

  1. IDs with special characters
  2. Very long IDs
  3. Unicode IDs
  4. Similar looking IDs (e.g., with different Unicode normalizations)

Consider adding test helper methods for generating various types of test IDs:

impl TestTreeState {
    pub fn test_with_special_chars_id(&mut self) -> String {
        "test!@#$%^&*()_+".to_string()
    }
    
    pub fn test_with_unicode_id(&mut self) -> String {
        "test_🦀_κόσμε".to_string()
    }
}

Also applies to: 97-97


219-219: Enhance random ID generation for better test coverage.

The current random string generation uses only alphanumeric characters. With the switch to raw IDs, consider expanding the character set to include special characters and Unicode for more comprehensive testing.

Consider replacing the current random string generation with a more comprehensive approach:

-let random_string: String = (0..10)
-    .map(|_| rng.sample(rand::distributions::Alphanumeric) as char)
-    .collect();
+let random_string = generate_test_id(rng, TestIdType::Complex);

Also applies to: 247-247

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e007955 and b1ca2e7.

📒 Files selected for processing (4)
  • crates/common/src/test_utils.rs (4 hunks)
  • crates/common/src/transaction_builder.rs (3 hunks)
  • crates/common/src/tree/snarkable_tree.rs (4 hunks)
  • crates/node_types/prover/src/prover/mod.rs (1 hunks)
🔇 Additional comments (3)
crates/common/src/tree/snarkable_tree.rs (1)

36-36: Verify the security implications of using raw IDs for key generation.

The change from using hashed IDs to raw IDs for KeyHash generation could have security implications:

  1. Key Predictability: Using raw IDs makes keys more predictable
  2. Key Uniqueness: Collision resistance now depends on ID uniqueness rather than hash properties
  3. Key Length: Raw IDs might be longer than their hash equivalents

Also applies to: 54-54, 64-64, 101-101

✅ Verification successful

Let me gather more specific information about the key hash implementation and its usage.


Let me gather more specific information about the KeyHash implementation and transaction ID generation.


Let me gather more information about the transaction ID validation and hash generation.


Based on the gathered information, I can now provide a final response regarding the security implications of using raw IDs for key generation.

Using raw transaction IDs for key generation is secure in this implementation

The implementation uses the KeyHash::with::<Hasher> function to generate key hashes from transaction IDs, which provides several security guarantees:

  1. The IDs are hashed before being used as keys, preventing direct exposure of raw IDs
  2. The hash function is cryptographically secure through the generic Hasher type parameter
  3. The key generation is part of a larger append-only hashchain system that maintains integrity through cryptographic commitments
  4. The system uses Jellyfish Merkle Trees with versioning, providing additional security through state verification
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential ID collisions in the codebase
# Look for patterns where IDs might conflict

# Search for ID generation/validation patterns
rg -A 3 'id: String|id: &str|id\.to_string\(\)'

# Search for any existing ID validation or sanitization
ast-grep --pattern 'fn $name($params) {
  $$$
  ensure!($condition, $message)
  $$$
}'

Length of output: 13447


Script:

#!/bin/bash
# Check KeyHash implementation and usage
rg -A 5 "impl.*KeyHash"

# Check transaction ID generation/validation
rg -A 5 "transaction\.id"

# Look for any hash-related security measures
ast-grep --pattern 'struct KeyHash {
  $$$
}'

# Check for any validation or sanitization of transaction IDs
ast-grep --pattern 'fn $name($params) -> $ret {
  $$$
  hash($expr)
  $$$
}'

Length of output: 131070


Script:

#!/bin/bash
# Check KeyHash implementation and usage
ast-grep --pattern 'impl KeyHash {
  $$$
}'

# Look for transaction ID generation/validation
ast-grep --pattern 'fn $name($params) -> $ret {
  $$$
  transaction.id
  $$$
}'

# Check for any hash-related security measures on transaction IDs
rg -A 3 "with::<Hasher>\(&"

# Look for any transaction ID validation
rg -A 3 "validate.*id|verify.*id"

Length of output: 103693


Script:

#!/bin/bash
# Check for transaction ID validation in hashchain
rg -A 5 "fn create_account|fn register_service" crates/common/src/hashchain.rs

# Look for KeyHash implementation details
rg -A 5 "impl KeyHash" crates/common/src/

# Check for any transaction ID format requirements or validation
rg -A 3 "transaction.*id.*format|validate.*transaction.*id"

# Look for any hash-related security measures in the codebase
rg -A 3 "hash.*security|secure.*hash"

Length of output: 87091

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

193-193: 🛠️ Refactor suggestion

Enhance error handling for invalid IDs.

With the change to use raw IDs for key generation, the error handling should be enhanced to handle invalid ID cases consistently across all methods.

Consider adding ID validation before key generation:

+fn validate_id(id: &str) -> Result<(), anyhow::Error> {
+    if id.is_empty() {
+        bail!("ID cannot be empty");
+    }
+    // Add more validation as needed
+    Ok(())
+}

 pub fn add_key(
     &mut self,
     id: &str,
     key: VerifyingKey,
     signing_key: &SigningKey,
     key_idx: usize,
 ) -> UncommittedTransaction {
+    validate_id(id).expect("Invalid ID");
     let key_hash = KeyHash::with::<Hasher>(id);

Also applies to: 230-230, 307-307

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

462-462: LGTM! Change aligns with avoiding double hashing of JMT keys.

The modification correctly implements the PR's objective by directly using the id string to create the KeyHash instead of performing an intermediate hashing step. This change is consistent with similar modifications across other components mentioned in the AI summary.

Let's verify the consistency of this change with other components that interact with JMT keys:

✅ Verification successful

Verified: Change correctly implements direct key hashing

The verification confirms that:

  • All KeyHash::with usages across the codebase directly use the identifier without pre-hashing
  • The remaining Digest::hash operations with IDs are used for different purposes (signatures, challenges) and not for key generation
  • The change maintains consistency with similar usage patterns in other components (transaction_builder.rs, snarkable_tree.rs, test_utils.rs)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the consistent usage of KeyHash::with across the codebase
# Expected: All KeyHash::with calls should directly use the identifier without pre-hashing

# Search for KeyHash::with usage patterns
rg "KeyHash::with" -A 3

# Search for any remaining Digest::hash calls that might be used with KeyHash
rg "Digest::hash.*KeyHash::with" -A 3

Length of output: 4123


Script:

#!/bin/bash
# Let's verify if there are any direct usages of Digest::hash with strings that might be related to key hashing
rg "Digest::hash.*id" -A 3

# Also check for any KeyHash related code to ensure we're not missing any implementation details
ast-grep --pattern 'impl $_ for KeyHash { $$ }'

# And check the KeyHash struct definition
ast-grep --pattern 'struct KeyHash { $$ }'

Length of output: 1272

@jns-ps jns-ps merged commit a05b9a1 into main Dec 12, 2024
5 checks passed
@jns-ps jns-ps deleted the no-double-hashing branch December 12, 2024 11:19
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