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): pool validation #2344

Merged
merged 11 commits into from
Aug 26, 2024
Merged

feat(katana): pool validation #2344

merged 11 commits into from
Aug 26, 2024

Conversation

kariy
Copy link
Member

@kariy kariy commented Aug 26, 2024

ref #2335

add a validator for validating incoming transaction on the rpc level. the validation will happen right before the transaction is added to the pool, and its result will determine whether the tx will get added to the pool or not.

before this all txs regardless of their validity are added to the pool. the validation will happen asynchronously where txs will get validated the same time as it is being executed. this happen later in the execution stage of the pipeline which is detached from the rpc side, at this point the rpc has already finished its request and has no context of the tx validity (hence what it means by asyncly).

this doesn't follow the same behaviour as mainnet, which would invalidate the txs on the rpc level. meaning if your tx, eg has invalid signatures, the sequencer would return the validation error as the response in the same add_*_transaction request you used to send the invalid tx.

this change also requires some changes on the blockifier side. added the necessary changes in a new branch blockifier:cairo-2.7-new

expected regression as now we're executing the tx 1.5 times; validation on the rpc side plus (validation + execution) on the block production side.

Summary by CodeRabbit

  • New Features

    • Enhanced transaction validation integrated with block production, utilizing a dynamic TxValidator.
    • Improved transaction pool functionality with detailed error handling and feedback on transaction addition.
    • New tests for handling rapid transaction submissions, insufficient fees, invalid signatures, and nonces.
  • Bug Fixes

    • Streamlined transaction hash handling in the Starknet API to improve clarity and efficiency.
  • Documentation

    • Added comments and improved clarity in transaction handling and validation logic.
  • Chores

    • Updated dependencies in Cargo.toml for better modularity and functionality.

@kariy kariy changed the title feat(katana): incoming tx validation feat(katana): pool validation Aug 26, 2024
Copy link

coderabbitai bot commented Aug 26, 2024

Walkthrough

Ohayo, sensei! The changes involve significant updates across multiple files in the katana project, primarily focusing on enhancing transaction validation, restructuring the BlockProducer, and improving error handling in the transaction pool. Key modifications include integrating a TxValidator for better transaction checks, updating method signatures, and refining test cases to cover various transaction scenarios.

Changes

