Skip to content

fix: accept header at most 100ms earlier than timestamp #1129

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 3 commits into from
Mar 3, 2025

Conversation

Thegaram
Copy link

@Thegaram Thegaram commented Mar 3, 2025

1. Purpose or design rationale of this PR

Attempt to fix the following ocassional issue:

failed to mine block                     err="failed committing new work: block in the future"

Context.

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:

  • fix: A bug fix

3. Deployment tag versioning

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

  • Yes

4. Breaking change label

Does this PR have the breaking-change label?

  • This PR is not a breaking change

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced block validation to accommodate slight timing discrepancies, reducing false rejections.
  • New Features
    • Introduced additional logging for improved traceability during block adjustments.
    • Added adaptive deadline management that adjusts based on system settings.
  • Chores
    • Updated the patch version to 19 for this release.

@Thegaram Thegaram requested review from ranchalp and omerfirmak March 3, 2025 14:25
Copy link

coderabbitai bot commented Mar 3, 2025

Walkthrough

This pull request refines consensus and miner functionality. In the consensus module, the verifyHeader function now allows a 100ms leeway when comparing block timestamps to address timing discrepancies. In the miner module, additional logging has been added for backdated blocks during the EuclidV2 transition, and the deadline is dynamically calculated when the system contract operates in a relaxed period. Additionally, the patch version in the versioning file is incremented.

Changes

File(s) Change Summary
consensus/system_contract/consensus.go Updated verifyHeader to include a 100ms leeway for future block timestamp checks.
consensus/clique/clique.go Updated verifyHeader to include a 100ms leeway for future block timestamp checks.
miner/scroll_worker.go Added a logging statement in collectPendingL1Messages for backdated timestamps; enhanced newWork to calculate the deadline using the system contract's relaxed period.
params/version.go Bumped the VersionPatch constant from 18 to 19.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant verifyHeader
    participant Timer

    Caller->>verifyHeader: Pass block header with timestamp
    verifyHeader->>Timer: Capture current time (now)
    alt header.Time > now
        verifyHeader->>verifyHeader: Check for 100ms leeway conditions
        alt Conditions not met
            verifyHeader-->>Caller: Return future block error
        else Conditions met
            verifyHeader-->>Caller: Accept header
        end
    else
        verifyHeader-->>Caller: Accept header
    end
Loading
sequenceDiagram
    participant ScrollWorker
    participant Logger

    Note over ScrollWorker: In collectPendingL1Messages
    ScrollWorker->>Logger: Log warning if block timestamp is backdated

    Note over ScrollWorker: In newWork
    ScrollWorker->>ScrollWorker: Check if system contract relaxed period is active
    alt Relaxed period active
        ScrollWorker->>ScrollWorker: Set deadline to header time + period
    else
        ScrollWorker->>ScrollWorker: Use standard deadline calculation
    end
Loading

Possibly related PRs

Suggested labels

bump-version

Suggested reviewers

  • colinlyguo
  • omerfirmak

Poem

Hop along the line of code,
I nibble bugs off this old road.
With time tweaks and logs so neat,
Each patch makes our system complete.
A joyful hop in version light—
A rabbit's cheer in code tonight!

✨ Finishing Touches
  • 📝 Generate Docstrings

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings 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: 0

🧹 Nitpick comments (1)
consensus/system_contract/consensus.go (1)

119-124: Excellent enhancement to allow a small timing leeway for future blocks.

This change adds a sophisticated tolerance mechanism for blocks that appear to be slightly in the future:

  1. It captures the current time once at the beginning of the check
  2. For blocks with timestamps in the future, it adds a ~100ms leeway by:
    • Allowing blocks with timestamps exactly 1 second ahead, but only when we're already 900ms into the current second
    • This effectively creates a small buffer to handle timer inaccuracies

This directly addresses the "block in the future" error mentioned in the PR objectives by allowing for small timing discrepancies between different components of the system.

For improved readability, you could extract the leeway logic into a named helper function:

-// Don't waste time checking blocks from the future
-now := time.Now()
-if header.Time > uint64(now.Unix()) {
-    // Add 100ms leeway since the scroll_worker internal timers might trigger early.
-    if uint64(now.Unix())+1 != header.Time || now.Nanosecond() < 900000000 {
-        return consensus.ErrFutureBlock
-    }
-}
+// Don't waste time checking blocks from the future
+now := time.Now()
+if header.Time > uint64(now.Unix()) {
+    // Add 100ms leeway since the scroll_worker internal timers might trigger early.
+    if !isWithinFutureBlockLeeway(now, header.Time) {
+        return consensus.ErrFutureBlock
+    }
+}
+
+// isWithinFutureBlockLeeway checks if the header time is within
+// the allowed leeway (100ms) for future blocks
+func isWithinFutureBlockLeeway(now time.Time, headerTime uint64) bool {
+    return uint64(now.Unix())+1 == headerTime && now.Nanosecond() >= 900000000
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 40ebbd6 and 3411e9f.

📒 Files selected for processing (3)
  • consensus/system_contract/consensus.go (1 hunks)
  • miner/scroll_worker.go (2 hunks)
  • params/version.go (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • params/version.go
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test
🔇 Additional comments (2)
miner/scroll_worker.go (2)

467-467: Enhanced logging for timestamp adjustment during EuclidV2 transition.

This log message provides valuable visibility into when block timestamps are being backdated to ensure they precede the EuclidV2 transition. This will help with debugging and monitoring the transition process.


545-548: Good addition for handling system contracts with relaxed periods.

This change appropriately extends the deadline calculation logic to support system contracts with relaxed periods, similar to how it's handled for Clique consensus. When a system contract is configured with relaxed period, the deadline is now properly calculated as the current header time plus the system contract's period.

This change directly addresses the PR's objective of fixing timing issues, as it ensures that blocks have appropriate deadlines when using system contracts with relaxed periods.

ranchalp
ranchalp previously approved these changes Mar 3, 2025
omerfirmak
omerfirmak previously approved these changes Mar 3, 2025
@Thegaram Thegaram changed the title fix: address timing issue in system config worker fix: accept header at most 100ms earlier than timestamp Mar 3, 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/clique/clique.go (1)

257-261: Good fix for timing issue by adding leeway to future block validation

This change adds a 100ms leeway when checking for blocks from the future, addressing the intermittent "block in the future" errors mentioned in the PR objective. The implementation correctly:

  1. Captures the current time once in a variable to ensure consistency
  2. Applies the leeway only when needed by checking both conditions
  3. Clearly documents the rationale in the comments

For slightly improved readability, you could consider extracting the time difference into a named variable:

 now := time.Now()
-if header.Time > uint64(now.Unix()) && time.Unix(int64(header.Time), 0).Sub(now) > 100*time.Millisecond {
+// Calculate the time difference between block timestamp and current time
+timeDiff := time.Unix(int64(header.Time), 0).Sub(now)
+if header.Time > uint64(now.Unix()) && timeDiff > 100*time.Millisecond {
     return consensus.ErrFutureBlock
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b2fb98e and e9db464.

📒 Files selected for processing (1)
  • consensus/clique/clique.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test
  • GitHub Check: check

@Thegaram Thegaram merged commit 748fb82 into develop Mar 3, 2025
9 checks passed
@Thegaram Thegaram deleted the fix-system-config-worker-timing-issue branch March 3, 2025 15:31
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.

3 participants