Skip to content

fix(l1): use SUPPORTED_SNAP_CAPABILITIES in snap client peer selection#6154

Closed
pablodeymo wants to merge 39 commits intomainfrom
fix/snap-protocol-capabilities
Closed

fix(l1): use SUPPORTED_SNAP_CAPABILITIES in snap client peer selection#6154
pablodeymo wants to merge 39 commits intomainfrom
fix/snap-protocol-capabilities

Conversation

@pablodeymo
Copy link
Copy Markdown
Contributor

Motivation

All three snap client get_best_peer() calls in peer_handler.rs use SUPPORTED_ETH_CAPABILITIES instead of SUPPORTED_SNAP_CAPABILITIES. This selects peers that support eth/68 or eth/69 but may not support snap/1. The snap client then sends snap protocol messages (GetAccountRange, GetStorageRanges, GetByteCodes) to these peers, which will either ignore the message (timeout, wasted 15s) or disconnect (peer score hit).

The healing modules (healing/state.rs, healing/storage.rs) already use SUPPORTED_SNAP_CAPABILITIES correctly.

Description

Replace SUPPORTED_ETH_CAPABILITIES with SUPPORTED_SNAP_CAPABILITIES in 3 snap client call sites + add import in peer_handler.rs.

Changes

Line Function Before After
13 import SUPPORTED_ETH_CAPABILITIES SUPPORTED_ETH_CAPABILITIES, SUPPORTED_SNAP_CAPABILITIES
740 request_account_range get_best_peer(&SUPPORTED_ETH_CAPABILITIES) get_best_peer(&SUPPORTED_SNAP_CAPABILITIES)
1027 request_byte_codes get_best_peer(&SUPPORTED_ETH_CAPABILITIES) get_best_peer(&SUPPORTED_SNAP_CAPABILITIES)
1553 request_storage_ranges get_best_peer(&SUPPORTED_ETH_CAPABILITIES) get_best_peer(&SUPPORTED_SNAP_CAPABILITIES)

Not changed (correctly use ETH):

  • Line 339: request_block_headers — ETH protocol operation
  • Line 207: get_peer_connections — ETH protocol operation
  • Lines 450, 536: get_random_peer — ETH protocol operations
  • sync.rs:1075: update_pivot — uses GetBlockHeaders (ETH)

Impact

In practice, most peers that support ETH also support snap (negotiated during the RLPx handshake). But some don't — this causes unnecessary timeouts and peer score degradation during snap sync.

How to Test

  1. cargo clippy -p ethrex-p2p && cargo build -p ethrex-p2p && cargo test -p ethrex-p2p
  2. Run a snap sync — observe fewer peer timeouts in logs

Related Issues

pablodeymo and others added 30 commits January 22, 2026 13:19
…tory

Reorganize state_healing.rs and storage_healing.rs into a shared
sync/healing/ module structure with clearer naming conventions:

- Create sync/healing/ directory with mod.rs, types.rs, state.rs, storage.rs
- Rename MembatchEntryValue to HealingQueueEntry
- Rename MembatchEntry to StorageHealingQueueEntry
- Rename Membatch type to StorageHealingQueue
- Rename children_not_in_storage_count to missing_children_count
- Rename membatch variables to healing_queue throughout
- Extract shared HealingQueueEntry and StateHealingQueue types to types.rs
- Update sync.rs imports to use new healing module
Reorganize snap protocol code for better maintainability:

- Split rlpx/snap.rs into rlpx/snap/ directory:
  - codec.rs: RLP encoding/decoding for snap messages
  - messages.rs: Snap protocol message types
  - mod.rs: Module re-exports

- Split snap.rs into snap/ directory:
  - constants.rs: Snap sync constants and configuration
  - server.rs: Snap protocol server implementation
  - mod.rs: Module re-exports

- Move snap server tests to dedicated tests/ directory
- Update imports in p2p.rs, peer_handler.rs, and code_collector.rs
Document the phased approach for reorganizing snap sync code:
- Phase 1: rlpx/snap module split
- Phase 2: snap module split with server extraction
- Phase 3: healing module unification
Split the large sync.rs (1631 lines) into focused modules:

- sync/full.rs (~260 lines): Full sync implementation
  - sync_cycle_full(), add_blocks_in_batch(), add_blocks()

