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

Release v2.0.3 #4243

Open
wants to merge 3 commits into
base: dag-master
Choose a base branch
from
Open

Release v2.0.3 #4243

wants to merge 3 commits into from

Conversation

sanlee42
Copy link
Member

@sanlee42 sanlee42 commented Oct 20, 2024

Pull request type

Please check the type of change your PR introduces:

  • Bugfix
  • Feature
  • Code style update (formatting, renaming)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • Documentation content changes
  • Other (please describe):

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Other information

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced new pruning configuration capabilities in the blockchain, allowing for more dynamic management of pruning parameters.
    • Added a new method to retrieve the DAG configuration, enhancing access to on-chain settings.
  • Improvements

    • Simplified method signatures across various components, reducing complexity in initialization processes.
    • Enhanced error handling and logging in the NodeService for improved reliability during operations.
  • Bug Fixes

    • Updated logic in several methods to ensure consistent handling of pruning parameters and configurations.
  • Tests

    • Streamlined test setups for the BlockDAG, maintaining core functionality while improving clarity.

Copy link

coderabbitai bot commented Oct 20, 2024

Walkthrough

The pull request involves multiple changes across various files, primarily focusing on dependency updates, method additions, and modifications related to pruning configurations within the blockchain framework. Notable updates include the revision of the starcoin-framework dependency in Cargo.toml, the introduction of new methods for pruning configuration retrieval, and adjustments to existing methods in the MockChain, BlockChain, and BlockDAG structs. The changes aim to enhance the flexibility and functionality of pruning logic while maintaining overall structural integrity.

Changes

File Change Summary
Cargo.toml Updated starcoin-framework dependency from commit hash 94bcd77... to a2546b3.... Reformatted various dependency entries.
chain/api/src/chain.rs Added method fn get_pruning_config(&self) -> (u64, u64) to ChainReader trait.
chain/mock/src/mock_chain.rs Updated new_with_params method to remove pruning_depth and pruning_finality parameters. Modified produce_block_for_pruning to include new parameters in calc_mergeset_and_tips method.
chain/src/chain.rs Added method fn get_pruning_config(&self) -> (u64, u64) to BlockChain. Updated verify_and_ghostdata and get_pruning_height methods for improved pruning logic.
chain/tests/test_prune.rs Updated test instantiation of MockChain to reflect new method signature with fewer parameters.
flexidag/src/blockdag.rs Removed pruning_depth and pruning_finality parameters from create_blockdag, new, and create_for_testing_with_parameters. Added them to calc_mergeset_and_tips and verify_pruning_point methods.
flexidag/src/prune/pruning_point_manager.rs Removed pruning_depth and pruning_finality from struct fields and constructor. Updated finality_score and next_pruning_point methods to accept these parameters.
flexidag/tests/tests.rs Updated test cases to reflect changes in BlockDAG instantiation and method calls.
genesis/src/lib.rs Modified init_storage_for_test_with_param to remove pruning_depth and pruning_finality parameters.
node/src/node.rs Enhanced NodeService with new request handling logic and improved logging and error handling in launch method. Added shutdown_system method.
state/api/src/chain_state.rs Added method pub fn get_dag_config(&self) -> Result<Option<FlexiDagConfigV2>> to AccountStateReader.
sync/src/block_connector/block_connector_service.rs Updated handle method in BlockConnectorService to include new parameters for calc_mergeset_and_tips.
sync/src/parallel/executor.rs Added sleep duration in start_to_execute method when waiting for parent blocks.
vm/types/src/on_chain_config/flexi_dag_config.rs Introduced FlexiDagConfigV2 struct with fields pruning_depth and pruning_finality. Added methods for configuration handling.
vm/types/src/on_chain_config/mod.rs Updated module structure and added new modules and configurations.

Possibly related PRs

  • Refactor move runtime #4166: This PR updates the Cargo.toml file, specifically changing the starcoin-framework dependency, which is directly related to the changes in the main PR that also involve updating dependencies in Cargo.toml.
  • Pruning logic #4194: This PR introduces significant modifications to the ChainReader trait and related methods, which are relevant to the pruning logic discussed in the main PR, as it also focuses on enhancing pruning capabilities within the blockchain.

Suggested reviewers

  • simonjiao
  • nkysg
  • welbon
  • yourmoonlight

Poem

🐇 In the code where bunnies play,
Pruning paths now find their way.
Dependencies updated with care,
New methods help us boldly dare.
With each change, our blockchain grows,
Hopping forward, as progress flows! 🌱


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.

@sanlee42 sanlee42 removed the request for review from jolestar October 20, 2024 08:56
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: 9

🧹 Outside diff range and nitpick comments (5)
chain/api/src/chain.rs (1)

119-119: Add documentation for the new method.

