> ## 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.

# Networking

## Purpose and Scope

This document provides an overview of StableNet’s peer-to-peer networking subsystem, which handles node discovery, peer connection management, blockchain synchronization, and message propagation.\
The networking layer is built on Ethereum’s DevP2P protocol stack and implements the `eth` protocol for block and transaction exchange.

For detailed information on specific networking components, refer to the following documents:

* Connection lifecycle and peer tracking: [P2P Server and Peer Management](/en/networking/7.1-p2p-server-and-peer-management)
* Node discovery mechanisms and peer compatibility: [Discovery and Fork ID](/en/networking/7.2-discovery-mechanisms)
* Blockchain download and synchronization strategies: [Chain Synchronization](/en/networking/7.3-chain-synchronization)
* Message routing and protocol version management: [Protocol Handlers](/en/networking/7.4-protocol-handlers)

For transaction propagation details, see [Transaction Lifecycle](/en/transaction-processing/6.1-transaction-lifecycle).\
For block production and broadcasting, see [Block Production and Mining](/en/consensus-and-block-production/4.2-block-production-and-mining).

## Networking Architecture Overview

StableNet’s networking layer consists of four major subsystems that work together to maintain network connectivity and synchronize blockchain state.

## P2P Server

`p2p.Server` is the foundation of the networking stack and manages the lifecycle of all peer connections.\
It coordinates peer discovery, connection establishment, protocol negotiation, and graceful disconnection.

The server maintains different categories of peers:

* Dynamic peers: Discovered through DHT mechanisms and subject to connection limits
* Static peers: Preconfigured nodes that are always reconnected upon disconnection
* Trusted peers: Nodes that bypass `MaxPeers` limits and receive priority treatment

**Key components:**

| Component          | Type                 | Purpose                            |
| ------------------ | -------------------- | ---------------------------------- |
| `Server.localnode` | `*enode.LocalNode`   | Local node ENR record and identity |
| `Server.ntab`      | `*discover.UDPv4`    | Discovery v4 table                 |
| `Server.DiscV5`    | `*discover.UDPv5`    | Discovery v5 table                 |
| `Server.dialsched` | `*dialScheduler`     | Outbound connection scheduling     |
| `Server.peers`     | `map[enode.ID]*Peer` | Currently connected peer set       |

The server runs a main event loop that handles:

* Peer connection setup stages
* Peer disconnection processing
* Dynamic updates to the trusted peer list
* Thread-safe access to the peer set

## Peer Discovery

StableNet supports multiple peer discovery mechanisms that can operate simultaneously:

| Mechanism     | Protocol           | Use Case                               |
| ------------- | ------------------ | -------------------------------------- |
| Discovery v4  | UDP / Kademlia DHT | Default discovery for public networks  |
| Discovery v5  | UDP / Topic-based  | Advanced discovery and topic filtering |
| DNS Discovery | DNS TXT            | Bootstrapping and known nodes          |
| Static Nodes  | Configuration file | Persistent peer relationships          |
| Trusted Nodes | Configuration file | Priority peers                         |

Discovery services forward candidate peers to the `dialScheduler` and apply the following policies:

* Maintain inbound/outbound connection ratios
* Prevent duplicate dials
* Apply exponential backoff for failed connections
* Relax limits for trusted peers

### Fork ID Validation

Before establishing full peer relationships, nodes exchange fork IDs (EIP-2124) to verify chain compatibility.\
The fork ID is computed based on the genesis hash and upcoming fork block numbers:

```text theme={null}
ForkID = CRC32(genesisHash + fork1Block + fork2Block + ...)
```

Peers with incompatible fork IDs are rejected during the handshake phase, preventing network splits.

## Chain Synchronization

The chain synchronization subsystem downloads and verifies blockchain data from peers.\
This system operates through the collaboration of multiple components.

**Diagram: Synchronization component interaction**

### Synchronization Modes

StableNet supports the following synchronization modes depending on node state:

| Mode      | Description                        | Use Case                     |
| --------- | ---------------------------------- | ---------------------------- |
| FullSync  | Download and execute all blocks    | Archive nodes                |
| SnapSync  | State snapshot + recent blocks     | Fast initial synchronization |
| LightSync | Header-only and request-based data | Lightweight clients          |

### Downloader

The downloader performs the following tasks:

* Common ancestor block discovery
* Skeleton chain construction
* Parallel data downloads
* Memory-based queue limiting
* Chain insertion after verification

## Protocol Handlers

Protocol handlers bridge the P2P layer and blockchain logic and are responsible for routing messages.

**Diagram: Protocol handler message flow**

### Protocol Version Management

StableNet implements the `eth/68` protocol.\
During the handshake, protocol version and chain information are exchanged:

```text theme={null}
Handshake {
    ProtocolVersion: 68
    NetworkID: <chain ID>
    TD: <total difficulty>
    Head: <head block hash>
    Genesis: <genesis hash>
    ForkID: <fork identifier>
}
```

Peers must share the same genesis hash and a compatible fork ID to establish a connection.

### Message Handling

**Request/response messages:**

* GetBlockHeaders / BlockHeaders
* GetBlockBodies / BlockBodies
* GetReceipts / Receipts
* GetPooledTransactions / PooledTransactions

**Broadcast messages:**

* NewBlock
* NewBlockHashes
* Transactions
* NewPooledTransactionHashes

Smart propagation strategies are used to balance bandwidth usage and propagation latency.

## Peer Management

Each peer goes through the following lifecycle:

1. Discovery
2. Dialing
3. Encryption handshake
4. Protocol handshake
5. Registration
6. Message exchange
7. Disconnection

The P2P layer is responsible for transport and encryption, while the `eth` layer handles blockchain logic.

### Peer Reputation

The downloader continuously tracks peer performance:

* Header processing capacity
* Body processing capacity
* Receipt processing capacity
* Round-trip latency

This reputation data is used to select peers for synchronization requests.

## Network Security

The networking layer includes the following security mechanisms:

| Mechanism                 | Purpose                        |
| ------------------------- | ------------------------------ |
| Connection limits         | Prevent resource exhaustion    |
| Inbound limits            | Defend against connection spam |
| Fork ID validation        | Prevent chain splits           |
| Reputation-based eviction | Block malicious peers          |
| Message size limits       | Prevent memory attacks         |
| Request rate limits       | Protect I/O and bandwidth      |

Peers may be disconnected due to protocol violations, excessive resource usage, or compatibility issues.
