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

f: stash #249

Closed
wants to merge 1 commit into from
Closed

f: stash #249

wants to merge 1 commit into from

Conversation

maxrobot
Copy link
Contributor

@maxrobot maxrobot commented Nov 29, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new dependency on regex for improved functionality.
    • Added a testing module for the address generation feature, ensuring generated addresses are valid and unique.
  • Bug Fixes

    • Enhanced clarity in variable naming within the address generation logic and simplified error handling.
  • Chores

    • Updated various dependencies in the Cargo.toml files to ensure compatibility and stability.

Copy link

coderabbitai bot commented Nov 29, 2024

Walkthrough

The pull request includes updates to the Cargo.toml files across multiple packages, focusing on dependency management. Key changes involve the addition of new dependencies such as regex, updates to existing dependencies like rand and secp256k1, and the removal of some others. Additionally, modifications to the calculate_spot_market_id function in spot_market.rs reflect a change in how the Keccak hasher is instantiated. The address_generator.rs file sees enhancements in variable naming, error handling, and the introduction of a new test module.

Changes

File Path Change Summary
Cargo.toml Updated dependency versions; added regex (1.11.1); retained rand (0.4.6) and secp256k1 (0.7.1); removed some dependencies.
packages/injective-cosmwasm/src/exchange/spot_market.rs Updated Keccak hasher instantiation in calculate_spot_market_id function.
packages/injective-testing/Cargo.toml Added regex as a workspace dependency.
packages/injective-testing/src/multi_test/address_generator.rs Enhanced InjectiveAddressGenerator functionality; added a test module for generate_inj_address.

Possibly related PRs

Suggested reviewers

  • jbernal87

🐰 In the garden of code, we hop and play,
With dependencies updated, we brighten the day.
Regex joins the party, oh what a delight,
Spot markets are hashed, everything feels right!
So let’s test our addresses, unique and true,
A joyful rabbit dance, for the changes we brew! 🐇✨


🪧 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

@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 (5)
Cargo.toml (1)

35-52: Consider dependency modernization strategy

The pattern of downgrading multiple critical dependencies (rand, secp256k1, tiny-keccak) suggests underlying architectural constraints. Consider:

  1. Documenting the specific constraints requiring these older versions
  2. Creating a modernization plan to upgrade these dependencies
  3. If the constraints are from indirect dependencies, consider using cargo-tree to identify and resolve the conflicts

Would you like assistance in creating a dependency modernization plan or analyzing the constraint tree?

packages/injective-testing/src/multi_test/address_generator.rs (4)

5-7: Remove commented import statements.

Clean up the code by removing the commented-out import statements as they're no longer needed and maintaining them adds unnecessary noise to the codebase.

-// use rand::rngs::OsRng;
use secp256k1::Secp256k1;
-// use secp256k1::{rand, Secp256k1, SecretKey};

77-79: Improve error handling for RNG initialization.

Using expect() with a descriptive message is preferred over unwrap() for better error diagnostics in production.

-    let mut rng = OsRng::new().expect("failed to create new random number generator");
+    let mut rng = OsRng::new().expect("Failed to initialize secure random number generator for key generation");

80-80: Remove commented code.

Clean up the implementation by removing commented-out code. If this information is important, consider adding it as documentation instead.

-    // let (_, public_key) = secp256k1.generate_keypair(&mut rng).expect("failed to generate key pair");
-    // let keccak = tiny_keccak::keccakf(public_key_array);

Also applies to: 84-84


102-129: Enhance test coverage and performance.

The test module is well-structured but could be improved in the following ways:

  1. The uniqueness test with just two addresses isn't comprehensive enough. Consider testing with a larger sample size.
  2. The regex pattern could be defined as a constant to avoid recompilation in each test run.

Here's a suggested improvement:

 #[cfg(test)]
 mod tests {
     use super::*;
     use regex::Regex;
+    
+    // Define regex as a constant using lazy_static
+    use lazy_static::lazy_static;
+    lazy_static! {
+        static ref BECH32_REGEX: Regex = Regex::new(r"^inj[1-9a-z]{38}$").unwrap();
+    }

     #[test]
     fn test_generate_inj_address() {
         // Generate an Injective address
         let generated_address = generate_inj_address();

         // Ensure the generated address is not empty
         assert!(!generated_address.to_string().is_empty(), "Generated address should not be empty");

         // Ensure the generated address starts with the Injective prefix
         assert!(generated_address.as_str().starts_with("inj"), "Generated address should start with 'inj'");

         // Ensure the address matches a valid bech32 format
-        let bech32_regex = Regex::new(r"^inj[1-9a-z]{38}$").unwrap();
         assert!(
-            bech32_regex.is_match(generated_address.as_str()),
+            BECH32_REGEX.is_match(generated_address.as_str()),
             "Generated address does not match valid bech32 format"
         );

-        // Ensure each generated address is unique (you can extend this for more iterations)
-        let another_generated_address = generate_inj_address();
-        assert_ne!(generated_address, another_generated_address, "Generated addresses should be unique");
+        // Test uniqueness with a larger sample
+        let mut addresses = std::collections::HashSet::new();
+        for _ in 0..100 {
+            let addr = generate_inj_address();
+            assert!(addresses.insert(addr), "Generated duplicate address");
+        }
     }
 }

Don't forget to add the lazy_static dependency to your Cargo.toml:

[dependencies]
lazy_static = "1.4"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 78f9ab9 and fea6453.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • Cargo.toml (1 hunks)
  • packages/injective-cosmwasm/src/exchange/spot_market.rs (2 hunks)
  • packages/injective-testing/Cargo.toml (1 hunks)
  • packages/injective-testing/src/multi_test/address_generator.rs (3 hunks)