- sync/snap_sync.rs (~1100 lines): Snap sync implementation
  - sync_cycle_snap(), snap_sync(), SnapBlockSyncState
  - store_block_bodies(), update_pivot(), block_is_stale()
  - validate_state_root(), validate_storage_root(), validate_bytecodes()
  - insert_accounts(), insert_storages() (both rocksdb and non-rocksdb)

- sync.rs (~285 lines): Orchestration layer
  - Syncer struct with start_sync() and sync_cycle()
  - SyncMode, SyncError, AccountStorageRoots types
  - Re-exports for public API
…p/client.rs

Move all snap protocol client-side request methods from peer_handler.rs
to a dedicated snap/client.rs module:
- request_account_range and request_account_range_worker
- request_bytecodes
- request_storage_ranges and request_storage_ranges_worker
- request_state_trienodes
- request_storage_trienodes

Also moves related types: DumpError, RequestMetadata, SnapClientError,
RequestStateTrieNodesError, RequestStorageTrieNodes.

This reduces peer_handler.rs from 2,060 to 670 lines (~68% reduction),
leaving it focused on ETH protocol methods (block headers/bodies).

Added SnapClientError variant to SyncError for proper error handling.
Updated plan_snap_sync.md to mark Phase 4 as complete.
…napError type

Implement Phase 5 of snap sync refactoring plan - Error Handling.

- Create snap/error.rs with unified SnapError enum covering all snap protocol errors
- Update server functions (process_account_range_request, process_storage_ranges_request,
  process_byte_codes_request, process_trie_nodes_request) to return Result<T, SnapError>
- Remove SnapClientError and RequestStateTrieNodesError, consolidate into SnapError
- Keep RequestStorageTrieNodesError struct for request ID tracking in storage healing
- Add From<SnapError> for PeerConnectionError to support error propagation in message handlers
- Update sync module to use SyncError::Snap variant
- Update healing modules (state.rs, storage.rs) to use new error types
- Move DumpError struct to error.rs module
- Update test return types to use SnapError
- Mark Phase 5 as completed in plan document

All phases of the snap sync refactoring are now complete.
Change missing_children_count from u64 to usize in HealingQueueEntry
and node_missing_children function to match StorageHealingQueueEntry
and be consistent with memory structure counting conventions.
Resolve conflicts from #5977 and #6018 merge to main:
- Keep modular sync structure (sync.rs delegates to full.rs and snap_sync.rs)
- Keep snap client code in snap/client.rs (removed from peer_handler.rs)
- Add InsertingAccountRanges metric from #6018 to snap_sync.rs
- Remove unused info import from peer_handler.rs
in the multisync monitoring script (docker_monitor.py).

The sync completion logs already contain per-phase completion markers
(e.g. "✓ BLOCK HEADERS complete: 25,693,009 headers in 0:29:00")
but this data was not surfaced in the Slack messages or run summaries.

This adds a parse_phase_timings() function that reads saved container
logs and extracts timing, count, and duration for all 8 snap sync
phases: Block Headers, Account Ranges, Account Insertion, Storage
Ranges, Storage Insertion, State Healing, Storage Healing, and
Bytecodes. The breakdown is appended to both the Slack notification
(as a code block per network instance) and the text-based run log
(run_history.log and per-run summary.txt). When a phase did not
complete (e.g. on a failed run), it is simply omitted from the
breakdown.
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
proof conversion helpers (encodable_to_proof, proof_to_encodable) from
server.rs to mod.rs since they are shared utilities used by both client
and server.
peer selection, extract magic numbers into named constants
(ACCOUNT_RANGE_CHUNK_COUNT, STORAGE_BATCH_SIZE, HASH_MAX), remove unused
contents field from DumpError and use derive Debug, rename
missing_children to pending_children in healing code, and wrap
process_byte_codes_request in spawn_blocking for consistency with other
server handlers.
@github-actions github-actions bot added the L1 Ethereum client label Feb 6, 2026
@github-actions
Copy link
Copy Markdown

github-actions bot commented Feb 6, 2026

🤖 Kimi Code Review

Review Summary

This PR changes the peer selection criteria for SNAP protocol requests from SUPPORTED_ETH_CAPABILITIES to SUPPORTED_SNAP_CAPABILITIES. This is a critical bug that will break SNAP protocol functionality.