The addition of the get_pruning_config method is appropriate and aligns with the pruning-related changes mentioned in the PR summary. However, to improve code clarity and maintainability, please add documentation for this method.

Consider adding a doc comment explaining the purpose of the method and the meaning of the returned values. For example:

/// Returns the pruning configuration as a tuple of (pruning_depth, pruning_finality).
///
/// - `pruning_depth`: The depth at which pruning occurs in the blockchain.
/// - `pruning_finality`: The number of blocks to keep for finality purposes.
fn get_pruning_config(&self) -> (u64, u64);

This documentation will help other developers understand the purpose and usage of this method.

state/api/src/chain_state.rs (1)

204-206: LGTM: New method for retrieving DAG configuration

The get_dag_config method is a well-implemented addition to the AccountStateReader struct. It correctly uses the existing get_on_chain_config method to retrieve the FlexiDagConfigV2.

Consider adding a brief documentation comment to explain the purpose of this method and what FlexiDagConfigV2 represents. For example:

/// Retrieves the on-chain FlexiDagConfigV2, which contains parameters for pruning depth and finality.
pub fn get_dag_config(&self) -> Result<Option<FlexiDagConfigV2>> {
    self.get_on_chain_config::<FlexiDagConfigV2>()
}
sync/src/parallel/executor.rs (1)

106-110: Approve with suggestions: Sleep duration added to reduce CPU usage

The addition of a sleep duration after yielding control is a good approach to reduce CPU usage when waiting for parent blocks. This change likely improves overall system efficiency by allowing other tasks to proceed.

However, consider the following suggestions:

  1. Make the sleep duration configurable:
    Instead of hardcoding the 100ms duration, consider making it a configurable parameter. This would allow for fine-tuning based on different network conditions or system requirements.

  2. Add a comment explaining the purpose:
    To improve code maintainability, add a brief comment explaining why this sleep was introduced.

Here's a suggested implementation incorporating these changes:

// Configuration struct (add this at an appropriate place in your code)
pub struct DagBlockExecutorConfig {
    pub parent_block_wait_sleep_duration: Duration,
}

// In the DagBlockExecutor struct, add:
config: DagBlockExecutorConfig,

// In the start_to_execute method:
Ok(false) => {
    tokio::task::yield_now().await;
    // Sleep to reduce CPU usage while waiting for parent blocks
    tokio::time::sleep(self.config.parent_block_wait_sleep_duration).await
}

This approach allows for easier adjustment of the sleep duration and clearly communicates the purpose of the added delay.

chain/mock/src/mock_chain.rs (1)

47-47: LGTM! Consider updating the method name.

The simplification of the new_with_params method by removing the pruning-related parameters is a good change. It aligns with the overall goal of reducing complexity in method signatures.

Consider renaming the method to new_with_k_param or something similar, as it now only takes the k parameter in addition to the network. This would make the method name more descriptive of its current functionality.

genesis/src/lib.rs (1)

Line range hint 1-524: Summary: Update related to pruning configuration removal

This change appears to be part of a larger refactoring effort to remove pruning-related parameters from the BlockDAG creation process. While the modification itself is straightforward, it's important to ensure that this change is consistent across the entire codebase.

Key points:

  1. The BlockDAG::create_for_testing_with_parameters call has been updated to remove pruning_depth and pruning_finality parameters.
  2. The function signature of init_storage_for_test_with_param needs to be updated to reflect this change.
  3. All calls to init_storage_for_test_with_param throughout the project should be reviewed and updated if necessary.

Please ensure that these changes align with the overall project goals regarding pruning configuration and that all related parts of the codebase are consistently updated.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 42cae36 and a329c4b.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (15)
  • Cargo.toml (1 hunks)
  • chain/api/src/chain.rs (1 hunks)
  • chain/mock/src/mock_chain.rs (2 hunks)
  • chain/src/chain.rs (4 hunks)
  • chain/tests/test_prune.rs (1 hunks)
  • flexidag/src/blockdag.rs (6 hunks)
  • flexidag/src/prune/pruning_point_manager.rs (3 hunks)
  • flexidag/tests/tests.rs (4 hunks)
  • genesis/src/lib.rs (1 hunks)
  • node/src/node.rs (0 hunks)
  • state/api/src/chain_state.rs (2 hunks)
  • sync/src/block_connector/block_connector_service.rs (1 hunks)
  • sync/src/parallel/executor.rs (1 hunks)
  • vm/types/src/on_chain_config/flexi_dag_config.rs (2 hunks)
  • vm/types/src/on_chain_config/mod.rs (0 hunks)
💤 Files with no reviewable changes (2)
  • node/src/node.rs
  • vm/types/src/on_chain_config/mod.rs
🧰 Additional context used
🔇 Additional comments (24)
chain/tests/test_prune.rs (1)

9-9: LGTM. Verify test effectiveness with new initialization.

