Introducing a new way to review your PRs.

Read the announcement

celestiaorg / celestia-core

A fork of CometBFT

View on GitHub

20 documents · Updated Nov 23, 2026

docs / networking

Peer-to-peer networking

Peer-to-peer networking connects CometBFT nodes so they can exchange chain data, consensus data, transactions, evidence, and peer addresses. It gives each connection an authenticated identity, carries many message channels over one transport, and routes each message to the reactor that owns its channel. Peer identity also remains visible when peers appear in structured logs.

Network model

The network has three main roles. The transport creates safe connections, the switch owns the set of connected peers, and reactors use those peers to run product-level protocols. Peer exchange helps the switch find more addresses, while the other reactors use the same network to share chain and application data.

The main relationship is:

flowchart LR
    A[Node identity and node information] --> B[Transport]
    B --> C[Authenticated peer]
    C --> D[P2P switch]
    D --> E[Reactor peer sets]
    E --> F[Protocol messages]
    G[Peer exchange] --> D
    F --> H[Consensus and application state]

Peer identity and compatibility

Cryptographic identity

A peer ID is the hexadecimal form of the hash of a node's public key. The node keeps the matching private key as its persistent node key. This identity authenticates the connection and distinguishes a peer from its IP address or listening port.

The secure connection also checks that the remote authentication key is an authority key before it accepts the signed challenge. This prevents a key with universal signature behavior from becoming a peer identity.

References: p2p/key.go• L15-46 p2p/peer.go• L24-40 p2p/…/secret_connection.go• L174-190 p2p/…/weak_key_test.go• L29-50 p2p/…/conn_fuzz_test.go• L92-235

Peer representation

A peer's string form combines its connection direction, network state, and cryptographic ID. When a logger encodes a peer as JSON, the peer uses this same identifying form instead of exposing internal service fields. This keeps peer identity useful in both text and structured logs.

References: p2p/peer.go• L187-201 p2p/peer_test.go• L53-77

Node information

During the connection handshake, each node shares node information. This record describes the peer's identity, listening address, network name, protocol versions, and supported channels. The record lets the transport check that the peer can take part in the same network before the switch accepts it.

The advertised listening address is checked for valid address syntax without a DNS lookup. A connected peer may advertise a host name. When another subsystem needs that peer's usable address, it combines the connection IP with the advertised port instead of resolving the name. Local configured addresses such as seeds and persistent peers still use normal address resolution.

References: p2p/node_info.go• L28-45 p2p/node_info.go• L78-97 p2p/node_info.go• L110-174 p2p/node_info.go• L218-303 p2p/netaddress.go• L69-125 p2p/node_info_test.go• L134-210 p2p/…/pex_reactor_test.go• L1071-1127

Compatibility checks

A node accepts a peer only when the node information is valid and compatible. The block protocol version and network name must match. The nodes must also share at least one message channel. The authenticated public-key identity must match the identity in the node information.

References: p2p/node_info.go• L177-215 p2p/transport.go• L455-623 p2p/p2p_fuzz_test.go• L179-221

Connection lifecycle

Transport establishment

The transport listens for inbound TCP connections and dials known network addresses for outbound connections. It filters duplicate connections and addresses before it performs the handshake. The handshake first creates an encrypted connection and then exchanges node information. The encrypted connection verifies a signed challenge from an acceptable authority key. A failed check closes the connection instead of exposing it to the switch.

Configured dial addresses can resolve host names. A host name in peer-supplied node information is handled by syntax validation and the active connection address, so the handshake does not make a DNS request for it.

References: p2p/transport.go• L225-303 p2p/transport.go• L349-433 p2p/transport.go• L448-625 p2p/…/secret_connection.go• L90-190 p2p/…/conn_fuzz_test.go• L92-235 p2p/p2p_fuzz_test.go• L140-222

Listener recovery

The inbound listener keeps serving when the operating system reports a temporary resource error. It retries with a short backoff that grows to a bounded delay, then resets that delay after a successful accept. The retry also stops when the transport closes. A non-temporary error ends the accept loop and is returned to its caller.

The transport recognizes common resource errors on all platforms and adds the matching Winsock errors on Windows. This keeps connection admission available during temporary socket or system-resource pressure without hiding a fatal listener error.

