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

feat(katana): limit number of proof keys #2814

Merged
merged 2 commits into from
Dec 16, 2024

Conversation

kariy
Copy link
Member

@kariy kariy commented Dec 16, 2024

ref #2809

@kariy kariy marked this pull request as ready for review December 16, 2024 21:52
@kariy kariy changed the base branch from main to katana/dev December 16, 2024 21:52
Copy link

coderabbitai bot commented Dec 16, 2024

Walkthrough

Ohayo, sensei! This pull request introduces a comprehensive enhancement to the Katana blockchain's state management and proof generation capabilities. The changes primarily focus on consolidating and expanding the trie-based state tracking, introducing new traits for state proofs and roots, and refactoring the existing database and provider interfaces. The modifications span multiple crates, including storage, provider, RPC, and trie implementations, with a significant emphasis on improving the flexibility and functionality of state retrieval and verification mechanisms.

Changes

File Change Summary
Cargo.toml files Added new dependencies, particularly proc-macro2, quote, syn, and katana-trie across various crates
crates/katana/storage/provider/src/traits/state.rs Introduced StateProofProvider and StateRootProvider traits
crates/katana/trie/src/ Added new modules: classes.rs, contracts.rs, storages.rs, and id.rs for enhanced trie management
RPC-related files Added support for get_storage_proof method and related error handling

Sequence Diagram

sequenceDiagram
    participant Client
    participant StarknetAPI
    participant StateProvider
    participant TrieDatabase
    participant MultiProofGenerator

    Client->>StarknetAPI: Request storage proof
    StarknetAPI->>StateProvider: Get multiproof
    StateProvider->>TrieDatabase: Retrieve trie data
    TrieDatabase->>MultiProofGenerator: Generate multiproof
    MultiProofGenerator-->>StateProvider: Return proof
    StateProvider-->>StarknetAPI: Return proof
    StarknetAPI-->>Client: Return storage proof response
Loading

Possibly Related PRs

