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

feat(p2p): block sync protocol #915

Merged
merged 109 commits into from
Aug 8, 2024
Merged

feat(p2p): block sync protocol #915

merged 109 commits into from
Aug 8, 2024

Conversation

srene
Copy link
Contributor

@srene srene commented Jun 13, 2024

PR Standards

This PR is aimed at providing a new feature to be able to sync from P2P, retrieving blocks from other peers using the P2P network, mainly using available libp2p and IPFS libraries.

ADR is defined here https://www.notion.so/ADR-x-Rollapp-block-sync-protocol-6ee48b232a6a45e09989d67f1a6c0297?pvs=4

--

PR naming convention: https://hackmd.io/@nZpxHZ0CT7O5ngTp0TP9mg/HJP_jrm7A


Close #914

<-- Briefly describe the content of this pull request -->

For Author:

  • Targeted PR against correct branch
  • included the correct type prefix in the PR title
  • Linked to Github issue with discussion and accepted design
  • Targets only one github issue
  • Wrote unit and integration tests
  • All CI checks have passed
  • Added relevant godoc comments

For Reviewer:

  • confirmed the correct type prefix in the PR title
  • Reviewers assigned
  • confirmed all author checklist items have been addressed

After reviewer approval:

  • In case targets main branch, PR should be squashed and merged.
  • In case PR targets a release branch, PR should be rebased.

Summary by CodeRabbit

  • New Features

    • Introduced block caching and synchronization improvements, enhancing overall system performance and reliability.
    • Added new configuration parameters for block sync retry intervals and request timings, allowing better control over synchronization behavior.
    • Implemented a new BlockSync protocol for efficient retrieval of blocks in a peer-to-peer network.
    • Launched a BlockSyncDagService for structured block storage and retrieval.
  • Bug Fixes

    • Improved error handling during block removal, increasing robustness in block management.
  • Refactor

    • Enhanced block synchronization logic for better error handling and synchronization processes.
    • Updated logging and error reporting mechanisms for more informative and actionable logs.
  • Tests

    • Updated tests for block synchronization and client startup, ensuring robustness and reliability of the new features.

@srene srene self-assigned this Jun 13, 2024
@srene srene requested a review from a team as a code owner June 13, 2024 16:09
@srene srene marked this pull request as draft June 13, 2024 16:10
Copy link
Contributor

coderabbitai bot commented Jun 13, 2024

Walkthrough

The changes introduce a robust peer-to-peer (P2P) block syncing mechanism across the block and p2p modules. Enhancements include new methods for event subscriptions, block caching, and synchronization processes, alongside improved logging and error handling. Configuration updates ensure seamless integration of new synchronization features while maintaining system reliability.

Changes

Files / Groups Change Summary
block/block.go, block/produce.go Added attemptCacheBlock function for block caching, updated applyBlock logic, and included logging for block sizes.
block/manager.go, block/retriever.go Introduced new event subscriptions, refactored syncing logic, and replaced syncBlockManager with syncFromSettlement.
block/manager_test.go, p2p/client.go Updated tests to use datastore.NewMapDatastore() and modified NewClient to include parameters for synchronization.
p2p/block_sync.go, p2p/block_sync_dag.go, p2p/blocks_received.go Implemented BlockSync protocol for managing block synchronization, including new structures and methods to handle received blocks in a DAG format.
config/defaults.go Added BlockSyncRetryTime and BlockSyncRequestIntervalTime fields to P2PConfig for enhanced configuration of sync behavior.
types/block_source.go Renamed BlockSource constants for clarity and updated CachedBlock struct to include a new Source field.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Manager
    participant P2P Network
    participant Data Layer

    Client->>Manager: StartBlockSync
    Manager->>P2P Network: AdvertiseBlock
    P2P Network-->>Manager: NewBlockSyncBlockEvent
    Manager->>Client: AddBlock(block)
    Client-->>Data Layer: StoreBlock(block)
    Client-->>P2P Network: GetBlockId
    P2P Network-->>Manager: RequestBlock(blockId)
    Manager->>Client: SyncBlock(blockId)
    Client-->>Data Layer: RetrieveBlock(blockId)
    Data Layer-->>Client: BlockData
    Client-->>Manager: UpdateBlock(blockData)
Loading

Assessment against linked issues