Files and Paths Change Summary
crates/katana/core/src/service/block_producer.rs Restructured BlockProducer to include TxValidator, updated methods to reference the new structure, and modified constructors to return both producer and validator instances.
crates/katana/core/src/service/messaging/service.rs Clarified transaction handling in add_transaction method with comments and variable usage.
crates/katana/core/src/service/mod.rs Added a commented-out line for a StatefulValidator and updated validator state after metrics processing in NodeService.
crates/katana/executor/Cargo.toml Updated blockifier dependency branch from "cairo-2.7" to "cairo-2.7-new".
crates/katana/executor/benches/execution.rs Modified StateProviderDb instantiation from StateProviderDb::from(state) to StateProviderDb::new(state).
crates/katana/executor/src/abstraction/executor.rs Added execution_flags method to ExecutorFactory trait.
crates/katana/executor/src/abstraction/mod.rs Made StateProviderDb field private, replaced From trait with a new constructor.
crates/katana/executor/src/implementation/blockifier/mod.rs Re-exported blockifier crate and added execution_flags method to BlockifierFactory.
crates/katana/executor/src/implementation/blockifier/state.rs Refactored method calls on StateProviderDb and changed visibility of CachedState.
crates/katana/executor/src/implementation/blockifier/utils.rs Changed to_executor_tx function from private to public.
crates/katana/executor/src/implementation/noop.rs Added execution_flags field to NoopExecutorFactory.
crates/katana/node/src/lib.rs Replaced NoopValidator with a dynamic validator from block_producer.
crates/katana/pool/Cargo.toml Added katana-provider dependency to workspace.
crates/katana/pool/src/lib.rs Replaced NoopValidator with TxValidator, introduced PoolResult and PoolError types.
crates/katana/pool/src/pool.rs Updated add_transaction method to return PoolResult<TxHash> and expanded validation logic.
crates/katana/pool/src/tx.rs Added added_at field to PendingTx struct for timestamp tracking.
crates/katana/pool/src/validation/mod.rs Implemented transaction validation module with structured error handling and a Validator trait.
crates/katana/pool/src/validation/stateful.rs Introduced TxValidator struct with transaction validation functionalities.
crates/katana/rpc/rpc-types/Cargo.toml Added katana-pool dependency to workspace.
crates/katana/rpc/rpc-types/src/error/starknet.rs Enhanced StarknetApiError with detailed ValidationFailure structure and added error conversion implementations.
crates/katana/rpc/rpc/Cargo.toml Added indexmap and rstest dependencies to workspace.
crates/katana/rpc/rpc/src/dev.rs Changed block producer access from self.block_producer.inner to self.block_producer.producer.
crates/katana/rpc/rpc/src/saya.rs Updated block producer access similarly to dev.rs.
crates/katana/rpc/rpc/src/starknet/mod.rs Modified block producer access and introduced new logic for pending blocks.
crates/katana/rpc/rpc/src/starknet/write.rs Streamlined transaction hash handling in transaction addition methods.
crates/katana/rpc/rpc/src/torii.rs Updated block producer access in ToriiApi and ToriiApiServer.
crates/katana/rpc/rpc/tests/starknet.rs Added new test cases for various transaction scenarios, enhancing test coverage.

Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f9606d8 and c766bd3.

Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
Files selected for processing (27)
  • crates/katana/core/src/service/block_producer.rs (7 hunks)
  • crates/katana/core/src/service/messaging/service.rs (2 hunks)
  • crates/katana/core/src/service/mod.rs (2 hunks)
  • crates/katana/executor/Cargo.toml (1 hunks)
  • crates/katana/executor/benches/execution.rs (1 hunks)
  • crates/katana/executor/src/abstraction/executor.rs (1 hunks)
  • crates/katana/executor/src/abstraction/mod.rs (1 hunks)
  • crates/katana/executor/src/implementation/blockifier/mod.rs (3 hunks)
  • crates/katana/executor/src/implementation/blockifier/state.rs (8 hunks)
  • crates/katana/executor/src/implementation/blockifier/utils.rs (1 hunks)
  • crates/katana/executor/src/implementation/noop.rs (2 hunks)
  • crates/katana/node/src/lib.rs (3 hunks)
  • crates/katana/pool/Cargo.toml (1 hunks)
  • crates/katana/pool/src/lib.rs (2 hunks)
  • crates/katana/pool/src/pool.rs (10 hunks)
  • crates/katana/pool/src/tx.rs (3 hunks)
  • crates/katana/pool/src/validation/mod.rs (1 hunks)
  • crates/katana/pool/src/validation/stateful.rs (1 hunks)
  • crates/katana/rpc/rpc-types/Cargo.toml (1 hunks)
  • crates/katana/rpc/rpc-types/src/error/starknet.rs (7 hunks)
  • crates/katana/rpc/rpc/Cargo.toml (1 hunks)
  • crates/katana/rpc/rpc/src/dev.rs (1 hunks)
  • crates/katana/rpc/rpc/src/saya.rs (1 hunks)
  • crates/katana/rpc/rpc/src/starknet/mod.rs (2 hunks)
  • crates/katana/rpc/rpc/src/starknet/write.rs (3 hunks)
  • crates/katana/rpc/rpc/src/torii.rs (3 hunks)
  • crates/katana/rpc/rpc/tests/starknet.rs (3 hunks)
Files skipped from review due to trivial changes (3)
  • crates/katana/core/src/service/messaging/service.rs
  • crates/katana/pool/Cargo.toml
  • crates/katana/rpc/rpc/Cargo.toml
Additional comments not posted (69)
crates/katana/rpc/rpc-types/Cargo.toml (1)

12-12: Ohayo, sensei! Dependency addition looks good.

The addition of katana-pool as a dependency is straightforward and should enhance the project's capabilities.

crates/katana/executor/Cargo.toml (1)

18-18: Ohayo, sensei! Dependency update looks good.

The update to the blockifier dependency branch is straightforward and should incorporate any new enhancements or fixes from the new branch.

crates/katana/pool/src/lib.rs (5)

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

The import of TxValidator is necessary for the new validation mechanism and is correctly added.


19-19: Ohayo, sensei! Type alias addition looks good.

