Crate kona_p2p

Source
Expand description

§kona-p2p

A peer-to-peer networking library for the OP Stack, providing decentralized node communication and coordination for Optimism rollups.

§Features

  • Peer Discovery: Automatic discovery of network peers using Ethereum’s Discv5 protocol
  • Block Gossip: Efficient propagation of blocks and network payloads via GossipSub mesh networking
  • Connection Management: Intelligent peer connection gating with rate limiting and IP filtering
  • RPC Interface: Administrative JSON-RPC API for network monitoring and control
  • Metrics: Prometheus-compatible observability and monitoring (optional)

§Architecture

The library is organized into four main modules:

  • gossip: GossipSub-based block propagation and validation using libp2p
  • discv5: Peer discovery service using Ethereum’s Discv5 distributed hash table
  • rpc: Administrative RPC API for network status and peer management
  • metrics: Observability and monitoring capabilities

§Quick Start

use kona_p2p::{GossipDriverBuilder, Discv5Builder, LocalNode};
use kona_genesis::RollupConfig;
use libp2p_identity::Keypair;
use alloy_primitives::Address;
use std::net::{IpAddr, Ipv4Addr};
use discv5::{ConfigBuilder, ListenConfig, enr::k256};

// Create a keypair for the node
let keypair = Keypair::generate_secp256k1();

// Example rollup config and signer address
let rollup_config = RollupConfig::default();
let signer = Address::ZERO;
let listen_addr = "/ip4/127.0.0.1/tcp/9000".parse()?;

// Build the gossip driver
let (gossip_driver, _signer_tx) = GossipDriverBuilder::new(
    rollup_config.clone(),
    signer,
    listen_addr,
    keypair.clone()
).build()?;

// Convert keypair to the required signing key format
let secp256k1_keypair = keypair.try_into_secp256k1()
    .map_err(|_| "Failed to convert keypair")?;
let signing_key = k256::ecdsa::SigningKey::from_bytes(&secp256k1_keypair.secret().to_bytes().into())
    .map_err(|_| "Failed to create signing key")?;

// Build the discovery service
let local_node = LocalNode::new(
    signing_key,
    IpAddr::V4(Ipv4Addr::LOCALHOST),
    9000,
    9001
);
let discovery_config = ConfigBuilder::new(
    ListenConfig::Ipv4 { ip: Ipv4Addr::LOCALHOST, port: 9001 }
).build();

let discv5_driver = Discv5Builder::new(local_node, rollup_config.l2_chain_id.into(), discovery_config)
    .build()?;

§Network Protocol

The library implements the OP Stack networking protocol, which consists of:

  1. Discovery Layer: Uses Discv5 to maintain a distributed hash table of network peers
  2. Transport Layer: TCP connections secured with libp2p Noise encryption
  3. Application Layer: GossipSub mesh for efficient message propagation

§Message Types

The primary message type is OpNetworkPayloadEnvelope, which contains:

  • Block payloads for consensus coordination
  • Network metadata and validation information
  • Cryptographic signatures for message authenticity

§Connection Management

The library includes sophisticated connection management:

  • Rate Limiting: Prevents connection flooding attacks
  • IP Filtering: Blocks malicious or unwanted IP ranges
  • Peer Protection: Maintains connections to important peers
  • Automatic Pruning: Removes stale or poor-quality connections

§Configuration

Key configuration options include:

  • Mesh Parameters: Control GossipSub mesh topology (D, D_low, D_high, D_lazy)
  • Discovery Settings: Bootstrap nodes, query intervals, and table maintenance
  • Connection Limits: Maximum peers, connection timeouts, and rate limits
  • Validation Rules: Message validation thresholds and scoring parameters

§Technical Notes

Peer Scoring: Unlike the reference op-node, kona-node relies on libp2p’s built-in peer scoring rather than implementing custom scoring. This simplifies the implementation while maintaining network health through proven scoring mechanisms.

