Skip to content

fix!: sync#7088

Merged
SWvheerden merged 2 commits intotari-project:developmentfrom
SWvheerden:sw_fix_sync
May 23, 2025
Merged

fix!: sync#7088
SWvheerden merged 2 commits intotari-project:developmentfrom
SWvheerden:sw_fix_sync

Conversation

@SWvheerden
Copy link
Copy Markdown
Collaborator

@SWvheerden SWvheerden commented May 23, 2025

Description

Adds a validation of allowed algo type
Fixes sync to ensure node correctly updates the consensus constants when going over swap heights

Summary by CodeRabbit

  • New Features

    • Introduced enhanced header validation with tracking and usage of VM keys at specific block heights.
    • Added validation to ensure only permitted proof-of-work algorithms are accepted according to consensus rules.
  • Bug Fixes

    • Improved orphan block validation by ensuring correct VM key context is used during processing.
  • Other Improvements

    • Updated internal mechanisms for managing and updating permitted proof-of-work algorithms.
    • Expanded error reporting for invalid proof-of-work algorithms.

@SWvheerden SWvheerden requested a review from a team as a code owner May 23, 2025 10:19
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented May 23, 2025

## Walkthrough

This change introduces the concept of a "vm_key" (a block hash at a computed height) into block header validation and orphan block processing. The validator now tracks, caches, and passes the vm_key as context during validation, updating the cache at regular intervals. Related method signatures and trait interfaces are updated to accommodate this additional parameter.

## Changes

| File(s)                                                                                                 | Change Summary                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
|---------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| base_layer/core/src/base_node/sync/header_sync/validator.rs                                             | Added a `vm_key` cache to the validator state, seeded at genesis. Updated validation logic to compute, retrieve, and cache vm_key hashes, passing them to the header validator, and updating the cache at defined intervals.                                                                                                 |
| base_layer/core/src/chain_storage/blockchain_database.rs                                                | Added a helper to compute the vm_key for candidate/orphan blocks. Updated orphan block validation logic to fetch and pass the vm_key hash to the validator.                                                                                                                      |
| base_layer/core/src/validation/header/header_full_validator.rs                                          | Updated the `validate` method and trait implementation to require a vm_key parameter. Removed internal vm_key lookup logic. Enhanced proof-of-work validation to check algorithm validity against consensus rules.                                                                |
| base_layer/core/src/validation/traits.rs<br>base_layer/core/src/validation/mocks.rs                     | Updated the `HeaderChainLinkedValidator` trait and its mock implementation to include the vm_key parameter in the `validate` method signature.                                                                                                                                    |
| base_layer/core/src/chain_storage/target_difficulties.rs                                                | Added methods to update permitted proof-of-work algorithms and count them, ensuring current consensus rules are respected at a given height.                                                                                                                                    |
| base_layer/core/src/blocks/block_header.rs                                                              | Added a new error variant for invalid proof-of-work algorithms.                                                                                                                                                                                                                                                         |
| base_layer/core/src/validation/difficulty_calculator.rs                                                 | Made the `TARI_RX_VM_KEY_BLOCK_SWAP` constant public.                                                                                                                                                                                                                                                                    |
| base_layer/core/src/validation/helpers.rs                                                               | Removed a redundant blank line; no logic changes.                                                                                                                                                                                                                                                                        |
| base_layer/core/src/validation/test.rs<br>base_layer/core/tests/tests/block_validation.rs               | Updated test calls to `validate` methods to include the new `vm_key` parameter, typically passing `FixedHash::zero()`.                                                                                                                                                                  |

## Sequence Diagram(s)