Sensei, this PR represents a significant step in enhancing the state management capabilities of the Katana blockchain, providing more robust and flexible proof generation mechanisms! 🚀🔍


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. (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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 12

🔭 Outside diff range comments (2)
crates/katana/trie/src/lib.rs (1)

Line range hint 76-91: Handle potential panics in compute_merkle_root

Ohayo, sensei! In the compute_merkle_root function, there are several unwrap() calls that could lead to panics:

  • bs.insert(IDENTIFIER, key.as_bitslice(), value).unwrap();
  • bs.commit(id).unwrap();
  • bs.root_hash(IDENTIFIER).unwrap();

Consider handling these results using ? or proper error handling to prevent unexpected panics.

Apply this diff to handle errors gracefully:

-    bs.insert(IDENTIFIER, key.as_bitslice(), value).unwrap();
+    bs.insert(IDENTIFIER, key.as_bitslice(), value)?;

-    bs.commit(id).unwrap();
+    bs.commit(id)?;

-    Ok(bs.root_hash(IDENTIFIER).unwrap())
+    Ok(bs.root_hash(IDENTIFIER)?)
crates/katana/storage/provider/src/providers/fork/mod.rs (1)

Ohayo! The TrieWriter implementation needs a comment, sensei!

The ForkedProvider is a special provider that doesn't need to maintain its own state tries since it's forking from another node. This is evident from:

  1. Other unimplemented features like StageCheckpointProvider that explicitly state "syncing is not supported for forked provider"
  2. The DbProvider implementation that shows the actual trie operations that are intentionally skipped here

Let's add a comment to explain this behavior:

impl TrieWriter for ForkedProvider {
    /// ForkedProvider doesn't maintain its own state tries since it relies on the forked node's state.
    /// Therefore, these operations are no-ops that return ZERO as the root.
    fn trie_insert_declared_classes(
        &self,
        block_number: BlockNumber,
        updates: &BTreeMap<ClassHash, CompiledClassHash>,
    ) -> ProviderResult<Felt> {
🔗 Analysis chain

Line range hint 602-621: Ohayo! Please verify the TrieWriter implementation, sensei!

The implementation currently returns Felt::ZERO for both methods without actually processing the updates. While this might be intentional for forked providers, we should verify:

  1. Is returning ZERO the intended behavior for forked providers?
  2. Should we add a comment explaining why we're ignoring the updates?

Let me try to find more context about the expected behavior of TrieWriter implementations. The previous ast-grep pattern might have been too specific, so I'm using ripgrep to get a broader view of the implementations and documentation.


I need to see the actual implementation in DbProvider and the trait definition to understand if returning ZERO is valid for a forked provider. This will help us determine if we need a comment explaining this behavior.


I need to see if there's any documentation or context around the ForkedProvider that explains why it might intentionally ignore updates and return ZERO. This will help us determine if we need to add explanatory comments.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if other providers have similar implementations
ast-grep --pattern 'impl TrieWriter for $_ {
  $$$
  fn trie_insert_declared_classes($$$) -> $$ {
    $$$
  }
  $$$
}'

Length of output: 120


Script:

#!/bin/bash
# Let's search for TrieWriter implementations with ripgrep for better results
rg "impl TrieWriter for" -A 20

# Also search for any documentation about TrieWriter behavior
rg "TrieWriter" --type rust

Length of output: 2973


Script:

#!/bin/bash
# Let's check the DbProvider implementation for comparison
rg "impl.*TrieWriter for DbProvider" -A 30 crates/katana/storage/provider/src/providers/db/trie.rs

# Also check the trait definition to understand the expected behavior
cat crates/katana/storage/provider/src/traits/trie.rs

Length of output: 1893


Script:

#!/bin/bash
# Let's check the ForkedProvider documentation and implementation context
rg -B 10 "impl TrieWriter for ForkedProvider" crates/katana/storage/provider/src/providers/fork/mod.rs

# Also check if there are any comments about forking behavior
rg "ForkedProvider" -A 5 -B 5 crates/katana/storage/provider/src/providers/fork/

Length of output: 20877

🧹 Nitpick comments (29)
crates/katana/trie/src/storages.rs (1)

8-11: Ohayo, sensei! Consider adding documentation comments to StoragesTrie

Adding Rust doc comments to the StoragesTrie struct enhances code readability and helps other developers understand its purpose and usage.

crates/katana/trie/src/classes.rs (1)

10-13: Ohayo, sensei! Consider adding documentation comments to ClassesTrie

Adding Rust doc comments to ClassesTrie will enhance code readability and assist other developers in understanding its purpose and usage.

crates/katana/storage/provider/src/traits/state.rs (1)

85-95: Ohayo, sensei! Consider passing parameters as slices to improve performance

In the StateProofProvider trait methods, passing parameters as slices (&[StorageKey], &[ContractAddress], &[ClassHash]) can avoid unnecessary allocations and cloning.

Apply this diff to modify the method signatures:

 pub trait StateProofProvider: Send + Sync {
     fn storage_multiproof(
         &self,
         address: ContractAddress,
-        key: Vec<StorageKey>,
+        key: &[StorageKey],
     ) -> ProviderResult<MultiProof>;

     fn contract_multiproof(
         &self,
-        addresses: Vec<ContractAddress>,
+        addresses: &[ContractAddress],
     ) -> ProviderResult<MultiProof>;

     fn class_multiproof(
         &self,
-        classes: Vec<ClassHash>,
+        classes: &[ClassHash],
     ) -> ProviderResult<MultiProof>;
 }
crates/katana/storage/db/src/models/trie.rs (1)

70-70: Fix typo in panic message, sensei

There's a typo in the panic message: "emptyy" should be "empty".

Apply this diff:

-    panic!("emptyy buffer")
+    panic!("empty buffer")
crates/katana/storage/db/src/trie/snapshot.rs (1)

67-67: Implement the create_batch method or provide justification for empty implementation

Ohayo, sensei! The create_batch method is currently empty. If batch operations are not required for SnapshotTrieDb, consider documenting this behavior to avoid confusion.

crates/katana/trie/src/lib.rs (1)

1-4: Remove unused imports to clean up the code

Ohayo, sensei! The imports from bitvec seem comprehensive. If any of the imported modules (array::BitArray, order::Msb0, vec::BitVec, view::AsBits) are unused, consider removing them to keep the code tidy.

crates/katana/rpc/rpc-types/src/trie.rs (2)

90-109: Optimize serialization in Nodes struct

Ohayo, sensei! The custom serialization in Nodes could be simplified by deriving Serialize and Deserialize if possible. If custom behavior is required, ensure that the serialization is efficient and error-free.


179-193: Enhance test coverage for path_felt_roundtrip

Ohayo, sensei! The unit test test_path_felt_roundtrip checks the round-trip conversion between Felt and Path. To strengthen the test:

  • Include more diverse Felt values, including random and edge values.
  • Verify that the original and converted paths are identical in all aspects.
crates/katana/storage/db/src/trie/mod.rs (4)

28-37: Avoid Unnecessary References to PhantomData

Ohayo, sensei! The usage of &'a PhantomData<()> and storing a reference to PhantomData in structs may not be necessary. Typically, PhantomData is used without a reference to indicate unused lifetime or type parameters. Consider using PhantomData directly to simplify the code.

Apply this diff to use PhantomData without a reference:

-pub struct TrieDbFactory<'a, Tx: DbTxRef<'a>> {
-    tx: Tx,
-    _phantom: &'a PhantomData<()>,
+pub struct TrieDbFactory<'a, Tx: DbTxRef<'a>> {
+    tx: Tx,
+    _phantom: PhantomData<&'a ()>,
}

...

-    pub fn new(tx: Tx) -> Self {
-        Self { tx, _phantom: &PhantomData }
+    pub fn new(tx: Tx) -> Self {
+        Self { tx, _phantom: PhantomData }

174-181: Clarify Unimplemented Methods in Read-Only TrieDb

Ohayo, sensei! The methods insert, remove, and write_batch in TrieDb are unimplemented for a read-only transaction. It might be beneficial to explicitly return an error instead of panicking with unimplemented!(), to prevent potential runtime panics.

Apply this diff to return errors:

-    unimplemented!("not supported in read-only transaction")
+    Err(Error(anyhow::anyhow!("Method not supported in read-only transaction")))

236-238: Specify Return Type for Empty Batch Creation

Ohayo, sensei! In the create_batch method of TrieDbMut, the empty implementation {} might be unclear. Consider explicitly returning a unit type () to improve readability.

Apply this diff:

-fn create_batch(&self) -> Self::Batch {}
+fn create_batch(&self) -> Self::Batch {
+    ()
+}

364-365: Remove Debugging Statements

Ohayo, sensei! There's a dbg! macro used for debugging purposes. It's recommended to remove such statements in production code to prevent unnecessary console output.

Apply this diff to remove the debug statement:

-dbg!("getting snapshot", id);
crates/katana/storage/provider/src/providers/db/state.rs (1)

364-365: Remove Debugging Statements

Ohayo, sensei! There's a dbg! macro used for debugging when getting a snapshot. It's best practice to remove or disable debugging statements in the production code.

Apply this diff to remove the debug statement:

-dbg!("getting snapshot", id);
crates/katana/storage/db/src/tables.rs (1)

56-56: Consider deriving NUM_TABLES dynamically to prevent mismatches

Ohayo, sensei! Instead of hardcoding NUM_TABLES to 33, consider computing it dynamically based on the number of entries in Tables::ALL to prevent potential mismatches if tables are added or removed in the future.

Apply this diff to compute NUM_TABLES dynamically:

-pub const NUM_TABLES: usize = 33;
+pub const NUM_TABLES: usize = {
+    let mut count = 0;
+    $(let _ = $table; count += 1;)*
+    count
+};
crates/katana/executor/src/implementation/blockifier/state.rs (2)

241-267: Handle unimplemented methods in StateProofProvider

Ohayo, sensei! The StateProofProvider methods are marked with unimplemented!() indicating they are not supported in the executor's state. If this is intentional, consider documenting this behavior to inform users. Alternatively, you could return a descriptive error to gracefully handle these unsupported methods.


269-278: Handle unimplemented methods in StateRootProvider

Ohayo, sensei! The StateRootProvider methods use unimplemented!() to indicate unsupported functionality. If these methods are not intended to be implemented, consider adding comments to explain this, or return a specific error to improve clarity for users.

crates/katana/storage/provider/src/traits/trie.rs (1)

Line range hint 11-24: Ohayo! Clean trait refactoring, sensei!

The trait renaming and method updates improve clarity while maintaining functionality. The auto_impl attribute for common smart pointers is a nice touch!

Consider adding documentation comments to explain:

  • The purpose of the trait
  • Expected behavior of each method
  • The relationship between block numbers and state updates

Here's a suggested enhancement:

+/// Trait for writing state updates to the trie structure
+/// Implementations should ensure thread-safety and proper state management
 #[auto_impl::auto_impl(&, Box, Arc)]
 pub trait TrieWriter: Send + Sync {
+    /// Inserts declared classes into the trie for a specific block
+    /// Returns the resulting state root as a Felt
     fn trie_insert_declared_classes(
         &self,
         block_number: BlockNumber,
         updates: &BTreeMap<ClassHash, CompiledClassHash>,
     ) -> ProviderResult<Felt>;

+    /// Inserts contract state updates into the trie for a specific block
+    /// Returns the resulting state root as a Felt
     fn trie_insert_contract_updates(
         &self,
         block_number: BlockNumber,
         state_updates: &StateUpdates,
     ) -> ProviderResult<Felt>;
 }
crates/katana/trie/src/id.rs (1)

1-38: Ohayo sensei! Clean implementation of CommitId for state tracking.

The implementation provides a type-safe wrapper around BlockNumber with all necessary traits and conversions. The use of big-endian byte order in to_bytes is appropriate for network protocol compatibility.

This abstraction will help enforce type safety when managing state proofs across different block numbers, which aligns well with the PR's objective of limiting proof keys.

crates/katana/trie/src/contracts.rs (1)

25-29: Consider implementing proof key limits

Given the PR objective to limit proof keys, consider adding a check in the multiproof method to enforce a maximum number of addresses.

Example implementation:

 pub fn multiproof(&mut self, addresses: Vec<ContractAddress>) -> MultiProof {
+    const MAX_PROOF_KEYS: usize = 1000; // adjust as needed
+    if addresses.len() > MAX_PROOF_KEYS {
+        panic!("Number of proof keys exceeds maximum allowed: {}", MAX_PROOF_KEYS);
+    }
     let keys = addresses.into_iter().map(Felt::from).collect::<Vec<Felt>>();
     self.trie.multiproof(Self::BONSAI_IDENTIFIER, keys)
 }
crates/katana/rpc/rpc-types-builder/src/state_update.rs (1)

33-37: Consider adding error context for better debugging

While the historical state retrieval looks good, the error message could be more specific.

-            .expect("should exist if block exists")
+            .expect("historical state should exist for existing block")
crates/dojo/test-utils/src/sequencer.rs (1)

128-128: Ohayo! LGTM, but consider adding documentation for max_proof_keys

The addition of max_proof_keys with a limit of 100 aligns well with the PR objective. However, it would be helpful to add a comment explaining the significance of this limit in the test environment.

+        /// Maximum number of keys allowed in a storage proof request
         max_proof_keys: Some(100),
crates/katana/rpc/rpc/tests/proofs.rs (2)

23-73: Ohayo sensei! Comprehensive test for proof key limits

The test effectively validates the enforcement of maximum proof keys limit by:

  1. Generating 105 keys (35 each for classes, contracts, and storages)
  2. Verifying the error response when exceeding the default limit of 100
  3. Checking both error code and detailed error data

However, consider adding edge case tests:

Consider adding test cases for:

  • Exactly at the limit (100 keys)
  • Just one over the limit (101 keys)
  • Empty key lists

75-119: Well-structured class proof verification test

The test thoroughly validates the class proof functionality by:

  1. Declaring a contract
  2. Retrieving and verifying its proof
  3. Checking against computed Poseidon hash

Consider adding assertions for:

assert!(classes_proof.nodes.len() > 0, "proof should contain nodes");
crates/katana/executor/src/implementation/noop.rs (2)

174-197: Ohayo! Clean implementation of StateProofProvider

The no-op implementation correctly returns empty proofs for all methods, maintaining consistency with the no-op pattern.

Consider adding a doc comment explaining the no-op behavior:

/// No-op implementation that returns empty proofs for all methods
impl StateProofProvider for NoopStateProvider {

199-207: Simple and consistent StateRootProvider implementation

The implementation returns Felt::ZERO for both root methods, which is consistent with the no-op pattern.

Consider adding a doc comment explaining the no-op behavior:

/// No-op implementation that returns zero for all root values
impl StateRootProvider for NoopStateProvider {
crates/katana/storage/db/src/abstraction/transaction.rs (2)

72-92: Ohayo! Well-designed reference-based transaction trait!

The DbTxRef trait elegantly mirrors the original DbTx trait while properly handling references. The Clone bound is a good choice for reference types, ensuring that the trait can be implemented safely.

This reference-based design pattern is excellent for scenarios where you need to share transaction context without transferring ownership, potentially reducing unnecessary cloning of transaction state.


130-180: Excellent implementation of the reference traits, sensei!

The implementations for both DbTxRef and DbTxMutRef follow a clean and consistent delegation pattern, properly forwarding all operations to the underlying transaction type.

This delegation pattern is a great example of the proxy pattern, providing a transparent reference-based interface while maintaining all the original functionality.

crates/katana/rpc/rpc-api/src/starknet.rs (1)

189-199: Clean addition of storage proof RPC method!

The new get_storage_proof method is well-designed with clear documentation and appropriate use of optional parameters for flexibility. The method signature aligns well with the existing API style.

The design choice to allow querying multiple types of storage proofs (classes, contracts, and storage) in a single request is efficient and user-friendly, reducing the need for multiple RPC calls.

crates/katana/core/src/backend/storage.rs (1)

48-48: Ohayo! Good trait consolidation, sensei.

The consolidation of multiple trie-related traits into a single TrieWriter trait simplifies the interface while maintaining functionality. This is a good example of the Interface Segregation Principle.

Consider documenting the rationale for this consolidation in the module-level documentation to help future maintainers understand the design decision.

Also applies to: 71-71

🛑 Comments failed to post (12)
crates/katana/storage/db/src/models/trie.rs (1)

84-85: ⚠️ Potential issue

Avoid panicking; return an error when buffer is too short, sensei

Replace panic! with an appropriate error return to allow the caller to handle the error.

Apply this diff:

 if bytes.len() < 2 + key_len {
-    panic!("Buffer too short for key length");
+    return Err(CodecError::from("Buffer too short for key length"));
 }
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

            return Err(CodecError::from("Buffer too short for key length"));
        }
crates/katana/storage/db/src/trie/snapshot.rs (4)

69-71: ⚠️ Potential issue

Handle unimplemented methods to prevent runtime panics

Ohayo, sensei! The remove_by_prefix method is unimplemented and will panic if called. If modifying the trie snapshot is unsupported, consider returning an appropriate error or documenting this limitation.


92-97: ⚠️ Potential issue

Implement or safely handle the get_by_prefix method

Ohayo, sensei! The get_by_prefix method contains a todo!() macro, which will panic at runtime. Please implement this method or handle it appropriately to prevent potential panics.


116-118: ⚠️ Potential issue

Address the unimplemented contains method

Ohayo, sensei! The contains method is currently marked with todo!(), which may lead to runtime panics if invoked. Consider implementing this method or providing a safe placeholder.


120-122: ⚠️ Potential issue

Ensure write_batch method is properly handled

Ohayo, sensei! The write_batch method is unimplemented with a message indicating that modifying the trie snapshot is not supported. To prevent unexpected behavior, consider returning an appropriate error or documenting this restriction.

crates/katana/storage/db/src/trie/mod.rs (2)

353-359: ⚠️ Potential issue

Unimplemented Merge Method

Ohayo, sensei! The merge method is marked as unimplemented!(). If merging is not yet supported, consider returning an error to handle this case gracefully and avoid potential panics.

Would you like assistance in implementing the merge method or handling the unimplemented case properly?


156-161: 🛠️ Refactor suggestion

Unimplemented Method Should Return Error Instead of Silent Success

Ohayo, sensei! The remove_by_prefix method in TrieDb returns Ok(()) without performing any action. Since this is a read-only transaction, it's better to return an error to indicate that the operation is unsupported.

Apply this diff to return an error:

-fn remove_by_prefix(&mut self, _: &DatabaseKey<'_>) -> Result<(), Self::DatabaseError> {
-    Ok(())
+fn remove_by_prefix(&mut self, _: &DatabaseKey<'_>) -> Result<(), Self::DatabaseError> {
+    Err(Error(anyhow::anyhow!("remove_by_prefix is not supported in read-only transaction")))
}

Committable suggestion skipped: line range outside the PR's diff.

crates/katana/storage/provider/src/providers/fork/state.rs (2)

126-134: 🛠️ Refactor suggestion

Clarify the implementation of StateRootProvider methods

Ohayo, sensei! The methods classes_root and contracts_root in StateRootProvider currently return Felt::ZERO. If these functionalities are not supported in ForkedStateDb, consider returning an error or using the unimplemented!() macro to indicate that these methods are not implemented, maintaining consistency with other providers.

Apply this diff to update the methods:

 fn classes_root(&self) -> ProviderResult<katana_primitives::Felt> {
-    Ok(katana_primitives::Felt::ZERO)
+    unimplemented!("not supported in forked mode")
 }

 fn contracts_root(&self) -> ProviderResult<katana_primitives::Felt> {
-    Ok(katana_primitives::Felt::ZERO)
+    unimplemented!("not supported in forked mode")
 }
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

impl StateRootProvider for ForkedStateDb {
    fn classes_root(&self) -> ProviderResult<katana_primitives::Felt> {
        unimplemented!("not supported in forked mode")
    }

    fn contracts_root(&self) -> ProviderResult<katana_primitives::Felt> {
        unimplemented!("not supported in forked mode")
    }
}

105-124: 🛠️ Refactor suggestion

Clarify the implementation of StateProofProvider methods

Ohayo, sensei! The methods class_multiproof, contract_multiproof, and storage_multiproof in StateProofProvider currently return empty MultiProof instances. If these functionalities are not supported in ForkedStateDb, consider returning an error or using the unimplemented!() macro to clearly indicate that these methods are not implemented, ensuring consistency across the codebase.

Apply this diff to update the methods:

 fn class_multiproof(&self, _: Vec<ClassHash>) -> ProviderResult<katana_trie::MultiProof> {
-    Ok(katana_trie::MultiProof(Default::default()))
+    unimplemented!("not supported in forked mode")
 }

 fn contract_multiproof(&self, _: Vec<ContractAddress>) -> ProviderResult<katana_trie::MultiProof> {
-    Ok(katana_trie::MultiProof(Default::default()))
+    unimplemented!("not supported in forked mode")
 }

 fn storage_multiproof(
     &self,
     _: ContractAddress,
     _: Vec<StorageKey>,
 ) -> ProviderResult<katana_trie::MultiProof> {
-    Ok(katana_trie::MultiProof(Default::default()))
+    unimplemented!("not supported in forked mode")
 }
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

impl StateProofProvider for ForkedStateDb {
    fn class_multiproof(&self, _: Vec<ClassHash>) -> ProviderResult<katana_trie::MultiProof> {
        unimplemented!("not supported in forked mode")
    }

    fn contract_multiproof(
        &self,
        _: Vec<ContractAddress>,
    ) -> ProviderResult<katana_trie::MultiProof> {
        unimplemented!("not supported in forked mode")
    }

    fn storage_multiproof(
        &self,
        _: ContractAddress,
        _: Vec<StorageKey>,
    ) -> ProviderResult<katana_trie::MultiProof> {
        unimplemented!("not supported in forked mode")
    }
}
crates/katana/trie/Cargo.toml (1)

20-23: 💡 Codebase verification

Ohayo sensei! Consider pinning to commit 9108a126

The branch kariy/public-path is actively maintained with recent commits (last commit on Dec 16, 2024) that make the Path struct public. For better stability, consider updating the dependency to:

git = "https://github.com/dojoengine/bonsai-trie/"
rev = "9108a1264fd82f5e68f5056f8df767042440825f"
default-features = false
features = ["std"]
🔗 Analysis chain

Ohayo sensei! Consider dependency stability risks

While the dependency configuration is clean, there are some considerations:

  1. Using a specific branch (kariy/public-path) could be unstable. Consider using a specific commit hash instead.
  2. The repository change from madara-alliance to dojoengine is significant - ensure this is an intentional migration.

Let's check the branch status:

Consider:

  • Adding a comment explaining why this specific branch is needed
  • Creating an issue to track migrating to a stable release version

Ohayo sensei! Branch exists but needs commit pinning

The branch kariy/public-path exists and is active (commit 9108a126). Let's verify if this is a recent commit and check its stability:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the branch exists and its latest commit
gh api repos/dojoengine/bonsai-trie/branches/kariy/public-path --jq '.commit.sha'

Length of output: 122


Script:

#!/bin/bash
# Check when this commit was made and if it's the latest
gh api repos/dojoengine/bonsai-trie/commits/9108a1264fd82f5e68f5056f8df767042440825f --jq '.commit.author.date'

# Check if there are newer commits on this branch
gh api repos/dojoengine/bonsai-trie/commits?sha=kariy/public-path&per_page=2 --jq '.[].sha'

Length of output: 65859

crates/katana/trie/src/contracts.rs (1)

25-29: ⚠️ Potential issue

Remove debug print statement

The dbg! macro on line 27 should not be present in production code.

 pub fn multiproof(&mut self, addresses: Vec<ContractAddress>) -> MultiProof {
     let keys = addresses.into_iter().map(Felt::from).collect::<Vec<Felt>>();
-    dbg!(&keys);
     self.trie.multiproof(Self::BONSAI_IDENTIFIER, keys)
 }
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

    pub fn multiproof(&mut self, addresses: Vec<ContractAddress>) -> MultiProof {
        let keys = addresses.into_iter().map(Felt::from).collect::<Vec<Felt>>();
        self.trie.multiproof(Self::BONSAI_IDENTIFIER, keys)
    }
crates/katana/rpc/rpc/src/starknet/read.rs (1)

271-282: ⚠️ Potential issue

Ohayo sensei! Add input validation for proof keys.

The implementation should validate the total number of requested proof keys to prevent resource exhaustion.

Consider adding validation like this:

 async fn get_storage_proof(
     &self,
     block_id: BlockIdOrTag,
     class_hashes: Option<Vec<ClassHash>>,
     contract_addresses: Option<Vec<ContractAddress>>,
     contracts_storage_keys: Option<Vec<ContractStorageKeys>>,
 ) -> RpcResult<GetStorageProofResponse> {
+    let total_keys = class_hashes.as_ref().map(|v| v.len()).unwrap_or(0)
+        + contract_addresses.as_ref().map(|v| v.len()).unwrap_or(0)
+        + contracts_storage_keys.as_ref().map(|v| v.len()).unwrap_or(0);
+    
+    if total_keys > self.config.max_proof_keys {
+        return Err(Error::from(StarknetApiError::TooManyKeys {
+            limit: self.config.max_proof_keys,
+        }));
+    }
+
     let proofs = self
         .get_proofs(block_id, class_hashes, contract_addresses, contracts_storage_keys)
         .await?;
     Ok(proofs)
 }

Committable suggestion skipped: line range outside the PR's diff.

Copy link

codecov bot commented Dec 16, 2024

Codecov Report

Attention: Patch coverage is 80.76923% with 5 lines in your changes missing coverage. Please review.

Please upload report for BASE (katana/dev@6aa41f8). Learn more about missing BASE report.

Files with missing lines Patch % Lines
crates/katana/cli/src/options.rs 33.33% 4 Missing ⚠️
crates/katana/rpc/rpc/src/starknet/mod.rs 90.00% 1 Missing ⚠️
Additional details and impacted files
@@              Coverage Diff              @@
##             katana/dev    #2814   +/-   ##
=============================================
  Coverage              ?   55.27%           
=============================================
  Files                 ?      444           
  Lines                 ?    56294           
  Branches              ?        0           
=============================================
  Hits                  ?    31119           
  Misses                ?    25175           
  Partials              ?        0           

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

@kariy kariy merged commit 3a37aae into katana/dev Dec 16, 2024
14 checks passed
@kariy kariy deleted the katana/storage-proof-endpoint-limit branch December 16, 2024 22:48
kariy added a commit that referenced this pull request Dec 16, 2024
kariy added a commit that referenced this pull request Dec 17, 2024
kariy added a commit that referenced this pull request Dec 18, 2024
kariy added a commit that referenced this pull request Dec 19, 2024
kariy added a commit that referenced this pull request Dec 20, 2024
kariy added a commit that referenced this pull request Dec 20, 2024
kariy added a commit that referenced this pull request Dec 23, 2024
kariy added a commit that referenced this pull request Dec 25, 2024
kariy added a commit that referenced this pull request Dec 31, 2024
@kariy kariy mentioned this pull request Dec 31, 2024
kariy added a commit that referenced this pull request Dec 31, 2024
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