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: randomX seed management #6910

Merged

Conversation

SWvheerden
Copy link
Collaborator

@SWvheerden SWvheerden commented Apr 2, 2025

Description

Atm we dont remove old seeds if we reorg the chain.
If we mine a block while syncing it might be that we insert the first seen height of the monero seed way too early and thus cause the node to think the seed is too old when verifying the chain. This PR will remove seeds for blocks that have been reorged out of the chain.

Summary by CodeRabbit

  • New Features

    • Introduced a new database index for improved seed height tracking, ensuring consistent management during block header deletions and insertions.
    • Added a conversion method to transform internal byte arrays into more flexible vector formats.
    • Enhanced block validation by incorporating additional checks on Monero seed height to maintain protocol integrity.
  • Refactor

    • Streamlined proof-of-work data verification by removing legacy logic and unnecessary parameters for a cleaner validation process.

@SWvheerden SWvheerden requested a review from a team as a code owner April 2, 2025 13:09
Copy link
Contributor

coderabbitai bot commented Apr 2, 2025

Walkthrough

This pull request enhances the Monero seed management by introducing a new LMDB index for mapping block heights to RandomX seeds. It updates the LMDB database creation, deletion, and insertion operations accordingly. Additionally, a new method is added to convert a fixed byte array into a vector, and the block body validator now validates Monero seed height against consensus rules. Separately, the header validator has been streamlined by removing Monero-specific proof-of-work checks.

Changes

File(s) Change Summary
base_layer/core/src/chain_storage/lmdb_db/…/lmdb_db.rs Added constant LMDB_DB_MONERO_SEED_HEIGHT_INDEX, new field monero_seed_height_index_db, and updated database creation. Updated deletion and insertion methods to keep indexes in sync.
base_layer/core/src/proof_of_work/monero_rx/fixed_array.rs Added a new public method to_vec to convert the internal byte array to a Vec<u8>.
base_layer/core/src/validation/block_body/block_body_full_validator.rs Introduced check_monero_seed_height to validate Monero seed height and updated validate to invoke this check.
base_layer/core/src/validation/header/header_full_validator.rs Modified check_pow_data by removing unnecessary parameters and Monero-specific PoW logic, with corresponding update to its usage in validate.
base_layer/core/tests/tests/block_validation.rs Updated test_monero_blocks to use BlockBodyFullValidator instead of MockValidator for enhanced validation logic.

Possibly related PRs

  • fix!: monero seed validation #6850: Addresses enhancements in Monero seed validation and database handling, closely related to the modifications in index management and seed height checks.

📜 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 0db015e and 1fbffd8.