The addition of the TxPool type alias, which uses TxValidator, is necessary for the new validation mechanism and is correctly added.


21-21: Ohayo, sensei! Type alias addition looks good.

The addition of the PoolResult type alias is necessary for the new error handling mechanism and is correctly added.


23-29: Ohayo, sensei! Enum addition looks good.

The addition of the PoolError enum is necessary for the new error handling mechanism and is correctly added.


44-44: Ohayo, sensei! Method signature modification looks good.

The modification of the add_transaction method signature to return PoolResult<TxHash> is necessary for the new error handling mechanism and is correctly added.

crates/katana/executor/benches/execution.rs (1)

48-48: Ohayo, sensei! Verify the correctness of the new method usage.

The change from StateProviderDb::from(state) to StateProviderDb::new(state) might affect the initialization logic or underlying behavior. Ensure that the new method is correctly used and does not introduce any issues.

Run the following script to verify the implementation of StateProviderDb::new:

crates/katana/executor/src/abstraction/executor.rs (1)

31-33: LGTM, sensei!

The addition of the execution_flags method enhances the functionality of the ExecutorFactory trait by providing additional information regarding the execution context.

The code changes are approved.

crates/katana/rpc/rpc/src/dev.rs (1)

24-24: Ohayo, sensei! Verify the correctness of the new field usage.

The change from self.block_producer.inner.read() to self.block_producer.producer.read() suggests a potential restructuring of the block_producer component. Ensure that the new field producer is correctly used and does not introduce any issues.

Run the following script to verify the implementation of the BlockProducer struct:

crates/katana/rpc/rpc/src/starknet/write.rs (3)

26-28: Ohayo, sensei! LGTM!

The function is correctly implemented, with the transaction hash being directly retrieved from the add_transaction method.


48-50: Ohayo, sensei! LGTM!

The function is correctly implemented, with the transaction hash being directly retrieved from the add_transaction method.


68-70: Ohayo, sensei! LGTM!

The function is correctly implemented, with the transaction hash being directly retrieved from the add_transaction method.

crates/katana/executor/src/implementation/noop.rs (1)

58-60: Ohayo, sensei! LGTM!

The function is correctly implemented, providing access to the execution_flags field.

crates/katana/rpc/rpc/src/saya.rs (1)

47-47: Ohayo, sensei! LGTM!

The function is correctly implemented, with the adjustment to access self.block_producer.producer.read().

crates/katana/pool/src/validation/mod.rs (3)

71-85: LGTM!

The Validator trait is well-defined and follows good practices.


87-106: LGTM!

The ValidationOutcome enum is comprehensive and covers various scenarios.


108-130: LGTM!

The NoopValidator struct and its implementation are straightforward and follow good practices.

crates/katana/core/src/service/mod.rs (2)

47-47: LGTM!

The commented-out StatefulValidator line suggests future plans for validation integration.


103-104: LGTM!

The update_validator call ensures the validator's state is updated with the service's operational metrics.

crates/katana/pool/src/tx.rs (3)

1-2: LGTM!

The import of std::time::Instant is necessary for the new added_at field.


60-65: LGTM!

The new added_at field enhances the struct's capability to manage transaction timing.


74-79: LGTM!

The Clone implementation ensures that cloned instances retain the timestamp of their creation.

crates/katana/executor/src/abstraction/mod.rs (2)

152-152: Ohayo, sensei! Good encapsulation practice.

The removal of pub(crate) enhances encapsulation by restricting direct access to the underlying state provider.

The code changes are approved.


154-155: Ohayo, sensei! Clearer instantiation method.

The new constructor method new simplifies instantiation and clarifies the API's intent.

The code changes are approved.

crates/katana/pool/src/validation/stateful.rs (2)

1-30: Ohayo, sensei! Imports and struct definition look good.

The imports are necessary and the TxValidator struct is well-defined with relevant fields.

The code changes are approved.


154-206: Ohayo, sensei! Error mapping looks good.

The map_invalid_tx_err function is well-implemented and correctly maps different transaction errors.

The code changes are approved.

crates/katana/executor/src/implementation/blockifier/mod.rs (3)

1-2: Ohayo, sensei! Re-exporting blockifier enhances accessibility.