The simplification of the MockChain::new_with_params method call aligns with the broader modifications in the MockChain struct. This change removes the explicit setting of pruning_depth and pruning_finality parameters.

Please ensure that:

  1. The test still effectively checks the pruning functionality with the new initialization.
  2. If the removed parameters (4 and 3) were significant for this specific test case, verify that their absence doesn't reduce the test's coverage.

Consider updating the test documentation to reflect this change in initialization, explaining how pruning parameters are now determined if it's relevant to understanding the test setup.

state/api/src/chain_state.rs (2)

21-21: LGTM: New import for FlexiDagConfigV2

The import of FlexiDagConfigV2 from starcoin_vm_types::on_chain_config is consistent with the existing import style and is necessary for the new method being added.


21-21: Summary: Successful integration of FlexiDagConfigV2

The changes in this file are minimal and well-integrated:

  1. A new import for FlexiDagConfigV2 has been added.
  2. A new method get_dag_config has been implemented in the AccountStateReader struct.

These additions enhance the functionality related to DAG configuration retrieval, which aligns with the PR's focus on improving pruning configurations. The changes are consistent with the existing code structure and do not introduce any apparent issues or conflicts.

Also applies to: 204-206

Cargo.toml (2)

Line range hint 1-457: File review complete

The only significant change in this file is the update to the starcoin-framework dependency. The rest of the Cargo.toml configuration remains unchanged. This update is likely part of regular maintenance to keep dependencies up-to-date.


457-457: Dependency update: starcoin-framework

The starcoin-framework dependency has been updated to a new commit hash:

-starcoin-framework = { git = "https://github.com/starcoinorg/starcoin-framework", rev = "94bcd77e80232b169cf95754ef4e87775645afcd" }
+starcoin-framework = { git = "https://github.com/starcoinorg/starcoin-framework", rev = "a2546b32ad26d048e97d729e45153e0cba26ba18" }

This update likely includes bug fixes, feature additions, or performance improvements in the starcoin-framework library. Please ensure that this change is compatible with the current codebase and doesn't introduce any breaking changes.

To verify the changes in the starcoin-framework between the two versions, you can run the following script:

This script will show the commit messages and detailed changes between the two versions, helping you understand the scope of the update.

✅ Verification successful

Dependency update verified: starcoin-framework

The starcoin-framework dependency has been successfully updated to commit a2546b32ad26d048e97d729e45153e0cba26ba18. The changes introduced are additive, including new configurations and upgrade scripts, and do not modify or remove existing functionality. This update is compatible with the current codebase and does not introduce any breaking changes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Compare changes between two versions of starcoin-framework

OLD_REV="94bcd77e80232b169cf95754ef4e87775645afcd"
NEW_REV="a2546b32ad26d048e97d729e45153e0cba26ba18"

echo "Comparing starcoin-framework changes between $OLD_REV and $NEW_REV"
echo "----------------------------------------------------------------"
git clone https://github.com/starcoinorg/starcoin-framework.git tmp_starcoin_framework
cd tmp_starcoin_framework
git log --oneline $OLD_REV..$NEW_REV
echo "----------------------------------------------------------------"
echo "Detailed diff:"
git diff $OLD_REV $NEW_REV
cd ..
rm -rf tmp_starcoin_framework

Length of output: 3779

flexidag/tests/tests.rs (5)

892-892: Update BlockDAG creation to use only k parameter

The BlockDAG::create_for_testing_with_parameters method now only takes the k parameter. This change simplifies the BlockDAG creation for testing purposes.


1055-1060: Consistent update of calc_mergeset_and_tips method call

This is another instance of updating the calc_mergeset_and_tips method call with the new pruning parameters. The change is consistent with the previous update.


1077-1077: Update BlockDAG creation in test_verification_blue_block

Similar to the change in the test_prune function, the BlockDAG creation here has been updated to use only the k parameter. This change maintains consistency across the test functions.


Line range hint 892-1077: Summary of changes in flexidag/tests/tests.rs

The modifications in this file focus on updating the BlockDAG creation and pruning-related method calls in the test functions. Key changes include:

  1. Simplifying BlockDAG::create_for_testing_with_parameters to use only the k parameter.
  2. Updating calc_mergeset_and_tips method calls to include pruning_depth and pruning_finality parameters.

These changes improve the flexibility of pruning configuration in tests and maintain consistency across different test functions. The modifications appear to be part of a larger refactoring effort to enhance the BlockDAG implementation.

No issues or errors were introduced by these changes, and they seem to align well with the intended improvements to the pruning functionality.


1014-1019: Update calc_mergeset_and_tips method call with pruning parameters

The calc_mergeset_and_tips method now includes pruning_depth and pruning_finality as parameters. This change allows for more flexible pruning configuration during testing.

To ensure this change is consistent across the codebase, let's check for other occurrences of calc_mergeset_and_tips:

