Skip to content

SystemContract: support millisecond block generation #1174

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

Merged
merged 34 commits into from
Aug 14, 2025

Conversation

georgehao
Copy link
Member

@georgehao georgehao commented Apr 27, 2025

1. Purpose or design rationale of this PR

This PR enables sub-second block generation on l2geth sequencer nodes.

If genesis.config.systemContract.period is set to 1, and genesis.config.systemContract.blocks_per_second is also set, it will then be used to determine the block time. E.g. with blocks_per_second = 4, the sequencer will produce blocks every 250ms.

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

3. Deployment tag versioning

Has the version in params/version.go been updated?

  • This PR doesn't involve a new deployment, git tag, docker image tag, and it doesn't affect traces
  • Yes

4. Breaking change label

Does this PR have the breaking-change label?

  • This PR is not a breaking change
  • Yes

Summary by CodeRabbit

  • New Features
    • Added blocks-per-second configuration and refined block-deadline calculations for high-rate modes.
  • Bug Fixes
    • Corrected timestamp progression and single-second period handling for block timing.
  • Enhancements
    • More precise deadline computation with sub-second resolution; relaxed-period behavior preserved.
  • Tests
    • Added tests validating block-intervals and worker deadline timing.
  • Dependencies
    • Updated export-headers-toolkit dependencies.
  • Version
    • Bumped patch version.

Copy link

coderabbitai bot commented Apr 27, 2025

Walkthrough

Adds BlocksPerSecond to SystemContract config, adds CalcBlocksPerSecond and CalcPeriodMs helpers, refactors SystemContract.CalcTimestamp to handle Period==1 using per-block indexing, introduces nanosecond-precision CalculateBlockDeadline and a test, bumps VersionPatch to 3, and updates two go.mod dependency revisions.

Changes

Cohort / File(s) Change Summary
Consensus timestamp helpers & logic
consensus/system_contract/consensus.go
Add CalcBlocksPerSecond and CalcPeriodMs; refactor SystemContract.CalcTimestamp to treat Period == 1 by computing block index within the second and conditionally advancing timestamp, keeping existing RelaxedPeriod/current-time override.
Miner deadline logic
miner/scroll_worker.go
Add CalculateBlockDeadline(config *params.SystemContractConfig, header *types.Header) time.Time; call it in newWork when system contract Period == 1 to compute nanosecond-precision deadlines.
Miner tests
miner/scroll_worker_test.go
Add TestBlockIntervalWithWorkerDeadline to validate intervals between calculated worker deadlines across period and blocks-per-second scenarios.
System contract config
params/config.go
Add BlocksPerSecond uint64 to SystemContractConfig (json:"blocks_per_second,omitempty"); other field formatting/reordering only.
Version bump
params/version.go
Increment VersionPatch constant from 2 to 3.
Rollup toolkit deps
rollup/missing_header_fields/export-headers-toolkit/go.mod
Bump commits for github.com/scroll-tech/da-codec and github.com/scroll-tech/go-ethereum.

Sequence Diagram(s)

sequenceDiagram
    participant Worker
    participant Config
    participant SystemContract

    Worker->>Config: read Period, BlocksPerSecond, RelaxedPeriod
    alt Period == 1
        Worker->>SystemContract: CalcBlocksPerSecond(BlocksPerSecond)
        Worker->>SystemContract: CalcPeriodMs(BlocksPerSecond)
        Worker->>Worker: CalculateBlockDeadline(config, header) -> deadline (ns precision)
    else Period != 1
        Worker->>SystemContract: CalcTimestamp(parent) -> timestamp (parent + period)
        Worker->>Worker: default deadline based on timestamp (+ relaxed override)
    end
    Worker->>Worker: use deadline for newWork/mining
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Possibly related PRs

Suggested reviewers

  • colinlyguo

Poem

"I nibble at timestamps, hop by hop,
Counting blocks till the next tick-stop.
Milliseconds sprinkled, deadlines in line,
I time each block — precise and fine.
Hop on, miners — one more cozy crop!" 🐇


📜 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 0837abe and 826c3d9.

📒 Files selected for processing (1)
  • params/config.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • params/config.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: test
  • GitHub Check: check
  • GitHub Check: Analyze (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/support_ms_block_generation

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.
    • 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.
  • 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 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/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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 5e956fe and 2f9555e.

📒 Files selected for processing (4)
  • consensus/system_contract/consensus.go (1 hunks)
  • consensus/system_contract/system_contract.go (1 hunks)
  • miner/scroll_worker.go (1 hunks)
  • params/config.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
consensus/system_contract/system_contract.go (1)
common/types.go (1)
  • HexToAddress (218-218)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test
  • GitHub Check: Analyze (go)
🔇 Additional comments (3)
params/config.go (1)

800-800: Documentation update aligns with implementation changes

The comment has been updated to clarify that the Period is measured in milliseconds rather than seconds, which aligns with the implementation changes in other files that now treat this value as milliseconds.

miner/scroll_worker.go (1)

561-578: Improved deadline calculation with millisecond precision

The mining deadline calculation has been refined to use millisecond-level granularity, correctly interpreting the system contract period as milliseconds. This provides more precise scheduling of blocks within each second.

The implementation includes proper handling of edge cases like zero blocksPerSecond and calculates timestamps with nanosecond precision, aligning with the changes in the consensus timestamp calculation.

consensus/system_contract/consensus.go (1)

229-256: Enhanced timestamp calculation with millisecond precision

The timestamp calculation has been improved to support millisecond-level block periods, calculating how many blocks fit within each second and appropriately incrementing the timestamp for the last block in each second interval.

This change allows for more flexible and precise block timing, while still maintaining compatibility with the Unix timestamp format (which uses seconds). The implementation also properly handles edge cases like when blocksPerSecond would be zero.

@georgehao georgehao changed the title SystemContract: support ms block generation SystemContract: support millisecond block generation Apr 27, 2025
@georgehao georgehao requested review from roylou and colinlyguo April 27, 2025 08:44
Copy link

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

Let's not merge this until we decide about the block time.

Copy link

@jonastheis jonastheis left a comment

Choose a reason for hiding this comment

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

Let's get this merged soon so we can test and deploy it

jonastheis
jonastheis previously approved these changes Jul 23, 2025
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)
consensus/system_contract/consensus.go (1)