References: p2p/transport.go• L25-33 p2p/transport.go• L318-380 p2p/transport_accept_errno_other.go• L1-9 p2p/transport_accept_errno_windows.go• L1-17 p2p/transport_test.go• L807-995 p2p/transport_accept_errno_windows_test.go• L12-31

The connection setup follows this sequence:

sequenceDiagram
    participant T as Transport
    participant P as Remote node
    participant S as Switch
    T->>P: Connect or accept TCP connection
    T->>P: Authenticate public keys
    T->>P: Exchange node information
    T->>T: Check identity, duplicates, and compatibility
    T->>S: Provide authenticated peer
    S->>S: Apply peer and reactor acceptance rules

Peer lifecycle

The switch starts an accepted peer before it adds the peer to the global peer set or reactor peer sets. A running peer owns the send and receive work for its multiplexed connection. When the connection stops, the switch removes it from the reactors and global set, then asks the transport to clean up its resources.

Persistent peers can enter a reconnect loop after an error. Outbound persistent peers use their configured dial address. Inbound persistent peers are recognized by authenticated peer ID and are also redialed through their configured address. Other inbound peers use the connection IP with the port from their advertised listening address.

References: p2p/switch.go• L248-277 p2p/switch.go• L361-437 p2p/switch.go• L459-481 p2p/switch.go• L483-540 p2p/switch.go• L719-741 p2p/transport.go• L48-59 p2p/transport.go• L628-661 p2p/switch_test.go• L494-650 p2p/switch_test.go• L573-650

P2P switch

Connection ownership

The P2P switch is the central owner of connection admission, dialing, peer limits, removal, and reconnection. It keeps one global view of connected peers and maps each registered channel to its reactor. This gives the rest of the node one place to ask which peers are connected without making each protocol manage sockets.

The switch also prevents duplicate peer IDs and can reject duplicate IP connections when that policy is enabled. A dial that loses a race to an inbound connection from the same peer ID is treated as already connected. A duplicate IP or a different peer ID remains a real dial failure.

References: p2p/switch.go• L72-105 p2p/switch.go• L116-151 p2p/switch.go• L177-193 p2p/switch.go• L327-358 p2p/switch.go• L642-669 p2p/switch.go• L892-996 p2p/switch_test.go• L224-385 p2p/switch_test.go• L629-718 p2p/…/pex_reactor_test.go• L1037-1099

Reactor-specific peer sets

Each reactor can keep its own view of the peers that it needs. A peer may be accepted by some reactors and rejected by others. A graceful removal affects only the requesting reactor while another reactor still needs the connection. An error removes the peer from all reactors and closes the connection.

References: p2p/switch.go• L917-971 p2p/switch.go• L985-1020 p2p/switch.go• L436-446 docs/…/adr-010-reactor-specific-peers.md• L59-93 p2p/switch_test.go• L961-1081

Reactors and channels

Reactor contract

A reactor is the owner of one or more message channels and the protocol behavior carried on them. The switch gives the reactor peer lifecycle events. The reactor can prepare per-peer state, start work when a peer joins, handle messages, and release state when the peer leaves. The shared reactor boundary can check raw messages before decoding, bound concurrent prechecks and decoding, preserve message order, apply queue backpressure or dropping, and isolate processing failures from the rest of the node.

References: p2p/base_reactor.go• L18-63 p2p/base_reactor.go• L95-148 p2p/base_reactor.go• L172-195 p2p/base_reactor.go• L198-244 p2p/base_reactor_test.go• L23-40 p2p/base_reactor_test.go• L411-593 p2p/p2p_fuzz_test.go• L225-463

Channel assignments

Each channel has a unique byte ID and belongs to one reactor. Channel descriptors define the message type and the rules that control its queues, priority, and receive limits. The switch rejects duplicate channel ownership, so a received channel ID has one clear protocol destination. The current channel map is summarized in p2p-channels.md.

References: p2p/switch.go• L177-193 p2p/…/connection.go• L753-809 docs/p2p-channels.md• L5-22 p2p/…/conn_fuzz_test.go• L482-653

Peer exchange

Address discovery