The re-export allows users to directly utilize blockifier functionalities from the module's public interface.

The code changes are approved.


70-73: Ohayo, sensei! New method enhances configurability.

The execution_flags method provides access to the execution flags set by the factory, enhancing configurability and usability.

The code changes are approved.


94-94: Ohayo, sensei! Improved state initialization.

The update to create a new instance of StateProviderDb using a constructor method suggests an improvement in state initialization and management.

The code changes are approved.

crates/katana/rpc/rpc/src/torii.rs (2)

58-58: LGTM!

The change from inner to producer is clear and maintains the existing control flow.

The code changes are approved.


155-155: LGTM!

The change from inner to producer is clear and maintains the existing control flow.

The code changes are approved.

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

168-168: LGTM!

The initialization of the transaction pool and miner is clear and logical.

The code changes are approved.


169-169: LGTM!

The new line improves readability.

The code changes are approved.


170-170: LGTM!

Retrieving the validator from the block producer enhances the flexibility of the transaction pool's validation mechanism.

The code changes are approved.


171-171: LGTM!

The initialization of the transaction pool with the validator and FiFo ordering is clear and logical.

The code changes are approved.


172-172: LGTM!

The initialization of the transaction miner with a listener from the transaction pool is clear and logical.

The code changes are approved.

crates/katana/rpc/rpc-types/src/error/starknet.rs (6)

4-4: LGTM!

The import for InvalidTransactionError is necessary for the new error handling functionality.

The code changes are approved.


5-5: LGTM!

The import for PoolError is necessary for the new error handling functionality.

The code changes are approved.


58-58: LGTM!

The modification to include a reason field in the ValidationFailure variant enhances error reporting.

The code changes are approved.


106-106: LGTM!

The update to the code method ensures correct handling of the new ValidationFailure variant.

The code changes are approved.


128-132: LGTM!

The update to the data method ensures correct handling of the new ValidationFailure variant.

The code changes are approved.


166-189: LGTM!

The implementations of From<PoolError> and From<Box<InvalidTransactionError>> for StarknetApiError enhance error handling by providing a mechanism to seamlessly convert errors from the pool and transaction validation layers into the API error type.

The code changes are approved.

crates/katana/pool/src/pool.rs (3)

96-137: Ohayo, sensei! Great job on enhancing the add_transaction function.

The changes improve transaction validation and error handling. The function now returns a PoolResult<TxHash>, which is a significant improvement. Logging for received and invalid transactions adds valuable traceability.

The code changes are approved.


104-132: Ohayo, sensei! The validation outcomes handling is well-structured.

The function correctly handles Valid, Invalid, and Dependent outcomes, providing clear feedback on transaction validation failures. The introduction of a new error type for dependent transactions is a good addition.

The code changes are approved.


117-137: Ohayo, sensei! The error handling is robust and clear.

The function logs errors for invalid transactions and returns appropriate errors. The InvalidTransactionError and the new error type for dependent transactions provide clear feedback on validation failures.

The code changes are approved.

crates/katana/rpc/rpc/tests/starknet.rs (4)

232-279: Ohayo, sensei! The rapid_transactions_submissions test is well-structured.

The function effectively tests the scenario of rapid transaction submissions, ensuring that the correct number of transactions is submitted and that the nonce is incremented appropriately.

The code changes are approved.


288-353: Ohayo, sensei! The send_txs_with_insufficient_fee test is well-structured.

The function effectively tests the scenario of transactions with insufficient fees, ensuring that the expected errors are checked and that the nonce remains unchanged for invalid transactions.

The code changes are approved.


355-412: Ohayo, sensei! The send_txs_with_invalid_signature test is well-structured.

The function effectively tests the scenario of transactions with invalid signatures, ensuring that the nonce is only incremented for valid transactions.

The code changes are approved.


414-483: Ohayo, sensei! The send_txs_with_invalid_nonces test is well-structured.

The function effectively tests the scenario of transactions with invalid nonces, ensuring that invalid transactions do not change the nonce, while valid transactions do.

The code changes are approved.

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

134-137: Ohayo, sensei! The pending_executor function update is a good improvement.

The change to reference self.inner.block_producer.producer.read() improves consistency in accessing the block producer's state.