flexidag/src/prune/pruning_point_manager.rs (2)

79-81: Ensure correctness in pruning condition

The condition that checks whether pruning should occur:

if min_required_blue_score_for_next_pruning_point + pruning_depth
    <= next_ghostdata.blue_score
{
    // ...
}

appears to be correctly implemented, effectively determining if the pruning point needs to be updated based on the provided parameters.


95-96: Comparison of finality scores is correctly implemented

The comparison between the finality scores of next_pruning_ghostdata and latest_pruning_ghost_data correctly determines if the pruning point should be updated:

if self.finality_score(next_pruning_ghostdata.blue_score, pruning_finality)
    > self.finality_score(latest_pruning_ghost_data.blue_score, pruning_finality)
{
    // Update latest_pruning_ghost_data
}

This logic aligns with the intended pruning mechanism.

sync/src/block_connector/block_connector_service.rs (2)

411-413: Retrieve pruning configuration parameters

The code correctly retrieves pruning_depth and pruning_finality from get_pruning_config(), preparing them for use in the DAG calculation.


414-419: Update calc_mergeset_and_tips call with pruning parameters

The call to dag.calc_mergeset_and_tips now includes pruning_depth and pruning_finality, aligning with the updated method signature and ensuring accurate mergeset and tips calculation.

flexidag/src/blockdag.rs (6)

57-57: Simplified create_blockdag function

The create_blockdag function now calls Self::new with DEFAULT_GHOSTDAG_K and dag_storage, removing unnecessary parameters and simplifying the initialization process.


73-73: Initialize PruningPointManager without pruning parameters

The PruningPointManager::new method is now called without pruning_depth and pruning_finality. Verify that PruningPointManager is correctly initialized and that it obtains these parameters when needed, perhaps from a configuration or context.


91-94: Updated create_for_testing_with_parameters Function

The create_for_testing_with_parameters function has been modified to exclude pruning_depth and pruning_finality from its parameters, aligning it with the changes made to the new function. This streamlines the testing setup.


535-536: Added pruning_depth and pruning_finality Parameters to verify_pruning_point

Similarly, the verify_pruning_point function now includes pruning_depth and pruning_finality as parameters. Verify that all calls to this function have been updated accordingly.

To check all invocations of verify_pruning_point:

#!/bin/bash
# Description: Find all calls to `verify_pruning_point` and confirm they include the new parameters.

rg 'verify_pruning_point\(' src/ -A 3 -B 3

Also applies to: 542-543


478-479: Added pruning_depth and pruning_finality Parameters to calc_mergeset_and_tips

The calc_mergeset_and_tips function now requires pruning_depth and pruning_finality as parameters. Ensure that all calls to this function provide the correct values for these parameters.

To verify all invocations of calc_mergeset_and_tips are updated:

#!/bin/bash
# Description: Find all calls to `calc_mergeset_and_tips` and ensure they pass the new parameters.

rg 'calc_mergeset_and_tips\(' src/ -A 3 -B 3

Also applies to: 492-493


Line range hint 60-73: Removed pruning_depth and pruning_finality from new function

The new function no longer requires pruning_depth and pruning_finality as parameters. Ensure that any initialization or configuration dependent on these parameters is appropriately adjusted elsewhere in the codebase.

To confirm that the removal of these parameters does not cause any issues, please verify their usage:

chain/src/chain.rs (4)

48-48: LGTM!

The import statement for FlexiDagConfigV2 is added correctly.


1393-1393: Verify the correctness of get_pruning_config usage

The method get_pruning_config is used to retrieve pruning parameters. Please ensure that this method is correctly implemented and returns the expected values for pruning_depth and pruning_finality.

Would you like assistance in verifying the implementation of get_pruning_config?


1413-1414: Ensure correct parameters for verify_pruning_point

The parameters pruning_depth and pruning_finality are passed to self.dag().verify_pruning_point. Please confirm that these parameters match the method's expected signature and order.

Let me know if you need help verifying the method signature.


1428-1429: ⚠️ Potential issue

Fix infinite recursion in get_pruning_height method

The get_pruning_height method calls itself recursively without a base case, causing infinite recursion and potential stack overflow.

Apply this diff to provide a proper implementation:

-fn get_pruning_height(&self) -> BlockNumber {
-    self.get_pruning_height()
+fn get_pruning_height(&self) -> BlockNumber {
+    let chain_id = self.status().head().chain_id();
+    if chain_id.is_vega() {
+        4000000
+    } else if chain_id.is_proxima() {
+        850000
+    } else if chain_id.is_halley() {
+        4090000
+    } else if chain_id.is_main() {
+        1
+    } else if chain_id.is_dag_test() || chain_id.is_test() || chain_id.is_dev() {
+        BlockNumber::MAX
+    } else {
+        1
+    }
+}

Likely invalid or redundant comment.

Comment on lines 262 to 271
let MineNewDagBlockInfo {
tips: pruned_tips,
blue_blocks,
pruning_point,
} = self
.head
.dag()
.calc_mergeset_and_tips(previous_pruning, prevous_ghostdata.as_ref())?;
} = self.head.dag().calc_mergeset_and_tips(
previous_pruning,
prevous_ghostdata.as_ref(),
4,3
)?;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve code readability and fix typo.