```mermaid
sequenceDiagram
    participant Validator
    participant State
    participant DB
    participant HeaderValidator

    Validator->>State: Retrieve/calculate vm_key for header.height
    State->>DB: Try fetch vm_key hash at vm_key_height
    alt Not found in DB
        State->>State: Search vm_key cache
    end
    Validator->>HeaderValidator: validate(header, prev_header, ..., vm_key)
    HeaderValidator->>HeaderValidator: Check PoW algorithm validity
    HeaderValidator->>HeaderValidator: Validate header with vm_key context
    alt header.height % TARI_RX_VM_KEY_BLOCK_SWAP == 0
        Validator->>State: Update vm_key cache with (height, hash)
    end

Possibly related PRs

  • feat!: vm calc height #7082: Refactored vm_key height calculation logic, which is now leveraged and extended in this PR for improved header validation and orphan block processing.

Suggested reviewers

  • hansieodendaal

Poem

In fields of code where hashes hop,
The vm_key leaps from block to block.
With every swap and every check,
The headers march, their chains connect.
Now orphan blocks can find their way—
A bunny’s guide through blockchain hay!
🐇🔑✨


<!-- walkthrough_end -->


---

<details>
<summary>📜 Recent review details</summary>

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


<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between cf14e382936a692ea67d0e8e5d4a9faaa30d86ea and 60121f451f3f4a078cc352943684dcbeb1409284.

</details>

<details>
<summary>📒 Files selected for processing (6)</summary>

* `base_layer/core/src/base_node/sync/header_sync/validator.rs` (8 hunks)
* `base_layer/core/src/chain_storage/blockchain_database.rs` (4 hunks)
* `base_layer/core/src/chain_storage/target_difficulties.rs` (2 hunks)
* `base_layer/core/src/validation/header/header_full_validator.rs` (3 hunks)
* `base_layer/core/src/validation/test.rs` (4 hunks)
* `base_layer/core/tests/tests/block_validation.rs` (9 hunks)

</details>

<details>
<summary>🚧 Files skipped from review as they are similar to previous changes (4)</summary>

* base_layer/core/src/chain_storage/target_difficulties.rs
* base_layer/core/src/base_node/sync/header_sync/validator.rs
* base_layer/core/src/validation/header/header_full_validator.rs
* base_layer/core/src/chain_storage/blockchain_database.rs

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🧬 Code Graph Analysis (1)</summary>

<details>
<summary>base_layer/core/src/validation/test.rs (5)</summary><blockquote>

<details>
<summary>base_layer/core/src/chain_storage/blockchain_database.rs (1)</summary>

* `db` (1687-1722)

</details>
<details>
<summary>base_layer/core/src/test_helpers/blockchain.rs (2)</summary>

* `db` (191-193)
* `db` (675-677)

</details>
<details>
<summary>base_layer/core/src/blocks/accumulated_data.rs (2)</summary>

* `header` (279-281)
* `header` (345-347)

</details>
<details>
<summary>base_layer/core/src/blocks/historical_block.rs (1)</summary>

* `header` (56-58)

</details>
<details>
<summary>base_layer/wallet/src/output_manager_service/service.rs (1)</summary>

* `zero` (3566-3573)

</details>

</blockquote></details>

</details>

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (7)</summary>

* GitHub Check: test (mainnet, stagenet)
* GitHub Check: test (nextnet, nextnet)
* GitHub Check: test (testnet, esmeralda)
* GitHub Check: ci
* GitHub Check: cargo check with stable
* GitHub Check: Cucumber tests / FFI
* GitHub Check: Cucumber tests / Base Layer

</details>

<details>
<summary>🔇 Additional comments (13)</summary><blockquote>

<details>
<summary>base_layer/core/src/validation/test.rs (4)</summary>

`51-51`: **LGTM: Import addition is correct and necessary.**

The `FixedHash` import is properly added to support the new `vm_key` parameter in the header validation calls.

---

`122-129`: **LGTM: Header validation call correctly updated.**

The addition of `FixedHash::zero()` as the `vm_key` parameter is appropriate for this test scenario and maintains compatibility with the updated `HeaderFullValidator` interface.

---

`157-157`: **LGTM: Consistent parameter addition.**

The `vm_key` parameter is correctly added with the appropriate default value for testing purposes.

---

`170-170`: **LGTM: Error case validation properly updated.**

The `vm_key` parameter addition maintains the test's ability to validate error conditions correctly.

</details>
<details>
<summary>base_layer/core/tests/tests/block_validation.rs (9)</summary>

`537-537`: **LGTM: Test adaptation for orphan body validation.**

The `vm_key` parameter is correctly added to maintain compatibility with the updated header validator interface.

---

`566-566`: **LGTM: Chain sequence validation test properly updated.**

The parameter addition maintains the test's ability to validate broken chain sequences correctly.

---

`610-610`: **LGTM: Unknown inputs validation test updated correctly.**

The addition of the `vm_key` parameter preserves the test's validation logic for unknown inputs scenarios.

---

`643-643`: **LGTM: Duplicate transaction outputs test properly adapted.**

The `vm_key` parameter addition ensures continued validation of duplicate transaction output scenarios.

---

`674-674`: **LGTM: MMR roots validation test updated appropriately.**

The parameter addition maintains the test's ability to validate MMR root mismatches correctly.

---

`756-757`: **LGTM: Header validation test properly updated.**

The `vm_key` parameter is correctly added to the successful header validation test case.

---

`777-778`: **LGTM: FTL rules validation test correctly adapted.**

The parameter addition preserves the test's validation of future time limit rule violations.

---

`793-793`: **LGTM: Difficulty validation test properly updated.**

The `vm_key` parameter addition maintains the test's ability to validate difficulty requirement failures.

---

`809-809`: **LGTM: Difficulty validation retry logic updated correctly.**

The parameter addition maintains the test's retry mechanism for difficulty validation scenarios.

</details>

</blockquote></details>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gMEWTFnH7ToAy+xSWivgGrQMUzkabUEKNyajRts+sbIdA3Qm7N0O6PbVFufnRYLcn8fdHFjRl8TkAoqYnIlrr0aau8GUNAjDMymbxKcbeKnbpvb3U6lUQ8AzIfrf3dR454yTKTKrJ3uaEp1+UafAJlBEScMM+EHVvmFyxK0xPQ3QVkH7zuxWdHQ+8YvqiVL5EBy+7pcNs31b7t98AnfdYFYGXD/9EAmdPcPIMAGX9BopAhsvYmex38zoAsHrhDgVDyB50K6dQJKBeqvAjBnlVaEpnTDBAbM2FIcLzjVBKgh8wNdAAaCWDIAIENhaBNwNCBiD5wklG2inmFo7d7MZbbGNcAL7DwQgdiUEMWnLiIABYRwTAn1hNKuJ0g0gAkG3GHBCgsgWAfYP+G1Dz1pQK6IFJ0NIoEhcEuCOwGLTd5IA+I5uJofrE54wk8hWIHznlwgE6DNmtAfAIWEdqn484zFb5txAQE94+88dbrm7zQrv4BQBQ/UDiD1Y40NupzV0GK1OZZdc2UpGPKdz8iHN5A/gIIMDGNp80x6DoegBXiTbtdOuwpE/JN2wHTc260pebt3UW7gVluuLT/JWhQGcgu6i6LFkqUUryAZuKyftD1jjbnBnBVhHzjF0yETo+EYSNnKFgkyu8FAhfTYm/y8CegYKYsVoJAPJzslAkxoC4ZDh1Bwhq235HkZjXLbrc8aOyDitiIlIotZu5AslJJCojnJ9EOARiKwKiBsQMImSbiL0wEiERhQJENQKJAogSQDAiotiOoHkhfB1c5g1cHQFQzOBQg4EU0ZBEYCxAAAjPNBIAABmAYAACYAAnF6NmhoBZo/o30S1Fmg9BaAfQEgAMBIAABWWgPNDQD+iOuaANAF6L6C0ABgs0FqOJEMCKjZofQN0b6LdGxB5o8YssV6PLFoA+gPQAYDbC9HxiAx80IMQMHmi0AGA3QAQB6L6Bhj2x+YqSFAHNFXMrR4cbfCbjXDyRoI+YoAA -->

<!-- internal state end -->
<!-- finishing_touch_checkbox_start -->

<details open="true">
<summary>✨ Finishing Touches</summary>

- [ ] <!-- {"checkboxId": "7962f53c-55bc-4827-bfbf-6a18da830691"} --> 📝 Generate Docstrings

</details>

<!-- finishing_touch_checkbox_end -->
<!-- tips_start -->

---

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.

<details>
<summary>❤️ Share</summary>

- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai)
- [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai)
- [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai)
- [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)

</details>

<details>
<summary>🪧 Tips</summary>

### Chat

There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=tari-project/tari&utm_content=7088):

- Review comments: Directly reply to a review comment made by CodeRabbit. Example:
  - `I pushed a fix in commit <commit_id>, please review it.`
  - `Explain this complex logic.`
  - `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 explain this code block.`
  -	`@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 explain its main purpose.`
  - `@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.`

### Support

Need help? Create a ticket on our [support page](https://www.coderabbit.ai/contact-us/support) for assistance with any issues or questions.

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](https://docs.coderabbit.ai/finishing-touches/docstrings) for this PR.
- `@coderabbitai generate sequence diagram` to generate a sequence diagram of the changes in 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](https://docs.coderabbit.ai/guides/configure-coderabbit) 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](https://docs.coderabbit.ai) for detailed information on how to use CodeRabbit.
- Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback.
- Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.

</details>

<!-- tips_end -->

Copy link
Copy Markdown
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: 3

🧹 Nitpick comments (2)
base_layer/core/src/chain_storage/blockchain_database.rs (2)

2199-2199: Fix typo in comment.

There's a grammatical error in the comment.

-            // Now we now the orphan links back to the main chain here
+            // Now we know the orphan links back to the main chain here

2373-2376: Consider using consistent approach for vm_key calculation.

This code directly calculates the vm_key using fetch_chain_header_by_height, while the other location uses the helper function get_vm_key_for_candidate_block. This inconsistency could lead to different behavior in edge cases.

Consider either:

  1. Using the helper function here as well for consistency
  2. Or documenting why this simpler approach is safe in this specific context
-        let vm_key = *db
-            .fetch_chain_header_by_height(tari_rx_vm_key_height(child.header.height))?
-            .hash();
+        let vm_key = get_vm_key_for_candidate_block(db, Arc::new(child.clone()))?;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0132068 and cf14e38.

📒 Files selected for processing (9)
  • base_layer/core/src/base_node/sync/header_sync/validator.rs (8 hunks)
  • base_layer/core/src/blocks/block_header.rs (1 hunks)
  • base_layer/core/src/chain_storage/blockchain_database.rs (4 hunks)
  • base_layer/core/src/chain_storage/target_difficulties.rs (2 hunks)
  • base_layer/core/src/validation/difficulty_calculator.rs (1 hunks)
  • base_layer/core/src/validation/header/header_full_validator.rs (3 hunks)
  • base_layer/core/src/validation/helpers.rs (0 hunks)
  • base_layer/core/src/validation/mocks.rs (2 hunks)
  • base_layer/core/src/validation/traits.rs (2 hunks)
💤 Files with no reviewable changes (1)
  • base_layer/core/src/validation/helpers.rs
🧰 Additional context used
🧬 Code Graph Analysis (1)
base_layer/core/src/validation/header/header_full_validator.rs (1)
base_layer/core/src/consensus/consensus_manager.rs (1)
  • consensus_constants (110-119)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: test (nextnet, nextnet)
  • GitHub Check: test (testnet, esmeralda)
  • GitHub Check: test (mainnet, stagenet)
  • GitHub Check: ci
  • GitHub Check: cargo check with stable
  • GitHub Check: Cucumber tests / Base Layer
  • GitHub Check: Cucumber tests / FFI
🔇 Additional comments (18)
base_layer/core/src/validation/difficulty_calculator.rs (1)

31-31: LGTM! Good visibility change for vm_key integration.

Making TARI_RX_VM_KEY_BLOCK_SWAP public enables consistent vm_key height calculations across modules while maintaining the same constant value (2048).

base_layer/core/src/blocks/block_header.rs (1)

85-86: LGTM! Well-designed error variant for POW algorithm validation.

The new InvalidPowAlgorithm(String) variant follows the established pattern and provides descriptive error messages for enhanced proof-of-work validation.

base_layer/core/src/chain_storage/target_difficulties.rs (2)

49-66: LGTM! Solid implementation for dynamic algorithm updates.

The update_algos method correctly:

  • Retrieves current permitted algorithms from consensus rules
  • Removes outdated algorithms
  • Adds new algorithms with proper error handling
  • Maintains consistency between difficulty tracking and consensus rules

100-102: LGTM! Simple and useful accessor method.

The algo_count method provides a clean way to query the number of tracked algorithms.

base_layer/core/src/validation/mocks.rs (2)

28-31: LGTM! Proper import update for trait compatibility.

Adding FixedHash to the imports supports the updated trait interface requirements.


120-120: LGTM! Appropriate mock signature update.

The unused FixedHash parameter maintains compatibility with the updated HeaderChainLinkedValidator trait while correctly indicating it's not used in the mock implementation.

base_layer/core/src/validation/traits.rs (2)

23-26: LGTM: Import addition supports new vm_key functionality.

The addition of FixedHash to the imports is necessary to support the new vm_key parameter in the trait method.


70-70:

Details

✅ Verification successful

Breaking change: Verify all implementations are updated.

The addition of the vm_key: FixedHash parameter to the validate method is a breaking change to the HeaderChainLinkedValidator trait interface. Ensure all implementations of this trait have been updated to match the new signature.


🏁 Script executed:

#!/bin/bash
# Description: Find all implementations of HeaderChainLinkedValidator trait to verify they handle the new vm_key parameter
# Expected: All implementations should have been updated with the new parameter

ast-grep --pattern $'impl $_ HeaderChainLinkedValidator<$_> for $_ {
  $$$
  fn validate($$$) {
    $$$
  }
  $$$
}'

Length of output: 117


🏁 Script executed:

#!/bin/bash
# Locate the trait definition
rg --type rust -n "trait HeaderChainLinkedValidator" 
# Find all implementations of the trait
rg --type rust -n "impl.*HeaderChainLinkedValidator"

Length of output: 736


🏁 Script executed:

#!/bin/bash
# Show the trait definition and its validate method signature
rg -n 'trait HeaderChainLinkedValidator' -C5 base_layer/core/src/validation/traits.rs
rg -n 'fn validate' -C5 base_layer/core/src/validation/traits.rs

# Inspect MockValidator implementation
rg -n 'impl.*HeaderChainLinkedValidator' -C2 base_layer/core/src/validation/mocks.rs
rg -n 'fn validate' -C3 base_layer/core/src/validation/mocks.rs

# Inspect HeaderFullValidator implementation
rg -n 'impl.*HeaderChainLinkedValidator' -C2 base_layer/core/src/validation/header/header_full_validator.rs
rg -n 'fn validate' -C3 base_layer/core/src/validation/header/header_full_validator.rs

Length of output: 4374


🏁 Script executed:

#!/bin/bash
# Search for vm_key occurrences in the validation directory to verify implementations
rg -n 'vm_key' -C3 base_layer/core/src/validation

Length of output: 8659


🏁 Script executed:

#!/bin/bash
# Display the full validate method signature in MockValidator implementation
sed -n '110,140p' base_layer/core/src/validation/mocks.rs

Length of output: 1239


HeaderChainLinkedValidator implementations updated

Both MockValidator and HeaderFullValidator now include the new vm_key: FixedHash parameter in their validate signatures:

• base_layer/core/src/validation/mocks.rs
• base_layer/core/src/validation/header/header_full_validator.rs

No further changes required.

base_layer/core/src/chain_storage/blockchain_database.rs (2)

111-111: LGTM: Import addition supports vm_key functionality.

The import of tari_rx_vm_key_height is necessary for the new vm_key calculation logic.


2272-2279: LGTM: Validator call updated with vm_key parameter.

The validator call has been correctly updated to include the new vm_key parameter, maintaining consistency with the updated trait interface.

base_layer/core/src/validation/header/header_full_validator.rs (3)

69-69: Enhanced validation with vm_key context.

The addition of the vm_key parameter aligns with the architectural changes to track block hashes at computed heights during validation. This provides the necessary context for proper validation flow.


82-82: Improved PoW validation with consensus constants.

The enhanced check_pow_data call now receives consensus constants, enabling validation of permitted PoW algorithms. This is a critical security improvement.


190-197: Critical security enhancement: PoW algorithm validation.

This validation logic correctly ensures that only consensus-permitted PoW algorithms are accepted in block headers. The implementation properly:

  1. Retrieves allowed algorithms from consensus constants
  2. Validates the header's PoW algorithm against the allowed set
  3. Returns appropriate error for invalid algorithms

This addresses a critical security requirement mentioned in the PR objectives.

base_layer/core/src/base_node/sync/header_sync/validator.rs (5)

64-64: VM key cache implementation.

The addition of vm_key: Vec<(u64, FixedHash)> to cache height-hash pairs is appropriate for tracking block hashes at specific heights during validation.


115-115: Proper genesis initialization for vm_key cache.

Correctly initializes the vm_key cache with the genesis block hash at height 0, providing a foundation for the caching mechanism.


127-136: Critical sync fix: Update target difficulties at consensus height changes.

This logic correctly addresses the sync issue mentioned in the PR objectives by updating target difficulties when consensus constants change at specific heights (swap heights). This ensures proper synchronization behavior across consensus constant transitions.


150-166: Robust vm_key lookup with database and cache fallback.

The implementation correctly:

  1. Attempts to fetch the vm_key from the database first
  2. Falls back to searching the cached vm_key vector if not found in database
  3. Provides appropriate error handling if vm_key cannot be located

The linear search through the cache is acceptable given the cache is only updated at TARI_RX_VM_KEY_BLOCK_SWAP intervals, keeping the cache size manageable.


234-237: Strategic vm_key caching at swap intervals.

The caching logic correctly stores block hashes at heights that are multiples of TARI_RX_VM_KEY_BLOCK_SWAP. This provides efficient access to required vm_keys for future validations while maintaining a reasonable cache size.

@github-actions
Copy link
Copy Markdown

Test Results (Integration tests)

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

Results for commit cf14e38. ± Comparison against base commit 0132068.

@github-actions
Copy link
Copy Markdown

github-actions bot commented May 23, 2025

Test Results (CI)

1 088 tests   1 084 ✅  18m 39s ⏱️
   30 suites      0 💤
    1 files        4 ❌

For more details on these failures, see this check.

Results for commit 60121f4.

♻️ This comment has been updated with latest results.

@SWvheerden SWvheerden merged commit b268384 into tari-project:development May 23, 2025
12 of 16 checks passed
@SWvheerden SWvheerden deleted the sw_fix_sync branch May 23, 2025 11:02
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.

2 participants