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(katana): ensure paymaster accounts are unique #3017

Merged
merged 2 commits into from
Feb 13, 2025

Conversation

kariy
Copy link
Member

@kariy kariy commented Feb 13, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced the paymaster account setup with dynamic prompts and unique combination validation for public key and salt.
    • Updated the input format for paymaster accounts to require space-separated values for clarity.
    • Enabled the creation of genesis accounts with custom salt values, ensuring unique address derivation and proper balance assignment.
  • Tests

    • Introduced new test cases to verify the uniqueness validation and correct parsing of input parameters.

Copy link

coderabbitai bot commented Feb 13, 2025

Ohayo, sensei! Here’s the detailed breakdown of the changes in this PR:

Walkthrough

This pull request updates the CLI initialization and genesis account creation processes. The prompt function now uses Rc<RefCell<>> to manage slot paymaster states with runtime uniqueness validation for public key-salt combinations. Additionally, the slot argument parsing has been enhanced with a new boolean flag and an updated PaymasterAccountArgs structure that parses both public key and salt. New methods in the GenesisAccount struct facilitate account creation using salt.

Changes

File(s) Change Summary
bin/katana/src/cli/init/prompt.rs Replaced a simple vector with Rc<RefCell<Vec<PaymasterAccountArgs>>> in the prompt function; added dynamic prompts and a closure for validating unique public key-salt pairs; updated outcome processing.
bin/katana/src/cli/init/slot.rs Added a new slot boolean to SlotArgs, modified the paymaster_accounts field to accept space-separated public key and salt pairs; updated PaymasterAccountArgs and its FromStr parser; added tests for duplicate prevention.
crates/katana/primitives/src/genesis/allocation.rs Added two methods (new_with_salt_and_balance and new_inner) to the GenesisAccount struct to enable account creation with a specified salt and compute the contract address accordingly.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant PF as Prompt Function
    participant VM as Validator Closure
    participant SP as SlotPaymasters (Rc<RefCell>)

    U->>PF: Initiate slot paymaster prompt
    PF->>SP: Initialize empty paymaster list
    PF->>U: Prompt for public key (with count)
    U->>PF: Provide public key
    PF->>U: Prompt for salt input
    U->>PF: Provide salt
    PF->>VM: Validate uniqueness of public key-salt
    VM-->>PF: Return validation result
    PF->>SP: Append validated account
    PF->>U: Confirm addition or re-prompt
Loading
sequenceDiagram
    participant C as Caller
    participant GA as GenesisAccount::new_with_salt_and_balance
    participant NI as GenesisAccount::new_inner

    C->>GA: Call new_with_salt_and_balance(pub_key, class_hash, salt, balance)
    GA->>NI: Invoke new_inner(pub_key, class_hash, salt)
    NI-->>GA: Return (ContractAddress, GenesisAccount)
    GA-->>C: Return computed (ContractAddress, GenesisAccount)
Loading

Possibly related PRs


🪧 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. (Beta)
  • @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.

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

🧹 Nitpick comments (4)
bin/katana/src/cli/init/slot.rs (3)

38-60: Ohayo! Consider enhancing error messages for better user experience.

The FromStr implementation could benefit from more descriptive error messages that include the expected format.

-        let public_key = parts.next().ok_or_else(|| anyhow!("missing public key"))?;
-        let salt = parts.next().ok_or_else(|| anyhow!("missing salt"))?;
+        let public_key = parts.next().ok_or_else(|| anyhow!("missing public key - expected format: <public_key>,<salt>"))?;
+        let salt = parts.next().ok_or_else(|| anyhow!("missing salt - expected format: <public_key>,<salt>"))?;

124-155: Consider adding more edge cases to the test suite.

The test effectively verifies address uniqueness, but could be enhanced with additional scenarios:

  • Test with zero salt
  • Test with maximum salt value
  • Test with consecutive salt values

171-202: Consider adding error case tests.

While the happy path is well tested, consider adding tests for:

  • Invalid public key format
  • Invalid salt format
  • Missing salt value
bin/katana/src/cli/init/prompt.rs (1)

132-171: Nice use of Rc for state management sensei!

The implementation effectively ensures unique paymaster accounts.

Consider extracting validation logic to a separate function.

The unique_salt_validator closure could be moved to a standalone function for better readability.

