Skip to content

fix: correctly select consensus engine during EuclidV2 transition #1130

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

Conversation

Thegaram
Copy link

@Thegaram Thegaram commented Mar 3, 2025

1. Purpose or design rationale of this PR

#1102 added UpgradableEngine, a consensus engine that chooses one of Clique and SystemContract based on the block timestamp.

However, as noted in #1126, this will not work well in multiple scenarios:

This PR fixes this by adding a timestamp override mechanism to consensus.Engine. UpgradableEngine inspects the resulting timestamps and chooses the correct engine accordingly. ScrollWorker re-runs Prepare with a timestamp override if needed.

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

  • New Features

    • Introduced an optional block timestamp override and a standardized timestamp calculation mechanism, enhancing control over block generation.
  • Refactor

    • Streamlined block assembly and consensus engine selection by centralizing time management and simplifying transition handling for pending messages.
  • Chores

    • Incremented the patch version, reflecting the latest update improvements.

Copy link

coderabbitai bot commented Mar 3, 2025

Walkthrough

The pull request introduces enhancements to timestamp handling across multiple consensus modules. A new CalcTimestamp method is added to various consensus engines, allowing for the calculation of block timestamps based on the parent header and configuration settings. The Prepare method in these engines now includes an optional timeOverride parameter, enabling explicit timestamp usage. Additionally, the chooseEngine method in the UpgradableEngine is updated to use a timestamp directly. Other changes include adjustments in L1 message handling during fork transitions and a patch version increment in the versioning constants.

Changes

File(s) Change Summary
consensus/clique/clique.go, consensus/consensus.go, consensus/ethash/consensus.go, consensus/system_contract/consensus.go Added a new CalcTimestamp(parent *types.Header) uint64 method and updated the Prepare method signature to include an optional parameter timeOverride *uint64 for refined timestamp handling.
consensus/wrapper/consensus.go Updated chooseEngine to accept a uint64 timestamp, added CalcTimestamp, and modified Prepare to include timeOverride *uint64, adjusting engine selection based on timestamp.
core/blockchain.go Modified BuildAndWriteBlock to pass the original timestamp via a pointer (&originalTime) to the engine during block preparation and removed header time resetting logic.
eth/catalyst/api.go Updated the internal call to Engine.Prepare by adding a third parameter (nil) to match the new signature.
miner/scroll_worker.go Altered L1 message handling in collectPendingL1Messages and introduced a new variable (nextL1MsgIndex) in newWork; updated the call to Prepare to include time override logic during EuclidV2 transitions.
params/version.go Bumped the VersionPatch constant from 19 to 20.

Sequence Diagram(s)

sequenceDiagram
    participant BC as BlockChain
    participant CE as Consensus Engine
    participant CLK as Clock/Time Source

    BC->>CE: Prepare(chain, header, timeOverride)
    alt timeOverride provided
        CE-->>BC: Use provided timeOverride for header timestamp
    else
        CE->>CE: CalcTimestamp(parent header)
        alt Calculated timestamp is in past or relaxed period enabled
            CE->>CLK: Fetch current time
            CE-->>CE: Adjust timestamp to current time
        end
        CE-->>BC: Return computed timestamp in header
    end
    BC->>BC: Write block with finalized header
Loading
sequenceDiagram
    participant UE as UpgradableEngine
    participant E as SelectedConsensusEngine

    UE->>UE: Extract timestamp from header or use timeOverride
    UE->>UE: chooseEngine(timestamp)
    UE-->>E: Return selected consensus engine
    UE->>E: Call Prepare(chain, header, timeOverride)
Loading

Possibly related PRs

Suggested labels

bump-version

Suggested reviewers

  • georgehao
  • colinlyguo

Poem

I'm a little rabbit, hopping through the code,
Timestamps now dance with a fresh, new mode.
Overriding time or computing it right,
My hoppy methods shine ever so bright.
Code and carrots, both a delight! 🐇💻