Issues Found

1. Critical Bug: Incorrect Capability Matching (Lines 740, 1027, 1553)

The changes replace SUPPORTED_ETH_CAPABILITIES with SUPPORTED_SNAP_CAPABILITIES when selecting peers for SNAP protocol requests. This is fundamentally incorrect because:

  • get_best_peer() expects a list of required capabilities that the peer must support
  • SUPPORTED_SNAP_CAPABILITIES contains SNAP protocol capabilities (like snap/1)
  • But SNAP protocol requests require both ETH and SNAP capabilities to work properly

Current behavior: The code will only find peers that support SNAP capabilities, but these peers might not support ETH capabilities, making the SNAP protocol requests impossible to execute.

Fix: Use both ETH and SNAP capabilities:

// Create a combined capability set
let mut required_caps = SUPPORTED_ETH_CAPABILITIES.clone();
required_caps.extend(SUPPORTED_SNAP_CAPABILITIES);
let Some((peer_id, connection)) = self
    .peer_table
    .get_best_peer(&required_caps)
    .await
    // ... rest of the code

2. Missing Capability Validation (All changed lines)

There's no validation that the selected peer actually supports the required capabilities for the specific request type. Consider adding debug logging to verify peer capabilities before making requests.

Additional Notes

  • The PR appears to be attempting to fix SNAP protocol peer selection, but the implementation is incomplete
  • Consider adding a helper method to get peers with both ETH and SNAP capabilities to avoid code duplication across these three locations

Automated review by Kimi (Moonshot AI) · custom prompt

@pablodeymo pablodeymo mentioned this pull request Feb 6, 2026
1 task
@github-actions
Copy link
Copy Markdown

github-actions bot commented Feb 6, 2026

🤖 Codex Code Review

Looks good overall — this change makes the SNAP-specific request paths select SNAP-capable peers, which is the correct protocol selection and should prevent invalid requests to ETH-only peers.

Findings

  • Minor: If SUPPORTED_SNAP_CAPABILITIES can be empty or disabled via config, these loops will now only ever see None and keep logging “missing peers.” If that’s a supported configuration, consider guarding the SNAP sync entrypoints with an explicit capability check or returning a clear error early. crates/networking/p2p/peer_handler.rs:738, crates/networking/p2p/peer_handler.rs:1025, crates/networking/p2p/peer_handler.rs:1551

If you want, I can verify call sites for these SNAP sync routines to confirm they’re only invoked when SNAP is enabled.


Automated review by OpenAI Codex · custom prompt

@github-actions
Copy link
Copy Markdown

github-actions bot commented Feb 6, 2026

🤖 Claude Code Review

Excellent! Now I have a comprehensive understanding. Let me create the review.

PR Review: Fix snap client peer selection

Summary

This PR correctly fixes a bug where snap protocol operations were selecting peers based on SUPPORTED_ETH_CAPABILITIES instead of SUPPORTED_SNAP_CAPABILITIES. This is a straightforward and important correctness fix.

✅ Correctness & Logic

LGTM - The fix is correct and well-targeted:

  • Lines 740, 1027, 1553: All three changes correctly update peer selection for snap protocol operations:

    • request_account_range → sends GetAccountRange (snap protocol) at line 848
    • request_byte_codes → sends GetByteCodes (snap protocol) at line 1074
    • request_storage_ranges → sends GetStorageRanges (snap protocol) at line 1669
  • Unchanged ETH operations verified: The PR author correctly identified that other get_best_peer(&SUPPORTED_ETH_CAPABILITIES) calls should remain unchanged because they use ETH protocol messages:

    • Line 339: request_block_headers → sends GetBlockHeaders (ETH protocol)
    • Line 207: get_peer_connections → queries peer head numbers (ETH protocol)
    • Lines 450, 536: get_random_peer → for block headers/bodies (ETH protocol)
    • sync.rs:1075: update_pivot → uses GetBlockHeaders (ETH protocol)

🔒 Security & Correctness Impact

Low risk, high value fix:

  • This is a pure correctness fix with no security implications
  • Reduces unnecessary peer timeouts and score degradation
  • Aligns with how healing modules already correctly use SUPPORTED_SNAP_CAPABILITIES (state_healing.rs:229, storage_healing.rs:328)

