Skip to content

Conversation

colinlyguo
Copy link
Contributor

@colinlyguo colinlyguo commented Jul 29, 2025

Purpose or design rationale of this PR

PR title

Your PR title must follow conventional commits (as we are doing squash merge for each PR), so it must start with one of the following types:

  • feat: A new feature

Deployment tag versioning

Has tag in common/version.go been updated or have you added bump-version label to this PR?

  • Yes

Breaking change label

Does this PR have the breaking-change label?

  • No, this PR is not a breaking change

Summary by CodeRabbit

  • New Features

    • Added extensive data validation and sanity checks to enhance the integrity of batch and chunk processing.
    • Introduced a method to retrieve batch records by their hash.
  • Bug Fixes

    • Corrected parent batch hash and block number assignments in test setups for improved accuracy.
  • Tests

    • Updated tests to align with new validation logic and ensure accurate data relationships.
  • Chores

    • Updated version tag to v4.5.39.

Copy link

coderabbitai bot commented Jul 29, 2025

Walkthrough

This update introduces comprehensive sanity checks and validation routines for Layer 2 batch and chunk data processing in the relayer logic. It adds a new file with detailed validation functions, integrates these checks into batch processing and transaction construction, and updates related tests to ensure correct parent hash assignment and block numbering. Additionally, a database method for batch lookup by hash is added.

Changes

Cohort / File(s) Change Summary
Relayer Sanity Checks Implementation
rollup/internal/controller/relayer/l2_relayer_sanity.go
Introduces new validation and sanity check methods for Layer2 batch and chunk data, including checks for field presence, sequential indices, hash consistency, codec version uniformity, message queue integrity, and continuity across batches and chunks.
Relayer Core Logic & Validation Integration
rollup/internal/controller/relayer/l2_relayer.go
Integrates sanity checks at key points in batch processing and transaction construction. Adds validation to multiple methods to enforce data integrity, prevent malformed data submission, and abort on validation failure.
ORM Batch Lookup Extension
rollup/internal/orm/batch.go
Adds a new method GetBatchByHash for retrieving a batch from the database by its hash, mirroring the existing lookup by index.
Relayer Batch Processing Test Update
rollup/internal/controller/relayer/l2_relayer_test.go
Updates the test to fetch the genesis batch and use its hash as the parent for a new batch, ensuring parent hash assignment is correct in test scenarios.
Relayer Environment Test Setup
rollup/internal/controller/relayer/relayer_test.go
Modifies test environment setup to explicitly set block numbers for deserialized blocks, ensuring defined block numbers before further processing in tests.
Version Tag Update
common/version/version.go
Updates the version tag string from "v4.5.38" to "v4.5.39".

Sequence Diagram(s)

sequenceDiagram
    participant Test/Relayer
    participant Layer2Relayer
    participant SanityChecks
    participant Database

    Test/Relayer->>Layer2Relayer: ProcessPendingBatches()
    Layer2Relayer->>SanityChecks: sanityChecksBeforeConstructingTransaction(batches)
    SanityChecks->>Database: getPreviousChunkForContinuity()
    SanityChecks-->>Layer2Relayer: Validation result (error or success)
    alt Validation fails
        Layer2Relayer-->>Test/Relayer: Abort with error
    else Validation passes
        Layer2Relayer->>Layer2Relayer: constructCommitBatchPayload...
        Layer2Relayer->>Layer2Relayer: Submit transaction
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Possibly related PRs

Suggested reviewers

  • colinlyguo
  • georgehao
  • jonastheis

Poem

🐇 Hopping through code with a keen little eye,
Checking each batch so no errors slip by.
Roots and hashes all tidy and neat,
Every chunk’s puzzle now fits complete.
With sanity checks, our relayer’s a star —
Safe and sound, near and far! 🌟🐰


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8717281 and dd0ddbc.