📜 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 af424a5 and 630c4e6.

📒 Files selected for processing (1)
  • miner/scroll_worker.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • miner/scroll_worker.go
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test

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.

@Thegaram Thegaram marked this pull request as ready for review March 3, 2025 20:40
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

🧹 Nitpick comments (3)
core/blockchain.go (1)

1835-1838: Preserve the original timestamp when signing blocks
Passing &originalTime into bc.engine.Prepare is a clean way to ensure the timestamp isn't overwritten by the consensus engine. Consider adding unit tests around this logic to verify that the timestamp remains intact when signing is enabled.

consensus/consensus.go (1)

82-82: Clarify behavior of the new 'timeOverride' parameter in Prepare
Document more clearly that a non-nil timeOverride instructs the engine to use that time value and skip its usual timestamp logic. This helps avoid confusion for future maintainers.

consensus/wrapper/consensus.go (1)

154-157: Unimplemented CalcTimestamp method triggers a panic
Currently, calling this method will cause a runtime error. Consider either implementing it or removing it if not used.

Below is an example implementation delegating to the chosen engine, if that matches your intent:

-func (ue *UpgradableEngine) CalcTimestamp(parent *types.Header) uint64 {
-	panic("Called CalcTimestamp on UpgradableEngine, not implemented")
-}
+func (ue *UpgradableEngine) CalcTimestamp(parent *types.Header) uint64 {
+    // Delegate to the underlying engine based on the parent's timestamp
+    return ue.chooseEngine(parent.Time).CalcTimestamp(parent)
+}

Would you like me to open a new issue or provide a full implementation?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 748fb82 and 732eae8.

📒 Files selected for processing (9)
  • consensus/clique/clique.go (2 hunks)
  • consensus/consensus.go (2 hunks)
  • consensus/ethash/consensus.go (1 hunks)
  • consensus/system_contract/consensus.go (2 hunks)
  • consensus/wrapper/consensus.go (6 hunks)
  • core/blockchain.go (1 hunks)
  • eth/catalyst/api.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 (27)
eth/catalyst/api.go (1)

153-153: Updated method call to match the new Engine interface.

The Prepare method call has been updated to include an additional nil parameter, which aligns with the new Engine interface that accepts an optional timeOverride parameter.

consensus/ethash/consensus.go (2)

582-584: Added unimplemented CalcTimestamp method that throws a panic.

The method is required to fulfill the Engine interface, but it's not actually implemented for Ethash. This approach clearly communicates that this functionality isn't supported in Ethash.

However, consider the implications of using a panic in a production system. If this method somehow gets called, it will crash the application rather than returning an error that could be handled gracefully.

Would it be safer to return a predictable fallback value or error rather than panicking? Or is the panic intentional to ensure this path is never accidentally taken?


588-588: Updated Prepare method signature to include timeOverride parameter.

The method signature has been updated to match the changes in the Engine interface, which now accepts an optional timestamp override parameter.

consensus/clique/clique.go (3)

510-520: Added CalcTimestamp method for flexible timestamp calculation.

This new method encapsulates the logic for calculating block timestamps, considering both the configured period and real-time constraints. It properly handles the RelaxedPeriod configuration, ensuring timestamps are always current when needed.


524-524: Updated Prepare method signature to include timeOverride parameter.

The method signature has been updated to match the changes in the Engine interface, adding support for an optional timestamp override.


583-587: Refactored timestamp calculation logic to use the new CalcTimestamp method.

The timestamp setting logic has been improved to either use an explicitly provided timestamp override or call the new CalcTimestamp method. This refactoring improves code organization by centralizing timestamp calculation logic.

consensus/system_contract/consensus.go (3)

228-238: Added CalcTimestamp method with logic consistent with Clique implementation.