🎯 Ethereum/Snap Sync Specific

Protocol compliance improvement:

  • The snap protocol (devp2p snap/1) is separate from eth protocol (eth/68, eth/69)
  • Peers may support ETH but not SNAP - sending snap messages to non-snap peers causes:
    • 15-second timeouts (wasted PEER_REPLY_TIMEOUT)
    • Peer disconnections and score penalties
  • This fix ensures snap messages only go to snap-capable peers

📝 Code Quality

Clean implementation:

  • Minimal diff (4 lines changed)
  • Consistent with existing healing modules
  • Clear commit message and PR description
  • No unnecessary changes or refactoring

Minor Observation

The PR description mentions the capability definitions are:

SUPPORTED_ETH_CAPABILITIES: [eth/68, eth/69]
SUPPORTED_SNAP_CAPABILITIES: [snap/1]

These are defined in crates/networking/p2p/rlpx/p2p.rs:17-18 and correctly imported.

Verdict

✅ Approve - This is a straightforward correctness fix that:

  • Properly aligns peer selection with protocol message types
  • Reduces unnecessary network overhead and peer management issues
  • Has no negative side effects
  • Is well-documented and tested by the author

The code is ready to merge.


Automated review by Claude (Anthropic) · custom prompt

@jrchatruc jrchatruc marked this pull request as ready for review February 6, 2026 21:00
@jrchatruc jrchatruc requested a review from a team as a code owner February 6, 2026 21:00
@ethrex-project-sync ethrex-project-sync bot moved this to In Review in ethrex_l1 Feb 6, 2026
@github-actions
Copy link
Copy Markdown

github-actions bot commented Feb 6, 2026

🤖 Kimi Code Review

Security & Correctness Issues

Critical Issue: Capability mismatch in snap protocol requests

The changes replace SUPPORTED_ETH_CAPABILITIES with SUPPORTED_SNAP_CAPABILITIES for snap protocol requests, but this appears to be incorrect.

Looking at the context:

  • Lines 737, 1024, and 1550 are all snap protocol operations (GetAccountRange, bytecodes, GetStorageRanges)
  • However, get_best_peer() likely expects a list of capabilities that the peer must support
  • SUPPORTED_SNAP_CAPABILITIES appears to be snap-specific, but snap protocol requires both ETH and SNAP capabilities

The fix should be:

// Create a combined capability set for snap requests
let mut required_caps = SUPPORTED_ETH_CAPABILITIES.to_vec();
required_caps.extend(SUPPORTED_SNAP_CAPABILITIES);
self.peer_table.get_best_peer(&required_caps)

Additional Concerns

1. Missing capability validation

  • The snap protocol messages should verify that the peer actually supports snap capabilities before sending requests
  • Consider adding a check like if !connection.capabilities.contains(&Capability::Snap) { ... }

2. Error handling inconsistency

  • The .unwrap_or(None) pattern on lines 742, 1029, and 1555 silently swallows errors
  • Consider whether these should be logged more verbosely or propagated

3. Code duplication

  • The peer selection logic is duplicated across three functions
  • Consider extracting a helper method like get_snap_peer() to reduce duplication and ensure consistent capability requirements

Automated review by Kimi (Moonshot AI) · custom prompt

@github-actions
Copy link
Copy Markdown

github-actions bot commented Feb 6, 2026

🤖 Codex Code Review

No correctness or security issues found in this diff.

Notes

  • crates/networking/p2p/peer_handler.rs:738 / :1025 / :1551 now select peers by SNAP capability for SNAP requests, which matches the protocol being used and avoids sending SNAP messages to ETH-only peers. This looks correct and improves robustness.

Open question

  • If SNAP sync is optional and you want a fallback to ETH-only peers, there’s no fallback path here; the loop will keep waiting. If that’s intended for SNAP mode, all good. Otherwise, consider an explicit fallback or clearer log message.

Automated review by OpenAI Codex · custom prompt

@github-actions
Copy link
Copy Markdown

github-actions bot commented Feb 6, 2026

🤖 Claude Code Review

Perfect! GetBlockHeaders is indeed an ETH protocol message. Let me now compile my review:

PR Review: Use SUPPORTED_SNAP_CAPABILITIES for snap client peer selection

Summary

This PR fixes a critical bug where snap sync operations were selecting peers based on ETH protocol capabilities instead of SNAP protocol capabilities. This is a well-identified and correctly implemented fix.


✅ Positive Findings

  1. Correct Problem Identification: The bug is accurately described - using SUPPORTED_ETH_CAPABILITIES for snap protocol operations (GetAccountRange, GetByteCodes, GetStorageRanges) could select peers that don't support snap/1, leading to:

    • 15-second timeouts per request
    • Peer score degradation
    • Unnecessary connection failures
  2. Precise Changes: All three call sites are correctly updated:

    • request_account_range (peer_handler.rs:740)
    • request_byte_codes (peer_handler.rs:1027)
    • request_storage_ranges (peer_handler.rs:1553)
  3. Verified Protocol Correctness: I confirmed:

    • GetAccountRange, GetByteCodes, GetStorageRanges are indeed SNAP protocol messages (snap.rs)
    • ETH operations (GetBlockHeaders at line 339) correctly remain unchanged
    • Healing modules (state_healing.rs:229, storage_healing.rs:328) already use SUPPORTED_SNAP_CAPABILITIES correctly
  4. Clean Implementation:

    • Import added properly (line 13)
    • No functional changes beyond the fix
    • No side effects

🔍 Code Quality

Strengths:

  • Minimal, targeted fix
  • Well-documented PR with clear impact analysis
  • Consistent with existing patterns in healing modules

No issues found with:

  • Error handling (unchanged, already present)
  • Timeout handling (15s timeout already configured)
  • Peer selection logic (uses existing get_best_peer infrastructure)

🎯 Ethereum-Specific Considerations

  • Protocol Compliance: ✅ Correct - SNAP/1 is the proper capability for snap sync operations per Ethereum devp2p specs
  • Peer Discovery: ✅ Proper separation of ETH (68/69) and SNAP (1) capabilities
  • State Sync: ✅ Fix ensures snap sync only communicates with snap-capable peers

📊 Impact Assessment

Before Fix:

  • Peers selected from ETH-capable pool (may not support snap)
  • Wasted 15s timeouts on non-snap peers
  • Peer score penalties for protocol mismatches

After Fix:

  • Peers selected from SNAP-capable pool only
  • Reduced sync time and more efficient peer utilization
  • Better peer reputation management

✅ Final Verdict

LGTM - Approved

This is a textbook bug fix:

  • Problem correctly identified
  • Solution is minimal and precise
  • All related code paths verified
  • No security, safety, or correctness concerns
  • Improves sync efficiency and peer management

No changes requested.


Automated review by Claude (Anthropic) · custom prompt

@greptile-apps
Copy link
Copy Markdown

greptile-apps bot commented Feb 6, 2026

Greptile Overview

Greptile Summary

  • Fixes snap-sync peer selection by switching snap request paths to use SUPPORTED_SNAP_CAPABILITIES instead of ETH-only capabilities.
  • Affects PeerHandler snap methods for account ranges, bytecodes, and storage ranges; ETH header/body paths remain unchanged.
  • Reduces snap request timeouts and peer score penalties by ensuring selected peers negotiated snap/1 before sending snap protocol messages.

Confidence Score: 5/5

  • This PR is safe to merge with minimal risk.
  • Change is narrowly scoped to swapping the capability filter used by get_best_peer() in three snap-specific request loops; the referenced constant exists and matches snap/1, and the rest of the peer selection logic and request/response handling is unchanged.
  • No files require special attention

Important Files Changed

Filename Overview
crates/networking/p2p/peer_handler.rs Swaps snap client peer selection from SUPPORTED_ETH_CAPABILITIES to SUPPORTED_SNAP_CAPABILITIES in request_account_range/request_bytecodes/request_storage_ranges; adds corresponding import. No functional regressions found in the changed lines.

Sequence Diagram

sequenceDiagram
    participant Sync as Snap sync loop
    participant PH as PeerHandler
    participant PT as PeerTable
    participant Peer as Selected peer

    Sync->>PH: "Snap request_* call"
    PH->>PT: "get_best_peer(SUPPORTED_SNAP_CAPABILITIES)"
    alt No suitable peer
        PT-->>PH: "None"
        PH-->>Sync: "Sleep + retry"
    else Suitable peer found
        PT-->>PH: "(peer_id, PeerConnection)"
        PH->>Peer: "GetAccountRange / GetByteCodes / GetStorageRanges"
        Peer-->>PH: "AccountRange / ByteCodes / StorageRanges"
        PH-->>Sync: "Record success/failure, process result"
    end
Loading

…ation' into fix/snap-protocol-capabilities

# Conflicts:
#	crates/networking/p2p/peer_handler.rs
Copilot AI review requested due to automatic review settings February 6, 2026 21:28
@github-actions
Copy link
Copy Markdown

github-actions bot commented Feb 6, 2026

Lines of code report

Total lines added: 4045
Total lines removed: 2330
Total lines changed: 6375

Detailed view
+--------------------------------------------------------+-------+-------+
| File                                                   | Lines | Diff  |
+--------------------------------------------------------+-------+-------+
| ethrex/crates/networking/p2p/peer_handler.rs           | 546   | -1187 |
+--------------------------------------------------------+-------+-------+
| ethrex/crates/networking/p2p/rlpx/connection/server.rs | 1053  | +2    |
+--------------------------------------------------------+-------+-------+
| ethrex/crates/networking/p2p/rlpx/error.rs             | 131   | +11   |
+--------------------------------------------------------+-------+-------+
| ethrex/crates/networking/p2p/rlpx/snap/codec.rs        | 284   | +284  |
+--------------------------------------------------------+-------+-------+
| ethrex/crates/networking/p2p/rlpx/snap/messages.rs     | 64    | +64   |
+--------------------------------------------------------+-------+-------+
| ethrex/crates/networking/p2p/rlpx/snap/mod.rs          | 7     | +7    |
+--------------------------------------------------------+-------+-------+
| ethrex/crates/networking/p2p/snap/client.rs            | 1182  | +1182 |
+--------------------------------------------------------+-------+-------+
| ethrex/crates/networking/p2p/snap/constants.rs         | 23    | +23   |
+--------------------------------------------------------+-------+-------+
| ethrex/crates/networking/p2p/snap/error.rs             | 94    | +94   |
+--------------------------------------------------------+-------+-------+
| ethrex/crates/networking/p2p/snap/mod.rs               | 22    | +22   |
+--------------------------------------------------------+-------+-------+
| ethrex/crates/networking/p2p/snap/server.rs            | 150   | +150  |
+--------------------------------------------------------+-------+-------+
| ethrex/crates/networking/p2p/sync.rs                   | 241   | -1140 |
+--------------------------------------------------------+-------+-------+
| ethrex/crates/networking/p2p/sync/full.rs              | 243   | +243  |
+--------------------------------------------------------+-------+-------+
| ethrex/crates/networking/p2p/sync/healing/mod.rs       | 7     | +7    |
+--------------------------------------------------------+-------+-------+
| ethrex/crates/networking/p2p/sync/healing/state.rs     | 387   | +387  |
+--------------------------------------------------------+-------+-------+
| ethrex/crates/networking/p2p/sync/healing/storage.rs   | 615   | +615  |
+--------------------------------------------------------+-------+-------+
| ethrex/crates/networking/p2p/sync/healing/types.rs     | 9     | +9    |
+--------------------------------------------------------+-------+-------+
| ethrex/crates/networking/p2p/sync/snap_sync.rs         | 945   | +945  |
+--------------------------------------------------------+-------+-------+
| ethrex/crates/networking/p2p/utils.rs                  | 191   | -3    |
+--------------------------------------------------------+-------+-------+

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes snap sync peer selection to require snap/1 capability (avoiding timeouts/peer-score hits when sending snap messages to non-snap peers), and includes a broader refactor that modularizes snap/sync code and adds snap server test coverage.

Changes:

  • Use SUPPORTED_SNAP_CAPABILITIES for snap client peer selection (account ranges, bytecodes, storage ranges).
  • Split snap/sync implementation into dedicated modules (snap/, sync/full.rs, sync/snap_sync.rs, sync/healing/*) and centralize snap constants/errors.
  • Add Hive-derived snap server tests to the test crate.

Reviewed changes

Copilot reviewed 26 out of 27 changed files in this pull request and generated 9 comments.

Show a summary per file
File Description
crates/networking/p2p/p2p.rs Makes snap module public (module visibility change as part of refactor).
crates/networking/p2p/peer_handler.rs Removes snap client methods from PeerHandler, re-exports snap constants/types/errors for compatibility.
crates/networking/p2p/utils.rs Adjusts snapshot dump error payload after DumpError change.
crates/networking/p2p/snap/mod.rs Introduces snap module facade + re-exports (client/server/errors/constants).
crates/networking/p2p/snap/client.rs Snap client request implementations now select peers via SUPPORTED_SNAP_CAPABILITIES.
crates/networking/p2p/snap/server.rs Server-side snap request processing moved here (now consistently async via spawn_blocking).
crates/networking/p2p/snap/constants.rs Centralizes snap/sync constants (limits, batch sizes, timeouts, etc.).
crates/networking/p2p/snap/error.rs Introduces unified SnapError + DumpError definitions.
crates/networking/p2p/snap.rs Removes old monolithic snap module implementation (deleted).
crates/networking/p2p/rlpx/snap/mod.rs New RLPx snap module layout (re-exports messages + codec codes).
crates/networking/p2p/rlpx/snap/messages.rs Defines snap protocol message structs.
crates/networking/p2p/rlpx/snap/codec.rs Implements RLPxMessage encoding/decoding + message code constants.
crates/networking/p2p/rlpx/error.rs Adds From<SnapError> mapping into PeerConnectionError.
crates/networking/p2p/rlpx/connection/server.rs Updates bytecode request handling to await the now-async server handler.
crates/networking/p2p/sync.rs Sync module now delegates to full, snap_sync, and healing submodules.
crates/networking/p2p/sync/full.rs New full-sync implementation module.
crates/networking/p2p/sync/snap_sync.rs New snap-sync implementation module (pivot selection, validation helpers, etc.).
crates/networking/p2p/sync/code_collector.rs Moves buffer sizing constant to snap::constants.
crates/networking/p2p/sync/healing/mod.rs Introduces healing module + re-exports.
crates/networking/p2p/sync/healing/types.rs Adds shared healing queue entry types.
crates/networking/p2p/sync/healing/state.rs Refactors state healing to use shared queue types + snap request helpers/constants.
crates/networking/p2p/sync/healing/storage.rs Refactors storage healing similarly; switches to snap request helpers/constants/types.
test/tests/p2p/mod.rs Registers new snap server tests module.
test/tests/p2p/snap_server_tests.rs Adds Hive-derived AccountRange server tests and test state fixture.
test/Cargo.toml Adds lazy_static dependency for tests.
Cargo.lock Adds lazy_static to lockfile.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +627 to +631
// We multiply the estimation by 0.9 in order to account for missing slots (~9% in tesnets)
let new_pivot_block_number = block_number
+ ((current_unix_time().saturating_sub(block_timestamp) / SECONDS_PER_BLOCK) as f64
* MISSING_SLOTS_PERCENTAGE) as u64;
debug!(
Copy link

Copilot AI Feb 6, 2026

Choose a reason for hiding this comment

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

The comment says the pivot estimation is multiplied by 0.9, but the code multiplies by MISSING_SLOTS_PERCENTAGE (currently 0.8). Please reconcile the comment with the actual constant/value used so the pivot update behavior is clear and not accidentally mis-tuned.

Copilot uses AI. Check for mistakes.
Comment on lines +701 to +707
if validated.is_ok() {
info!("Succesfully validated tree, {state_root} found");
} else {
error!("We have failed the validation of the state tree");
std::process::exit(1);
}
validated.is_ok()
Copy link

Copilot AI Feb 6, 2026

Choose a reason for hiding this comment

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

These validation helpers call std::process::exit(1) on failure. Even if currently invoked under debug_assert!, exiting the process from a library/module function makes failures hard to handle/test and can bypass upstream cleanup. Prefer returning an error/boolean and let the caller decide whether to panic/abort.

Copilot uses AI. Check for mistakes.
&& first_block_hash == current_head
&& current_head != sync_head
{
// There is no path to the sync head this goes back until it find a common ancerstor
Copy link

Copilot AI Feb 6, 2026

Choose a reason for hiding this comment

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

Typo in comment: “ancerstor” → “ancestor”.

Suggested change
// There is no path to the sync head this goes back until it find a common ancerstor
// There is no path to the sync head this goes back until it find a common ancestor

Copilot uses AI. Check for mistakes.
Comment on lines 74 to 80
pub mod network;
pub mod peer_handler;
pub mod rlpx;
pub(crate) mod snap;
pub mod snap;
pub mod sync;
pub mod sync_manager;
pub mod tx_broadcaster;
Copy link

Copilot AI Feb 6, 2026

Choose a reason for hiding this comment

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

The PR description/title suggest a small peer-capability selection fix, but this change set introduces a much broader refactor (new public snap module, new sync submodules, moved tests, error type changes). Please update the PR description/scope (or split into separate PRs) so reviewers can reason about risk and intent accurately.

Copilot uses AI. Check for mistakes.
Comment on lines +110 to +113
/// Assumed percentage of slots that are missing blocks.
///
/// This is used to adjust timestamp-based pivot updates and to find "safe"
/// blocks in the chain that are unlikely to be re-orged.
Copy link

Copilot AI Feb 6, 2026

Choose a reason for hiding this comment

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

MISSING_SLOTS_PERCENTAGE is documented as “percentage of slots that are missing blocks”, but it’s used as a multiplier when estimating the new pivot distance. With the current value 0.8, the math and naming/docs appear inconsistent (and snap_sync.rs comments mention 0.9). Please align the constant name/value and the pivot update logic/comment so it’s unambiguous what factor is being applied.

Suggested change
/// Assumed percentage of slots that are missing blocks.
///
/// This is used to adjust timestamp-based pivot updates and to find "safe"
/// blocks in the chain that are unlikely to be re-orged.
/// Multiplier applied when estimating the pivot distance to account for empty slots.
///
/// This factor scales the timestamp-based pivot distance so we don't overestimate
/// the number of blocks that should exist. A value of `0.8` means we assume that
/// up to ~20% of slots may be missing blocks when computing a "safe" pivot that is
/// unlikely to be re-orged.

Copilot uses AI. Check for mistakes.

// Reward peer
peers.peer_table.record_success(&peer_id).await?;
info!("Succesfully updated pivot");
Copy link

Copilot AI Feb 6, 2026

Choose a reason for hiding this comment

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

Typo in log message: “Succesfully” → “Successfully”.

Suggested change
info!("Succesfully updated pivot");
info!("Successfully updated pivot");

Copilot uses AI. Check for mistakes.
.expect("We should be able to create threads");

if validated.is_ok() {
info!("Succesfully validated tree, {state_root} found");
Copy link

Copilot AI Feb 6, 2026

Choose a reason for hiding this comment

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

Typo in log message: “Succesfully” → “Successfully”.

Suggested change
info!("Succesfully validated tree, {state_root} found");
info!("Successfully validated tree, {state_root} found");

Copilot uses AI. Check for mistakes.
Comment on lines +732 to +734
if is_valid.is_err() {
std::process::exit(1);
}
Copy link

Copilot AI Feb 6, 2026

Choose a reason for hiding this comment

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

validate_storage_root calls std::process::exit(1) on failure. Prefer returning an error/boolean (and letting the caller decide) rather than terminating the process from within a helper.

Copilot uses AI. Check for mistakes.
Comment on lines +757 to +759
if !is_valid {
std::process::exit(1);
}
Copy link

Copilot AI Feb 6, 2026

Choose a reason for hiding this comment

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

validate_bytecodes calls std::process::exit(1) when missing code is detected. It would be more testable and easier to integrate if this returned an error/boolean and allowed the caller to decide how to handle the failure.

Copilot uses AI. Check for mistakes.
@pablodeymo
Copy link
Copy Markdown
Contributor Author

Fixed in #5975

@pablodeymo pablodeymo closed this Feb 6, 2026
@github-project-automation github-project-automation bot moved this from In Review to Done in ethrex_l1 Feb 6, 2026
pablodeymo added a commit that referenced this pull request Feb 6, 2026
Already fixed on the refactor/snapsync-healing-unification branch, PR #6154 for main.
ElFantasma pushed a commit that referenced this pull request Mar 13, 2026
Already fixed on the refactor/snapsync-healing-unification branch, PR #6154 for main.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

L1 Ethereum client snapsync

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

5 participants