It focuses on the
p2p.Server architecture, peer lifecycle management, connection types, and protocol multiplexing.
For peer discovery mechanisms, see Discovery Mechanisms.For blockchain synchronization protocols, see Chain Synchronization.
For protocol handler implementations, see Protocol Handlers.
Server Architecture
The P2P layer is centered around thep2p.Server structure, which manages all peer connections and implements the core networking functionality of a StableNet node.It unifies inbound and outbound connections and acts as an intermediary between discovery protocols and protocol handlers.
Server Structure
TheServer structure maintains the following core components:
| Component | Type | Purpose |
|---|---|---|
Config | p2p.Config | Network configuration such as maximum peers, listen address, and enabled protocols |
localnode | *enode.LocalNode | Local node identity and ENR management |
listener | net.Listener | Accepts inbound TCP connections |
dialsched | *dialScheduler | Schedules outbound connection attempts |
discmix | *enode.FairMix | Aggregates multiple discovery sources |
ntab | *discover.UDPv4 | Discovery v4 protocol handler |
DiscV5 | *discover.UDPv5 | Discovery v5 protocol handler |
nodedb | *enode.DB | Persistent node database |
Server Configuration and Initialization
Server initialization proceeds through the following steps:setupLocalNode()
Generates the local node ID and ENR from the private key and initializes the node database.setupListening()
Starts the TCP listener on the configured network address.setupDiscovery()
Initializes Discovery v4/v5 and configures the discovery mixer.setupDialScheduler()
Creates the dial scheduler for static and discovered nodes.run()
Starts the server’s main event loop for peer event handling.listenLoop()
Continuously accepts inbound connections.
Server Main Loop
The server’s main event loop performs the following tasks:- Handles peer addition and removal events
- Processes connection requests from the dial scheduler
- Gracefully shuts down all peers on termination signals
- Broadcasts peer state changes via the event feed
Peer Lifecycle
Each connected peer is represented by aPeer structure that encapsulates connection state, protocol handlers, and lifecycle metadata.
Connection Establishment Flow
Peer connections follow this sequence:- TCP connection establishment
- Encrypted handshake
- Protocol handshake and capability negotiation
- Protocol multiplexing setup
- Peer registration and event emission
Handshake Protocols
Connection setup consists of two handshake phases:- Encryption Handshake (
doEncHandshake)
Establishes an RLPx-encrypted communication channel. - Protocol Handshake (
doProtoHandshake)
Negotiates supported protocols and versions.
protoHandshake structure includes:
| Field | Type | Description |
|---|---|---|
Version | uint64 | P2P protocol version |
Name | string | Client identification string |
Caps | []Cap | List of supported protocol capabilities |
ListenPort | uint64 | Listening port |
ID | []byte | Node public key |
Protocol Multiplexing
After the handshake, the server matches commonly supported protocols and assigns message code ranges to each protocol.- Base P2P messages: codes 0–15
- First matched subprotocol: starting at code 16
- Subsequent protocols: offset increased by the previous protocol’s length
Connection Types and Management
The P2P server usesconnFlag values to distinguish connection types:
| Flag | Value | Description |
|---|---|---|
dynDialedConn | 1 << 0 | Outbound connection created via discovery |
staticDialedConn | 1 << 1 | Outbound connection to a static node |
inboundConn | 1 << 2 | Inbound connection initiated externally |
trustedConn | 1 << 3 | Trusted peer (may exceed MaxPeers limit) |
Peer Limits and Capacity
Default peer capacity control policies include:MaxPeers: total peer count limitMaxPendingPeers: limit on pending connection attempts (default 50 per direction)DialRatio: outbound peer ratio (default 1/3)
Dial Scheduler
ThedialScheduler manages outbound connection attempts:
- Tracks recent dial history to avoid excessive retries
- Prioritizes static nodes over discovered nodes
- Enforces maximum concurrent dial limits
- Uses exponential backoff to throttle retries for failed endpoints
Peer Operations and Lifecycle
Adding and Removing Peers
The server manages its peer set using the following methods:| Method | Purpose |
|---|---|
AddPeer(node) | Add a static peer with automatic reconnection |
RemovePeer(node) | Remove a static peer and disconnect |
AddTrustedPeer(node) | Add a trusted peer |
RemoveTrustedPeer(node) | Remove a trusted peer |
Disconnect Reasons
Disconnect reasons are recorded usingDiscReason codes:
| Reason | Code | Description |
|---|---|---|
DiscRequested | 0x00 | Graceful shutdown |
DiscNetworkError | 0x01 | Network error |
DiscProtocolError | 0x02 | Protocol violation |
DiscUselessPeer | 0x03 | Invalid or unhelpful peer |
DiscTooManyPeers | 0x04 | Peer limit exceeded |
DiscAlreadyConnected | 0x05 | Duplicate connection |
DiscIncompatibleVersion | 0x06 | Version mismatch |
DiscInvalidIdentity | 0x07 | Invalid node identity |
DiscQuitting | 0x08 | Server shutting down |
DiscSubprotocolError | 0x10 | Subprotocol error |
Peer Event Feed
The server emits peer state changes viaPeerEvent notifications:
| Event Type | Description |
|---|---|
PeerEventTypeAdd | Peer connected and registered |
PeerEventTypeDrop | Peer disconnected |
PeerEventTypeMsgSend | Message sent |
PeerEventTypeMsgRecv | Message received |
Integration with the Ethereum Backend
The Ethereum backend integrates with the P2P server through protocol registration. Integration flow:eth.Ethereum.Protocols()– returns protocol definitionseth.MakeProtocols()– createsethsubprotocol handlerssnap.MakeProtocols()– createssnapprotocol handlers (if enabled)node.Stack.RegisterProtocols()– registers protocols with the P2P serverhandler.Start()– begins protocol message processing
Backend Access to the P2P Server
The backend maintains a reference to the P2P server for RPC services, used for:NetAPI– network information queriesAdminAPI– peer management RPCs- Dynamic ENR updates
Configuration Flags
Key flags used to configure the P2P network include:| Flag | Type | Default | Description |
|---|---|---|---|
--maxpeers | int | DefaultConfig.P2P.MaxPeers | Maximum number of peers |
--maxpendpeers | int | 0 | Pending peer limit |
--port | int | 30303 | Network listening port |
--bootnodes | string | Network-specific | Bootstrap nodes |
--nodekey | string | - | P2P node key file path |
--nodekeyhex | string | - | Test node key (hex) |
--nodiscover | bool | false | Disable peer discovery |
--netrestrict | string | - | CIDR-based network restriction |
SetP2PConfig() and setNodeKey().