+fn is_unique_salt(paymasters: &[PaymasterAccountArgs], public_key: Felt, salt: &Felt) -> bool {
+    !paymasters.iter().any(|pm| pm.public_key == public_key && pm.salt == *salt)
+}
+
 let slot_paymasters_clone = slot_paymasters.clone();
 let unique_salt_validator = move |salt: &Felt| {
-    let pred = |pm: &PaymasterAccountArgs| pm.public_key == public_key && pm.salt == *salt;
-    let duplicate = slot_paymasters_clone.borrow().iter().any(pred);
+    let unique = is_unique_salt(&slot_paymasters_clone.borrow(), public_key, salt);
 
-    if !duplicate {
+    if unique {
         Ok(Validation::Valid)
     } else {
         Ok(Validation::Invalid(ErrorMessage::Custom(
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3ed03d9 and 3d30b19.

📒 Files selected for processing (3)
  • bin/katana/src/cli/init/prompt.rs (4 hunks)
  • bin/katana/src/cli/init/slot.rs (6 hunks)
  • crates/katana/primitives/src/genesis/allocation.rs (1 hunks)
🔇 Additional comments (2)
bin/katana/src/cli/init/slot.rs (1)

62-87: LGTM sensei! Clean implementation of paymaster account creation.

The function correctly utilizes the new salt-based account creation to ensure unique addresses.

crates/katana/primitives/src/genesis/allocation.rs (1)

214-228: Clean implementation of salt-based account creation sensei!

The new methods follow the existing pattern and properly handle salt for unique address generation.

Copy link
Collaborator

@glihm glihm left a comment

Choose a reason for hiding this comment

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

Thank you @kariy for the quick adjustment!

@glihm glihm enabled auto-merge (squash) February 13, 2025 04:32
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

🧹 Nitpick comments (2)
bin/katana/src/cli/init/slot.rs (2)

21-40: Ohayo! Update documentation to match current implementation.

The example in the documentation shows comma as a delimiter (0x1,0x2 0x3,0x4), but the code uses space delimiter as specified in value_delimiter = ' '. Let's also add a note about uniqueness validation.

 /// This argument accepts a list of values, where each value is a pair of public key and salt
-/// separated by a comma. If more than one pair is provided, the double quotes are required to
+/// separated by a space. If more than one pair is provided, the double quotes are required to
 /// prevent the shell from prematurely splitting the argument.
+///
+/// Note: Each public key and salt combination must be unique to ensure unique paymaster accounts.
 ///
 /// For example:
 ///
 /// ```
-/// --slot.paymasters 0x1,0x2
+/// --slot.paymasters "0x1,0x2"
 /// ```
 ///
 /// ```
-/// --slot.paymasters "0x1,0x2 0x3,0x4 0x5,0x6"
+/// --slot.paymasters "0x1,0x2 0x1,0x3 0x2,0x1"
 /// ```

54-64: Consider validating for extra parts, sensei!

The parsing looks good with proper error handling, but we should validate that there are no unexpected extra parts after the salt.

 fn from_str(s: &str) -> Result<Self> {
     let mut parts = s.split(',');

     let public_key = parts.next().ok_or_else(|| anyhow!("missing public key"))?;
     let salt = parts.next().ok_or_else(|| anyhow!("missing salt"))?;
+    if parts.next().is_some() {
+        return Err(anyhow!("unexpected extra parts after salt"));
+    }

     let public_key = Felt::from_str(public_key)?;
     let salt = Felt::from_str(salt)?;

     Ok(PaymasterAccountArgs { public_key, salt })
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3d30b19 and 8858868.

📒 Files selected for processing (1)
  • bin/katana/src/cli/init/slot.rs (6 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: build
  • GitHub Check: clippy
  • GitHub Check: docs
  • GitHub Check: ensure-wasm
🔇 Additional comments (2)
bin/katana/src/cli/init/slot.rs (2)

77-82: LGTM! Good use of salt for unique account generation.

The implementation correctly uses new_with_salt_and_balance to ensure unique paymaster accounts by combining public key and salt.


129-206: Excellent test coverage, sensei!

The new tests thoroughly validate:

  • Uniqueness of addresses with same public key but different salts
  • CLI argument parsing with and without paymaster args
  • Edge cases with multiple paymasters

@glihm glihm disabled auto-merge February 13, 2025 04:34
@glihm glihm enabled auto-merge (squash) February 13, 2025 04:35
@glihm glihm merged commit ac52ea6 into main Feb 13, 2025
14 checks passed
@glihm glihm deleted the katana/fix-unique-paymaster branch February 13, 2025 04:52
Copy link

codecov bot commented Feb 13, 2025

Codecov Report

Attention: Patch coverage is 72.27723% with 28 lines in your changes missing coverage. Please review.

Project coverage is 56.24%. Comparing base (1aa06e1) to head (8858868).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
bin/katana/src/cli/init/prompt.rs 0.00% 25 Missing ⚠️
bin/katana/src/cli/init/slot.rs 95.23% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3017      +/-   ##
==========================================
+ Coverage   56.21%   56.24%   +0.02%     
==========================================
  Files         436      436              
  Lines       58737    58829      +92     
==========================================
+ Hits        33021    33087      +66     
- Misses      25716    25742      +26     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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