The peer exchange reactor keeps an address book of possible peers. It learns addresses from configured seeds, inbound peers, and explicit exchange requests. It asks connected peers for more addresses when the node needs connections, then asks the switch to dial selected addresses. This turns a small set of starting addresses into a wider set of possible routes through the network.

In seed mode, the reactor can crawl known addresses and later disconnect temporary peers while retaining persistent peers. A node with an empty address book can fall back to configured seeds. Successful and failed dials affect which addresses are selected and how soon a failed address is tried again.

Inbound peer addresses use the active connection IP when the peer advertises a host name. This lets peer exchange store and share a usable route without resolving a name supplied by the peer.

References: p2p/…/pex_reactor.go• L74-101 p2p/…/pex_reactor.go• L196-221 p2p/…/pex_reactor.go• L356-394 p2p/…/pex_reactor.go• L465-534 p2p/…/pex_reactor.go• L674-777 p2p/…/pex_reactor_test.go• L365-430 p2p/…/pex_reactor_test.go• L432-507 p2p/…/pex_reactor_test.go• L886-920 p2p/…/pex_reactor_test.go• L1114-1157

Address quality

The address book separates new addresses from addresses that have proved useful. It records successful peers, failed attempts, and banned peers. It filters self addresses, private IDs, invalid addresses, and non-routable addresses when strict routing is enabled. Selections are shuffled before they are shared or dialed.

An address that proves useful moves from the new set to the established set. The address book limits the number of stored addresses and bans. It persists its contents so a node can keep useful discovery data across restarts. Selection can favor new addresses while still returning established addresses, which helps discovery grow without discarding known routes.

References: p2p/…/addrbook.go• L33-79 p2p/…/addrbook.go• L209-218 p2p/…/addrbook.go• L266-360 p2p/…/addrbook.go• L367-443 p2p/…/addrbook.go• L573-631 p2p/…/addrbook.go• L671-782 p2p/…/addrbook.go• L840-895 p2p/…/params.go• L5-57 p2p/…/addrbook_test.go• L23-56 p2p/…/addrbook_test.go• L195-345 p2p/…/addrbook_test.go• L377-449 p2p/…/addrbook_test.go• L600-719

Exchange safeguards

Peer exchange limits request frequency and accepts an address list only when the node sent a matching request. It also caps the size of an address response. The response path does not wait on a full peer send queue. It drops the response so the peer can ask again later. These rules reduce address amplification and prevent unsolicited lists from changing the address book.

A dial rejection is success-equivalent only when the rejected peer ID matches the peer the node wanted to reach. Duplicate-IP rejections, mismatched IDs, and ordinary dial errors remain failures and keep normal retry backoff. This prevents a peer that shares an address from suppressing backoff for a different peer.

References: p2p/…/pex_reactor.go• L79-81 p2p/…/pex_reactor.go• L243-305 p2p/…/pex_reactor.go• L307-393 p2p/…/pex_reactor.go• L396-428 p2p/…/pex_reactor.go• L550-616 p2p/…/pex_reactor.go• L779-787 p2p/…/pex_reactor_test.go• L171-320 p2p/…/pex_reactor_test.go• L991-1099 p2p/…/pex_reactor_test.go• L1159-1219

Network-level message routing

Secure multiplexing

One peer connection carries several independent protocol channels. The connection places outbound messages in per-channel queues and selects queued channels by priority and recent send use. Latency-critical channels can flush as soon as their queued message is complete, while bulk channels remain subject to the normal flush throttle. Large messages are split into bounded packets and rebuilt on receipt. Send and receive rate limits, queue limits, and message-size limits keep one peer from consuming unbounded resources. Ping and pong messages check link liveness.

References: p2p/…/connection.go• L55-79 p2p/…/connection.go• L123-155 p2p/…/connection.go• L428-506 p2p/…/connection.go• L556-715 p2p/…/connection.go• L753-952 p2p/…/connection_test.go• L623-695 p2p/…/connection_test.go• L757-872 p2p/…/conn_fuzz_test.go• L247-441 p2p/…/conn_fuzz_test.go• L482-653

Incoming message path

The connection reads framed packets and handles ping and pong control packets itself. For a data packet, it validates the channel, rebuilds the message until the final packet arrives, and passes complete bytes to the peer callback. The peer maps the channel to its reactor and queues a raw envelope. A full reactor queue can apply backpressure to the connection reader.