Objective (Issue Number) Addressed Explanation
Implement robust P2P block syncing (#914)
Include improved error handling (#914)
Add and document necessary configurations (#914)
Introduce comprehensive logging (#914)
Test synchronization processes (#914)

Poem

In the network of blocks anew,
P2P sync makes its debut,
With caches and retries, it flows,
Ensuring each block knows,
The place where it belongs,
Singing synchrony’s songs,
A change both sure and true! 🌐


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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.

block/manager.go Fixed Show fixed Hide fixed
block/manager.go Fixed Show fixed Hide fixed
block/manager.go Fixed Show resolved Hide resolved
block/manager.go Fixed Show fixed Hide fixed
p2p/client.go Fixed Show fixed Hide fixed
block/manager.go Fixed Show fixed Hide fixed
Copy link

codecov bot commented Jun 16, 2024

Codecov Report

Attention: Patch coverage is 58.96861% with 183 lines in your changes missing coverage. Please review.

Project coverage is 34.71%. Comparing base (c5f8f07) to head (21109fd).
Report is 4 commits behind head on main.

Files Patch % Lines
p2p/client.go 48.05% 71 Missing and 9 partials ⚠️
p2p/block_sync_dag.go 58.13% 24 Missing and 12 partials ⚠️
block/p2p.go 8.00% 23 Missing ⚠️
block/retriever.go 20.00% 12 Missing ⚠️
block/manager.go 76.92% 4 Missing and 2 partials ⚠️
node/node.go 40.00% 6 Missing ⚠️
p2p/block_sync.go 90.47% 4 Missing and 2 partials ⚠️
config/p2p.go 0.00% 2 Missing and 1 partial ⚠️
store/pruning.go 0.00% 2 Missing and 1 partial ⚠️
store/store.go 85.00% 2 Missing and 1 partial ⚠️
... and 4 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #915      +/-   ##
==========================================
+ Coverage   34.16%   34.71%   +0.55%     
==========================================
  Files         131      132       +1     
  Lines       21405    21739     +334     
==========================================
+ Hits         7312     7547     +235     
- Misses      13046    13114      +68     
- Partials     1047     1078      +31     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

block/manager.go Fixed Show fixed Hide fixed
@srene srene marked this pull request as ready for review June 17, 2024 14:39
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: 15

Outside diff range and nitpick comments (3)
block/p2p.go (1)

92-110: The refreshBlockSyncAdvertiseBlocks function correctly re-advertises block IDs. This is critical for ensuring data availability upon node restarts. Consider adding more detailed logging to trace the re-advertisement process for debugging purposes.

store/store_test.go (1)

205-251: The test TestBlockId effectively tests the storage and retrieval of block IDs using CIDs, ensuring proper error handling and batch commit functionality. However, consider adding more detailed comments within the test to explain the significance of each step, especially around the creation of the CID and its storage logic, which might not be immediately clear to someone unfamiliar with the codebase.

block/produce.go (1)

70-70: The logging of the new block size is a good practice for monitoring and debugging. However, consider adding more detailed logging at different steps of the block production process to provide better visibility into the workflow, especially in error scenarios.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2b5d21b and 50ccd36.

Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
Files selected for processing (30)
  • block/block.go (3 hunks)
  • block/manager.go (2 hunks)
  • block/manager_test.go (2 hunks)
  • block/p2p.go (1 hunks)
  • block/produce.go (1 hunks)
  • block/retriever.go (2 hunks)
  • block/types.go (2 hunks)
  • config/defaults.go (1 hunks)
  • config/p2p.go (1 hunks)
  • da/celestia/celestia.go (1 hunks)
  • da/da.go (1 hunks)
  • da/grpc/grpc.go (1 hunks)
  • go.mod (10 hunks)
  • node/node.go (3 hunks)
  • p2p/block_sync.go (1 hunks)
  • p2p/block_sync_dag.go (1 hunks)
  • p2p/block_sync_test.go (1 hunks)
  • p2p/client.go (13 hunks)
  • p2p/client_test.go (4 hunks)
  • p2p/events.go (1 hunks)
  • p2p/gossip.go (2 hunks)
  • p2p/p2p_block.go (3 hunks)
  • p2p/validator.go (1 hunks)
  • p2p/validator_test.go (1 hunks)
  • store/kv.go (2 hunks)
  • store/store.go (4 hunks)
  • store/storeIface.go (2 hunks)
  • store/store_test.go (2 hunks)
  • testutil/block.go (2 hunks)
  • testutil/p2p.go (2 hunks)
Files skipped from review due to trivial changes (3)
  • block/retriever.go
  • da/da.go
  • da/grpc/grpc.go
Additional context used
GitHub Check: CodeQL
block/manager.go

[notice] 153-153: Spawning a Go routine
Spawning a Go routine may be a possible source of non-determinism


[notice] 154-154: Spawning a Go routine
Spawning a Go routine may be a possible source of non-determinism


[notice] 176-181: Spawning a Go routine
Spawning a Go routine may be a possible source of non-determinism


[notice] 159-159: Spawning a Go routine
Spawning a Go routine may be a possible source of non-determinism

p2p/client.go

[notice] 351-351: Spawning a Go routine
Spawning a Go routine may be a possible source of non-determinism

Additional comments not posted (54)
block/types.go (2)

18-18: Introduced a new block source blocksyncBlock. Ensure that this new source type is fully integrated and utilized where block synchronization is relevant.


30-30: Added Source field to CachedBlock struct. This is crucial for tracking the origin of blocks, enhancing traceability and debugging capabilities.

store/kv.go (2)

22-22: Refined the path construction for databases to ensure proper handling of relative and absolute paths. This change promotes better flexibility and reliability in database file management.


33-33: Improved path handling by introducing Rootify which smartly handles absolute and relative paths. This is a good practice to avoid path manipulation errors and potential security risks.

p2p/events.go (2)

18-18: Added a new event EventNewBlockSyncBlock. This event is essential for the new block sync feature, enabling efficient communication and processing within the P2P network.


28-29: Introduced a new query for the EventNewBlockSyncBlock. This facilitates the subscription to and handling of this event, crucial for the operational integrity of the block sync feature.

config/p2p.go (1)

18-19: Introduced BlockSyncRetryTime to manage the retry intervals for block synchronization attempts. This is a critical parameter for maintaining robustness in block retrieval in adverse network conditions.

p2p/p2p_block.go (1)

Line range hint 13-57: The implementation of P2PBlock methods for serialization, deserialization, and validation is robust and follows best practices. Good job on maintaining clarity and efficiency in the code.

config/defaults.go (1)

43-43: The addition of BlockSyncRetryTime to the default configuration is appropriate and enhances the flexibility of block synchronization settings.

p2p/validator.go (1)

74-74: The BlockValidator method is well-implemented, with clear error handling and validation logic. It effectively ensures the integrity of gossiped blocks.

p2p/gossip.go (2)

25-25: The addition of GossipMessageHandler type is well-defined and aligns with the enhancement of P2P functionalities.


104-104: Correct usage of msgHandler within ProcessMessages. Proper context and message data are passed, adhering to the expected functionality.

p2p/block_sync.go (3)

41-80: The StartBlockSync function is well-implemented, correctly setting up the block synchronization service with all necessary components properly initialized.


83-85: The AddBlock method correctly delegates block addition to the BlockSyncDagService, maintaining good separation of concerns.


87-97: The GetBlock method is robust, featuring comprehensive error handling and logging, which aids in effective debugging and monitoring.

testutil/p2p.go (1)

119-119: The updated StartTestNetwork function correctly initializes a test network for P2P clients, enhancing the test setup with necessary configurations and robust error handling.

store/storeIface.go (1)

77-79: The addition of SaveBlockID and LoadBlockID methods to the Store interface enhances the storage capabilities, allowing for more efficient indexing and retrieval of blocks.

p2p/block_sync_dag.go (2)

23-35: The NewDAGService function is straightforward and follows good practices in initializing the BlockSyncDagService. Using merkledag.NewDAGService directly within the constructor ensures that the service is ready to use immediately after instantiation.


86-101: The GetBlock method effectively retrieves and reconstructs the block data from its CID. The use of dagReader to abstract the reading logic is a good practice. Ensure proper handling and propagation of errors from the io.ReadAll function to avoid data inconsistency.

testutil/block.go (2)

97-97: The initialization of the P2P client in the GetManagerWithProposerKey function is correctly parameterized, allowing for flexible configuration during testing. This is a good practice as it enhances test robustness and configurability.


12-12: The import of github.com/ipfs/go-datastore is crucial for the test utility functions that interact with the P2P client and data storage. Ensure that all datastore interactions are properly mocked to isolate unit tests from external dependencies.

Verification successful

The use of datastore.NewMapDatastore() in the following files indicates that datastore interactions are properly mocked for unit tests:

  • testutil/p2p.go
  • testutil/block.go
  • p2p/block_sync_test.go
  • p2p/client_test.go
  • node/node.go
  • block/manager_test.go

These usages are consistent with best practices for isolating unit tests from external dependencies.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Check if datastore interactions are mocked
rg --type go $'datastore.NewMapDatastore()'

Length of output: 685

p2p/validator_test.go (1)

172-172: The test case TestValidator_BlockValidator effectively checks the validation logic for blocks signed by different keys. The introduction of a P2PBlock instance here is appropriate and aligns with the testing of signature verification logic.

block/block.go (1)

117-141: The attemptCacheBlock method efficiently handles the caching of blocks with proper mutex locking to avoid race conditions. However, consider adding error handling for the SetLatestSeenHeight method call inside the mutex lock to ensure that any potential issues are caught and handled appropriately.
[REFACTOR_SUGGESTion]

- m.p2pClient.SetLatestSeenHeight(block.Header.Height)
+ if err := m.p2pClient.SetLatestSeenHeight(block.Header.Height); err != nil {
+     m.retrieverMu.Unlock()
+     return false, fmt.Errorf("set latest seen height: %w", err)
+ }
block/manager.go (2)

153-154: The use of Go routines for handling block synchronization and gossiping is noted. While this introduces potential non-determinism, it is necessary for the asynchronous nature of block handling. Ensure that all access to shared resources is properly synchronized to mitigate any issues arising from this non-determinism.

Also applies to: 159-159, 176-181

Tools
GitHub Check: CodeQL

[notice] 153-153: Spawning a Go routine
Spawning a Go routine may be a possible source of non-determinism


[notice] 154-154: Spawning a Go routine
Spawning a Go routine may be a possible source of non-determinism


214-215: The method SetLatestSeenHeight is used to update the latest height seen by the P2P client. Ensure that this method handles errors appropriately and that these errors are either logged or handled at a higher level to prevent silent failures.

p2p/client_test.go (1)

36-36: The use of datastore.NewMapDatastore() directly in the test setup might be appropriate for unit tests, but consider mocking or using configurable datastores for more flexibility and control in different test environments.

store/store.go (2)

25-25: The addition of cidPrefix is consistent with the existing pattern of defining prefixes for different types of data in the store. Ensure that this prefix does not conflict with any existing keys in the database to avoid data corruption.


251-257: The method SaveBlockID correctly uses the cidPrefix for storing block IDs. However, consider handling potential errors from cid.String() as it might fail if the CID is not properly formatted or initialized.

go.mod (13)

20-20: Updated github.com/google/uuid to v1.5.0.

This update should provide access to newer features and bug fixes in the UUID package.


27-27: Added github.com/ipfs/boxo v0.18.0.

Ensure this new dependency is utilized appropriately in the codebase, particularly in relation to IPFS-related functionality.


41-41: Updated gonum.org/v1/gonum to v0.14.0.

This update might bring performance improvements or new functionalities. Verify that existing code using this library still functions as expected.


46-47: Added github.com/ipfs/go-block-format v0.2.0 as an indirect dependency.

This addition likely supports other IPFS functionalities. Check for any indirect implications or required changes in related modules.


78-78: Updated github.com/go-logr/logr to v1.4.1.

This version might include improvements in logging capabilities. Review the logging configurations to make the most out of this update.


84-84: Updated github.com/hashicorp/golang-lru/v2 to v2.0.7.

This could enhance caching mechanisms. Ensure the cache behavior aligns with the system's requirements and performance expectations.


105-107: Updated go.opentelemetry.io/otel to v1.21.0.

This update is crucial for tracing and metrics. Confirm that telemetry integrations are functioning correctly post-update.


111-111: Updated golang.org/x/xerrors to v0.0.0-20231012003039-104605ab7028.

This update may include important fixes or enhancements in error handling. Review usage across the codebase to ensure compatibility.


167-167: Updated github.com/ipfs/go-cid to v0.4.1.

This version update should support newer features or improvements in content addressing in IPFS. Check integration points in the code.


168-168: Updated github.com/ipfs/go-datastore to v0.6.0.

This update likely includes optimizations or new features for data storage mechanisms. Validate datastore integrations for performance and correctness.


170-170: Updated github.com/ipld/go-ipld-prime to v0.21.0.

This library update is crucial for IPLD data model manipulations. Ensure that all data handling and transformations are still performing correctly.


269-269: Added github.com/ipfs/go-ds-leveldb v0.5.0.

This addition enhances the LevelDB support in IPFS. Verify that the database interactions are efficient and error-free.


295-295: Replaced github.com/libp2p/go-libp2p-pubsub with a custom version.

This change indicates a forked version specific to project needs. Ensure that this custom version meets all the required functionality and security standards.

block/manager_test.go (2)

9-9: Added import for github.com/ipfs/go-datastore. Ensure it is used properly in the file.


60-60: Updated p2p.NewClient instantiation to include datastore.NewMapDatastore(). Ensure that the datastore is appropriately integrated and utilized within the p2p.Client.

p2p/client.go (8)

6-6: Added imports for various packages. Verify that all these imports are utilized in the file, especially github.com/ipfs/go-cid and github.com/ipfs/go-datastore which are crucial for the new block synchronization features.

Also applies to: 8-8, 10-10, 13-13, 14-14


35-35: Added StatusCode type. Ensure it is used consistently across the P2P client to represent various status conditions.


51-52: Introduced blockSyncProtocolPrefix. Verify its usage in DHT operations related to block synchronization to ensure it aligns with the intended protocol specifications.


Line range hint 101-118: Updated the NewClient function to include new fields related to block synchronization. Ensure that these fields are properly initialized and used throughout the client's operations.


200-216: Added AddBlock, AdvertiseBlock, and GetBlockId methods to handle block operations in the P2P network. Ensure these methods are correctly implemented and align with the block synchronization protocol requirements.


457-482: Implemented blockSyncReceived and blockGossipReceived methods to handle the reception of blocks through synchronization and gossip protocols. Verify that these methods correctly manage block data and trigger appropriate events in the P2P network.


505-520: Updated SetLatestSeenHeight and SetAppliedHeight methods to manage block heights in the P2P client. Ensure these methods correctly update the client's state and handle edge cases appropriately.


522-556: Implemented BlockSyncLoop method to manage the block synchronization process. Ensure this method robustly handles synchronization tasks and maintains correct state management.

da/celestia/celestia.go (3)

266-267: Properly logging the final error after retries in RetrieveBatches is a good practice, ensuring that failures are not silent.


269-269: Returning structured results in RetrieveBatches maintains consistency and clarity in error handling and success reporting.


255-258: Ensure that the error handling is specific and appropriate for expected failures in RetrieveBatches.

p2p/client_test.go Outdated Show resolved Hide resolved
store/store.go Outdated Show resolved Hide resolved
block/block.go Outdated Show resolved Hide resolved
node/node.go Outdated Show resolved Hide resolved
p2p/block_sync_test.go Outdated Show resolved Hide resolved
block/p2p.go Outdated Show resolved Hide resolved
block/p2p.go Outdated Show resolved Hide resolved
block/p2p.go Outdated Show resolved Hide resolved
p2p/client.go Outdated Show resolved Hide resolved
block/block.go Outdated Show resolved Hide resolved
store/store.go Outdated Show resolved Hide resolved
store/storeIface.go Outdated Show resolved Hide resolved
store/storeIface.go Outdated Show resolved Hide resolved
config/p2p.go Outdated Show resolved Hide resolved
block/manager.go Outdated Show resolved Hide resolved
block/manager.go Outdated Show resolved Hide resolved
block/p2p.go Outdated Show resolved Hide resolved
block/p2p.go Outdated Show resolved Hide resolved
p2p/client.go Outdated Show resolved Hide resolved
@srene srene force-pushed the srene/p2p-block-sync-protocol branch from 3c748f7 to 522adab Compare June 20, 2024 10:40
block/manager.go Fixed Show fixed Hide fixed
block/manager.go Fixed Show fixed Hide fixed
block/manager.go Fixed Show fixed Hide fixed
block/manager.go Dismissed Show dismissed Hide dismissed
block/manager.go Dismissed Show dismissed Hide dismissed
@srene srene requested a review from mtsitrin June 21, 2024 08:45
block/p2p.go Outdated Show resolved Hide resolved
Copy link
Contributor

@danwt danwt left a comment

Choose a reason for hiding this comment

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

Few potential bugs highlighted

Please add more documentation/comments

block/manager.go Fixed Show resolved Hide resolved
block/manager.go Outdated Show resolved Hide resolved
block/manager.go Outdated Show resolved Hide resolved
block/retriever.go Outdated Show resolved Hide resolved
p2p/block_sync.go Outdated Show resolved Hide resolved
p2p/client.go Outdated Show resolved Hide resolved
p2p/client.go Outdated Show resolved Hide resolved
p2p/client.go Outdated Show resolved Hide resolved
p2p/client.go Outdated Show resolved Hide resolved
store/store_test.go Outdated Show resolved Hide resolved
block/manager.go Fixed Show fixed Hide fixed
@srene srene requested review from mtsitrin and danwt June 26, 2024 15:03
block/manager.go Outdated Show resolved Hide resolved
block/manager.go Outdated Show resolved Hide resolved
block/manager.go Outdated Show resolved Hide resolved
node/node.go Show resolved Hide resolved
block/p2p.go Outdated Show resolved Hide resolved
p2p/client.go Outdated Show resolved Hide resolved
@srene srene force-pushed the srene/p2p-block-sync-protocol branch from 13efe8d to 6468e60 Compare June 28, 2024 12:32
block/manager.go Dismissed Show dismissed Hide dismissed
block/manager.go Fixed Show fixed Hide fixed
p2p/client.go Fixed Show fixed Hide fixed
p2p/client.go Fixed Show fixed Hide fixed
omritoptix
omritoptix previously approved these changes Aug 6, 2024
Copy link
Contributor

@danwt danwt left a comment

Choose a reason for hiding this comment

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

Important: can you clarify the updateBlocksReceived call in p2p/client? #915 (comment)

I left some other less important suggestions

block/pruning.go Outdated Show resolved Hide resolved
block/retriever.go Outdated Show resolved Hide resolved
da/celestia/celestia.go Show resolved Hide resolved
p2p/block_sync_dag.go Outdated Show resolved Hide resolved
p2p/client.go Show resolved Hide resolved
p2p/client.go Outdated Show resolved Hide resolved
p2p/client.go Outdated Show resolved Hide resolved
p2p/client.go Outdated Show resolved Hide resolved
p2p/client.go Outdated Show resolved Hide resolved
p2p/client.go Outdated Show resolved Hide resolved
block/manager.go Show resolved Hide resolved
Co-authored-by: Daniel T <[email protected]>
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: 3

Outside diff range, codebase verification and nitpick comments (8)
p2p/p2p_block.go (2)

Line range hint 27-35:
Update variable name to reflect the new struct name.

Rename pbGossipedBlock to pbP2PBlockEvent for consistency.

- var pbGossipedBlock pb.GossipedBlock
- err := pbGossipedBlock.Unmarshal(data)
+ var pbP2PBlockEvent pb.GossipedBlock
+ err := pbP2PBlockEvent.Unmarshal(data)
- err = e.FromProto(&pbGossipedBlock)
+ err = e.FromProto(&pbP2PBlockEvent)

Line range hint 56-66:
Consider adding detailed comments to explain validation steps.

Adding comments will enhance readability and maintainability.

+ // Validate the basic structure of the block
if err := e.Block.ValidateBasic(); err != nil {
	return err
}
+ // Validate the basic structure of the commit
if err := e.Commit.ValidateBasic(); err != nil {
	return err
}
+ // Validate the commit with the block header
if err := e.Commit.ValidateWithHeader(proposer, &e.Block.Header); err != nil {
	return err
}
+ // Validate the data hash in the block header
abciData := tmtypes.Data{
	Txs: types.ToABCIBlockDataTxs(&e.Block.Data),
}
if e.Block.Header.DataHash != [32]byte(abciData.Hash()) {
	return types.ErrInvalidHeaderDataHash
}
config/defaults.go (2)

42-42: Consider adding a comment explaining the purpose of BlockSyncRequestIntervalTime.

Adding a comment will enhance readability and maintainability.

BlockSyncRequestIntervalTime: 30 * time.Second,
+ // Interval time between block sync requests

46-46: Consider adding a comment explaining the purpose of BlockSyncEnabled.

Adding a comment will enhance readability and maintainability.

BlockSyncEnabled: true,
+ // Enable or disable block synchronization
block/p2p.go (1)

Line range hint 64-76:
Simplify error wrapping in gossipBlock.

The error wrapping in the gossipBlock method can be simplified to make the error messages more readable.

- return fmt.Errorf("marshal binary: %w: %w", err, ErrNonRecoverable)
+ return fmt.Errorf("marshal binary: %w", err)
p2p/block_sync.go (1)

44-93: Ensure explicit error handling in client.go for SetupBlockSync initialization.

The SetupBlockSync function is properly tested in block_sync_test.go with appropriate error checks. However, in client.go, there is no explicit error handling for the SetupBlockSync function. It is recommended to add error handling to ensure that any issues during initialization are caught and handled appropriately.

  • File: p2p/client.go
  • Lines: Around the call to SetupBlockSync
Analysis chain

Function initialization looks good.

The SetupBlockSync function is well-structured and initializes the necessary services for block synchronization.

However, ensure that all services are properly initialized and started without errors.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the initialization of services in the SetupBlockSync function.

# Test: Search for the function usage. Expect: Proper initialization of services.
rg --type go -A 5 $'SetupBlockSync'

Length of output: 1222


Script:

#!/bin/bash
# Extract the relevant portions of block_sync_test.go to verify proper initialization and error handling
rg --type go -A 10 'SetupBlockSync' p2p/block_sync_test.go

# Extract the relevant portions of client.go to verify proper initialization and error handling
rg --type go -A 10 'SetupBlockSync' p2p/client.go

Length of output: 831

block/manager_test.go (1)

59-63: Ensure all calls to p2p.NewClient include the BlockSyncRequestIntervalTime parameter.

The following locations in the codebase call p2p.NewClient without the BlockSyncRequestIntervalTime parameter:

  • node/node.go (line 1)

Please update these instances to match the new function signature.

Analysis chain

LGTM! The new parameter enhances configurability.

The addition of BlockSyncRequestIntervalTime to the p2p.NewClient function call enhances configurability. The updates to the datastore management are appropriate.

However, ensure that all function calls to p2p.NewClient match the new signature.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `p2p.NewClient` match the new signature.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg --type go -A 5 $'p2p.NewClient'

Length of output: 2504

p2p/client.go (1)

Ensure all calls to NewClient match the new signature:

The following files contain calls to NewClient:

  • testutil/p2p.go
  • testutil/block.go
  • p2p/client_test.go
  • node/node.go
  • block/manager_test.go

Verified Instances:

  • testutil/block.go: Correct usage with all parameters.
  • p2p/client_test.go: Correct usage with all parameters.
  • node/node.go: Correct usage with all parameters.
  • block/manager_test.go: Correct usage with all parameters.

Potential Issues:

  • testutil/p2p.go: This file shows a partial call to NewClient without all parameters. This needs to be reviewed.

Please ensure the following call in testutil/p2p.go matches the new function signature:

  • testutil/p2p.go: client, err := p2p.NewClient(config.P2PConfig{...
Analysis chain

Line range hint 104-121:
LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all calls to NewClient match the new signature.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `NewClient` match the new signature.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg --type go -A 5 $'NewClient'

Length of output: 7058

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 50ccd36 and 21109fd.

Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
Files selected for processing (42)
  • block/block.go (2 hunks)
  • block/block_cache.go (1 hunks)
  • block/manager.go (6 hunks)
  • block/manager_test.go (2 hunks)
  • block/p2p.go (4 hunks)
  • block/produce.go (2 hunks)
  • block/pruning.go (2 hunks)
  • block/retriever.go (4 hunks)
  • block/state.go (1 hunks)
  • config/config_test.go (1 hunks)
  • config/defaults.go (1 hunks)
  • config/p2p.go (2 hunks)
  • config/toml.go (1 hunks)
  • da/celestia/celestia.go (1 hunks)
  • da/celestia/rpc.go (1 hunks)
  • da/da.go (1 hunks)
  • da/grpc/grpc.go (1 hunks)
  • go.mod (11 hunks)
  • node/node.go (4 hunks)
  • node/node_test.go (1 hunks)
  • p2p/block_sync.go (1 hunks)
  • p2p/block_sync_dag.go (1 hunks)
  • p2p/block_sync_test.go (1 hunks)
  • p2p/client.go (13 hunks)
  • p2p/client_test.go (4 hunks)
  • p2p/events.go (1 hunks)
  • p2p/gossip.go (2 hunks)
  • p2p/p2p_block.go (3 hunks)
  • p2p/validator.go (1 hunks)
  • p2p/validator_test.go (1 hunks)
  • rpc/client/client_test.go (5 hunks)
  • rpc/json/service_test.go (1 hunks)
  • store/badger.go (2 hunks)
  • store/pruning.go (1 hunks)
  • store/pruning_test.go (3 hunks)
  • store/store.go (4 hunks)
  • store/storeIface.go (2 hunks)
  • store/store_test.go (2 hunks)
  • testutil/block.go (2 hunks)
  • testutil/p2p.go (3 hunks)
  • testutil/types.go (1 hunks)
  • types/block_source.go (2 hunks)
Files skipped from review due to trivial changes (4)
  • da/celestia/celestia.go
  • da/celestia/rpc.go
  • da/da.go
  • da/grpc/grpc.go
Additional comments not posted (104)
types/block_source.go (3)

12-16: LGTM! Constants renamed for clarity.

The renaming of constants to Produced, Gossiped, BlockSync, and DA improves readability and maintainability.


23-23: LGTM! Updated AllSources for consistency.

The AllSources slice now correctly reflects the renamed constants, ensuring consistency.


33-33: LGTM! Added Source field to CachedBlock.

The addition of the Source field to the CachedBlock struct enhances its functionality by explicitly tracking the source of the cached block.

block/block_cache.go (1)

12-13: LGTM! Added source parameter to AddBlockToCache.

The addition of the source parameter to the AddBlockToCache method enhances its functionality by allowing it to store the source of the block in the cache.

block/pruning.go (1)

18-21: LGTM! Enhanced error handling in pruneBlocks.

The enhanced error handling ensures that any issues during the block removal process are logged for easier debugging.

p2p/events.go (3)

18-18: LGTM! New event constant added correctly.

The new event constant EventNewBlockSyncBlock is defined correctly and follows the naming conventions.


25-26: LGTM! Comment corrected appropriately.

The comment correction aligns with the defined event and improves clarity.


28-29: LGTM! New query variable added correctly.

The new query variable EventQueryNewBlockSyncBlock is defined correctly and follows the naming conventions.

config/p2p.go (3)

21-21: LGTM! New configuration parameter added correctly.

The new parameter BlockSyncEnabled is defined correctly and follows the naming conventions.


23-23: LGTM! New configuration parameter added correctly.

The new parameter BlockSyncRequestIntervalTime is defined correctly and follows the naming conventions.


36-38: LGTM! Validation check added correctly.

The validation check for BlockSyncRequestIntervalTime is implemented correctly and follows best practices.

store/pruning.go (1)

51-53: LGTM! CID key deletion added correctly.

The modification to include deletion of CID keys in the PruneBlocks function is implemented correctly and follows best practices.

p2p/p2p_block.go (3)

22-24: LGTM!

The method MarshalBinary is correctly implemented.


38-43: LGTM!

The method ToProto is correctly implemented.


Line range hint 46-54:
LGTM!

The method FromProto is correctly implemented.

p2p/validator.go (1)

Line range hint 74-78:
Verify the correctness of the type change.

The change from GossipedBlock to P2PBlockEvent needs to be verified for correctness. Ensure that P2PBlockEvent includes all necessary attributes and methods previously provided by GossipedBlock.

block/p2p.go (4)

21-24: Ensure proper error handling for event types.

The function checks the number of event types received and logs an error if it is not exactly one. This is a good practice to prevent unexpected behavior.


Line range hint 39-55:
Ensure proper mutex handling and logging.

The function uses a mutex to protect access to the block cache and includes logging for received blocks. This is a good practice to ensure thread safety and provide visibility into the block reception process.


12-18: Verify the correctness of the type assertion.

Ensure that the type assertion event.Data().(p2p.P2PBlockEvent) is correct and that P2PBlockEvent is the expected type for the event data.

Verification successful

The type assertion event.Data().(p2p.P2PBlockEvent) is correct.

The P2PBlockEvent type is defined and used appropriately as event data in the codebase, confirming the correctness of the type assertion in the onReceivedBlock function.

  • p2p/p2p_block.go: Definition of P2PBlockEvent.
  • block/p2p.go: Usage of P2PBlockEvent in the onReceivedBlock function.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correctness of the type assertion for `P2PBlockEvent`.

# Test: Search for the definition of `P2PBlockEvent` and its usage in event data. Expect: The definition and usage align with the type assertion.
rg --type go --pattern $'type P2PBlockEvent struct'

Length of output: 464


Script:

#!/bin/bash
# Description: Verify the correctness of the type assertion for `P2PBlockEvent`.

# Test: Search for the definition of `P2PBlockEvent` and its usage in event data. Expect: The definition and usage align with the type assertion.
rg 'type P2PBlockEvent struct'

Length of output: 77


Script:

#!/bin/bash
# Description: Verify the usage of `P2PBlockEvent` in the codebase.

# Test: Search for the usage of `P2PBlockEvent` to confirm it is used as event data in `pubsub.Message`.
rg 'P2PBlockEvent' -A 5

Length of output: 5526


26-34: Verify the correctness of the event type handling.

Ensure that the event types p2p.EventNewBlockSyncBlock and p2p.EventNewGossipedBlock are correctly handled and mapped to the appropriate BlockSource values.

Verification successful

Event type handling is correct.

The event types p2p.EventNewBlockSyncBlock and p2p.EventNewGossipedBlock are correctly defined in p2p/events.go and appropriately mapped to the BlockSource values in the switch statement.

  • p2p.EventNewBlockSyncBlock is mapped to types.BlockSync.
  • p2p.EventNewGossipedBlock is mapped to types.Gossiped.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correctness of the event type handling.

# Test: Search for the definitions of `p2p.EventNewBlockSyncBlock` and `p2p.EventNewGossipedBlock`. Expect: The definitions align with the event type handling.
rg --type go --pattern $'const EventNewBlockSyncBlock ='
rg --type go --pattern $'const EventNewGossipedBlock ='

Length of output: 938


Script:

#!/bin/bash
# Description: Verify the correctness of the event type handling.

# Test: Search for the definitions of `p2p.EventNewBlockSyncBlock` and `p2p.EventNewGossipedBlock`. Expect: The definitions align with the event type handling.
rg 'const EventNewBlockSyncBlock =' --type go
rg 'const EventNewGossipedBlock =' --type go

Length of output: 94


Script:

#!/bin/bash
# Description: Verify the correctness of the event type handling.

# Test: Search for all constants defined in the `p2p` package to identify the correct event type definitions.
rg 'const ' --type go | grep 'p2p'

Length of output: 251


Script:

#!/bin/bash
# Description: Verify the correctness of the event type handling.

# Test: Search for all constants defined in the `p2p/events.go` file to identify the correct event type definitions.
rg 'const ' p2p/events.go

Length of output: 43


Script:

#!/bin/bash
# Description: Extract the full content of the `const` blocks within `p2p/events.go` to identify the correct event type definitions.

# Extract the content of the `const` blocks
sed -n '/const (/,/^)/p' p2p/events.go

Length of output: 240

store/storeIface.go (2)

81-82: Verify the correctness of the method signature LoadBlockCid.

Ensure that the method signature for LoadBlockCid is correct and aligns with the intended functionality.

Verification successful

The method signature for LoadBlockCid is correct and properly integrated within the Store interface.

  • Implementation found in store/store.go:
    func (s *DefaultStore) LoadBlockCid(height uint64) (cid.Cid, error)
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correctness of the method signature for `LoadBlockCid`.

# Test: Search for the implementation of `LoadBlockCid`. Expect: The implementation aligns with the method signature.
rg --type go --pattern $'func (s *StoreImpl) LoadBlockCid'

Length of output: 471


Script:

#!/bin/bash
# Description: Verify the correctness of the method signature for `LoadBlockCid`.

# Test: Search for the implementation of `LoadBlockCid`. Expect: The implementation aligns with the method signature.
rg 'func (s *StoreImpl) LoadBlockCid' --type go -A 5

Length of output: 54


Script:

#!/bin/bash
# Description: Verify the correctness of the method signature for `LoadBlockCid`.

# Test: Search for the implementation of `LoadBlockCid` with any receiver name. Expect: The implementation aligns with the method signature.
rg 'func .* LoadBlockCid' --type go -A 5

Length of output: 389


79-80: Verify the correctness of the method signature SaveBlockCid.

Ensure that the method signature for SaveBlockCid is correct and aligns with the intended functionality.

Verification successful

The method signature for SaveBlockCid is correct and aligns with its implementation and references in the codebase.

  • Implementation found in store/store.go
  • References found in store/store_test.go, store/pruning_test.go, storeIface.go, and p2p/client.go
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correctness of the method signature for `SaveBlockCid`.

# Test: Search for the implementation of `SaveBlockCid`. Expect: The implementation aligns with the method signature.
rg --type go --pattern $'func (s *StoreImpl) SaveBlockCid'

Length of output: 471


Script:

#!/bin/bash
# Description: Verify the correctness of the method signature for `SaveBlockCid`.

# Test: Search for the implementation of `SaveBlockCid`. Expect: The implementation aligns with the method signature.
rg --type go 'func (s *StoreImpl) SaveBlockCid'

Length of output: 49


Script:

#!/bin/bash
# Description: Verify the correctness of the method signature for `SaveBlockCid`.

# Test: Search for the method name `SaveBlockCid` across the Go codebase to locate its implementation or any references.
rg --type go 'SaveBlockCid'

Length of output: 581

p2p/gossip.go (2)

28-28: LGTM! The change improves context-aware message handling.

The updated GossipMessageHandler type allows for better management of request lifetimes and cancellation.


106-106: LGTM! The change ensures context-aware message handling.

The ProcessMessages method now correctly passes the context and the message data to the msgHandler.

testutil/p2p.go (2)

12-12: LGTM! The addition of the datastore dependency improves state management.

The new in-memory key-value store enhances the functionality and control flow of the StartTestNetwork function.


111-124: LGTM! The changes enhance the client's configuration and data management.

The new parameters for block sync configurations and the integration of the datastore improve the testing capabilities of the p2p network.

store/pruning_test.go (2)

68-80: LGTM! The addition of CID handling improves block management.

The changes ensure that both blocks and their identifiers are managed consistently within the store.


113-121: LGTM! The validation ensures consistent pruning of blocks and CIDs.

The assertions verify that both blocks and their corresponding CIDs are correctly managed during pruning.

node/node_test.go (1)

72-72: LGTM! Verify the usage of the new parameter.

The new configuration parameter BlockSyncRequestIntervalTime is correctly added to the P2PConfig structure.

However, ensure that the new parameter is correctly utilized in the codebase.

Verification successful

The new configuration parameter BlockSyncRequestIntervalTime is correctly utilized across the codebase.

The parameter is used in various files, including configuration files and test cases, ensuring its integration is comprehensive and functional.

  • testutil/p2p.go
  • testutil/block.go
  • node/node_test.go
  • p2p/client_test.go
  • rpc/json/service_test.go
  • p2p/client.go
  • rpc/client/client_test.go
  • config/defaults.go
  • config/toml.go
  • config/p2p.go
  • config/config_test.go
  • block/manager_test.go
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the new configuration parameter `BlockSyncRequestIntervalTime`.

# Test: Search for the usage of the new parameter. Expect: Occurrences of `BlockSyncRequestIntervalTime`.
rg --type go -A 5 $'BlockSyncRequestIntervalTime'

Length of output: 5749

p2p/block_sync_dag.go (3)

28-40: LGTM! The NewDAGService method is well-defined.

The method correctly initializes the BlockSyncDagService struct with the necessary components.


95-115: LGTM! The LoadBlock method is well-defined.

The method correctly retrieves block data from the DAGService using the root CID and handles errors appropriately.


117-139: LGTM! The dagReader method is well-defined.

The method correctly reads the DAG from the root node and handles errors appropriately.

store/badger.go (2)

34-34: LGTM! The function name change is correctly reflected.

The function name change from rootify to Rootify is correctly reflected in the function call.


49-53: LGTM! The Rootify function is well-defined.

The function correctly makes the configuration creation independent of the root directory.

p2p/block_sync.go (4)

28-40: Struct definition looks good.

The BlockSync struct is well-defined with appropriate fields for managing block synchronization.


96-99: Function implementation looks good.

The SaveBlock function is straightforward and stores blocks in the DAG service.


114-117: Function implementation looks good.

The DeleteBlock function is straightforward and removes blocks from the DAG service.


101-112: Function implementation looks good.

The LoadBlock function is well-structured and retrieves blocks from the local blockstore or the network.

However, ensure that the blocks are properly retrieved and deserialized without errors.

Verification successful

Deserialization process in LoadBlock function is properly tested and works as expected.

The LoadBlock function is used and tested in p2p/block_sync_test.go, ensuring that blocks are correctly deserialized without errors.

  • p2p/block_sync_test.go: The test verifies that the function does not return errors and that the deserialized block matches the expected block.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the deserialization process in the LoadBlock function.

# Test: Search for the function usage. Expect: Proper deserialization of blocks.
rg --type go -A 5 $'LoadBlock'

Length of output: 27226

testutil/block.go (2)

Line range hint 100-108:
Function implementation looks good.

The GetManager function is straightforward and initializes a block manager without a proposer key.


Line range hint 12-99:
Function initialization looks good.

The GetManagerWithProposerKey function is well-structured and initializes various components, including the P2P client.

However, ensure that all components are properly initialized and started without errors.

Verification successful

Initialization and error handling are properly tested.

The GetManagerWithProposerKey function is well-tested for component initialization and error handling. The tests ensure that components like pubsubServer, settlementlc, dalc, and proxyApp are correctly initialized without errors.

  • Verified in the following test files:
    • settlement/local/local_test.go
    • p2p/client_test.go
    • p2p/validator_test.go
    • settlement/dymension/dymension_test.go
    • da/da_test.go
    • da/avail/avail_test.go
    • da/celestia/rpc_test.go
    • block/manager_test.go
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the initialization of components in the GetManagerWithProposerKey function.

# Test: Search for the function usage. Expect: Proper initialization of components.
rg --type go -A 5 $'GetManagerWithProposerKey'

Length of output: 1543


Script:

#!/bin/bash
# Description: Verify the comprehensive testing of component initialization and error handling in GetManagerWithProposerKey.

# Test: Search for tests related to GetManagerWithProposerKey.
rg --type go -A 5 -g '*_test.go' $'GetManagerWithProposerKey'

Length of output: 436


Script:

#!/bin/bash
# Description: Verify the testing of component initialization and error handling in GetManagerWithProposerKey.

# Test: Search for tests related to pubsubServer initialization.
rg --type go -A 5 -g '*_test.go' $'pubsub.NewServer'

# Test: Search for tests related to settlementlc initialization.
rg --type go -A 5 -g '*_test.go' $'slregistry.GetClient'

# Test: Search for tests related to dalc initialization.
rg --type go -A 5 -g '*_test.go' $'localda.DataAvailabilityLayerClient'

# Test: Search for tests related to proxyApp initialization.
rg --type go -A 5 -g '*_test.go' $'GetABCIProxyAppMock'

Length of output: 6412

block/retriever.go (4)

15-27: Function implementation looks good.

The onReceivedBatch function is well-structured and handles incoming batch events to initiate synchronization.

However, ensure that the event data is properly processed and synchronization is correctly initiated.

Verification successful

Function implementation looks good.

The onReceivedBatch function is well-structured and handles incoming batch events to initiate synchronization. The function is properly subscribed to the settlement.EventQueryNewSettlementBatchAccepted event and processes the event data correctly.

  • block/manager.go: Subscription to the settlement.EventQueryNewSettlementBatchAccepted event using onReceivedBatch.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the event handling process in the onReceivedBatch function.

# Test: Search for the function usage. Expect: Proper handling of batch events.
rg --type go -A 5 $'onReceivedBatch'

Length of output: 1077


Line range hint 87-105:
Function implementation looks good.

The applyLocalBlock function is well-structured and applies a block from the local store.

However, ensure that the block is properly applied and validated without errors.

Verification successful

Function implementation looks good.

The applyLocalBlock function is well-structured and applies a block from the local store. The validateBlock and applyBlock methods ensure that the block is properly validated and applied without errors.

  • validateBlock method: Validates the block and commit using ValidateProposedTransition.
  • applyBlock method: Handles the application process, including validation, saving, executing, committing, updating state, and pruning old blocks.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the block application process in the applyLocalBlock function.

# Test: Search for the function usage. Expect: Proper application and validation of blocks.
rg --type go -A 5 $'applyLocalBlock'

Length of output: 686


Script:

#!/bin/bash
# Description: Verify the implementation of validateBlock and applyBlock methods used in applyLocalBlock function.

# Search for the validateBlock method implementation
ast-grep --lang go --pattern $'func (m *Manager) validateBlock($_, $_) error {
  $$$
}'

# Search for the applyBlock method implementation
ast-grep --lang go --pattern $'func (m *Manager) applyBlock($_, $_, $_) error {
  $$$
}'

Length of output: 5417


Line range hint 106-145:
Function implementation looks good.

The ProcessNextDABatch function is well-structured and processes the next batch of blocks from the DA.

However, ensure that the batch is properly processed and blocks are correctly applied without errors.


Line range hint 28-55:
Function implementation looks good.

The syncToTargetHeight function is well-structured and synchronizes blocks until the target height is reached.

However, ensure that the synchronization process is correctly implemented and handles potential errors.

p2p/validator_test.go (1)

171-171: Verify compatibility of the new structure P2PBlockEvent.

Ensure that the new structure P2PBlockEvent is compatible with the existing logic and that the test correctly validates the block.

Verification successful

The new structure P2PBlockEvent is compatible with the existing logic and the test correctly validates the block.

  • The P2PBlockEvent structure encapsulates both Block and Commit data.
  • The MarshalBinary method is used to serialize the P2PBlockEvent, and the serialized data is used in the validation process.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the structure and usage of `P2PBlockEvent`.

# Test: Search for the definition and usage of `P2PBlockEvent`. Expect: The structure should correctly encapsulate block and commit data.
rg --type go 'type P2PBlockEvent struct' -A 10

Length of output: 552


Script:

#!/bin/bash
# Description: Verify the usage of `P2PBlockEvent` within `validator_test.go`.

# Test: Search for the usage of `P2PBlockEvent` in `validator_test.go`. Expect: The structure should be used correctly within the test logic.
rg 'P2PBlockEvent' p2p/validator_test.go -A 10

Length of output: 434

block/state.go (1)

89-89: Improved error message clarity.

The updated error message accurately describes the operation that failed, improving the clarity of the error handling.

block/block.go (2)

Line range hint 1-1:
Minor formatting update.

The removal of the extraneous newline contributes to cleaner code.


134-134: Enhanced flexibility of block application.

The change to use cachedBlock.Source for the BlockMetaData enhances the flexibility of block application by ensuring that the source information reflects the actual origin of the cached block.

config/toml.go (2)

113-114: Addition of p2p_blocksync_enabled is correct.

The parameter p2p_blocksync_enabled allows users to enable or disable block syncing from P2P sources. It follows the existing configuration format.


116-117: Addition of p2p_blocksync_block_request_interval is correct.

The parameter p2p_blocksync_block_request_interval specifies the time interval for checking and retrieving missing blocks from peers. It follows the existing configuration format.

config/config_test.go (1)

223-225: Addition of BlockSyncRequestIntervalTime is correct.

The field BlockSyncRequestIntervalTime is added to the P2PConfig struct and initialized with a value of 30 * time.Second. This enhances the functionality of the configuration.

store/store_test.go (1)

205-252: Addition of TestBlockId is correct.

The function TestBlockId validates the functionality of saving and loading CIDs associated with specific block heights, both with and without batching. It enhances the test coverage by ensuring that CID management in the store works as intended.

block/manager.go (8)

67-75: Good use of mutex and atomic variables for synchronization.

The introduction of syncFromDaMu mutex and TargetHeight atomic variable enhances thread safety and ensures proper synchronization.


103-113: Initialization of new fields in NewManager.

The initialization of p2pClient and Retriever fields is essential for the new synchronization functionality.


158-182: Enhanced synchronization and event subscription in Start method.

The updated logic for syncing from the settlement layer and subscribing to events improves the block manager's responsiveness and synchronization process.


206-224: Renamed and updated syncFromSettlement method.

The renaming and updates clarify the method's broader scope and functionality, reflecting synchronization from both SL and DA.


Line range hint 226-231:
Ensuring correct target height with UpdateTargetHeight.

The UpdateTargetHeight method is crucial for maintaining the correct target height during synchronization.


Line range hint 233-243:
Verification of sequencer role with IsSequencerVerify.

The IsSequencerVerify method is essential for determining the node's role by comparing public keys.


Line range hint 245-247:
Simplified sequencer check with IsSequencer.

The IsSequencer method simplifies the process of checking if the node is a sequencer by calling IsSequencerVerify.


Line range hint 249-251:
Determining the next height to submit with NextHeightToSubmit.

The NextHeightToSubmit method is crucial for determining the next block height for submission based on the last submitted height.

testutil/types.go (1)

Line range hint 45-45:
Verify the impact of removing NamespaceID initialization.

The removal of the NamespaceID field initialization could affect functionality relying on this identifier. Ensure that this change does not introduce any issues.

block/produce.go (2)

74-74: Enhanced logging in ProduceBlockLoop.

The added logging statement improves observability by providing information about the size of each new block generated.


185-185: Verify the alignment of Source field change in BlockMetaData.

The change from types.ProducedBlock to types.Produced likely reflects a refinement in the block's source designation. Ensure that this change aligns with the overall block handling logic.

store/store.go (4)

25-25: LGTM!

The constant cidPrefix is correctly defined and used in the new methods.


306-310: LGTM!

The method getCidKey correctly constructs the key for accessing CIDs in the database.


256-262: LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to SaveBlockCid are correctly implemented.

Verification successful

LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to SaveBlockCid are correctly implemented.

  • p2p/client.go: The function SaveBlockCid is called with appropriate parameters and error handling.
  • store/store_test.go: The function is tested, ensuring its correctness.
  • store/pruning_test.go: Additional tests confirm functionality.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `SaveBlockCid` are correctly implemented.

# Test: Search for the function usage. Expect: Correct usage of the function.
rg --type go -A 5 $'SaveBlockCid'

Length of output: 2015


264-274: LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to LoadBlockCid are correctly implemented.

p2p/client_test.go (4)

34-40: LGTM!

The method TestClientStartup correctly includes the store instance in the NewClient constructor.


195-227: LGTM!

The method TestAdvertiseWrongCid correctly tests advertising an invalid CID in the DHT.


273-277: LGTM!

The method TestSeedStringParsing correctly includes the store instance in the NewClient constructor.


144-193: LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to AdvertiseBlockIdToDHT and GetBlockIdFromDHT are correctly implemented.

Verification successful

Function usage is correctly implemented.

The functions AdvertiseBlockIdToDHT and GetBlockIdFromDHT are correctly used and tested in the codebase. No issues were found.

  • AdvertiseBlockIdToDHT is implemented in p2p/client.go and used in both p2p/client.go and p2p/client_test.go.
  • GetBlockIdFromDHT is implemented in p2p/client.go and used in both p2p/client.go and p2p/client_test.go.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `AdvertiseBlockIdToDHT` and `GetBlockIdFromDHT` are correctly implemented.

# Test: Search for the function usage. Expect: Correct usage of the functions.
rg --type go -A 5 $'AdvertiseBlockIdToDHT'
rg --type go -A 5 $'GetBlockIdFromDHT'

Length of output: 2434

node/node.go (3)

106-120: LGTM!

The method NewNode correctly initializes the dstore variable based on configuration settings.


Line range hint 269-293:
LGTM!

The method OnStart correctly starts the P2P client, pubsub server, data availability layer client, and settlement layer client.


168-168: LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to NewNode are correctly implemented.

Verification successful

The function calls to NewNode appear to be correctly implemented across the codebase. Each call passes the expected parameters, including context, config, key, signingKey, and proxy.ClientCreator.

  • Files and Lines to Verify:
    • testutil/node.go
    • rpc/client/client_test.go
    • rpc/json/service_test.go
    • node/node_test.go
    • cmd/dymint/commands/start.go

The function definition in node/node.go matches the usage patterns observed.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `NewNode` are correctly implemented.

# Test: Search for the function usage. Expect: Correct usage of the function.
rg --type go -A 5 $'NewNode'

Length of output: 3466

rpc/json/service_test.go (1)

316-319: LGTM! The new field enhances configurability.

The addition of BlockSyncRequestIntervalTime to the P2PConfig structure enhances the configurability of block synchronization requests.

go.mod (12)

27-27: LGTM! The new dependency enhances IPFS capabilities.

The addition of github.com/ipfs/boxo enhances the project's IPFS capabilities.


30-30: LGTM! The updated dependency improves P2P pubsub capabilities.

The update of github.com/libp2p/go-libp2p-pubsub from version 0.9.3 to 0.10.1 improves the project's P2P pubsub capabilities.


41-41: LGTM! The updated dependency improves numerical computing capabilities.

The update of gonum.org/v1/gonum from version 0.13.0 to 0.14.0 improves the project's numerical computing capabilities.


81-81: LGTM! The updated dependency improves logging capabilities.

The update of github.com/go-logr/logr from version 1.3.0 to 1.4.1 improves the project's logging capabilities.


87-87: LGTM! The updated dependency improves LRU cache capabilities.

The update of github.com/hashicorp/golang-lru/v2 from version 2.0.5 to 2.0.7 improves the project's LRU cache capabilities.


108-108: LGTM! The updated dependency improves telemetry capabilities.

The update of go.opentelemetry.io/otel from version 1.19.0 to 1.21.0 improves the project's telemetry capabilities.


139-139: LGTM! The updated dependency improves human-readable formatting capabilities.

The update of github.com/dustin/go-humanize from version 1.0.1-0.20200219035652-afde56e7acac to 1.0.1 improves the project's human-readable formatting capabilities.


165-165: LGTM! The updated dependency improves LRU cache capabilities.

The update of github.com/hashicorp/golang-lru from version 0.5.5-0.20210104140557-80c98217689d to 1.0.2 improves the project's LRU cache capabilities.


173-173: LGTM! The updated dependency improves IPLD capabilities.

The update of github.com/ipld/go-ipld-prime from version 0.20.0 to 0.21.0 improves the project's IPLD capabilities.


271-271: LGTM! The new dependency enhances IPFS bloom filter capabilities.

The addition of github.com/ipfs/bbloom enhances the project's IPFS bloom filter capabilities.


273-273: LGTM! The new dependency enhances IPFS delay capabilities.

The addition of github.com/ipfs/go-ipfs-delay enhances the project's IPFS delay capabilities.


274-274: LGTM! The new dependency enhances IPFS priority queue capabilities.

The addition of github.com/ipfs/go-ipfs-pq enhances the project's IPFS priority queue capabilities.

p2p/client.go (11)

166-176: LGTM!

The code changes are approved. The function correctly handles the block sync initialization based on the configuration.


209-227: LGTM!

The code changes are approved. The function correctly handles the block storage and advertisement, with proper error handling.


229-251: LGTM!

The code changes are approved. The function correctly handles the block removal with proper error handling.


253-257: LGTM!

The code changes are approved. The function correctly handles the advertisement process with proper error handling.


259-266: LGTM!

The code changes are approved. The function correctly handles the retrieval process with proper error handling.


397-403: LGTM!

The code changes are approved. The function correctly initializes the block sync process with proper error handling.


508-516: LGTM!

The code changes are approved. The function correctly processes the received blocks with proper error handling.


519-538: LGTM!

The code changes are approved. The function correctly processes the received blocks with proper error handling.


574-619: LGTM!

The code changes are approved. The function correctly handles the block retrieval process with proper error handling.


621-640: LGTM!

The code changes are approved. The function correctly handles the advertisement process with proper error handling.


652-676: LGTM!

The code changes are approved. The functions correctly handle the tracking process with proper error handling.

rpc/client/client_test.go (6)

110-110: LGTM!

The code changes are approved. The new configuration parameter is correctly integrated into the test function.


712-712: LGTM!

The code changes are approved. The new configuration parameter is correctly integrated into the test function.


870-870: LGTM!

The code changes are approved. The new configuration parameter is correctly integrated into the test function.


982-982: LGTM!

The code changes are approved. The new configuration parameter is correctly integrated into the test function.


1013-1013: LGTM!

The code changes are approved. The new configuration parameter is correctly integrated into the test function.


1013-1013: LGTM!

The code changes are approved. The new configuration parameter is correctly integrated into the test function.

block/pruning.go Show resolved Hide resolved
p2p/block_sync_dag.go Show resolved Hide resolved
p2p/block_sync_test.go Show resolved Hide resolved
block/manager.go Dismissed Show dismissed Hide dismissed
p2p/client.go Fixed Show fixed Hide fixed
p2p/blocks_received.go Dismissed Show dismissed Hide dismissed
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: 9

Outside diff range, codebase verification and nitpick comments (1)
p2p/client.go (1)

Line range hint 96-114:
Add documentation for each parameter.

The method should include documentation for each parameter to improve maintainability and readability.

// NewClient creates new Client object.
//
// Basic checks on parameters are done, and default parameters are provided for unset-configuration
// TODO(tzdybal): consider passing entire config, not just P2P config, to reduce number of arguments
func NewClient(conf config.P2PConfig, privKey crypto.PrivKey, chainID string, store store.Store, localPubsubServer *tmpubsub.Server, blockSyncStore datastore.Datastore, logger types.Logger) (*Client, error) {
	if privKey == nil {
		return nil, fmt.Errorf("private key: %w", gerrc.ErrNotFound)
	}
	if conf.ListenAddress == "" {
		conf.ListenAddress = config.DefaultListenAddress
	}

	return &Client{
		conf:              conf,              // P2P configuration
		privKey:           privKey,           // Private key for the client
		chainID:           chainID,           // Chain ID for the blockchain
		logger:            logger,            // Logger for the client
		localPubsubServer: localPubsubServer, // Local pubsub server
		blockSyncStore:    blockSyncStore,    // Datastore for block synchronization
		store:             store,             // Store for blockchain data
		blocksReceived: &BlocksReceived{
			blocksReceived: make(map[uint64]struct{}), // Map for tracking received blocks
		},
	}, nil
}
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 21109fd and 7150f44.

Files selected for processing (6)
  • block/manager.go (6 hunks)
  • block/pruning.go (2 hunks)
  • block/retriever.go (4 hunks)
  • p2p/block_sync_dag.go (1 hunks)
  • p2p/blocks_received.go (1 hunks)
  • p2p/client.go (13 hunks)
Files skipped from review as they are similar to previous changes (3)
  • block/pruning.go
  • block/retriever.go
  • p2p/block_sync_dag.go
Additional context used
GitHub Check: CodeQL
p2p/blocks_received.go

[warning] 33-37: Iteration over map
Iteration over map may be a possible source of non-determinism

block/manager.go

[notice] 177-177: Spawning a Go routine
Spawning a Go routine may be a possible source of non-determinism

p2p/client.go

[notice] 393-393: Spawning a Go routine
Spawning a Go routine may be a possible source of non-determinism


[notice] 394-394: Spawning a Go routine
Spawning a Go routine may be a possible source of non-determinism

Additional comments not posted (2)
p2p/blocks_received.go (1)

40-43: LGTM!

The method is simple and correct.

block/manager.go (1)

Line range hint 224-229:
LGTM!

The method is simple and correct.

p2p/blocks_received.go Show resolved Hide resolved
p2p/blocks_received.go Show resolved Hide resolved
p2p/blocks_received.go Show resolved Hide resolved
block/manager.go Show resolved Hide resolved
block/manager.go Outdated Show resolved Hide resolved
block/manager.go Show resolved Hide resolved
p2p/client.go Show resolved Hide resolved
p2p/client.go Show resolved Hide resolved
@srene srene requested review from danwt and omritoptix August 7, 2024 03:55
@mtsitrin mtsitrin linked an issue Aug 7, 2024 that may be closed by this pull request
@dymensionxyz dymensionxyz deleted a comment from coderabbitai bot Aug 7, 2024
@danwt danwt requested a review from mtsitrin August 8, 2024 12:19
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7150f44 and c9d3723.

Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
Files selected for processing (10)
  • block/block.go (2 hunks)
  • block/manager.go (5 hunks)
  • block/manager_test.go (2 hunks)
  • block/produce.go (2 hunks)
  • block/pruning.go (2 hunks)
  • block/state.go (1 hunks)
  • da/celestia/celestia.go (1 hunks)
  • go.mod (11 hunks)
  • store/store_test.go (2 hunks)
  • testutil/types.go (1 hunks)
Files skipped from review as they are similar to previous changes (8)
  • block/manager.go
  • block/manager_test.go
  • block/produce.go
  • block/pruning.go
  • block/state.go
  • da/celestia/celestia.go
  • store/store_test.go
  • testutil/types.go
Additional comments not posted (4)
block/block.go (1)

133-134: LGTM: Dynamic block source handling.

The update to use cachedBlock.Source for block metadata improves the accuracy of block provenance.

Ensure that cachedBlock.Source is correctly set in all relevant contexts.

go.mod (3)

27-30: LGTM: IPFS and libp2p updates.

The addition of github.com/ipfs/boxo and update of github.com/libp2p/go-libp2p-pubsub enhance P2P capabilities and align with the PR's objectives.


Line range hint 41-81:
LGTM: Gonum and logr updates.

The updates to gonum.org/v1/gonum and github.com/go-logr/logr bring potential improvements and align with dependency management best practices.


Line range hint 254-280:
LGTM: New IPFS-related dependencies.

The addition of new IPFS-related dependencies supports the enhanced P2P functionality and is consistent with the PR's goals.

@danwt danwt merged commit 4c9c2c3 into main Aug 8, 2024
5 of 6 checks passed
@danwt danwt deleted the srene/p2p-block-sync-protocol branch August 8, 2024 13:01
omritoptix added a commit that referenced this pull request Aug 13, 2024
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Michael Tsitrin <[email protected]>
Co-authored-by: Omri <[email protected]>
Co-authored-by: Daniel T <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Revise use of diode for communicating the target height Add support for p2p block syncing
4 participants