The addition of new parameters to calc_mergeset_and_tips enhances the pruning logic. However, there are a couple of issues to address:

  1. The use of magic numbers (4 and 3) reduces code readability and maintainability. Consider defining these as named constants with clear descriptions of their purpose.

  2. There's a typo in the variable name prevous_ghostdata (should be previous_ghostdata).

Here's a suggested improvement:

+ const PRUNING_INTERVAL: u64 = 4;
+ const PRUNING_DEPTH: u64 = 3;

- prevous_ghostdata
+ previous_ghostdata

- self.head.dag().calc_mergeset_and_tips(
-     previous_pruning,
-     prevous_ghostdata.as_ref(),
-     4,3
- )?;
+ self.head.dag().calc_mergeset_and_tips(
+     previous_pruning,
+     previous_ghostdata.as_ref(),
+     PRUNING_INTERVAL,
+     PRUNING_DEPTH
+ )?;

Also, consider adding comments explaining the significance of PRUNING_INTERVAL and PRUNING_DEPTH.

Committable suggestion was skipped due to low confidence.

) -> Result<(Arc<Storage>, ChainInfo, Self, BlockDAG)> {
debug!("init storage by genesis for test. {net:?}");
let storage = Arc::new(Storage::new(StorageInstance::new_cache_instance())?);
let genesis = Self::load_or_build(net)?;
let dag = BlockDAG::create_for_testing_with_parameters(k, pruning_depth, pruning_finality)?;
let dag = BlockDAG::create_for_testing_with_parameters(k)?;
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Update all instances of init_storage_for_test_with_param to match the new signature.

The function init_storage_for_test_with_param has been modified to remove the pruning_depth and pruning_finality parameters in genesis/src/lib.rs. However, there is at least one other usage in chain/mock/src/mock_chain.rs that still includes these parameters. All call sites must be updated to ensure consistency and prevent potential issues.

  • File: chain/mock/src/mock_chain.rs

    Update the function call to remove the deprecated parameters:

    - let (storage, chain_info, _, dag) = Genesis::init_storage_for_test_with_param(&net, k, pruning_depth, pruning_finality)?;
    + let (storage, chain_info, _, dag) = Genesis::init_storage_for_test_with_param(&net, k)?;

Ensure that any additional call sites are similarly updated to align with the new function signature.

🔗 Analysis chain

Update function signature to match the new usage.

The BlockDAG::create_for_testing_with_parameters call has been modified to remove the pruning_depth and pruning_finality parameters. However, the function signature of init_storage_for_test_with_param still includes these parameters. This inconsistency should be addressed.

Consider updating the function signature to match the new usage:

-    pub fn init_storage_for_test_with_param(
-        net: &ChainNetwork,
-        k: KType,
-        pruning_depth: u64,
-        pruning_finality: u64,
-    ) -> Result<(Arc<Storage>, ChainInfo, Self, BlockDAG)> {
+    pub fn init_storage_for_test_with_param(
+        net: &ChainNetwork,
+        k: KType,
+    ) -> Result<(Arc<Storage>, ChainInfo, Self, BlockDAG)> {

Also, ensure that all calls to this function throughout the codebase are updated accordingly.

To verify the impact of this change, let's search for other occurrences of this function:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other occurrences of init_storage_for_test_with_param
rg "init_storage_for_test_with_param" --type rust

Length of output: 239

Comment on lines +56 to +63
pub fn type_tag() -> TypeTag {
TypeTag::Struct(Box::new(StructTag {
address: CORE_CODE_ADDRESS,
module: Identifier::new(MV_FLEXI_DAG_CONFIG_MODULE_NAME).unwrap(),
name: Identifier::new(MV_FLEXI_DAG_CONFIG_STRUCT_NAME_V2).unwrap(),
type_params: vec![],
}))
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor Duplicate type_tag Methods to Reduce Code Duplication

The type_tag methods in both FlexiDagConfig and FlexiDagConfigV2 are nearly identical except for the struct name. To adhere to the DRY (Don't Repeat Yourself) principle and enhance maintainability, consider extracting the common logic into a helper function.

Example refactoring:

fn generate_type_tag(struct_name: &str) -> TypeTag {
    TypeTag::Struct(Box::new(StructTag {
        address: CORE_CODE_ADDRESS,
        module: Identifier::new(MV_FLEXI_DAG_CONFIG_MODULE_NAME).unwrap(),
        name: Identifier::new(struct_name).unwrap(),
        type_params: vec![],
    }))
}

impl FlexiDagConfig {
    pub fn type_tag() -> TypeTag {
        generate_type_tag(MV_FLEXI_DAG_CONFIG_STRUCT_NAME)
    }
}

impl FlexiDagConfigV2 {
    pub fn type_tag() -> TypeTag {
        generate_type_tag(MV_FLEXI_DAG_CONFIG_STRUCT_NAME_V2)
    }
}

Comment on lines +39 to +40
const G_PRUNING_DEPTH: u64 = 17280;
const G_PRUNING_FINALITY: u64 = 8640;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use Consistent Naming for Constants

The constants G_PRUNING_DEPTH and G_PRUNING_FINALITY use the G_ prefix, whereas existing constants use the MV_ prefix (e.g., MV_FLEXI_DAG_CONFIG_MODULE_NAME). For consistency, consider aligning the naming convention across constants.

Apply this diff to rename the constants:

-const G_PRUNING_DEPTH: u64 = 17280;
-const G_PRUNING_FINALITY: u64 = 8640;
+const MV_PRUNING_DEPTH: u64 = 17280;
+const MV_PRUNING_FINALITY: u64 = 8640;

Update all references to these constants accordingly.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const G_PRUNING_DEPTH: u64 = 17280;
const G_PRUNING_FINALITY: u64 = 8640;
const MV_PRUNING_DEPTH: u64 = 17280;
const MV_PRUNING_FINALITY: u64 = 8640;

Comment on lines +42 to +49
impl Default for FlexiDagConfigV2 {
fn default() -> Self {
Self {
pruning_depth: G_PRUNING_DEPTH,
pruning_finality: G_PRUNING_FINALITY,
}
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Encapsulate Default Values as Associated Constants

To improve code organization and encapsulation, consider defining PRUNING_DEPTH and PRUNING_FINALITY as associated constants within FlexiDagConfigV2. This keeps related values within the struct's scope and enhances readability.

Apply this refactoring:

-const G_PRUNING_DEPTH: u64 = 17280;
-const G_PRUNING_FINALITY: u64 = 8640;

 impl Default for FlexiDagConfigV2 {
     fn default() -> Self {
         Self {
-            pruning_depth: G_PRUNING_DEPTH,
-            pruning_finality: G_PRUNING_FINALITY,
+            pruning_depth: Self::PRUNING_DEPTH_DEFAULT,
+            pruning_finality: Self::PRUNING_FINALITY_DEFAULT,
         }
     }
 }

+impl FlexiDagConfigV2 {
+    pub const PRUNING_DEPTH_DEFAULT: u64 = 17280;
+    pub const PRUNING_FINALITY_DEFAULT: u64 = 8640;
+
+    // existing methods...
+}

Committable suggestion was skipped due to low confidence.

Comment on lines +92 to 93
if next_ghostdata.blue_score - next_pruning_ghostdata.blue_score < pruning_depth {
break;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Prevent potential underflow in blue score subtraction

In the condition:

if next_ghostdata.blue_score - next_pruning_ghostdata.blue_score < pruning_depth {
    break;
}

There is a potential for underflow if next_pruning_ghostdata.blue_score is greater than next_ghostdata.blue_score, which could cause unexpected behavior due to wrapping of unsigned integers. Consider adjusting the logic to prevent underflow.

Modify the condition to ensure next_pruning_ghostdata.blue_score is not greater than next_ghostdata.blue_score:

+if next_pruning_ghostdata.blue_score > next_ghostdata.blue_score {
+    break;
+}
 if next_ghostdata.blue_score - next_pruning_ghostdata.blue_score < pruning_depth {
     break;
 }

Comment on lines +35 to +36
pub(crate) fn finality_score(&self, blue_score: u64, pruning_finality: u64) -> u64 {
blue_score / pruning_finality
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Prevent potential division by zero in finality_score

The finality_score function divides blue_score by pruning_finality, but there is no check to ensure pruning_finality is not zero. This could lead to a division by zero error. Consider adding a check to prevent this scenario.

Apply this diff to add a validation check:

 pub(crate) fn finality_score(&self, blue_score: u64, pruning_finality: u64) -> u64 {
+    if pruning_finality == 0 {
+        // Handle the error appropriately, e.g., return an error or default value
+        return 0; // or consider returning an error
+    }
     blue_score / pruning_finality
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pub(crate) fn finality_score(&self, blue_score: u64, pruning_finality: u64) -> u64 {
blue_score / pruning_finality
pub(crate) fn finality_score(&self, blue_score: u64, pruning_finality: u64) -> u64 {
if pruning_finality == 0 {
// Handle the error appropriately, e.g., return an error or default value
return 0; // or consider returning an error
}
blue_score / pruning_finality
}

Comment on lines +66 to +71
pruning_depth: u64,
pruning_finality: u64,
) -> anyhow::Result<HashValue> {
let min_required_blue_score_for_next_pruning_point =
(self.finality_score(previous_ghostdata.blue_score) + 1) * self.pruning_finality;
(self.finality_score(previous_ghostdata.blue_score, pruning_finality) + 1)
* pruning_finality;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Validate pruning_depth and pruning_finality parameters

The next_pruning_point function now accepts pruning_depth and pruning_finality as parameters. To ensure robust operation, validate that these parameters are greater than zero to prevent potential runtime errors such as division by zero or incorrect logical comparisons.

Consider adding validation at the beginning of the function:

 pub(crate) fn next_pruning_point(
     &self,
     previous_pruning_point: HashValue,
     previous_ghostdata: &GhostdagData,
     next_ghostdata: &GhostdagData,
     pruning_depth: u64,
     pruning_finality: u64,
 ) -> anyhow::Result<HashValue> {
+    if pruning_depth == 0 || pruning_finality == 0 {
+        return Err(anyhow::anyhow!("pruning_depth and pruning_finality must be greater than zero"));
+    }
     let min_required_blue_score_for_next_pruning_point =
         (self.finality_score(previous_ghostdata.blue_score, pruning_finality) + 1)
             * pruning_finality;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pruning_depth: u64,
pruning_finality: u64,
) -> anyhow::Result<HashValue> {
let min_required_blue_score_for_next_pruning_point =
(self.finality_score(previous_ghostdata.blue_score) + 1) * self.pruning_finality;
(self.finality_score(previous_ghostdata.blue_score, pruning_finality) + 1)
* pruning_finality;
pub(crate) fn next_pruning_point(
&self,
previous_pruning_point: HashValue,
previous_ghostdata: &GhostdagData,
next_ghostdata: &GhostdagData,
pruning_depth: u64,
pruning_finality: u64,
) -> anyhow::Result<HashValue> {
if pruning_depth == 0 || pruning_finality == 0 {
return Err(anyhow::anyhow!("pruning_depth and pruning_finality must be greater than zero"));
}
let min_required_blue_score_for_next_pruning_point =
(self.finality_score(previous_ghostdata.blue_score, pruning_finality) + 1)
* pruning_finality;

Comment on lines +1430 to +1439
let reader = AccountStateReader::new(&self.statedb);
let FlexiDagConfigV2 {
pruning_depth,
pruning_finality,
} = reader
.get_dag_config()
.unwrap_or_default()
.unwrap_or_default();
(pruning_depth, pruning_finality)
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider handling errors explicitly in get_pruning_config

The method get_pruning_config uses multiple unwrap_or_default() calls, which may suppress errors and return default values unintentionally. Consider handling errors explicitly to ensure any issues are caught and addressed appropriately.

Refactor the method to handle errors properly:

-fn get_pruning_config(&self) -> (u64, u64) {
-    let reader = AccountStateReader::new(&self.statedb);
-    let FlexiDagConfigV2 {
-        pruning_depth,
-        pruning_finality,
-    } = reader
-        .get_dag_config()
-        .unwrap_or_default()
-        .unwrap_or_default();
-    (pruning_depth, pruning_finality)
-}
+fn get_pruning_config(&self) -> Result<(u64, u64)> {
+    let reader = AccountStateReader::new(&self.statedb);
+    if let Some(config) = reader.get_dag_config()? {
+        Ok((config.pruning_depth, config.pruning_finality))
+    } else {
+        Err(format_err!("Failed to retrieve DAG configuration"))
+    }
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let reader = AccountStateReader::new(&self.statedb);
let FlexiDagConfigV2 {
pruning_depth,
pruning_finality,
} = reader
.get_dag_config()
.unwrap_or_default()
.unwrap_or_default();
(pruning_depth, pruning_finality)
}
fn get_pruning_config(&self) -> Result<(u64, u64)> {
let reader = AccountStateReader::new(&self.statedb);
if let Some(config) = reader.get_dag_config()? {
Ok((config.pruning_depth, config.pruning_finality))
} else {
Err(format_err!("Failed to retrieve DAG configuration"))
}
}

Copy link

Benchmark for 0871fd5

Click to view benchmark
Test Base PR %
accumulator_append 796.2±105.19µs 872.7±192.66µs +9.61%
block_apply/block_apply_10 389.7±24.30ms 366.2±10.46ms -6.03%
block_apply/block_apply_1000 46.2±1.97s 41.4±1.82s -10.39%
get_with_proof/db_store 50.6±16.18µs 45.3±4.77µs -10.47%
get_with_proof/mem_store 39.3±6.96µs 35.7±1.66µs -9.16%
put_and_commit/db_store/1 122.7±20.04µs 126.8±16.57µs +3.34%
put_and_commit/db_store/10 1169.4±159.68µs 1120.9±128.45µs -4.15%
put_and_commit/db_store/100 10.4±1.23ms 10.2±1.13ms -1.92%
put_and_commit/db_store/5 596.6±82.68µs 562.9±46.12µs -5.65%
put_and_commit/db_store/50 5.5±0.63ms 5.5±0.66ms 0.00%
put_and_commit/mem_store/1 75.4±11.51µs 73.6±12.88µs -2.39%
put_and_commit/mem_store/10 690.3±106.73µs 666.7±82.06µs -3.42%
put_and_commit/mem_store/100 6.7±0.90ms 7.8±1.23ms +16.42%
put_and_commit/mem_store/5 351.3±52.20µs 341.1±42.07µs -2.90%
put_and_commit/mem_store/50 3.7±0.77ms 3.3±0.36ms -10.81%
query_block/query_block_in(10)_times(100) 8.9±1.01ms 11.2±2.20ms +25.84%
query_block/query_block_in(10)_times(1000) 85.3±4.93ms 85.0±5.53ms -0.35%
query_block/query_block_in(10)_times(10000) 855.9±45.61ms 1001.0±144.35ms +16.95%
query_block/query_block_in(1000)_times(100) 1683.4±340.02µs 1290.5±113.04µs -23.34%
query_block/query_block_in(1000)_times(1000) 15.2±2.59ms 13.6±1.49ms -10.53%
query_block/query_block_in(1000)_times(10000) 145.9±21.83ms 123.1±5.41ms -15.63%
storage_transaction 1130.4±436.28µs 1057.3±396.30µs -6.47%
vm/transaction_execution/1 428.9±23.19ms 480.0±113.03ms +11.91%
vm/transaction_execution/10 149.6±16.62ms 195.8±16.23ms +30.88%
vm/transaction_execution/20 134.3±11.45ms 137.0±5.08ms +2.01%
vm/transaction_execution/5 178.0±12.72ms 231.3±22.10ms +29.94%
vm/transaction_execution/50 157.4±9.34ms 151.5±8.25ms -3.75%

Copy link

Benchmark for 934e3b7

Click to view benchmark
Test Base PR %
accumulator_append 933.4±209.73µs 871.1±162.38µs -6.67%
block_apply/block_apply_10 391.5±24.33ms 381.0±20.07ms -2.68%
block_apply/block_apply_1000 46.5±3.24s 41.4±1.36s -10.97%
get_with_proof/db_store 44.9±4.95µs 46.0±3.02µs +2.45%
get_with_proof/mem_store 38.9±5.43µs 38.1±5.28µs -2.06%
put_and_commit/db_store/1 145.1±26.66µs 161.4±28.95µs +11.23%
put_and_commit/db_store/10 1360.7±322.56µs 1148.4±136.77µs -15.60%
put_and_commit/db_store/100 10.4±0.80ms 10.1±0.77ms -2.88%
put_and_commit/db_store/5 685.3±168.31µs 594.1±79.20µs -13.31%
put_and_commit/db_store/50 6.3±1.26ms 5.3±0.78ms -15.87%
put_and_commit/mem_store/1 77.6±12.76µs 76.7±13.09µs -1.16%
put_and_commit/mem_store/10 738.0±134.40µs 723.3±100.36µs -1.99%
put_and_commit/mem_store/100 6.8±0.83ms 6.5±0.34ms -4.41%
put_and_commit/mem_store/5 386.7±65.48µs 337.7±36.59µs -12.67%
put_and_commit/mem_store/50 3.4±0.51ms 3.3±0.29ms -2.94%
query_block/query_block_in(10)_times(100) 8.6±0.65ms 8.4±0.48ms -2.33%
query_block/query_block_in(10)_times(1000) 86.2±3.97ms 82.5±2.41ms -4.29%
query_block/query_block_in(10)_times(10000) 987.4±148.73ms 855.5±53.30ms -13.36%
query_block/query_block_in(1000)_times(100) 1269.4±77.13µs 1307.2±160.76µs +2.98%
query_block/query_block_in(1000)_times(1000) 14.2±1.69ms 12.2±1.13ms -14.08%
query_block/query_block_in(1000)_times(10000) 134.7±11.20ms 127.2±22.80ms -5.57%
storage_transaction 1068.5±407.73µs 1108.1±456.11µs +3.71%
vm/transaction_execution/1 468.2±46.65ms 448.0±50.79ms -4.31%
vm/transaction_execution/10 142.6±7.27ms 145.6±9.92ms +2.10%
vm/transaction_execution/20 136.6±8.11ms 128.2±6.94ms -6.15%
vm/transaction_execution/5 193.7±16.86ms 168.2±8.34ms -13.16%
vm/transaction_execution/50 156.9±20.03ms 152.6±28.40ms -2.74%

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