Skip to content

Modify block abortion [breaking]#814

Merged
FabijanC merged 4 commits intomainfrom
modify-block-abort
Jul 21, 2025
Merged

Modify block abortion [breaking]#814
FabijanC merged 4 commits intomainfrom
modify-block-abort

Conversation

@FabijanC
Copy link
Copy Markdown
Contributor

@FabijanC FabijanC commented Jul 21, 2025

Usage related changes

  • Breaking change:
    • Block abortion now completely removes from memory targeted blocks and their transactions
    • If invoking with block_id set to an aborted block, an error is returned with message: No block found.
  • Bugfix in block abortion: fix next block number after block abortion.
  • Improvements:
    • Removed redundant checks
    • Remove aborted state from historic states, too
  • Rationale: Starknet 0.14 (and RPC 0.9) no longer has block status REJECTED

Development related changes

  • Reduce line count in setting gas prices in generating pre-confirmed block.
  • Rename method for next block number to reflect the fact it's for the latest block.
  • Split block abortion test into two: one for state, one for block number.

Checklist:

  • Checked out the contribution guidelines
  • Applied formatting - ./scripts/format.sh
  • No linter errors - ./scripts/clippy_check.sh
  • No unused dependencies - ./scripts/check_unused_deps.sh
  • No spelling errors - ./scripts/check_spelling.sh
  • Performed code self-review
  • Rebased to the latest commit of the target branch (or merged it into my branch)
    • Once you make the PR reviewable, please avoid force-pushing
  • Updated the docs if needed - ./website/README.md
  • Linked the issues resolvable by this PR - linking info
  • Updated the tests if needed; all passing - execution info

Summary by CodeRabbit

  • New Features

    • Added ability to retrieve the last aborted block hash.
    • Improved block and transaction removal processes for aborted blocks.
  • Bug Fixes

    • Aborted blocks and their transactions are now completely removed and are no longer queryable.
    • Block number reporting is updated correctly after aborting blocks.
  • Tests

    • Enhanced and expanded tests to verify correct handling of aborted blocks, including state and block number updates.
    • Updated error expectations in tests to reflect new behavior for aborted and rejected blocks.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Jul 21, 2025

Walkthrough

This set of changes refactors the handling of block abortion and block number management in the Starknet Devnet codebase. The next_block_number method is replaced with next_latest_block_number, and new remove methods are introduced for both blocks and transactions to fully remove aborted blocks and their transactions from internal collections. The abort logic is reworked to ensure that aborted blocks and their transactions are no longer queryable and are instead treated as non-existent. The test suite is updated to reflect these semantics, shifting assertions from expecting "REJECTED" statuses to expecting "not found" errors for aborted blocks and transactions. Additional tests are added to verify correct state and block number behavior after aborting blocks.

Estimated code review effort

4 (60–120 minutes)

Possibly related PRs

  • 0xSpaceShard/starknet-devnet#802: Removes next_block_number and introduces remove and next_latest_block_number methods in StarknetBlocks, directly affecting the same core logic as this PR.
  • 0xSpaceShard/starknet-devnet#810: Modifies block lifecycle methods, including changes to abort_blocks and block status handling, which overlaps with the abort block logic refactoring in this PR.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@FabijanC
Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Jul 21, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown

@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 comments (1)
crates/starknet-devnet-core/src/starknet/mod.rs (1)

916-1005: Excellent refactoring of block abortion logic.

The new implementation correctly removes blocks and transactions from memory instead of marking them as rejected, which aligns with the PR objectives. The code properly handles state reversion, block number updates, and maintains the aborted blocks history.

However, consider improving error handling for edge cases:

-            let aborted_block = self.blocks.remove(&next_block_to_abort_hash).ok_or(
-                Error::UnexpectedInternalError {
-                    msg: format!("Cannot find block for abortion: {next_block_to_abort_hash:#x}"),
-                },
-            )?;
+            let aborted_block = match self.blocks.remove(&next_block_to_abort_hash) {
+                Some(block) => block,
+                None => {
+                    // This could happen if the block was already removed in a previous operation
+                    // Log the error and continue with remaining blocks
+                    error!("Block {next_block_to_abort_hash:#x} not found for abortion");
+                    continue;
+                }
+            };

This would make the abortion process more resilient to edge cases where blocks might have been removed by other operations.

🧹 Nitpick comments (1)
crates/starknet-devnet-core/src/starknet/mod.rs (1)

600-613: Good refactoring to reduce repeated method calls.