The code changes are approved.


294-303: Ohayo, sensei! The nonce_at function update is a good enhancement.

The change introduces a new pathway for handling pending blocks, improving nonce management within the Starknet API.

The code changes are approved.

crates/katana/executor/src/implementation/blockifier/state.rs (6)

30-30: LGTM!

The change improves readability by making it clear that StateProviderDb is being used directly.

The code changes are approved.


54-54: LGTM!

The change improves readability by making it clear that StateProviderDb is being used directly.

The code changes are approved.


69-69: LGTM!

The change improves readability by making it clear that StateProviderDb is being used directly.

The code changes are approved.


79-79: LGTM!

The change improves readability by making it clear that StateProviderDb is being used directly.

The code changes are approved.


86-86: LGTM!

The change broadens the accessibility of CachedState, allowing it to be used outside of its original module.

The code changes are approved.


285-285: LGTM!

The change improves clarity regarding the initialization process of StateProviderDb instances.

The code changes are approved.

crates/katana/core/src/service/block_producer.rs (10)

12-12: LGTM!

The import is necessary for the introduction of transaction validation.

The code changes are approved.


76-80: LGTM!

The changes enhance the functionality of the block production system by integrating transaction validation.

The code changes are approved.


86-87: LGTM!

The change ensures that the TxValidator is always in sync with the block producer's state.

The code changes are approved.


93-94: LGTM!

The change ensures that the TxValidator is always in sync with the block producer's state.

The code changes are approved.


100-101: LGTM!

The change ensures that the TxValidator is always in sync with the block producer's state.

The code changes are approved.


105-105: LGTM!

The change aligns the method with the updated structure of BlockProducer.

The code changes are approved.


114-114: LGTM!

The change aligns the method with the updated structure of BlockProducer.

The code changes are approved.


119-119: LGTM!

The change aligns the method with the updated structure of BlockProducer.

The code changes are approved.


132-134: LGTM!

The method provides external access to the TxValidator.

The code changes are approved.


136-161: LGTM!

The method updates the state of the TxValidator based on the current block producer's state.

The code changes are approved.

crates/katana/executor/src/implementation/blockifier/utils.rs (1)

182-182: LGTM!

The change allows to_executor_tx to be accessible from outside its defining module, enhancing its usability.

The code changes are approved.


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

crates/katana/pool/src/validation/mod.rs Show resolved Hide resolved
crates/katana/pool/src/validation/mod.rs Show resolved Hide resolved
Comment on lines +62 to +121
#[allow(missing_debug_implementations)]
struct StatefulValidatorAdapter {
inner: StatefulValidator<StateProviderDb<'static>>,
}

impl StatefulValidatorAdapter {
fn new(
state: Box<dyn StateProvider>,
block_env: &BlockEnv,
cfg_env: &CfgEnv,
) -> StatefulValidatorAdapter {
let inner = Self::new_inner(state, block_env, cfg_env);
Self { inner }
}

fn new_inner(
state: Box<dyn StateProvider>,
block_env: &BlockEnv,
cfg_env: &CfgEnv,
) -> StatefulValidator<StateProviderDb<'static>> {
let state = CachedState::new(StateProviderDb::new(state));
let block_context = block_context_from_envs(block_env, cfg_env);
StatefulValidator::create(state, block_context)
}

/// Used only in the [`Validator::validate`] trait
fn validate(
&mut self,
tx: ExecutableTxWithHash,
skip_validate: bool,
skip_fee_check: bool,
) -> ValidationResult<ExecutableTxWithHash> {
match to_executor_tx(tx.clone()) {
Transaction::AccountTransaction(blockifier_tx) => {
// Check if the transaction nonce is higher than the current account nonce,
// if yes, dont't run its validation logic but tag it as dependent
let account = to_blk_address(tx.sender());
let account_nonce = self.inner.get_nonce(account).expect("state err");

if tx.nonce() > account_nonce.0 {
return Ok(ValidationOutcome::Dependent {
current_nonce: account_nonce.0,
tx_nonce: tx.nonce(),
tx,
});
}

match self.inner.perform_validations(blockifier_tx, skip_validate, skip_fee_check) {
Ok(()) => Ok(ValidationOutcome::Valid(tx)),
Err(e) => match map_invalid_tx_err(e) {
Ok(error) => Ok(ValidationOutcome::Invalid { tx, error }),
Err(error) => Err(Error { hash: tx.hash, error }),
},
}
}

// we skip validation for L1HandlerTransaction
Transaction::L1HandlerTransaction(_) => Ok(ValidationOutcome::Valid(tx)),
}
}
Copy link

