Skip to content
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

fix: timestamp include genesis delay #18

Merged
merged 1 commit into from
Oct 17, 2024
Merged

Conversation

zsluedem
Copy link
Collaborator

@zsluedem zsluedem commented Oct 17, 2024

fix #17 #16

Summary by CodeRabbit

  • New Features

    • Introduced a new method for block submission (submit_block_v2) with enhanced optimistic processing capabilities.
    • Added a function to retrieve the genesis time, improving timestamp accuracy in slot management.
  • Bug Fixes

    • Enhanced error handling in payload decoding and header submission processes.
  • Improvements

    • Refined logging and checks for duplicate block hashes and payload delivery status.
    • Updated calculations for slot management to improve temporal accuracy.
    • Improved validation logic for block submissions, ensuring compliance with regional filtering preferences.

Copy link

coderabbitai bot commented Oct 17, 2024

Walkthrough

The pull request introduces significant modifications to the BuilderApi and ProposerApi structs, focusing on improving block submission processes and slot management. A new method, submit_block_v2, is added to handle optimistic block submissions with enhanced validation and error handling. The timestamp calculations are updated to incorporate a genesis_delay, affecting both block submission and slot management methods. Additionally, improvements are made to payload decoding and logging mechanisms, ensuring better handling of block submissions and constraints.

Changes

File Change Summary
crates/api/src/builder/api.rs - Added method: submit_block_v2 for optimistic block submission.
- Updated sanity_check_block_submission for timestamp calculation.
- Enhanced decode_payload and decode_header_submission for GZIP and error handling.
- Improved logging in process_gossiped_header and process_gossiped_payload.
crates/api/src/lib.rs - Added method: get_genesis_time to retrieve genesis time from ChainInfo.
crates/api/src/proposer/api.rs - Updated validate_set_constraints_request and calculate_slot_time_info to include genesis_delay in timestamp calculations.

Assessment against linked issues