240-245: Consider edge cases with non-divisible blocks per second values.

The implementation looks correct for typical values. However, be aware that for blocks per second values that don't divide evenly into 1000 (e.g., 3, 6, 7), integer division will truncate the result, potentially causing slight timing drift.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3abad55 and 7c997fb.

📒 Files selected for processing (5)
  • consensus/system_contract/consensus.go (1 hunks)
  • consensus/system_contract/consensus_test.go (1 hunks)
  • miner/scroll_worker.go (2 hunks)
  • miner/scroll_worker_test.go (1 hunks)
  • params/config.go (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • params/config.go
  • miner/scroll_worker_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • miner/scroll_worker.go
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: the `override` parameter in `dasyncer.synconeblock()` is intentionally designed to allow rewriting e...
Learnt from: jonastheis
PR: scroll-tech/go-ethereum#1115
File: rollup/da_syncer/da_syncer.go:35-41
Timestamp: 2025-02-14T04:10:06.754Z
Learning: The `override` parameter in `DASyncer.SyncOneBlock()` is intentionally designed to allow rewriting existing chain data during recovery mode, enabling reconstruction of a valid canonical L2 chain from permissionless committed batches.

Applied to files:

  • consensus/system_contract/consensus.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). (4)
  • GitHub Check: build-and-push
  • GitHub Check: check
  • GitHub Check: test
  • GitHub Check: Analyze (go)
🔇 Additional comments (7)
consensus/system_contract/consensus.go (2)

230-238: LGTM - Good default handling for blocks per second.

The function correctly handles the zero case by defaulting to 1 block per second, which addresses the devnet mode concern mentioned in previous reviews.


247-280: Complex but correct timestamp calculation logic.

The refactored logic correctly implements period-based timestamp increments using modular arithmetic. The approach properly handles:

  • Sub-second block intervals through blocks per second configuration
  • Period boundaries for timestamp increments
  • Genesis block edge case (nextBlockNumber > 0 check)
  • Existing RelaxedPeriod override behavior

While significantly more complex than the previous implementation, this enables the millisecond block generation feature as intended.

consensus/system_contract/consensus_test.go (5)

12-105: Excellent comprehensive test coverage for timestamp calculation.

The table-driven tests thoroughly validate the new timestamp calculation logic across various scenarios:

  • Different blocks per second configurations (1, 2)
  • Different period lengths (1s, 2s)
  • Period boundary detection and timestamp increment behavior
  • Clear test descriptions and detailed error messages

The use of future timestamps to avoid timing conflicts with the current time is a good practice.


107-165: Good validation of millisecond interval calculations.

The tests properly validate the CalcPeriodMs helper function with various blocks per second configurations. The mathematical verification that blocksPerSecond * interval = 1 second adds confidence in the timing calculations.


167-205: Excellent simulation of progressive timestamp behavior.

This test effectively validates the cumulative timestamp behavior over multiple blocks, ensuring that the modular arithmetic approach works correctly across period boundaries. The simulation of blockchain progression by updating baseTime is realistic and thorough.


207-238: Good validation of default configuration handling.

The test properly validates that zero/unset configuration values default to sensible values (period=1s, blocksPerSecond=1), ensuring backward compatibility and robust behavior when configuration is incomplete.


240-282: Precise validation of timestamp increment logic.

This test effectively validates the core increment logic by simulating blockchain progression and verifying that timestamps increment only at period boundaries (even-numbered blocks for 2 blocks per second). The modulo arithmetic in the test matches the implementation logic.

Copy link

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

Let's merge this only after #1230 (and the subsequent version bump) has been merged.

jonastheis
jonastheis previously approved these changes Aug 7, 2025
Thegaram
Thegaram previously approved these changes Aug 11, 2025
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 eb9f213 and 4bd59ee.

📒 Files selected for processing (1)
  • params/version.go (1 hunks)
⏰ 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: test
  • GitHub Check: Analyze (go)
🔇 Additional comments (1)
params/version.go (1)

27-27: Patch bump to 5.9.3 acknowledged

The version bump is minimal, scoped, and correctly updates Version, VersionWithMeta, and ArchiveVersion via the existing closures.

@jonastheis jonastheis merged commit 2ee0371 into develop Aug 14, 2025
14 checks passed
@jonastheis jonastheis deleted the feat/support_ms_block_generation branch August 14, 2025 06:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants