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 libp2pdiscv5: Peer discovery service using Ethereum’s Discv5 distributed hash tablerpc: Administrative RPC API for network status and peer managementmetrics: 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:
- Discovery Layer: Uses Discv5 to maintain a distributed hash table of network peers
- Transport Layer: TCP connections secured with libp2p Noise encryption
- 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
NetworkBehaviourof the node - Block
Handler - Responsible for managing blocks received via p2p gossip
- Connection
Gater - Connection Gater
- Dial
Info - Dial information tracking for peer connection management.
- Discv5
Builder - Discovery service builder.
- Discv5
Driver - The
Discv5Driverdrives the discovery service. - Discv5
Handler - Handler to the spawned
discv5::Discv5service. - GOSSIP_
HEARTBEAT - The gossip heartbeat.
- Gater
Config - Configuration parameters for the connection gater.
- Gossip
Driver - A driver for a
Swarminstance. - Gossip
Driver Builder - A builder for the
GossipDriver. - Gossip
Scores - Comprehensive GossipSub scoring metrics for peer quality assessment.
- Local
Node - 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.
- Peer
Count - Peer count data.
- Peer
Dump - A raw peer dump.
- Peer
Info - The peer info.
- Peer
Scores - Peer Scores
- Peer
Stats - Peer stats.
- ReqResp
Scores - Request-response protocol scoring metrics.
- SEEN_
MESSAGES_ TTL - The seen messages TTL. Limits the duration that message IDs are remembered for gossip deduplication purposes.
- Topic
Scores - GossipSub topic-specific scoring metrics.
Enums§
- Behaviour
Error - An error that can occur when creating a
Behaviour. - Block
Invalid Error - 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.
- Dial
Error - An error type representing reasons why a peer cannot be dialed.
- Direction
- Direction represents the direction of a connection.
- Discv5
Builder Error - An error that can occur when building the discovery service.
- Event
- High-level events emitted by the gossip networking system.
- Gossip
Driver Builder Error - An error type for the
crate::GossipDriverBuilder. - Handler
Encode Error - Error encountered when encoding payloads in the block handler.
- Handler
Request - Request message for communicating with the Discv5 discovery service.
- P2pRpc
Request - A p2p RPC Request.
- Publish
Error - 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§
- Connection
Gate - 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.