🔇 Additional comments (8)
packages/injective-testing/Cargo.toml (2)

21-21: Verify workspace dependency consistency.

Let's ensure the regex dependency is properly declared in the workspace root.

✅ Verification successful

Workspace dependency configuration is correctly set up

The regex dependency is properly declared in the root Cargo.toml with version "1.11.1" and correctly referenced as a workspace dependency in packages/injective-testing/Cargo.toml.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify regex dependency configuration in workspace
# Expected: Find regex declaration in root Cargo.toml with version 1.11.1

# Check root Cargo.toml for regex dependency
rg "regex.*=.*\"1\.11\.1\"" "Cargo.toml"

# Check other packages for regex usage to ensure consistent workspace usage
fd -e toml . packages/ -x rg -l "regex.*workspace.*true" {}

Length of output: 174


21-21: LGTM! Verify regex usage.

The addition of the regex dependency looks good, but let's verify where it's being used in the testing package.

✅ Verification successful

Regex dependency is properly used in tests

The regex dependency is actively used in the testing package's address generator tests to validate the format of generated Injective addresses. The implementation shows proper usage for bech32 address format validation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check where regex is being used in the testing package
# Expected: Find actual usage of the regex crate in the testing package

# Search for regex usage in the testing package
rg -l "use.*regex" "packages/injective-testing/src/"

Length of output: 115


Script:

#!/bin/bash
# Let's check the actual usage of regex in the address_generator.rs file
rg "regex" "packages/injective-testing/src/multi_test/address_generator.rs" -B 2 -A 2

Length of output: 440

packages/injective-cosmwasm/src/exchange/spot_market.rs (2)

6-7: LGTM! Import cleanup aligns with the new Keccak initialization.

The removal of the unused Hasher trait import and simplification to just Keccak matches the implementation changes below.


63-64: Migration to newer Keccak API looks good.

The change from v256() to new_keccak256() follows the newer tiny-keccak API while maintaining the same functionality, as verified by the existing test case.

Let's verify the impact on dependent crates:

✅ Verification successful

API migration is safe to proceed

The verification shows that:

  1. The old Keccak::v256() API is only present in the commented line being replaced
  2. The only usage of Keccak is in the spot_market.rs file being modified
  3. While there are several dependent crates, they rely on the public API of injective-cosmwasm and not on its internal implementation details

Since this is an internal implementation change that maintains the same functionality and doesn't affect the public API, the migration is safe.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any other usages of the old v256() API that might need updating
rg "Keccak::v256\(\)" 

# Check if any other crates depend on this package
fd -g "Cargo.toml" -x grep -l "injective-cosmwasm"

Length of output: 441


Script:

#!/bin/bash
# Let's check the content of dependent crates' Cargo.toml to see if they directly depend on injective-cosmwasm
for file in ./contracts/injective-cosmwasm-stargate-example/Cargo.toml ./contracts/injective-cosmwasm-mock/Cargo.toml ./contracts/dummy/Cargo.toml ./contracts/atomic-order-example/Cargo.toml ./packages/injective-testing/Cargo.toml; do
    echo "=== $file ==="
    cat "$file" | grep -A 5 "injective-cosmwasm"
done

# Let's also check if there are any other usages of Keccak in the codebase
rg "use.*Keccak" --type rust

Length of output: 4338

Cargo.toml (4)

37-37: Verify compatibility with new regex dependency and updated versions

The addition of regex and updates to serde and related dependencies look reasonable, but we should verify compatibility across the workspace.

Also applies to: 41-48

✅ Verification successful

Based on the results, I can generate the final response as we have sufficient information about the regex usage and dependency versions across the workspace.

Regex dependency addition is safe and compatible

The regex dependency is only used in test code (packages/injective-testing/src/multi_test/address_generator.rs) and is properly configured as a workspace dependency. All other dependencies, including serde and its ecosystem packages, are using workspace-inherited versions which ensures consistency across the project.

  • The regex crate is only used in tests via use regex::Regex
  • All dependent crates properly reference it through workspace inheritance (regex = { workspace = true })
  • No version conflicts or multiple versions of regex are found across the workspace
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for regex usage patterns
rg -A 5 "regex::"

# Look for potential version conflicts in nested Cargo.toml files
fd Cargo.toml --exec grep -A 5 -E "regex|serde"

Length of output: 3321


35-36: ⚠️ Potential issue

Security concern: Significant downgrade of rand dependency

The downgrade from rand 0.8.5 to 0.4.6 is concerning as:

  1. Version 0.4.6 is significantly outdated (released in 2019)
  2. Newer versions include important security fixes and improvements
  3. This could affect the quality and security of random number generation

50-51: ⚠️ Potential issue

Security concern: Downgrade of tiny-keccak

Downgrading tiny-keccak from 2.0.2 to 1.2.1 is concerning because:

  1. Version 1.2.1 is significantly older
  2. The newer version includes the explicit 'keccak' feature which suggests better modularity and potential security improvements
  3. This affects hash generation which is critical for spot market ID calculation (as mentioned in the PR summary)

39-40: ⚠️ Potential issue

Critical: Security risk in secp256k1 version downgrade

Downgrading secp256k1 from 0.29.0 to 0.7.1 introduces significant security risks:

  1. Version 0.7.1 is severely outdated
  2. Newer versions include critical security fixes and improvements
  3. This library is used for cryptographic operations, making the version crucial

@maxrobot maxrobot closed this Dec 2, 2024
@maxrobot maxrobot deleted the f/fix-injective-test-address-generator branch December 2, 2024 13:16
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.

1 participant