This implementation calculates a block timestamp based on the parent's timestamp and configured period, with appropriate handling for RelaxedPeriod. The consistency with the Clique implementation is good for maintaining uniform behavior across consensus engines.


242-242: Updated Prepare method signature to include timeOverride parameter.

The method signature has been updated to match the changes in the Engine interface, adding support for an optional timestamp override.


258-262: Refactored timestamp calculation logic to use the new CalcTimestamp method.

The modification provides a clear choice between using an explicitly provided timestamp or calculating one based on established rules. This change properly integrates with the EuclidV2 transition mentioned in the PR objective.

consensus/consensus.go (1)

114-117: Ensure comprehensive tests for CalcTimestamp
The newly introduced CalcTimestamp method should be tested under various scenarios (e.g., parent’s timestamp close to or equal to the next block’s). Include boundary cases to ensure correct behavior across different consensus transitions.

miner/scroll_worker.go (2)

497-501: Handle default L1 message index with care
Reading the parent’s queue index and defaulting to zero if absent works fine, but ensure that edge cases (e.g., genesis or missed writes) don’t cause silent off-by-one issues. A quick test verifying the fallback to zero explicitly can help prevent regressions.


511-511: Nil timeOverride usage
Here, Prepare is called with a nil time override, signaling that the engine should manage the header time as usual. Confirm that this is intended behavior in all normal mining scenarios without special overrides.

consensus/wrapper/consensus.go (15)

42-43: Refactored to a timestamp-based signature for chooseEngine
This new approach cleanly separates engine selection from header details, ensuring future flexibility.


54-54: Consistent use of timestamp-based engine selection in Author
Switching to header.Time for engine detection aligns well with the updated chooseEngine function.


59-59: Unified engine selection in VerifyHeader
This preserves the same logic while simplifying the parameter flow. The approach looks good.


75-76: Batch verification starts and ends with timestamp checks
Relying on the first and last header timestamps to determine engine transitions is valid under single-transition assumptions.


92-92: Conditional transition to system engine
The conditional logic for identifying system headers mid-batch is well-structured and aligns with the single-switchover assumption.


159-163: Time override logic in Prepare
This conditional override is helpful, but ensure inputs can't cause unexpected transitional edge cases (e.g., an override less than the parent's time).


165-169: Graceful handling of unknown ancestors
Properly returning ErrUnknownAncestor if the parent is missing is a robust error-check.


170-185: Clique-based transition block detection
Calculating clique timestamp for the parent, then deciding if the child block transitions to EuclidV2 is logical. Double-check boundary conditions where the parent's time is near the switchover threshold.


186-199: Post-EuclidV2 timestamp handling
Transition logic here correctly accounts for the possibility of reverting to clique by accident. Confirm that scenario never legitimately occurs.


204-204: Engine selection for Seal
Aligns with the new pattern of using block.Time().


209-209: Time-based difficulty calculation
The approach of re-selecting the engine based on parent.Time remains consistent with prior logic.


214-214: Finalize via chosen engine
Delegating finalization is a straightforward and coherent extension.


219-219: Finalize-and-assemble via chosen engine
Methodically follows the same pattern, promoting consistency in final assembly logic.


224-224: Timestamp-based uncle verification
Calling VerifyUncles on the appropriate engine is properly aligned with the overarching design.


249-249: Utilize chosen engine's SealHash
Sealing logic now uniformly routes through chooseEngine(header.Time), ensuring consistent calculations.

georgehao
georgehao previously approved these changes Mar 4, 2025
colinlyguo
colinlyguo previously approved these changes Mar 4, 2025
@Thegaram Thegaram dismissed stale reviews from georgehao and colinlyguo via 630c4e6 March 4, 2025 11:20
@Thegaram Thegaram merged commit 3c454e7 into develop Mar 4, 2025
9 checks passed
@Thegaram Thegaram deleted the fix-euclidv2-transition-consensus-engine branch March 4, 2025 11:25
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.

4 participants