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): added chunk size limit to events method #2644

Open
wants to merge 16 commits into
base: main
Choose a base branch
from

Conversation

PoulavBhowmick03
Copy link

@PoulavBhowmick03 PoulavBhowmick03 commented Nov 6, 2024

Description

This PR adds a Chunk Size Limit to starknet_getEvents method

Related issue

Fixes #2596

Tests

  • Yes
  • No, because they aren't needed
  • No, because I need help

Added to documentation?

  • README.md
  • Dojo Book
  • No documentation needed

Checklist

  • I've formatted my code (scripts/prettier.sh, scripts/rust_fmt.sh, scripts/cairo_fmt.sh)
  • I've linted my code (scripts/clippy.sh, scripts/docs.sh)
  • I've commented my code
  • I've requested a review after addressing the comments

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced enhanced error handling for event page size with detailed error messages.
    • Added configuration options for maximum event page size in the RPC server.
    • Enhanced the NodeArgs struct to allow configuration of maximum event page size through command line arguments.
  • Bug Fixes

    • Improved merging of command line arguments with configuration file settings for RPC options.
  • Documentation

    • Updated comments and formatting for clarity throughout the codebase.
  • Tests

    • Added new test cases to validate configuration merging behavior.

Copy link

coderabbitai bot commented Nov 6, 2024

Walkthrough

Ohayo, sensei! This pull request introduces significant changes to the StarknetApiError enum, particularly the PageSizeTooBig variant, which now includes two fields for better error reporting. Additionally, a new configuration struct, StarknetApiConfig, is introduced to manage maximum event page sizes, enhancing the validation logic in the events method. Other changes include updates to various structs and methods across the codebase to support these new configurations and error handling mechanisms.

Changes

File Path Change Summary
crates/katana/rpc/rpc-types/src/error/starknet.rs Updated StarknetApiError enum to change PageSizeTooBig to a tuple variant with requested and max_allowed fields. Modified code and data methods accordingly.
crates/katana/rpc/rpc/src/starknet/mod.rs Introduced StarknetApiConfig struct with max_event_page_size. Updated StarknetApi constructors and events method to validate chunk_size against this config.
crates/katana/node/src/config/rpc.rs Added constant DEFAULT_RPC_PAGE_SIZE and updated RpcConfig to include max_event_page_size. Updated default implementation.
crates/katana/node/src/lib.rs Introduced StarknetApiConfig in the spawn function to enhance Starknet API server configuration.
crates/katana/cli/src/args.rs Modified rpc_config method in NodeArgs to include max_event_page_size when server feature is enabled.
crates/katana/cli/src/options.rs Added constant DEFAULT_RPC_PAGE_SIZE and max_event_page_size field to ServerOptions. Updated default implementation.

Assessment against linked issues

Objective Addressed Explanation
Limit chunk size for starknet_getEvents method (2596)

Possibly related PRs

Suggested reviewers

  • steebchen: Suggested as a reviewer for their expertise in the relevant areas of the codebase.

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6d82fbd and 8772aa0.