📒 Files selected for processing (1)
  • base_layer/core/tests/tests/block_validation.rs (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
base_layer/core/tests/tests/block_validation.rs (4)
base_layer/core/src/chain_storage/blockchain_database.rs (4)
  • new (160-170)
  • new (233-252)
  • smt (399-401)
  • db (1733-1768)
base_layer/core/src/test_helpers/blockchain.rs (4)
  • new (166-175)
  • new (557-579)
  • db (191-193)
  • db (622-624)
base_layer/core/src/transactions/test_helpers.rs (1)
  • new (117-152)
base_layer/core/src/blocks/block_header.rs (1)
  • new (127-146)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: test (nextnet, nextnet)
  • GitHub Check: test (mainnet, stagenet)
  • GitHub Check: cargo check with stable
  • GitHub Check: ci
🔇 Additional comments (2)
base_layer/core/tests/tests/block_validation.rs (2)

129-129: Validator implementation changed to use full validator instead of mock.

The change replaces the mock validator with a real implementation of BlockBodyFullValidator that will perform complete validation, including the new Monero seed height validation logic.


133-133: Updated Validators configuration.

The Validators::new call now uses the previously defined block_validator (full validator) instead of a mock validator, which ensures that the test properly exercises the new seed management functionality. This change aligns with the PR objective to fix the RandomX seed management issue.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 plan to trigger planning for file edits and PR creation.
  • @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
Contributor

@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
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 594713c and 2107f9a.

📒 Files selected for processing (2)
  • base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs (8 hunks)
  • base_layer/core/src/proof_of_work/monero_rx/fixed_array.rs (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs (1)
base_layer/core/src/chain_storage/lmdb_db/lmdb.rs (4)
  • lmdb_get (233-256)
  • lmdb_delete (169-182)
  • lmdb_replace (132-166)
  • lmdb_insert (55-103)
🔇 Additional comments (5)
base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs (5)

166-166: New database index for RandomX seed mapping looks good.

Adding this new constant for mapping block heights to RandomX seeds is a good approach for solving the reorg issue mentioned in the PR description.


281-282: Well-documented field addition.

The field is properly documented with a clear comment explaining its purpose of mapping block heights to randomx seeds.


343-343: Proper database initialization.

The new index database is correctly initialized in the constructor.


562-589: Complete all_dbs update.

The method signature and array contents are properly updated to include the new database index, ensuring it's included in all database operations.


963-977: Good implementation of seed cleanup during header deletion.

This change is crucial for fixing the issue mentioned in the PR. When a header is deleted (e.g., during a reorg), the code now checks for and removes any associated seed from both the height-to-seed index and the seed-to-height mapping. This prevents seeds from orphaned blocks lingering in the database.

@SWvheerden SWvheerden changed the title fix!: randomX seed management fix: randomX seed management Apr 2, 2025
Copy link

github-actions bot commented Apr 2, 2025

Test Results (CI)

    2 files     73 suites   27m 10s ⏱️
1 352 tests 1 351 ✅ 0 💤 1 ❌
2 433 runs  2 432 ✅ 0 💤 1 ❌

For more details on these failures, see this check.

Results for commit 0db015e.

♻️ This comment has been updated with latest results.

Copy link

github-actions bot commented Apr 2, 2025

Test Results (Integration tests)

0 tests   0 ✅  0s ⏱️
0 suites  0 💤
0 files    0 ❌

Results for commit 3c671e5.

@SWvheerden SWvheerden force-pushed the sw_manage_monero_seeds branch from 3c671e5 to 05ed8b7 Compare April 2, 2025 14:37
@SWvheerden SWvheerden force-pushed the sw_manage_monero_seeds branch from dfb91f1 to 0db015e Compare April 2, 2025 15:49
Copy link
Contributor

@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)
base_layer/core/src/validation/block_body/block_body_full_validator.rs (1)

110-122: Consider adding debug logging for RandomX seed validation

While the validation logic is correct, adding debug logging would help diagnose issues when blocks are rejected due to outdated seeds, especially during the resynchronization process that this PR requires.

    fn check_monero_seed_height<B: BlockchainBackend>(
        header: &BlockHeader,
        rules: &ConsensusManager,
        backend: &B,
    ) -> Result<(), ValidationError> {
        if header.pow.pow_algo == PowAlgorithm::RandomX {
            let monero_data = MoneroPowData::from_header(header, rules)?;
            let seed_height = backend.fetch_monero_seed_first_seen_height(&monero_data.randomx_key)?;
+           log::debug!(
+               target: LOG_TARGET,
+               "Block at height {} using RandomX seed first seen at height {}",
+               header.height,
+               seed_height
+           );
            if seed_height != 0 {
                // Saturating sub: subtraction can underflow in reorgs / rewind-blockchain command
                let seed_used_height = header.height.saturating_sub(seed_height);
+               log::debug!(
+                   target: LOG_TARGET,
+                   "Seed age (blocks): {}, maximum allowed: {}",
+                   seed_used_height,
+                   rules.consensus_constants(header.height).max_randomx_seed_height()
+               );
                if seed_used_height > rules.consensus_constants(header.height).max_randomx_seed_height() {
+                   log::warn!(
+                       target: LOG_TARGET,
+                       "Block at height {} rejected: RandomX seed too old (age: {}, max: {})",
+                       header.height,
+                       seed_used_height,
+                       rules.consensus_constants(header.height).max_randomx_seed_height()
+                   );
                    return Err(ValidationError::BlockHeaderError(
                        BlockHeaderValidationError::OldSeedHash,
                    ));
                }
            }
        }
        Ok(())
    }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1c60911 and 0db015e.

📒 Files selected for processing (2)
  • base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs (11 hunks)
  • base_layer/core/src/validation/block_body/block_body_full_validator.rs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: test (nextnet, nextnet)
  • GitHub Check: test (mainnet, stagenet)
  • GitHub Check: cargo check with stable
  • GitHub Check: ci
🔇 Additional comments (3)
base_layer/core/src/validation/block_body/block_body_full_validator.rs (3)

31-34: Appropriate import additions for RandomX seed validation

The added imports for BlockHeader, BlockHeaderValidationError, and MoneroPowData are well-aligned with the new functionality for validating Monero seed heights.


100-101: Good integration of the new Monero seed height validation

Calling the new validation method here is appropriately placed after the other validation checks. This ensures that the Monero seed height is verified as part of the block validation process.


105-124:

❓ Verification inconclusive

Well-implemented validation for RandomX seed age

The implementation correctly validates that RandomX seeds aren't too old according to consensus rules. The method appropriately:

  1. Checks if the block uses RandomX algorithm
  2. Retrieves the seed's first seen height
  3. Calculates the seed age using saturating subtraction (to handle reorgs safely)
  4. Validates against the maximum allowed seed age

The saturating subtraction is a good approach to handle potential underflows during reorgs or blockchain rewinds.

Since this is a breaking change that requires resynchronization, we should verify the implications. Run this script to check the current implementation of fetch_monero_seed_first_seen_height:


🏁 Script executed:

#!/bin/bash
# Find implementation of fetch_monero_seed_first_seen_height to understand how it integrates with the new LMDB index
rg --type rust "fn fetch_monero_seed_first_seen_height" -A 5 -B 2

Length of output: 2410


Verified: RandomX Seed Age Validation and LMDB Integration
The validation logic for ensuring that RandomX seeds aren’t too old is implemented correctly. The function correctly:

  • Checks if the block uses the RandomX algorithm.
  • Constructs the Monero proof-of-work data from the header.
  • Retrieves the seed’s first seen height via backend.fetch_monero_seed_first_seen_height. The LMDB integration (verified in lmdb_db/lmdb_db.rs) confirms that the function returns 0 when the seed is unknown.
  • Uses saturating subtraction to safely calculate the seed age while guarding against underflows in reorgs or chain rewinds.
  • Compares the seed age against the maximum allowed age from consensus constants.

Note: Since this change modifies how seed heights are fetched (and thus represents a breaking change that requires resynchronization of the LMDB index), please ensure that the resynchronization procedures and database state updates are thoroughly verified in your deployment.

@SWvheerden SWvheerden merged commit 8f43ff5 into tari-project:development Apr 2, 2025
12 checks passed
@SWvheerden SWvheerden deleted the sw_manage_monero_seeds branch April 3, 2025 08:22
sdbondi added a commit to sdbondi/tari that referenced this pull request Apr 3, 2025
* development:
  chore: new release v1.13.3-pre.0 (tari-project#6919)
  fix: fix migration 5 (tari-project#6915)
  chore: update change logs (tari-project#6913)
  chore: new release v1.13.2-pre.0 (tari-project#6912)
  fix: randomX seed management (tari-project#6910)
  fix(comms/yamux): dont poll the substream after closing/error (tari-project#6911)
  fix: dont poll yamux substream after an error (tari-project#6909)
  feat: remove memory allocation for max_size_vec (tari-project#6903)
  feat: add display info to yamux (tari-project#6904)
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.

1 participant