The reactor then runs the channel's raw-byte check before decoding, unwraps the message when needed, and calls the protocol handler in queue order. An optional concurrency bound limits how many messages can be checked and decoded at the same time. A bad channel, malformed message, or processing error stops the source peer. A panic while processing one peer is contained and disconnects that peer, while a panic in the processor itself stops the reactor without crashing the node.

References: p2p/…/connection.go• L615-723 p2p/peer.go• L470-505 p2p/base_reactor.go• L186-271 p2p/base_reactor.go• L278-350 p2p/base_reactor_test.go• L129-237 p2p/base_reactor_test.go• L411-593 p2p/…/conn_fuzz_test.go• L482-653 p2p/p2p_fuzz_test.go• L286-463

Outgoing message path

A reactor sends a message through a peer or broadcasts it through the switch. The switch selects the peer set for the message's channel, so a broadcast reaches only peers attached to that channel's reactor. The peer wraps and serializes the message when required, then places it on the channel queue. The connection later frames and writes the queued data.

References: p2p/types.go• L19-41 p2p/switch.go• L283-325 p2p/peer.go• L325-363 p2p/…/connection.go• L367-613 p2p/switch_test.go• L135-192 p2p/switch_test.go• L961-1015

Synchronization protocols

Block and state synchronization use the same peer, channel, switch, and reactor model as the other network protocols. They differ in the data they request and verify: block sync downloads historical blocks, while state sync obtains recent application state in chunks. See the related Block and state synchronization page and its child pages for block synchronization and state synchronization. Consensus data uses the same network path through its own reactor; see Consensus propagation.

Change checklist

When these files or sections are changed, remember to consider these:

  • Update the channel ownership map when a reactor adds, removes, or renumbers a channel.
  • Check channel packet size, receive capacity, queue behavior, and rate limits together when changing connection framing or flow control.
  • Check low-latency flush rules with the normal flush throttle. Bulk traffic must not delay latency-critical messages, and a completed large receive must not retain its peak buffer.
  • Check ping interval and pong timeout together. The timeout must allow liveness checks to complete before the next ping resets them.
  • Check temporary accept-error classification, platform-specific error mappings, retry backoff, and close handling together. A resource error must retry, while a fatal listener error must still reach the caller.
  • Check both transport admission and switch admission when peer identity or duplicate-peer rules change.
  • Keep peer-advertised address syntax checks separate from local seed and persistent-peer DNS resolution. Use the active connection IP for a connected peer that advertises a host name.
  • Check inbound persistent-peer matching by authenticated ID and redial through the configured address. Outbound peers still match by their dialed address.
  • Treat only a duplicate rejection for the requested peer ID as success-equivalent in PEX. Duplicate-IP and different-ID rejections must keep normal failure backoff.
  • Check reactor peer-set removal when changing peer shutdown or error handling. A graceful removal and an error removal have different connection effects.
  • Check peer exchange request tracking and response size limits together when changing the PEX message flow.
  • Check the peer's structured-log representation when changing its string form or identity fields. Log output must keep enough information to identify the peer.
  • Check raw-message prechecks, message decoding, and reactor queue policy together. A non-blocking queue can drop messages when a reactor is stalled.
  • Check the unmarshal concurrency limit with raw-message prechecks, decoding cost, and queue capacity. A stalled precheck or decode can apply backpressure to peer receive loops.
  • Check peer-disconnect behavior for message errors and panics separately from processor-level panic recovery. One bad peer must not stop unrelated reactor work.
  • Check authority-key validation together with challenge verification and peer identity assignment. A signature that verifies without proving key ownership must not authenticate a peer.
  • Check address-book filtering, bucket indexes, and selection limits together when changing peer discovery or address trust.
  • Check the block, state, and consensus propagation pages when their reactor channels or peer needs change.

Important failure modes