Using a local reference to gas_prices improves readability and reduces redundant calls.

Consider extracting the gas price assignment logic into a helper method to reduce duplication with the similar code in generate_pre_confirmed_block (lines 328-335):

+fn set_block_gas_prices(block: &mut StarknetBlock, gas_prices: &GasPrices) {
+    let header = &mut block.header.block_header_without_hash;
+    header.l1_gas_price = GasPricePerToken {
+        price_in_fri: gas_prices.l1_gas_price(&FeeType::Strk).get(),
+        price_in_wei: gas_prices.l1_gas_price(&FeeType::Eth).get(),
+    };
+    header.l1_data_gas_price = GasPricePerToken {
+        price_in_fri: gas_prices.l1_data_gas_price(&FeeType::Strk).get(),
+        price_in_wei: gas_prices.l1_data_gas_price(&FeeType::Eth).get(),
+    };
+    header.l2_gas_price = GasPricePerToken {
+        price_in_fri: gas_prices.l2_gas_price(&FeeType::Strk).get(),
+        price_in_wei: gas_prices.l2_gas_price(&FeeType::Eth).get(),
+    };
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0747e22 and 1792eca.

📒 Files selected for processing (6)
  • crates/starknet-devnet-core/src/blocks/mod.rs (1 hunks)
  • crates/starknet-devnet-core/src/starknet/mod.rs (6 hunks)
  • crates/starknet-devnet-core/src/transactions.rs (1 hunks)
  • crates/starknet-devnet-server/src/api/json_rpc/mod.rs (1 hunks)
  • tests/integration/test_abort_blocks.rs (8 hunks)
  • tests/integration/test_accepting_blocks_on_l1.rs (1 hunks)
🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
Learnt from: FabijanC
PR: 0xSpaceShard/starknet-devnet#755
File: crates/starknet-devnet-server/test_data/spec/0.8.1/starknet_executables.json:1154-1168
Timestamp: 2025-04-14T09:33:59.391Z
Learning: FabijanC wants to configure CodeRabbit to ignore spec files from review, specifically the JSON schema files in the test_data/spec directory.
tests/integration/test_accepting_blocks_on_l1.rs (1)

Learnt from: FabijanC
PR: #799
File: crates/starknet-devnet-core/src/starknet/mod.rs:240-246
Timestamp: 2025-06-16T07:35:24.725Z
Learning: In the Starknet devnet codebase, get_class_hash_at has different behaviors at different layers: at the internal state level (blockifier), it returns Ok(ClassHash(Felt::ZERO)) for undeployed addresses, while at the RPC layer, this gets converted to Err(Error::ContractNotFound). When checking if a contract is deployed at the internal state level, use is_ok_and(|h| h.0 == Felt::ZERO) to detect undeployed addresses.

crates/starknet-devnet-core/src/blocks/mod.rs (1)

Learnt from: FabijanC
PR: #799
File: crates/starknet-devnet-core/src/starknet/mod.rs:240-246
Timestamp: 2025-06-16T07:35:24.725Z
Learning: In the Starknet devnet codebase, get_class_hash_at has different behaviors at different layers: at the internal state level (blockifier), it returns Ok(ClassHash(Felt::ZERO)) for undeployed addresses, while at the RPC layer, this gets converted to Err(Error::ContractNotFound). When checking if a contract is deployed at the internal state level, use is_ok_and(|h| h.0 == Felt::ZERO) to detect undeployed addresses.

tests/integration/test_abort_blocks.rs (1)

Learnt from: FabijanC
PR: #799
File: crates/starknet-devnet-core/src/starknet/mod.rs:240-246
Timestamp: 2025-06-16T07:35:24.725Z
Learning: In the Starknet devnet codebase, get_class_hash_at has different behaviors at different layers: at the internal state level (blockifier), it returns Ok(ClassHash(Felt::ZERO)) for undeployed addresses, while at the RPC layer, this gets converted to Err(Error::ContractNotFound). When checking if a contract is deployed at the internal state level, use is_ok_and(|h| h.0 == Felt::ZERO) to detect undeployed addresses.

crates/starknet-devnet-core/src/starknet/mod.rs (1)

Learnt from: FabijanC
PR: #799
File: crates/starknet-devnet-core/src/starknet/mod.rs:240-246
Timestamp: 2025-06-16T07:35:24.725Z
Learning: In the Starknet devnet codebase, get_class_hash_at has different behaviors at different layers: at the internal state level (blockifier), it returns Ok(ClassHash(Felt::ZERO)) for undeployed addresses, while at the RPC layer, this gets converted to Err(Error::ContractNotFound). When checking if a contract is deployed at the internal state level, use is_ok_and(|h| h.0 == Felt::ZERO) to detect undeployed addresses.

🧬 Code Graph Analysis (1)
crates/starknet-devnet-core/src/transactions.rs (1)
crates/starknet-devnet-core/src/blocks/mod.rs (1)
  • remove (186-193)
🔇 Additional comments (16)
crates/starknet-devnet-core/src/transactions.rs (1)

38-40: LGTM! Clean implementation of transaction removal.

The remove method is well-implemented using shift_remove to maintain ordering and follows standard Rust patterns with Option<T> return type. This supports the new block abortion behavior where transactions are completely removed rather than marked as rejected.

tests/integration/test_accepting_blocks_on_l1.rs (1)

208-208: Correctly updated assertion to reflect new block abortion behavior.

The error message change from "Rejected block cannot be accepted on L1" to "No block found" accurately reflects the new behavior where aborted blocks are completely removed from storage rather than being marked as rejected. This ensures the test validates the correct post-abortion semantics.

crates/starknet-devnet-core/src/blocks/mod.rs (2)

186-193: Well-implemented block removal with comprehensive cleanup.

The remove method correctly removes a block and all associated data (state, state diff, block mapping, and number mapping) from internal collections. Using the ? operator ensures atomic behavior - if any removal fails, the entire operation returns None. The use of shift_remove maintains ordering consistency.


195-196: Clean replacement for the removed next_block_number method.

The next_latest_block_number method provides a clear, focused interface for getting the next block number from the pre-confirmed block, which aligns with the refactored block number management approach.

crates/starknet-devnet-server/src/api/json_rpc/mod.rs (2)

405-410: LGTM! Proper error handling for the new approach.

The error handling correctly addresses the case where last_aborted_block_hash() returns None, which would indicate an unexpected internal state during a reorg scenario.


413-413: LGTM! Correct usage of the last aborted block hash.

Using the dereferenced last_aborted_block_hash as the starting block hash aligns well with the new approach where aborted blocks are completely removed from memory rather than marked as rejected.

crates/starknet-devnet-core/src/starknet/mod.rs (5)

23-23: LGTM: Unused import removed.

Good cleanup of the unused ExecutionResult import.


533-546: Good encapsulation of block number setting logic.

The new set_block_number method ensures consistent updates to both pre_confirmed_block and block_context, which is essential for maintaining state consistency after block abortion.


1007-1010: Clean implementation of last aborted block hash getter.

Simple and effective method for accessing the most recently aborted block.


1016-1019: Appropriate error message for deprecated block status.

The new error message correctly indicates that rejected blocks should no longer exist in the system and provides helpful guidance to report the issue.


375-375: Approve: next_latest_block_number rename is valid and implemented

The new next_latest_block_number method is defined in
• crates/starknet-devnet-core/src/blocks/mod.rs:195
and correctly used at lines 375 and 424 in
• crates/starknet-devnet-core/src/starknet/mod.rs

No further changes needed.

tests/integration/test_abort_blocks.rs (5)

25-44: Well-structured test helpers for the new abortion behavior.

The updated helper functions correctly validate that aborted blocks and transactions are no longer queryable, properly expecting "not found" errors instead of rejected statuses.


59-70: Test assertions correctly updated for new abortion semantics.

All test assertions have been properly updated to reflect that aborted blocks and their transactions are removed from storage rather than marked as rejected.

Also applies to: 92-93, 111-112, 125-125, 245-247, 269-270, 287-287


138-178: Excellent enhancement of state reversion test.

The expanded test with explicit balance checks at each stage provides strong validation that state changes are properly reverted during block abortion.


180-217: Valuable test for block number consistency.

This test ensures that block numbers are correctly updated after abortion, which is crucial for maintaining consistency in the blockchain state.


249-271: Important edge case test for multiple abortion operations.

This test validates that the aborted blocks list is properly maintained across multiple abortion operations, preventing the bug where the list could be overwritten.

@FabijanC FabijanC changed the title Modify block abortion Modify block abortion [breaking] Jul 21, 2025
@FabijanC FabijanC merged commit fbf584d into main Jul 21, 2025
2 checks passed
@FabijanC FabijanC deleted the modify-block-abort branch July 21, 2025 14:28
@coderabbitai coderabbitai bot mentioned this pull request Sep 5, 2025
10 tasks
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