Objective Addressed Explanation
Consider genesis delay in timestamp sanity check (#17)

Possibly related PRs

🐇 In the meadow where the bunnies play,
New blocks are submitted in a bright, bold way!
With timestamps adjusted, we hop with glee,
Optimistic processing, as smooth as can be!
Payloads decoded, errors kept at bay,
Hooray for the changes that brighten our day! 🌼


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

@zsluedem zsluedem linked an issue Oct 17, 2024 that may be closed by this pull request
@zsluedem zsluedem linked an issue Oct 17, 2024 that may be closed by this pull request
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: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2f7badd and eee8389.

📒 Files selected for processing (2)
  • crates/api/src/builder/api.rs (1 hunks)
  • crates/api/src/proposer/api.rs (2 hunks)
🧰 Additional context used
🔇 Additional comments (1)
crates/api/src/builder/api.rs (1)

Line range hint 1649-1661: Timestamp calculation correctly includes genesis_delay.

The updated expected_timestamp calculation now adds chain_info.context.genesis_delay, ensuring that the genesis delay is accounted for in timestamp validation during block submissions. This change aligns with the protocol specifications and accurately addresses the issue outlined in the PR objectives.

crates/api/src/proposer/api.rs Outdated Show resolved Hide resolved
crates/api/src/proposer/api.rs Outdated Show resolved Hide resolved
crates/api/src/lib.rs Outdated Show resolved Hide resolved
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.

Caution

Inline review comments failed to post

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (1)
crates/api/src/lib.rs (1)

22-27: LGTM: Function implementation is correct and aligns with PR objectives.

The get_genesis_time function correctly incorporates the genesis delay in timestamp calculations, addressing the issues mentioned in the PR objectives. The error handling is appropriate, providing a fallback calculation if genesis_time() fails.

Consider adding a brief documentation comment explaining the function's purpose and its fallback behavior. For example:

/// Returns the genesis time, considering the genesis delay if necessary.
/// Falls back to calculating genesis time from genesis_time_in_secs and genesis_delay
/// if the context's genesis_time() method fails.
pub fn get_genesis_time(chain_info: &ChainInfo) -> u64 {
    // ... (existing implementation)
}
🛑 Comments failed to post (1)
crates/api/src/builder/api.rs (1)

1650-1651: 💡 Codebase verification

get_genesis_time does not conditionally handle genesis delay for different network types

The get_genesis_time function applies genesis_delay uniformly without distinguishing between testnet and mainnet. This may lead to incorrect timestamp calculations for different network environments.

  • File: crates/api/src/lib.rs
🔗 Analysis chain

Ensure get_genesis_time correctly handles genesis delay for both testnet and mainnet

The function get_genesis_time is introduced to account for the genesis delay in timestamp calculations. Please verify that this function accurately computes the genesis time for both testnets (where genesis_time = min_genesis_time + genesis_delay) and mainnet (where genesis delay may differ or be zero), to prevent potential discrepancies in timestamp validation.

Run the following script to verify the implementation:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that `get_genesis_time` handles genesis delay correctly for both testnet and mainnet.

# Search for the definition and implementation of `get_genesis_time`.
rg --type rust -A 10 'fn get_genesis_time'

# Expected result: The function should conditionally include `genesis_delay` based on the network type.

Length of output: 415


Script:

#!/bin/bash
# Description: Check if `get_genesis_time` conditionally applies `genesis_delay` based on network type.

# Search for conditional statements involving network types within `get_genesis_time`.
rg --type rust 'fn get_genesis_time' -A 20 | rg -i 'testnet|mainnet|network_type|if|match'

Length of output: 160

Copy link

@chirag-bgh chirag-bgh left a comment

Choose a reason for hiding this comment

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

LGTM

@zsluedem zsluedem merged commit 03506d4 into taiyi Oct 17, 2024
1 of 2 checks passed
@zsluedem zsluedem deleted the fix-genesis-timestamp-delay branch October 17, 2024 06: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: 0

🧹 Outside diff range and nitpick comments (2)
crates/api/src/proposer/api.rs (1)

Line range hint 1-1325: Consider refactoring repeated timestamp calculations

While the current changes correctly address the genesis delay issue, there are still instances of repeated timestamp calculations throughout the file. For example, similar calculations are found in the calculate_slot_time_info function (around line 1325) and potentially in other methods.

To improve code maintainability and reduce the risk of inconsistencies, consider refactoring these repeated calculations into a single helper function. This would ensure that all timestamp calculations consistently use the get_genesis_time function and follow the same logic.

Would you like assistance in identifying all occurrences of timestamp calculations and proposing a refactored solution?

crates/api/src/builder/api.rs (1)

Line range hint 1012-1180: Well-implemented submit_block_v2 method with enhanced features

The new submit_block_v2 method is a comprehensive implementation that includes various checks, validations, and optimizations for block submission. It properly handles optimistic processing, builder collateral checks, and integrates well with the auctioneer and database services.

However, given the method's complexity and length, consider refactoring it to improve maintainability:

  1. Extract some of the validation logic into separate private methods.
  2. Use early returns for error cases to reduce nesting.
  3. Consider creating a separate struct to hold the state of the submission process, which could be passed between the extracted methods.

Here's a high-level example of how you might start refactoring:

impl<A, DB, S, G> BuilderApi<A, DB, S, G>
where
    // ... existing where clauses ...
{
    pub async fn submit_block_v2(...) -> Result<StatusCode, BuilderApiError> {
        let mut submission = BlockSubmissionV2::new(request_id, ...);
        
        submission.decode_payload(req).await?;
        submission.validate_slot(self.curr_slot_info.read().await)?;
        submission.fetch_and_validate_payload_attributes(&self.payload_attributes).await?;
        submission.validate_builder_info(self.auctioneer.as_ref()).await?;
        // ... more validation steps ...

        self.process_valid_submission(submission).await
    }

    async fn process_valid_submission(&self, submission: BlockSubmissionV2) -> Result<StatusCode, BuilderApiError> {
        // ... handle the actual submission process ...
    }
}

struct BlockSubmissionV2 {
    request_id: Uuid,
    trace: SubmissionTrace,
    payload: Option<SignedBidSubmission>,
    // ... other fields as needed ...
}

impl BlockSubmissionV2 {
    fn new(request_id: Uuid, ...) -> Self { ... }
    
    async fn decode_payload(&mut self, req: Request<Body>) -> Result<(), BuilderApiError> { ... }
    async fn validate_slot(&self, curr_slot_info: &(u64, Option<BuilderGetValidatorsResponseEntry>)) -> Result<(), BuilderApiError> { ... }
    // ... other validation methods ...
}

This refactoring would make the main submit_block_v2 method more readable and easier to maintain, while also improving testability of individual components.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 68e59a0 and 64df57a.

📒 Files selected for processing (3)
  • crates/api/src/builder/api.rs (2 hunks)
  • crates/api/src/lib.rs (2 hunks)
  • crates/api/src/proposer/api.rs (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/api/src/lib.rs
🧰 Additional context used
🔇 Additional comments (5)
crates/api/src/proposer/api.rs (2)

57-57: LGTM: New import for genesis time calculation

The addition of the get_genesis_time import is in line with the PR objective to include the genesis delay in timestamp calculations. This change appears to be correct and necessary for the implementation of the fix.


853-854: LGTM: Improved genesis time calculation for constraint validation

This change correctly implements the fix for including the genesis delay in timestamp calculations, addressing the issue described in #17. By using the get_genesis_time function, the code now properly accounts for the genesis delay specified in the network configuration.

This modification is crucial for ensuring accurate timestamp validation during the sanity check process, resolving the 60-second discrepancy mentioned in the issue.

crates/api/src/builder/api.rs (3)

1650-1651: Excellent addition to address the genesis delay issue!

This change correctly incorporates the genesis time when calculating the expected timestamp for block submissions. It addresses the issue mentioned in #17, ensuring that the sanity check considers the genesis delay specified in the network configuration.


Line range hint 1-1651: Summary of changes in crates/api/src/builder/api.rs

  1. The sanity_check_block_submission function has been updated to consider the genesis delay when calculating the expected timestamp, addressing the issue mentioned in Helix does't consider genesis delay when sanity check #17.
  2. A new submit_block_v2 method has been added, providing enhanced functionality for block submissions with optimistic processing and additional checks.
  3. The get_genesis_time function has been introduced to support the new timestamp calculation.

These changes appear to effectively address the PR objectives and improve the overall functionality of the builder API. The main areas for potential improvement are:

  1. Refactoring the submit_block_v2 method to enhance maintainability.
  2. Verifying the correct implementation of the get_genesis_time function.

52-52: Verify the implementation of get_genesis_time

The new get_genesis_time function is crucial for correctly calculating the expected timestamp in the sanity_check_block_submission function. However, its implementation is not visible in this file.

Please ensure that the get_genesis_time function is correctly implemented and returns the genesis time including the genesis delay. You can verify this by running the following command:

This will help locate the implementation of the function and allow for a review of its correctness.

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.

Helix does't consider genesis delay when sanity check SetConstraintsTooLate even it is 3 slots away
2 participants