📒 Files selected for processing (2)
  • crates/katana/rpc/rpc-types/src/error/starknet.rs (4 hunks)
  • crates/katana/rpc/rpc/src/starknet/mod.rs (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • crates/katana/rpc/rpc-types/src/error/starknet.rs
  • crates/katana/rpc/rpc/src/starknet/mod.rs

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 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: 1

🧹 Outside diff range and nitpick comments (2)
crates/katana/rpc/rpc-types/src/error/starknet.rs (2)

86-87: Ohayo sensei! Minor style improvement needed in error message.

The error message capitalization should be consistent with other variants. Consider changing "Chunk Size" to "Chunk size".

-    #[error("Chunk Size is too big")]
+    #[error("Chunk size is too big")]

86-87: Ohayo sensei! Consider standardizing size limit error handling.

For consistency in error reporting, consider:

  1. Adding similar context fields (requested/maximum) to other size-related errors like PageSizeTooBig
  2. Updating the data() method to include size information for all size-related errors

This would provide a consistent error handling pattern across all size limit validations.

Also applies to: 123-123

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7bf9be3 and 0c70748.

📒 Files selected for processing (2)
  • crates/katana/rpc/rpc-types/src/error/starknet.rs (2 hunks)
  • crates/katana/rpc/rpc/src/starknet/mod.rs (3 hunks)
🔇 Additional comments (3)
crates/katana/rpc/rpc-types/src/error/starknet.rs (1)

123-123: Ohayo sensei! The error code implementation looks good!

The error code 10001 is appropriately assigned in the custom error range (10000+), maintaining consistency with existing error codes.

crates/katana/rpc/rpc/src/starknet/mod.rs (2)

74-74: LGTM! Field addition looks good.

The max_chunk_size field is appropriately typed and well-placed within the Inner struct.


814-821: LGTM! Validation logic is robust and secure.

The chunk size validation effectively prevents DoS attacks by:

  1. Checking against the configured maximum
  2. Providing clear error context with both requested and maximum values

@@ -103,7 +104,7 @@ impl<EF: ExecutorFactory> StarknetApi<EF> {
let blocking_task_pool =
BlockingTaskPool::new().expect("failed to create blocking task pool");
let inner =
Inner { pool, backend, block_producer, blocking_task_pool, validator, forked_client };
Inner { pool, backend, block_producer, blocking_task_pool, validator, forked_client, max_chunk_size: 1000 };
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider making max_chunk_size configurable.

Ohayo sensei! The hardcoded value of 1000 should be made configurable via CLI as mentioned in issue #2596. This would allow users to adjust the limit based on their specific requirements.

Consider:

  1. Adding a CLI parameter for max chunk size
  2. Passing the configured value through the constructor
-            Inner { pool, backend, block_producer, blocking_task_pool, validator, forked_client, max_chunk_size: 1000 };
+            Inner { pool, backend, block_producer, blocking_task_pool, validator, forked_client, max_chunk_size: config.max_chunk_size };

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

@PoulavBhowmick03
Copy link
Author

@kariy Can you please take a look at this? Thanks!

Copy link
Member

@kariy kariy left a comment

Choose a reason for hiding this comment

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

looks good so far.

just need to make the value configurable from the cli.

crates/katana/rpc/rpc-types/src/error/starknet.rs Outdated Show resolved Hide resolved
crates/katana/rpc/rpc-types/src/error/starknet.rs Outdated Show resolved Hide resolved
@@ -71,6 +71,7 @@ struct Inner<EF: ExecutorFactory> {
block_producer: BlockProducer<EF>,
blocking_task_pool: BlockingTaskPool,
forked_client: Option<ForkedClient>,
max_chunk_size: u64,
Copy link
Member

Choose a reason for hiding this comment

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

lets make this field into an Option instead. also maybe lets create a config struct, StarknetApiConfig, to encapsulate this value.

Copy link
Member

Choose a reason for hiding this comment

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

we should also update all the StarknetApi::new functions to accept the new config struct

Copy link
Member

Choose a reason for hiding this comment

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

make sure to update the RpcConfig with the max_events_page_size option

/// Configuration for the RPC server.
#[derive(Debug, Clone)]
pub struct RpcConfig {
pub addr: IpAddr,
pub port: u16,
pub max_connections: u32,
pub allowed_origins: Option<Vec<String>>,
pub apis: HashSet<ApiKind>,
}

i think 'page size' is a much better name in this case. maybe we should just call it page size anywhere else and just leave the chunk size name in the server impl.

Copy link
Member

@kariy kariy left a comment

Choose a reason for hiding this comment

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

dont forget to add a test for this as well :)

@glihm glihm added katana This issue is related to Katana contributor labels Nov 7, 2024
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 (1)
crates/katana/rpc/rpc/src/starknet/mod.rs (1)

820-827: LGTM! Consider extracting validation to a method.

Ohayo sensei! The validation logic looks good and effectively prevents DoS attacks. However, consider extracting it to a separate method for better readability:

impl<EF: ExecutorFactory> StarknetApi<EF> {
+    fn validate_chunk_size(&self, chunk_size: u64) -> StarknetApiResult<()> {
+        if chunk_size > self.inner.max_chunk_size {
+            return Err(StarknetApiError::ChunkSizeTooBig {
+                requested: chunk_size,
+                maximum: self.inner.max_chunk_size,
+            });
+        }
+        Ok(())
+    }

     async fn events(&self, filter: EventFilterWithPage) -> StarknetApiResult<EventsPage> {
         let EventFilterWithPage { event_filter, result_page_request } = filter;
         let ResultPageRequest { continuation_token, chunk_size } = result_page_request;
-        let max_chunk_size = self.inner.max_chunk_size;
-        if chunk_size > max_chunk_size {
-            return Err(StarknetApiError::ChunkSizeTooBig {
-                requested: chunk_size,
-                maximum: max_chunk_size,
-            });
-        }
+        self.validate_chunk_size(chunk_size)?;
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0c70748 and 32597b7.

📒 Files selected for processing (1)
  • crates/katana/rpc/rpc/src/starknet/mod.rs (3 hunks)
🔇 Additional comments (2)
crates/katana/rpc/rpc/src/starknet/mod.rs (2)

74-74: Follow up on previous review suggestions.

Ohayo sensei! As suggested in the previous review:

  1. Consider making this field an Option<u64>
  2. Move this configuration to a dedicated StarknetApiConfig struct
  3. Rename to max_events_page_size for better clarity

107-107: Make max_chunk_size configurable via CLI.

Ohayo sensei! The hardcoded value should be configurable as mentioned in issue #2596.

@glihm glihm mentioned this pull request Nov 9, 2024
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: 2

🧹 Outside diff range and nitpick comments (6)
crates/katana/node/src/config/rpc.rs (1)

8-8: Ohayo! Add documentation for the page size constant.

The default value of 100 seems reasonable, but it would be helpful to document why this specific value was chosen and what factors were considered (e.g., memory usage, typical query patterns).

+/// Default maximum number of events that can be returned in a single page.
+/// This limit helps prevent potential DoS attacks through excessive resource consumption.
 pub const DEFAULT_RPC_PAGE_SIZE: u64 = 100;
bin/katana/src/cli/options.rs (1)

86-90: Enhance documentation for security context, sensei!

While the field is properly configured, consider adding documentation that explains its security implications:

-    /// Maximum page size for event queries.
+    /// Maximum page size for event queries to prevent potential DoS attacks.
+    /// Limits the number of events that can be returned in a single request.
crates/katana/node/src/lib.rs (2)

281-283: Consider extracting the default page size as a constant

The default value of 1000 should be defined as a named constant at the module level or in a constants module for better maintainability and documentation.

+ const DEFAULT_PAGE_SIZE: u64 = 1000;

  let starknet_api_config = StarknetApiConfig {
-     page_size: config.page_size.unwrap_or(1000), // Default value
+     page_size: config.page_size.unwrap_or(DEFAULT_PAGE_SIZE),
  };

294-294: Fix formatting: Add space after comma

There should be a space after the comma before starknet_api_config:

- StarknetApi::new(backend.clone(), pool.clone(), block_producer.clone(), validator,starknet_api_config)
+ StarknetApi::new(backend.clone(), pool.clone(), block_producer.clone(), validator, starknet_api_config)
crates/katana/rpc/rpc/src/starknet/mod.rs (2)

62-64: Add documentation for the StarknetApiConfig struct.

Ohayo sensei! Consider adding documentation to explain the purpose of this struct and its field:

+/// Configuration for the Starknet API.
 pub struct StarknetApiConfig {
+    /// Maximum number of events that can be returned in a single page.
     pub page_size: u64,
 }

836-836: Remove extra whitespace.

There's an extra blank line that should be removed to maintain consistent formatting.

-        
         self.on_io_blocking_task(move |this| {
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 32597b7 and c90845d.

📒 Files selected for processing (6)
  • bin/katana/src/cli/node.rs (1 hunks)
  • bin/katana/src/cli/options.rs (4 hunks)
  • crates/katana/node/src/config/rpc.rs (3 hunks)
  • crates/katana/node/src/lib.rs (2 hunks)
  • crates/katana/rpc/rpc-types/src/error/starknet.rs (5 hunks)
  • crates/katana/rpc/rpc/src/starknet/mod.rs (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/katana/rpc/rpc-types/src/error/starknet.rs
🔇 Additional comments (9)
crates/katana/node/src/config/rpc.rs (1)

27-27: Document the page_size field and verify its usage.

The field implementation looks good, but would benefit from documentation explaining its purpose and relationship to event queries.

✅ Verification successful

Ohayo, sensei! Document the page_size field and verify its usage.

The field implementation is correct and its usage across the codebase is consistent. Adding documentation will clarify its purpose and relationship to event queries.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify how page_size is used across the codebase

# Check for page_size usage in event-related code
rg -A 5 "page_size" --type rust

# Look for event-related structs and methods
ast-grep --pattern 'fn $name($$$) {
  $$$
  page_size
  $$$
}'

Length of output: 7385

bin/katana/src/cli/options.rs (3)

15-15: Ohayo! Import looks good, sensei!

The DEFAULT_RPC_PAGE_SIZE constant is properly imported alongside other RPC-related constants.


101-101: Default implementation is perfect, sensei!

The page_size field is properly initialized with DEFAULT_RPC_PAGE_SIZE in the Default implementation.


355-357: Helper function looks good! Let's verify the constant value, sensei!

The default_page_size function follows the established pattern for serde defaults.

✅ Verification successful

Ohayo, sensei!
The initial search didn't locate DEFAULT_RPC_PAGE_SIZE. Let's broaden our search to find where it's defined.


Ohayo, sensei!
Verified that DEFAULT_RPC_PAGE_SIZE is set to 100, which is appropriate.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the DEFAULT_RPC_PAGE_SIZE constant value is reasonable

# Search for the constant definition
rg -p "DEFAULT_RPC_PAGE_SIZE\s*=\s*\d+" crates/katana/node/src/config/rpc.rs

Length of output: 78


Script:

#!/bin/bash
# Description: Search the entire codebase for the DEFAULT_RPC_PAGE_SIZE constant definition

rg "const\s+DEFAULT_RPC_PAGE_SIZE\s*[:=]" --glob "*.rs"

Length of output: 138

crates/katana/node/src/lib.rs (2)

52-52: Ohayo sensei! LGTM - Import statement is well-placed

The import statement for StarknetApiConfig is correctly positioned with other starknet-related imports.


285-294: Verify consistent configuration usage

The changes look good, but let's verify that the page_size configuration is consistently used across the codebase.

✅ Verification successful

Consistent page_size configuration usage verified

Ohayo, sensei. The page_size configuration is consistently used throughout the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistent usage of page_size configuration

# Check for StarknetApiConfig usage
rg -A 2 "StarknetApiConfig" 

# Check for page_size references
rg "page_size" 

# Look for potential event-related pagination
ast-grep --pattern 'fn $event_method($$$) {
  $$$
  chunk_size
  $$$
}'

Length of output: 3648

bin/katana/src/cli/node.rs (1)

225-225: Verify the default page size value.

Let's ensure that a reasonable default value is set for the page size parameter.

✅ Verification successful

Ohayo sensei! Default page size is set appropriately.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for DEFAULT_RPC_PAGE_SIZE or similar constants
rg -A 1 "DEFAULT.*PAGE_SIZE|DEFAULT.*CHUNK_SIZE" 

# Search for page_size field definition in ServerOptions
ast-grep --pattern 'struct ServerOptions {
  $$$
  page_size: $_
  $$$
}'

Length of output: 2019

crates/katana/rpc/rpc/src/starknet/mod.rs (2)

79-79: LGTM! Constructor changes are well-implemented.

The changes consistently integrate the new configuration across all constructors, and the use of Option for max_chunk_size aligns with the review feedback.

Also applies to: 88-88, 99-99, 110-110, 115-115


828-835: LGTM! Chunk size validation is well-implemented.

The validation logic is correct and provides good error context by including both the requested and maximum allowed values. The check is performed early in the method, preventing unnecessary work for invalid requests.

crates/katana/node/src/config/rpc.rs Outdated Show resolved Hide resolved
bin/katana/src/cli/node.rs Outdated Show resolved Hide resolved
bin/katana/src/cli/options.rs Outdated Show resolved Hide resolved
crates/katana/node/src/config/rpc.rs Outdated Show resolved Hide resolved
crates/katana/rpc/rpc/src/starknet/mod.rs Outdated Show resolved Hide resolved
crates/katana/rpc/rpc/src/starknet/mod.rs Outdated Show resolved Hide resolved
crates/katana/rpc/rpc-types/src/error/starknet.rs Outdated Show resolved Hide resolved
crates/katana/node/src/config/rpc.rs Show resolved Hide resolved
bin/katana/src/cli/node.rs Outdated Show resolved Hide resolved
PoulavBhowmick03 and others added 6 commits November 13, 2024 17:14
Co-authored-by: Ammar Arif <evergreenkary@gmail.com>
Co-authored-by: Ammar Arif <evergreenkary@gmail.com>
Co-authored-by: Ammar Arif <evergreenkary@gmail.com>
Co-authored-by: Ammar Arif <evergreenkary@gmail.com>
Co-authored-by: Ammar Arif <evergreenkary@gmail.com>
Co-authored-by: Ammar Arif <evergreenkary@gmail.com>
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: 1

🧹 Outside diff range and nitpick comments (1)
crates/katana/rpc/rpc/src/starknet/mod.rs (1)

828-835: Consider simplifying the config access pattern.

Ohayo sensei! While the validation logic is correct, we can make it more idiomatic by using as_ref().map_or(true, |config| ...) pattern.

Consider this more concise approach:

-        if let Some(config) = self.inner.max_chunk_size.as_ref() {
-            if chunk_size > config.page_size {
-                return Err(StarknetApiError::PageSizeTooBig {
-                    requested: chunk_size,
-                    max_allowed: config.page_size,
-                });
-            }
-        }
+        if self.inner.config.max_event_page_size.as_ref().map_or(false, |&max_size| chunk_size > max_size) {
+            return Err(StarknetApiError::PageSizeTooBig {
+                requested: chunk_size,
+                max_allowed: self.inner.config.max_event_page_size.unwrap(),
+            });
+        }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between fd4c2e7 and 66bfe44.

📒 Files selected for processing (5)
  • bin/katana/src/cli/node.rs (1 hunks)
  • bin/katana/src/cli/options.rs (4 hunks)
  • crates/katana/node/src/config/rpc.rs (3 hunks)
  • crates/katana/rpc/rpc-types/src/error/starknet.rs (5 hunks)
  • crates/katana/rpc/rpc/src/starknet/mod.rs (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • bin/katana/src/cli/node.rs
  • bin/katana/src/cli/options.rs
  • crates/katana/node/src/config/rpc.rs
  • crates/katana/rpc/rpc-types/src/error/starknet.rs
🔇 Additional comments (2)
crates/katana/rpc/rpc/src/starknet/mod.rs (2)

62-64: LGTM! Clean struct definition.

The StarknetApiConfig struct with optional max_event_page_size field follows the recommended design pattern and naming convention.


79-79: LGTM! Config field added to Inner struct.

The integration of StarknetApiConfig into the Inner struct follows the suggested design pattern.

crates/katana/rpc/rpc/src/starknet/mod.rs Outdated Show resolved Hide resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@PoulavBhowmick03
Copy link
Author

@kariy can you PTAL, it is not allowing me to resolve the merge conflicts for some reason, i have made the suggested changes

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: 1

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 66bfe44 and 606a544.

📒 Files selected for processing (1)
  • crates/katana/rpc/rpc/src/starknet/mod.rs (7 hunks)
🔇 Additional comments (3)
crates/katana/rpc/rpc/src/starknet/mod.rs (3)

62-64: LGTM! Well-structured configuration struct.

Ohayo sensei! The StarknetApiConfig struct is well-designed with an optional max_event_page_size field, allowing for flexible configuration of page size limits.


79-79: LGTM! Clean integration of config field.

Ohayo sensei! The config field is properly integrated into the Inner struct.


88-88: LGTM! Consistent constructor updates.

Ohayo sensei! The constructors are consistently updated to accept and propagate the configuration parameter.

Also applies to: 99-99, 110-110, 115-115

Comment on lines 828 to 835
if let Some(config) = self.inner.max_chunk_size.as_ref() {
if chunk_size > config.page_size {
return Err(StarknetApiError::PageSizeTooBig {
requested: chunk_size,
max_allowed: config.page_size,
});
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect config field reference and error construction.

Ohayo sensei! There are two issues in the validation code:

  1. The code references self.inner.max_chunk_size instead of self.inner.config.max_event_page_size
  2. The error construction uses incorrect field names

Apply this fix:

-        if let Some(config) = self.inner.max_chunk_size.as_ref() {
-            if chunk_size > config.page_size {
+        if let Some(max_size) = self.inner.config.max_event_page_size {
+            if chunk_size > max_size {
                 return Err(StarknetApiError::PageSizeTooBig {
                     requested: chunk_size,
-                    max_allowed: config.page_size,
+                    max_allowed: max_size,
                 });
             }
         }
📝 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.

Suggested change
if let Some(config) = self.inner.max_chunk_size.as_ref() {
if chunk_size > config.page_size {
return Err(StarknetApiError::PageSizeTooBig {
requested: chunk_size,
max_allowed: config.page_size,
});
}
}
if let Some(max_size) = self.inner.config.max_event_page_size {
if chunk_size > max_size {
return Err(StarknetApiError::PageSizeTooBig {
requested: chunk_size,
max_allowed: max_size,
});
}
}

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: 1

🧹 Outside diff range and nitpick comments (2)
crates/katana/cli/src/options.rs (2)

27-27: Ohayo! The default page size looks good, sensei!

The default value of 100 for DEFAULT_RPC_PAGE_SIZE strikes a good balance between usability and security. It's large enough for typical use cases while preventing potential DoS attacks from excessive page sizes.

Consider documenting this constant in the codebase, explaining its security implications and how it helps prevent DoS attacks.


89-93: Enhance documentation for max_event_page_size field

The documentation could be more descriptive to help users understand the security implications and usage guidelines.

Consider expanding the documentation like this:

-    /// Maximum page size for event queries.
+    /// Maximum page size for event queries to prevent potential DoS attacks.
+    /// Limits the number of events that can be returned in a single query.
+    /// Default: 100 events per page
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 606a544 and 6d82fbd.

📒 Files selected for processing (5)
  • crates/katana/cli/src/args.rs (1 hunks)
  • crates/katana/cli/src/options.rs (4 hunks)
  • crates/katana/node/src/config/rpc.rs (3 hunks)
  • crates/katana/node/src/lib.rs (2 hunks)
  • crates/katana/rpc/rpc/src/starknet/mod.rs (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • crates/katana/node/src/config/rpc.rs
  • crates/katana/node/src/lib.rs
  • crates/katana/rpc/rpc/src/starknet/mod.rs
🔇 Additional comments (3)
crates/katana/cli/src/options.rs (2)

104-104: LGTM! Default implementation is correct

The default implementation properly initializes max_event_page_size with DEFAULT_RPC_PAGE_SIZE.


361-363: LGTM! Default function follows established pattern

The default_page_size function is correctly implemented and follows the same pattern as other default functions in the file.

crates/katana/cli/src/args.rs (1)

196-196: Ohayo! The RPC configuration change looks good, sensei!

The addition of max_event_page_size to the RPC configuration aligns well with the PR objective of preventing potential DoS attacks by limiting the chunk size in the starknet_getEvents method.

Let's verify that the max_event_page_size field is properly defined in the ServerOptions struct:

✅ Verification successful

Ohayo, sensei! The max_event_page_size field is properly defined in the ServerOptions struct.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence and configuration of max_event_page_size in ServerOptions

# Search for ServerOptions struct definition
rg -A 10 "struct ServerOptions"

# Search for any default implementations or constants related to max_event_page_size
rg "max_event_page_size"

Length of output: 2389

Comment on lines +89 to +93
/// Maximum page size for event queries.
#[arg(long = "rpc.max-event-page-size", value_name = "SIZE")]
#[arg(default_value_t = DEFAULT_RPC_PAGE_SIZE)]
#[serde(default = "default_page_size")]
pub max_event_page_size: u64,
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Ohayo, sensei!

max_event_page_size is not enforced in starknet_getEvents

The starknet_getEvents method does not enforce the max_event_page_size limit, which may allow potential DoS attacks.

  • File: crates/katana/rpc/rpc/src/starknet/mod.rs
🔗 Analysis chain

Verify enforcement of max_event_page_size limit

Let's ensure this limit is properly enforced in the starknet_getEvents method.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if max_event_page_size is enforced in starknet_getEvents

# Search for usage of max_event_page_size in the codebase
rg -l "max_event_page_size"

# Look for validation logic in starknet_getEvents
ast-grep --pattern 'fn events($$$) {
  $$$
}'

Length of output: 247

@glihm
Copy link
Collaborator

glihm commented Nov 13, 2024

@kariy can you PTAL, it is not allowing me to resolve the merge conflicts for some reason, i have made the suggested changes

You can always resolve merge conflicts by pulling the main branch from dojo and merging it into your branch locally. Then you push and your PR will be updated with merge conflicts revolved. 👍

** EDIT: just seen that you were able to do so, nice.

@PoulavBhowmick03 PoulavBhowmick03 changed the title Added chunk size limit to events method feat(katana): added chunk size limit to events method Nov 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
contributor katana This issue is related to Katana
Projects
None yet
Development

Successfully merging this pull request may close these issues.

feat(katana): add chunk size limit for starknet_getEvents method
3 participants