Security: The library implements multiple layers of protection against common P2P attacks including eclipse attacks, sybil attacks, and denial-of-service attempts.

§Observability

With the metrics feature enabled, the library exports Prometheus-compatible metrics for:

  • Peer connection counts and quality
  • Message propagation statistics
  • Discovery service performance
  • Network health indicators

§Compatibility

This implementation is compatible with the OP Stack networking protocol and can interoperate with:

  • op-node (reference implementation)
  • Other OP Stack rollup nodes
  • Ethereum consensus layer clients (for discovery)

§Acknowledgements

Largely based off magi’s p2p module, adapted for the kona ecosystem with additional features and OP Stack specific optimizations.

Re-exports§

pub use gossip::GOSSIP_HEARTBEAT;
pub use gossip::PEER_SCORE_INSPECT_FREQUENCY;
pub use gossip::SEEN_MESSAGES_TTL;

Structs§

Behaviour
Specifies the NetworkBehaviour of the node
BlockHandler
Responsible for managing blocks received via p2p gossip
ConnectionGater
Connection Gater
DialInfo
Dial information tracking for peer connection management.
Discv5Builder
Discovery service builder.
Discv5Driver
The Discv5Driver drives the discovery service.
Discv5Handler
Handler to the spawned discv5::Discv5 service.
GOSSIP_HEARTBEAT
The gossip heartbeat.
GaterConfig
Configuration parameters for the connection gater.
GossipDriver
A driver for a Swarm instance.
GossipDriverBuilder
A builder for the GossipDriver.
GossipScores
Comprehensive GossipSub scoring metrics for peer quality assessment.
LocalNode
The local node information exposed by the discovery service to the network.
Metrics
Container for metrics.
PEER_SCORE_INSPECT_FREQUENCY
The pper score inspect frequency. The frequency at which peer scores are inspected.
PeerCount
Peer count data.
PeerDump
A raw peer dump.
PeerInfo
The peer info.
PeerScores
Peer Scores
PeerStats
Peer stats.
ReqRespScores
Request-response protocol scoring metrics.
SEEN_MESSAGES_TTL
The seen messages TTL. Limits the duration that message IDs are remembered for gossip deduplication purposes.
TopicScores
GossipSub topic-specific scoring metrics.

Enums§

BehaviourError
An error that can occur when creating a Behaviour.
BlockInvalidError
Error that can occur when validating a block.
Connectedness
Represents the connectivity state of a peer in a network, indicating the reachability and interaction status of a node with its peers.
DialError
An error type representing reasons why a peer cannot be dialed.
Direction
Direction represents the direction of a connection.
Discv5BuilderError
An error that can occur when building the discovery service.
Event
High-level events emitted by the gossip networking system.
GossipDriverBuilderError
An error type for the crate::GossipDriverBuilder.
HandlerEncodeError
Error encountered when encoding payloads in the block handler.
HandlerRequest
Request message for communicating with the Discv5 discovery service.
P2pRpcRequest
A p2p RPC Request.
PublishError
Error encountered when publishing a payload to the gossip network.

Constants§

DEFAULT_MESH_D
The default mesh D.
DEFAULT_MESH_DHI
The default mesh D high.
DEFAULT_MESH_DLAZY
The default mesh D lazy.
DEFAULT_MESH_DLO
The default mesh D low.
GLOBAL_VALIDATE_THROTTLE
The global validate throttle.
MAX_GOSSIP_SIZE
The maximum gossip size. Limits the total size of gossip RPC containers as well as decompressed individual messages.
MAX_OUTBOUND_QUEUE
The maximum outbound queue.
MAX_VALIDATE_QUEUE
The maximum validate queue.
MIN_GOSSIP_SIZE
The minimum gossip size. Used to make sure that there is at least some data to validate the signature against.

Traits§

ConnectionGate
Connection Gate
Handler
This trait defines the functionality required to process incoming messages and determine their acceptance within the network.

Functions§

default_config
Returns the default Config for gossipsub.
default_config_builder
Builds the default gossipsub configuration.