TriggerConsequenceGuard
Remote public-key identity does not match the dialed ID or node informationThe connection is rejected before the switch accepts the peerSecret-connection authentication and identity checks in the transport
Remote authentication key is a weak or universal-signature keyThe secure connection rejects the peer before it receives an identityAuthority-key validation before challenge verification
A peer advertises a malformed listening host or portThe connection is rejected during node information validation without a DNS requestSyntax-only ListenAddr validation
Node information has a different network or block protocol versionThe peer cannot join this networkCompatibility validation during the handshake
The listener reports a temporary resource errorNew inbound connections pause briefly and then resumeCross-platform temporary-error classification with bounded exponential retry
The listener reports a fatal error or the transport closes during retryThe accept loop stops instead of hiding the error or leaking a waitFatal-error delivery and close-aware retry handling
A peer presents an unknown channel ID or packet typeThe connection is stopped and the peer is reported as failedChannel registration and receive-side packet validation
A reassembled message exceeds its channel capacityThe connection is stopped before the oversized message reaches a reactorPer-channel receive message capacity and bounded packet assembly
A large message completes on a long-lived connectionExcess receive memory remains attached to the connectionReset the receive buffer to its baseline capacity after message delivery
An invalid, self, private, or non-routable address enters peer exchangeThe address book can waste dial attempts or expose unusable routesAddress validation, self and private-ID filtering, and strict routability checks
A reactor receives a malformed or invalid messageThe source peer is stoppedRaw-message prechecks, decoding, and reactor error handling
A reactor's non-blocking queue is full while its processor is stalledThe incoming message is dropped and the protocol may not receive itQueue policy and capacity selected for the reactor's delivery needs
Reactor prechecks or decoding occupy all permitted unmarshal workPeer receive loops wait before they can queue more messagesAn unmarshal concurrency limit chosen with the queue and message workload
Reactor message processing panicsThe affected peer is disconnected while the node and other peer processing continuePer-message panic recovery and peer-scoped error handling
The reactor processor panics during startup or its main loopThe reactor stops instead of taking down the nodeProcessor-level panic recovery and controlled reactor shutdown
A peer stops answering ping messagesThe connection is closed and the switch can remove or reconnect the peerPong timeout and connection error handling
PEX sends an unsolicited address list or requests too oftenThe peer is treated as misbehaving and may be bannedMatching-request tracking and request-rate checks
A dial sees a duplicate IP or a different duplicate peer IDThe address follows normal failure handling and dial backoffDuplicate classification that grants success-equivalence only to the requested peer ID
A peer is removed from one reactor while another reactor still uses itA premature disconnect can interrupt the other protocolReactor-specific peer sets and active-connection counting

Key files

FileWhy to read it
p2p/switch.goShows connection ownership, dialing, peer admission, persistent-peer recovery, reactor membership, broadcasting, and reconnection.
p2p/transport.goShows how network connections become authenticated peers, how rejected connections are filtered, and how the inbound listener recovers from temporary errors.
p2p/transport_accept_errno_windows.goShows the Windows resource errors that must count as temporary during inbound accept.
p2p/node_info.goDefines the identity, advertised address, and compatibility information exchanged during the handshake.
p2p/netaddress.goDefines peer address parsing, local address resolution, and routability checks.
p2p/peer.goConnects a peer's identity and lifecycle to multiplexed message send and receive paths, including channel-to-reactor routing.
p2p/base_reactor.goDefines the reactor contract and the boundary between raw network messages and protocol messages, including queue and decode limits.
p2p/…/connection.goExplains channel multiplexing, packet assembly, message queues, traffic limits, low-latency flushing, and liveness checks.
p2p/…/secret_connection.goDefines the authenticated encrypted link used before a peer enters the switch.
p2p/…/pex_reactor.goShows how peer exchange discovers addresses, handles peer-address sources, and keeps the node connected.
p2p/…/addrbook.goShows how discovered addresses gain, lose, and retain trust for future dialing.
p2p/…/params.goDefines the address-book thresholds, selection bounds, retention limits, and timing values that shape discovery.
p2p/…/pex_reactor_test.goShows the peer exchange contracts for seed fallback, dial backoff, address limits, abuse handling, and duplicate classification.
p2p/…/addrbook_test.goShows the address-book contracts for persistence, trust promotion, filtering, bans, selection, and network grouping.
docs/p2p-channels.mdProvides the current channel-to-reactor map.
docs/block-and-state-sync.mdExplains how block and state synchronization use the networking model.
docs/consensus-propagation.mdExplains how consensus messages use the networking model.