Choose a reason for hiding this comment

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

Ohayo, sensei! Consider improving error handling in validate.

The validate method uses expect which could cause a panic. Consider handling the error more gracefully.

Apply this diff to improve error handling:

- let account_nonce = self.inner.get_nonce(account).expect("state err");
+ let account_nonce = self.inner.get_nonce(account).unwrap_or_else(|_| {
+     panic!("Failed to get nonce for account: {:?}", account);
+ });

Committable suggestion was skipped due to low confidence.

Comment on lines +124 to +151
impl Validator for TxValidator {
type Transaction = ExecutableTxWithHash;

fn validate(&self, tx: Self::Transaction) -> ValidationResult<Self::Transaction> {
let this = &mut *self.validator.lock();

// Check if validation of an invoke transaction should be skipped due to deploy_account not
// being proccessed yet. This feature is used to improve UX for users sending
// deploy_account + invoke at once.
let skip_validate = match tx.transaction {
// we skip validation for invoke tx with nonce 1 and nonce 0 in the state, this
ExecutableTx::DeployAccount(_) | ExecutableTx::Declare(_) => false,

// we skip validation for invoke tx with nonce 1 and nonce 0 in the state, this
_ => {
let address = to_blk_address(tx.sender());
let account_nonce = this.inner.get_nonce(address).expect("state err");
tx.nonce() == Nonce::ONE && account_nonce.0 == Nonce::ZERO
}
};

StatefulValidatorAdapter::validate(
this,
tx,
self.execution_flags.skip_validate || skip_validate,
self.execution_flags.skip_fee_transfer,
)
}
Copy link

Choose a reason for hiding this comment

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

Ohayo, sensei! Consider improving error handling in the validate method.

The validate method uses expect which could cause a panic. Consider handling the error more gracefully.

Apply this diff to improve error handling:

- let account_nonce = this.inner.get_nonce(address).expect("state err");
+ let account_nonce = this.inner.get_nonce(address).unwrap_or_else(|_| {
+     panic!("Failed to get nonce for address: {:?}", address);
+ });

Committable suggestion was skipped due to low confidence.

Comment on lines +32 to +59
impl TxValidator {
pub fn new(
state: Box<dyn StateProvider>,
execution_flags: SimulationFlag,
cfg_env: CfgEnv,
block_env: &BlockEnv,
) -> Self {
let inner = StatefulValidatorAdapter::new(state, block_env, &cfg_env);
Self { cfg_env, execution_flags, validator: Arc::new(Mutex::new(inner)) }
}

/// Reset the state of the validator with the given params. This method is used to update the
/// validator's state with a new state and block env after a block is mined.
pub fn update(&self, state: Box<dyn StateProvider>, block_env: &BlockEnv) {
let updated = StatefulValidatorAdapter::new(state, block_env, &self.cfg_env);
*self.validator.lock() = updated;
}

// NOTE:
// If you check the get_nonce method of StatefulValidator in blockifier, under the hood it
// unwraps the Option to get the state of the TransactionExecutor struct. StatefulValidator
// guaranteees that the state will always be present so it is safe to uwnrap. However, this
// safety is not guaranteed by TransactionExecutor itself.
pub fn get_nonce(&self, address: ContractAddress) -> Nonce {
let address = to_blk_address(address);
let nonce = self.validator.lock().inner.get_nonce(address).expect("state err");
nonce.0
}
Copy link

Choose a reason for hiding this comment

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

Ohayo, sensei! Consider improving error handling in get_nonce.

The get_nonce method uses expect which could cause a panic. Consider handling the error more gracefully.

Apply this diff to improve error handling:

- let nonce = self.validator.lock().inner.get_nonce(address).expect("state err");
+ let nonce = self.validator.lock().inner.get_nonce(address).unwrap_or_else(|_| {
+     panic!("Failed to get nonce for address: {:?}", address);
+ });
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
impl TxValidator {
pub fn new(
state: Box<dyn StateProvider>,
execution_flags: SimulationFlag,
cfg_env: CfgEnv,
block_env: &BlockEnv,
) -> Self {
let inner = StatefulValidatorAdapter::new(state, block_env, &cfg_env);
Self { cfg_env, execution_flags, validator: Arc::new(Mutex::new(inner)) }
}
/// Reset the state of the validator with the given params. This method is used to update the
/// validator's state with a new state and block env after a block is mined.
pub fn update(&self, state: Box<dyn StateProvider>, block_env: &BlockEnv) {
let updated = StatefulValidatorAdapter::new(state, block_env, &self.cfg_env);
*self.validator.lock() = updated;
}
// NOTE:
// If you check the get_nonce method of StatefulValidator in blockifier, under the hood it
// unwraps the Option to get the state of the TransactionExecutor struct. StatefulValidator
// guaranteees that the state will always be present so it is safe to uwnrap. However, this
// safety is not guaranteed by TransactionExecutor itself.
pub fn get_nonce(&self, address: ContractAddress) -> Nonce {
let address = to_blk_address(address);
let nonce = self.validator.lock().inner.get_nonce(address).expect("state err");
nonce.0
}
impl TxValidator {
pub fn new(
state: Box<dyn StateProvider>,
execution_flags: SimulationFlag,
cfg_env: CfgEnv,
block_env: &BlockEnv,
) -> Self {
let inner = StatefulValidatorAdapter::new(state, block_env, &cfg_env);
Self { cfg_env, execution_flags, validator: Arc::new(Mutex::new(inner)) }
}
/// Reset the state of the validator with the given params. This method is used to update the
/// validator's state with a new state and block env after a block is mined.
pub fn update(&self, state: Box<dyn StateProvider>, block_env: &BlockEnv) {
let updated = StatefulValidatorAdapter::new(state, block_env, &self.cfg_env);
*self.validator.lock() = updated;
}
// NOTE:
// If you check the get_nonce method of StatefulValidator in blockifier, under the hood it
// unwraps the Option to get the state of the TransactionExecutor struct. StatefulValidator
// guaranteees that the state will always be present so it is safe to uwnrap. However, this
// safety is not guaranteed by TransactionExecutor itself.
pub fn get_nonce(&self, address: ContractAddress) -> Nonce {
let address = to_blk_address(address);
let nonce = self.validator.lock().inner.get_nonce(address).unwrap_or_else(|_| {
panic!("Failed to get nonce for address: {:?}", address);
});
nonce.0
}

Copy link

codecov bot commented Aug 26, 2024

Codecov Report

Attention: Patch coverage is 80.00000% with 63 lines in your changes missing coverage. Please review.

Project coverage is 67.50%. Comparing base (a3ddf39) to head (c766bd3).
Report is 5 commits behind head on main.

Files Patch % Lines
crates/katana/pool/src/pool.rs 54.76% 19 Missing ⚠️
crates/katana/pool/src/validation/mod.rs 35.29% 11 Missing ⚠️
...rates/katana/core/src/service/messaging/service.rs 0.00% 8 Missing ⚠️
crates/katana/pool/src/tx.rs 14.28% 6 Missing ⚠️
crates/katana/pool/src/validation/stateful.rs 94.69% 6 Missing ⚠️
crates/katana/core/src/service/block_producer.rs 94.36% 4 Missing ⚠️
crates/katana/executor/src/implementation/noop.rs 0.00% 3 Missing ⚠️
crates/katana/rpc/rpc-types/src/error/starknet.rs 83.33% 3 Missing ⚠️
crates/katana/rpc/rpc/src/starknet/write.rs 66.66% 2 Missing ⚠️
crates/katana/pool/src/lib.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2344      +/-   ##
==========================================
+ Coverage   67.26%   67.50%   +0.24%     
==========================================
  Files         357      359       +2     
  Lines       46634    46836     +202     
==========================================
+ Hits        31367    31616     +249     
+ Misses      15267    15220      -47     

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

@kariy kariy merged commit 419d1cf into main Aug 26, 2024
15 checks passed
@kariy kariy deleted the katana/pool-validation branch August 26, 2024 17:41
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