📒 Files selected for processing (1)
  • common/version/version.go (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • common/version/version.go
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat-rollup-relayer-add-sanity-checks-in-committing-and-finalizing

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

Support

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

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 generate unit tests to generate unit tests for 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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6d62f8e and 18b6b65.

📒 Files selected for processing (3)
  • common/version/version.go (1 hunks)
  • rollup/internal/controller/relayer/l2_relayer.go (10 hunks)
  • rollup/internal/orm/batch.go (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
rollup/internal/controller/relayer/l2_relayer.go (1)

Learnt from: colinlyguo
PR: #1530
File: rollup/internal/controller/watcher/batch_proposer.go:291-294
Timestamp: 2024-10-20T16:13:20.397Z
Learning: In batch_proposer.go, it's acceptable to call utils.CalculateBatchMetrics multiple times within the loop because the batch's chunks are increasing in the loop, and each calculation reflects the updated batch state.

🔇 Additional comments (6)
rollup/internal/orm/batch.go (1)

266-278: LGTM!

The GetBatchByHash method implementation follows the established pattern used by GetBatchByIndex and other ORM methods in this file. Error handling and return values are consistent.

rollup/internal/controller/relayer/l2_relayer.go (4)

476-481: Good placement of sanity checks!

The sanity checks are appropriately placed after batch selection but before transaction construction. This ensures invalid batches are caught early without wasting resources on payload construction.


950-1074: Comprehensive validation in payload construction!

The added sanity checks provide excellent coverage:

  • Nil pointer protection for inputs
  • Batch index consistency validation
  • Block count verification
  • Hash field validation (preventing zero hashes)
  • L1 message queue hash consistency checks
  • Generated payload validation

These checks will prevent malformed transactions from being submitted to L1.


1398-1427: Well-structured validation architecture!

The validation flow is logical and comprehensive:

  1. Basic nil/empty checks
  2. Codec version consistency
  3. Continuity validation with previous chunks
  4. Detailed batch and chunk validation

The separation of concerns makes the code maintainable and easy to understand.


1077-1128: Consistent validation across all payload construction methods!

The sanity checks in validium-specific methods maintain the same high standard:

  • Nil input validation
  • Empty data checks
  • Zero hash prevention
  • Consistent error messaging

This ensures both regular and validium modes have robust validation.

Also applies to: 1131-1188, 1191-1231

common/version/version.go (1)

8-8: Version bump looks good.

The version increment from v4.5.35 to v4.5.36 appropriately reflects the addition of sanity checks in the rollup-relayer.

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

♻️ Duplicate comments (1)
rollup/internal/controller/relayer/l2_relayer.go (1)

1548-1555: Parent batch validation correctly implements strict checking.

As previously discussed and confirmed by the author, the function correctly errors out when the parent batch is not found, treating it as a genuine error condition rather than attempting graceful handling.

🧹 Nitpick comments (1)
rollup/internal/controller/relayer/l2_relayer.go (1)

1637-1646: Consider adding comments to clarify previous chunk selection logic.

The logic for selecting the previous chunk handles three distinct cases correctly, but would benefit from explicit documentation.

 	// Get previous chunk for continuity check
 	var prevChunk *orm.Chunk
 	if chunkIndex > 0 {
+		// Case 1: Not the first chunk in batch - use previous chunk from same batch
 		prevChunk = batch.Chunks[chunkIndex-1]
 	} else if i == 0 {
+		// Case 2: First chunk of first batch - use the provided previous chunk from previous batch
 		prevChunk = prevChunkFromPrevBatch
 	} else if i > 0 {
-		// Use the last chunk from the previous batch
+		// Case 3: First chunk of subsequent batch - use the last chunk from the previous batch
 		prevBatch := allBatches[i-1]
 		prevChunk = prevBatch.Chunks[len(prevBatch.Chunks)-1]
 	}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f225d25 and ae28f99.

📒 Files selected for processing (2)
  • rollup/internal/controller/relayer/l2_relayer.go (12 hunks)
  • rollup/internal/controller/relayer/relayer_test.go (2 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: colinlyguo
PR: scroll-tech/scroll#1714
File: rollup/internal/controller/relayer/l2_relayer.go:1548-1555
Timestamp: 2025-07-29T16:38:24.647Z
Learning: In rollup/internal/controller/relayer/l2_relayer.go, the validateBatchFields function should error out when GetBatchByHash fails to find a parent batch. This is intentional behavior - missing parent batches represent genuine error conditions that should halt batch submission processing. Genesis batch handling occurs separately from normal batch validation flow.
rollup/internal/controller/relayer/relayer_test.go (1)

Learnt from: colinlyguo
PR: #1714
File: rollup/internal/controller/relayer/l2_relayer.go:1548-1555
Timestamp: 2025-07-29T16:38:24.647Z
Learning: In rollup/internal/controller/relayer/l2_relayer.go, the validateBatchFields function should error out when GetBatchByHash fails to find a parent batch. This is intentional behavior - missing parent batches represent genuine error conditions that should halt batch submission processing. Genesis batch handling occurs separately from normal batch validation flow.

rollup/internal/controller/relayer/l2_relayer.go (2)

Learnt from: colinlyguo
PR: #1714
File: rollup/internal/controller/relayer/l2_relayer.go:1548-1555
Timestamp: 2025-07-29T16:38:24.647Z
Learning: In rollup/internal/controller/relayer/l2_relayer.go, the validateBatchFields function should error out when GetBatchByHash fails to find a parent batch. This is intentional behavior - missing parent batches represent genuine error conditions that should halt batch submission processing. Genesis batch handling occurs separately from normal batch validation flow.

Learnt from: colinlyguo
PR: #1530
File: rollup/internal/controller/watcher/batch_proposer.go:291-294
Timestamp: 2024-10-20T16:13:20.397Z
Learning: In batch_proposer.go, it's acceptable to call utils.CalculateBatchMetrics multiple times within the loop because the batch's chunks are increasing in the loop, and each calculation reflects the updated batch state.

🧬 Code Graph Analysis (1)
rollup/internal/controller/relayer/l2_relayer.go (2)
rollup/internal/orm/batch.go (2)
  • Batch (22-72)
  • Batch (80-82)
rollup/internal/orm/chunk.go (2)
  • Chunk (20-64)
  • Chunk (72-74)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: check
  • GitHub Check: tests
  • GitHub Check: tests
🔇 Additional comments (7)
rollup/internal/controller/relayer/relayer_test.go (1)

84-84: Test setup properly configured for block number validation.

The explicit assignment of block numbers ensures test blocks have the required metadata for the new sanity checks that validate block continuity and ranges.

Also applies to: 98-98

rollup/internal/controller/relayer/l2_relayer.go (6)

280-292: Good addition of genesis batch validation checks.

The sanity checks properly validate critical fields before committing the genesis batch, preventing invalid transactions from being sent to L1.

Also applies to: 312-316


494-499: Sanity checks appropriately placed before transaction construction.

The validation prevents invalid batches from progressing to transaction construction, failing fast with detailed error logging.


968-1090: Comprehensive validation in payload construction.

The extensive checks cover all critical aspects:

  • Nil safety and index consistency
  • Block presence and count verification
  • Parent batch hash validation
  • L1 message queue hash consistency with detailed edge case handling
  • Blob and calldata validation

These validations effectively prevent malformed payloads from being constructed.


1095-1148: Validium payload construction properly validated.

The checks ensure critical validium fields are present, including the commitment hash from the last chunk's end block hash.


1154-1217: Finalize bundle payload validation is thorough.

Both codec versions properly validate essential fields before finalization, with appropriate differences (e.g., state root check only for CodecV7).

Also applies to: 1219-1258


1427-1456: Well-structured validation architecture.

The hierarchical approach with clear separation of concerns makes the validation logic maintainable and easy to understand. The flow from basic to detailed validation is logical.

@codecov-commenter
Copy link

codecov-commenter commented Jul 29, 2025

Codecov Report

❌ Patch coverage is 37.82991% with 212 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (develop@6897cc5). Learn more about missing BASE report.

Files with missing lines Patch % Lines
...p/internal/controller/relayer/l2_relayer_sanity.go 40.71% 123 Missing and 59 partials ⚠️
rollup/internal/controller/relayer/l2_relayer.go 16.66% 17 Missing and 3 partials ⚠️
rollup/internal/orm/batch.go 0.00% 10 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             develop    #1714   +/-   ##
==========================================
  Coverage           ?   37.56%           
==========================================
  Files              ?      243           
  Lines              ?    20437           
  Branches           ?        0           
==========================================
  Hits               ?     7678           
  Misses             ?    11952           
  Partials           ?      807           
Flag Coverage Δ
rollup 37.66% <37.82%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@yiweichi yiweichi self-requested a review July 30, 2025 09:55
yiweichi
yiweichi previously approved these changes Jul 30, 2025
@colinlyguo colinlyguo force-pushed the feat-rollup-relayer-add-sanity-checks-in-committing-and-finalizing branch from 77bba2d to 450af64 Compare August 4, 2025 06:58
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
rollup/internal/controller/relayer/l2_relayer_sanity.go (1)

251-339: Complex but critical validation function - consider refactoring for maintainability.

The function implements comprehensive calldata and blob validation for codec v7, with proper ABI decoding, blob decoding, and thorough comparison with database data. The validation logic is sound and covers all critical aspects.

However, the function is quite long (88 lines) and handles multiple concerns. Consider breaking it down into smaller functions for better maintainability:

+// validateCalldataParams validates the decoded calldata parameters
+func (r *Layer2Relayer) validateCalldataParams(version uint8, parentBatchHash, lastBatchHash common.Hash, firstBatch, lastBatch *orm.Batch) error {
+	// Move lines 277-285 here
+}
+
+// validateBlobPayload validates a single blob payload against database data  
+func (r *Layer2Relayer) validateBlobPayload(blob *kzg4844.Blob, dbBatch *dbBatchWithChunks, codec encoding.Codec) error {
+	// Move lines 298-334 here
+}

This would make the main function more readable and each helper function more focused on a single responsibility.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1b28ff5 and 450af64.

📒 Files selected for processing (2)
  • rollup/internal/controller/relayer/l2_relayer.go (12 hunks)
  • rollup/internal/controller/relayer/l2_relayer_sanity.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • rollup/internal/controller/relayer/l2_relayer.go
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: colinlyguo
PR: scroll-tech/scroll#1714
File: rollup/internal/controller/relayer/l2_relayer.go:1548-1555
Timestamp: 2025-07-29T16:38:24.647Z
Learning: In rollup/internal/controller/relayer/l2_relayer.go, the validateBatchFields function should error out when GetBatchByHash fails to find a parent batch. This is intentional behavior - missing parent batches represent genuine error conditions that should halt batch submission processing. Genesis batch handling occurs separately from normal batch validation flow.
📚 Learning: in rollup/internal/controller/relayer/l2_relayer.go, the validatebatchfields function should error o...
Learnt from: colinlyguo
PR: scroll-tech/scroll#1714
File: rollup/internal/controller/relayer/l2_relayer.go:1548-1555
Timestamp: 2025-07-29T16:38:24.647Z
Learning: In rollup/internal/controller/relayer/l2_relayer.go, the validateBatchFields function should error out when GetBatchByHash fails to find a parent batch. This is intentional behavior - missing parent batches represent genuine error conditions that should halt batch submission processing. Genesis batch handling occurs separately from normal batch validation flow.

Applied to files:

  • rollup/internal/controller/relayer/l2_relayer_sanity.go
📚 Learning: in `batch_proposer.go`, it's acceptable to call `utils.calculatebatchmetrics` multiple times within ...
Learnt from: colinlyguo
PR: scroll-tech/scroll#1530
File: rollup/internal/controller/watcher/batch_proposer.go:291-294
Timestamp: 2024-10-20T16:13:20.397Z
Learning: In `batch_proposer.go`, it's acceptable to call `utils.CalculateBatchMetrics` multiple times within the loop because the batch's chunks are increasing in the loop, and each calculation reflects the updated batch state.

Applied to files:

  • rollup/internal/controller/relayer/l2_relayer_sanity.go
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: tests
  • GitHub Check: tests
  • GitHub Check: check
🔇 Additional comments (8)
rollup/internal/controller/relayer/l2_relayer_sanity.go (8)

14-50: LGTM! Well-structured message queue validation.

The function correctly validates L1 message queue hash consistency with proper handling of genesis batches, empty chunks, and appropriate zero-hash checks. The logic for ensuring hash differences when messages are processed is sound.


52-71: Function structure is solid.

The sanity check orchestration is well-organized with proper error handling and sequential validation steps.


73-86: LGTM! Proper continuity validation setup.

The function correctly identifies genesis chunks as inappropriate for normal batch submission flow and handles database retrieval with comprehensive error context.


88-118: LGTM! Comprehensive batch validation pipeline.

The function implements a well-structured validation pipeline with proper fail-fast basic checks, codec version consistency validation, and sequential detailed validation with appropriate state tracking.


120-138: LGTM! Well-organized validation orchestration.

The function properly delegates to specialized validation functions in a logical order, ensuring comprehensive batch validation with appropriate error propagation.


140-180: LGTM! Critical batch field validation implemented correctly.

The function properly validates essential batch fields including hash integrity, sequential indexing, and parent batch continuity. The database lookup for parent batch validation ensures blockchain integrity, which aligns with the requirement that missing parent batches should error out as genuine error conditions.


182-200: LGTM! Proper chunk validation with consistency checks.

The function correctly validates codec version consistency between chunks and their parent batch, and implements sequential chunk validation with appropriate state tracking for continuity checks.


202-249: LGTM! Comprehensive chunk validation with continuity checks.

The function implements thorough validation covering chunk integrity, sequential indexing, L1 message continuity, block range validation, and cross-chunk continuity. The L1 messages popped continuity calculation is particularly important for maintaining L1-L2 message processing integrity.

@colinlyguo colinlyguo force-pushed the feat-rollup-relayer-add-sanity-checks-in-committing-and-finalizing branch from 450af64 to 925ef74 Compare August 4, 2025 07:19
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
rollup/internal/controller/relayer/l2_relayer_sanity.go (1)

251-350: Consider optimizing database queries for large batches.

The function performs comprehensive validation of calldata and blobs, which is excellent. However, there's a potential performance concern: for each batch, it fetches all blocks from the database (lines 312-317). For large batches with many blocks, this could be expensive.

Consider batching the block retrieval or implementing a more efficient query strategy if performance becomes an issue.

 // Collect all blocks for the batch
 var batchBlocks []*encoding.Block
-for _, c := range dbChunks {
-	blocks, err := r.l2BlockOrm.GetL2BlocksInRange(r.ctx, c.StartBlockNumber, c.EndBlockNumber)
-	if err != nil {
-		return fmt.Errorf("failed to get blocks for batch %d chunk %d: %w", dbBatch.Index, c.Index, err)
-	}
-	batchBlocks = append(batchBlocks, blocks...)
-}
+// Collect block ranges first, then fetch in a single query if possible
+startBlock := dbChunks[0].StartBlockNumber
+endBlock := dbChunks[len(dbChunks)-1].EndBlockNumber
+blocks, err := r.l2BlockOrm.GetL2BlocksInRange(r.ctx, startBlock, endBlock)
+if err != nil {
+	return fmt.Errorf("failed to get blocks for batch %d: %w", dbBatch.Index, err)
+}
+batchBlocks = blocks
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 450af64 and 925ef74.

📒 Files selected for processing (2)
  • rollup/internal/controller/relayer/l2_relayer.go (12 hunks)
  • rollup/internal/controller/relayer/l2_relayer_sanity.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • rollup/internal/controller/relayer/l2_relayer.go
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: colinlyguo
PR: scroll-tech/scroll#1714
File: rollup/internal/controller/relayer/l2_relayer.go:1548-1555
Timestamp: 2025-07-29T16:38:24.647Z
Learning: In rollup/internal/controller/relayer/l2_relayer.go, the validateBatchFields function should error out when GetBatchByHash fails to find a parent batch. This is intentional behavior - missing parent batches represent genuine error conditions that should halt batch submission processing. Genesis batch handling occurs separately from normal batch validation flow.
📚 Learning: in rollup/internal/controller/relayer/l2_relayer.go, the validatebatchfields function should error o...
Learnt from: colinlyguo
PR: scroll-tech/scroll#1714
File: rollup/internal/controller/relayer/l2_relayer.go:1548-1555
Timestamp: 2025-07-29T16:38:24.647Z
Learning: In rollup/internal/controller/relayer/l2_relayer.go, the validateBatchFields function should error out when GetBatchByHash fails to find a parent batch. This is intentional behavior - missing parent batches represent genuine error conditions that should halt batch submission processing. Genesis batch handling occurs separately from normal batch validation flow.

Applied to files:

  • rollup/internal/controller/relayer/l2_relayer_sanity.go
📚 Learning: in `batch_proposer.go`, it's acceptable to call `utils.calculatebatchmetrics` multiple times within ...
Learnt from: colinlyguo
PR: scroll-tech/scroll#1530
File: rollup/internal/controller/watcher/batch_proposer.go:291-294
Timestamp: 2024-10-20T16:13:20.397Z
Learning: In `batch_proposer.go`, it's acceptable to call `utils.CalculateBatchMetrics` multiple times within the loop because the batch's chunks are increasing in the loop, and each calculation reflects the updated batch state.

Applied to files:

  • rollup/internal/controller/relayer/l2_relayer_sanity.go
🔇 Additional comments (8)
rollup/internal/controller/relayer/l2_relayer_sanity.go (8)

15-50: LGTM! Comprehensive L1 message queue validation.

The function correctly handles all validation scenarios including genesis batch handling, empty chunk validation, and hash consistency checks. The logic ensures proper L1 message queue state transitions.


53-71: LGTM! Well-structured sanity check orchestration.

The function properly orchestrates the sanity check workflow with appropriate error handling and logging for operational visibility.


74-86: LGTM! Proper continuity check implementation.

The function correctly prevents genesis chunks from normal batch submission flow and retrieves the previous chunk with appropriate error handling.


89-118: LGTM! Comprehensive batch validation with proper state tracking.

The function correctly combines basic validation, codec version consistency checks, and detailed validation while maintaining proper chunk continuity state throughout the process.


121-138: LGTM! Well-organized single batch validation.

The function properly delegates to specific validation functions, maintaining good separation of concerns and making the code maintainable.


141-180: LGTM! Thorough batch field validation with proper parent batch handling.

The function correctly validates all essential batch fields and properly handles parent batch continuity validation through database lookup, which aligns with the expected behavior for missing parent batches.


183-200: LGTM! Proper chunk validation with codec consistency checks.

The function correctly validates codec version consistency and maintains proper chunk continuity state while providing clear error context.


203-249: LGTM! Comprehensive single chunk validation.

The function correctly validates all essential chunk fields including hash values, sequential indices, L1 message continuity, block ranges, and inter-chunk continuity.

@colinlyguo colinlyguo changed the title feat(rollup-relayer): add sanity checks before committing and finalizing feat(rollup-relayer): add sanity checks before committing Aug 4, 2025
@colinlyguo colinlyguo force-pushed the feat-rollup-relayer-add-sanity-checks-in-committing-and-finalizing branch from 39fb299 to d3720a4 Compare August 4, 2025 07:58
@colinlyguo colinlyguo force-pushed the feat-rollup-relayer-add-sanity-checks-in-committing-and-finalizing branch from d3720a4 to f22bd44 Compare August 4, 2025 08:18
@colinlyguo colinlyguo changed the title feat(rollup-relayer): add sanity checks before committing feat(rollup-relayer): add sanity checks before committing and finalizing Aug 4, 2025
@colinlyguo colinlyguo force-pushed the feat-rollup-relayer-add-sanity-checks-in-committing-and-finalizing branch from f22bd44 to 52cf05c Compare August 4, 2025 08:22
@colinlyguo colinlyguo force-pushed the feat-rollup-relayer-add-sanity-checks-in-committing-and-finalizing branch from 52cf05c to cf85225 Compare August 4, 2025 08:37
@colinlyguo colinlyguo requested a review from Thegaram August 4, 2025 08:37
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 comments (1)
rollup/internal/controller/relayer/l2_relayer_sanity.go (1)

1-439: Address test coverage gap for critical validation functions.

Based on the coverage report, this file has only 34.72% patch coverage with 126 lines missing coverage. Given that these are critical sanity check functions that validate transaction data integrity, comprehensive test coverage is essential to ensure the validation logic works correctly and catches edge cases.

The low test coverage is concerning for such critical validation logic. Would you like me to help generate comprehensive unit tests for these sanity check functions to improve coverage and ensure reliability?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cf85225 and be22866.

📒 Files selected for processing (1)
  • rollup/internal/controller/relayer/l2_relayer_sanity.go (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: colinlyguo
PR: scroll-tech/scroll#1714
File: rollup/internal/controller/relayer/l2_relayer.go:1548-1555
Timestamp: 2025-07-29T16:38:24.647Z
Learning: In rollup/internal/controller/relayer/l2_relayer.go, the validateBatchFields function should error out when GetBatchByHash fails to find a parent batch. This is intentional behavior - missing parent batches represent genuine error conditions that should halt batch submission processing. Genesis batch handling occurs separately from normal batch validation flow.
📚 Learning: in rollup/internal/controller/relayer/l2_relayer.go, the validatebatchfields function should error o...
Learnt from: colinlyguo
PR: scroll-tech/scroll#1714
File: rollup/internal/controller/relayer/l2_relayer.go:1548-1555
Timestamp: 2025-07-29T16:38:24.647Z
Learning: In rollup/internal/controller/relayer/l2_relayer.go, the validateBatchFields function should error out when GetBatchByHash fails to find a parent batch. This is intentional behavior - missing parent batches represent genuine error conditions that should halt batch submission processing. Genesis batch handling occurs separately from normal batch validation flow.

Applied to files:

  • rollup/internal/controller/relayer/l2_relayer_sanity.go
📚 Learning: in `batch_proposer.go`, it's acceptable to call `utils.calculatebatchmetrics` multiple times within ...
Learnt from: colinlyguo
PR: scroll-tech/scroll#1530
File: rollup/internal/controller/watcher/batch_proposer.go:291-294
Timestamp: 2024-10-20T16:13:20.397Z
Learning: In `batch_proposer.go`, it's acceptable to call `utils.CalculateBatchMetrics` multiple times within the loop because the batch's chunks are increasing in the loop, and each calculation reflects the updated batch state.

Applied to files:

  • rollup/internal/controller/relayer/l2_relayer_sanity.go
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: check
  • GitHub Check: tests
  • GitHub Check: tests
🔇 Additional comments (10)
rollup/internal/controller/relayer/l2_relayer_sanity.go (10)

16-48: LGTM! Well-structured orchestration function with proper error handling.

The main validation function follows a clear, layered approach with appropriate error wrapping and early returns. The validation flow is logical and comprehensive.


58-91: LGTM! Robust calldata parsing with comprehensive type assertions.

The function properly handles ABI method unpacking and includes thorough type assertions for all parameters. Error messages are descriptive and actionable.


142-159: LGTM! Thorough validation of calldata against database records.

The validation correctly compares calldata parameters with database records, ensuring consistency between constructed transaction data and stored state.


162-203: LGTM! Comprehensive database consistency validation with proper error handling.

The function performs thorough consistency checks across batches and chunks, including codec version uniformity and proper chunk continuity validation. The logic for handling the previous chunk correctly avoids the genesis chunk scenario.


206-258: LGTM! Thorough single batch validation with proper parent batch verification.

The validation correctly checks all essential fields and handles batch index continuity. The special handling for the first batch (lines 242-250) properly validates against the parent batch from the database, which aligns with the retrieved learning about intentional error behavior when parent batches are missing.


261-279: LGTM! Proper chunk-batch consistency validation.

The function correctly validates codec version consistency between chunks and their parent batch, and properly validates each chunk individually with continuity checks.


282-329: LGTM! Comprehensive single chunk validation with proper continuity checks.

The validation thoroughly checks chunk hash fields, block ranges, and L1 message continuity. The logic correctly ensures chunks are sequential and properly linked with their predecessors.


332-351: LGTM! Proper blob validation orchestration.

The function correctly retrieves the appropriate codec and validates each blob against its corresponding batch data with proper error handling.


354-404: LGTM! Thorough blob-to-batch validation with comprehensive checks.

The function properly:

  1. Collects all blocks for the batch from multiple chunks
  2. Validates block counts match expected ranges
  3. Decodes blob payload using the correct codec
  4. Validates L1 message queue hashes match database records
  5. Ensures decoded block data matches database block data

407-438: LGTM! Robust L1 message queue consistency validation.

The function performs comprehensive validation of L1 message queue hashes, correctly:

  1. Validating that hashes are non-zero when messages have been processed
  2. Ensuring prev and post hashes differ when messages are processed in the batch
  3. Calculating total L1 messages processed correctly

This addresses potential issues with incorrect L1 message queue hash computation mentioned in past review comments.

@colinlyguo colinlyguo force-pushed the feat-rollup-relayer-add-sanity-checks-in-committing-and-finalizing branch from f4bc536 to 3f9d9cc Compare August 5, 2025 18:15
Copy link
Contributor

@Thegaram Thegaram left a comment

Choose a reason for hiding this comment

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

lgtm

jonastheis
jonastheis previously approved these changes Aug 7, 2025
@colinlyguo colinlyguo added the bump-version Bump the version tag for deployment label Aug 7, 2025
@colinlyguo colinlyguo merged commit c012f71 into develop Aug 11, 2025
1 check passed
@colinlyguo colinlyguo deleted the feat-rollup-relayer-add-sanity-checks-in-committing-and-finalizing branch August 11, 2025 09:49
@coderabbitai coderabbitai bot mentioned this pull request Aug 11, 2025
3 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bump-version Bump the version tag for deployment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants