> ## Documentation Index
> Fetch the complete documentation index at: https://docs.stablenet.network/llms.txt
> Use this file to discover all available pages before exploring further.

# Protocol Handlers

## Purpose and Scope

This document describes the Ethereum protocol handlers in go-stablenet that manage message routing, peer protocol lifecycles, and data propagation.\
Protocol handlers act as a bridge between the P2P networking layer and higher-level blockchain components such as the downloader, block fetcher, and transaction pool.

For basic P2P server and peer connection management, see [P2P Server and Peer Management](/en/networking/7.1-p2p-server-and-peer-management).\
For details on chain synchronization mechanisms, see [Chain Synchronization](/en/networking/7.3-chain-synchronization).

## Handler Architecture

The protocol handler system is composed of multiple layers.

### Core Handler Structure

The main `handler` struct coordinates all protocol-related activities.

The `handler` struct includes:

* **networkID**: Network identifier (mainnet, testnet, etc.)
* **forkFilter**: Fork ID validation filter
* **downloader**: Full chain synchronization component
* **blockFetcher**: Short-range block announcement handler
* **txFetcher**: Transaction propagation handler
* **peers**: Active peer set
* **chainSync**: Chain synchronization coordinator

## Protocol Registration and Lifecycle

### Handler Initialization

During handler initialization, the following steps are performed:

* Creation of the fork ID filter
* Initialization of the downloader, fetchers, and peerSet
* Registration of supported protocols (`eth`, `snap`)
* Setup of broadcast loops and event subscriptions

### Peer Protocol Lifecycle

When a peer connects, the handler operates in the following order:

1. Completion of the P2P handshake
2. Execution of the `eth` protocol handshake
3. Optional `snap` protocol handshake if required
4. Atomic registration in the peerSet
5. Start of the message handling loop

This flow is managed by the `runEthPeer` function.

### Snap Protocol Extension

The `snap` protocol operates as an extension layered on top of the `eth` protocol.

* Successful `eth` handshake is a prerequisite
* Handles messages dedicated to state snapshots and trie data requests
* Directly integrated with the downloader’s SnapSync path

## Message Routing

### Protocol Message Dispatch

The protocol handler forwards incoming messages to appropriate subsystems based on their type:

* Synchronization-related messages → downloader
* Block announcements → blockFetcher
* Transactions → txFetcher / txpool
* State snapshot requests → SnapSyncer

The handler maintains two primary broadcast loops:

1. **Transaction Broadcast Loop**\
   Listens for new transaction events and propagates them to peers.

2. **Mining Block Broadcast Loop**\
   Listens for new block events and propagates blocks across the network.

### Peer Message Handlers

Each protocol processes messages in a dedicated Run function.

| Protocol | Handler Function              | Message Types                                                |
| -------- | ----------------------------- | ------------------------------------------------------------ |
| `eth/68` | `eth.MakeProtocols()[0].Run`  | Headers, bodies, receipts, transactions, block announcements |
| `snap/1` | `snap.MakeProtocols()[0].Run` | Account ranges, storage ranges, code, trie nodes             |

## Block and Transaction Broadcasting

### Block Broadcasting Strategy

Block propagation is performed in two phases:

1. Send the full block to √n peers
2. Send block hash announcements to all remaining peers

This approach balances bandwidth usage and propagation latency.

### Transaction Broadcasting Strategy

Transaction propagation varies by transaction size:

* **Large transactions** (> 4096 bytes): Hash announcements only
* **Normal transactions**: Direct send to √n peers, announcements to the rest

## Protocol Versioning and Capabilities

### Supported Protocols

| Protocol | Version | Purpose                                               |
| -------- | ------- | ----------------------------------------------------- |
| `eth`    | 68      | Block and transaction synchronization and propagation |
| `snap`   | 1       | State snapshot and trie data synchronization          |

During the handshake, peers exchange capabilities and negotiate a common supported version.

### Fork ID Validation

Fork ID validation based on EIP-2124 ensures chain compatibility using:

* Genesis hash
* Fork block information
* Next scheduled fork

Peers with incompatible fork IDs are immediately disconnected.

## Peer Set Management

### Role of peerSet

`peerSet` centrally manages active peers:

* Atomically registers eth / snap protocols
* Tracks per-peer block and transaction reception status
* Used for synchronization and broadcast target selection

## Handler Lifecycle

### Start and Stop

* **`Start()`**\
  Starts broadcast loops and event subscriptions.
* **`Stop()`**\
  Terminates all goroutines and cleans up peers.

## Integration with Subsystems

### Downloader Integration

The handler provides the downloader with:

* Peer registration and removal notifications
* Synchronization start triggers
* Control over snap / full synchronization transitions

### Fetcher Integration

* **blockFetcher**: Handles fast block announcements
* **txFetcher**: Prevents transaction duplication and optimizes propagation

## Error Handling and Peer Removal

### Peer Removal Flow

Peers are removed under the following conditions:

* Protocol violations
* Fork ID mismatch
* Repeated invalid responses
* Timeouts or resource abuse

Upon removal, cleanup is performed consistently across the peerSet, downloader, and fetchers.

## Summary

The go-stablenet protocol handlers are responsible for:

1. Negotiation and management of multiple protocols (`eth`, `snap`)
2. Message routing and integration with subsystems
3. Efficient block and transaction broadcasting
4. Peer lifecycle management and error handling
5. Bridging P2P networking with the blockchain core

Protocol handlers are a central component that orchestrates all protocol-level network operations in the Ethereum backend.
