pea2pea
A clean, modular, and lightweight peer-to-peer networking library for Rust.
pea2pea abstracts away the complex, low-level boilerplate of P2P networking - TCP stream handling, connection pooling, framing, backpressure, etc. - allowing you to focus strictly on your network's logic and protocol implementation.
๐ Table of Contents
- โก Why pea2pea?
- ๐ Quick Start
- ๐งฉ Architecture
- ๐ Security
- ๐ Chaos Testing
- ๐ Benchmarking
- ๐ Examples
- ๐ฆ Installation
- ๐ง Project Status
- ๐ค Contributing
- ๐ License
โก Why pea2pea?
- Battle-Tested in Production: This library has been vendored and deployed in high-throughput, real-world decentralized networks, successfully managing complex topologies and heavy traffic.
- Simplicity First: No complex configuration objects or rigid frameworks. You can audit the library yourself in a single afternoon.
- Minimal Dependency Tree:
pea2pearelies strictly ontokioand standard crates, resulting in lightning-fast compile times and tiny binaries. - Uncompromising Performance: Designed as a zero-weight abstraction layer, the library imposes negligible overhead, allowing your application to saturate the underlying network hardware or loopback interface limits.
- Tiny Footprint: The core node structure occupies just ~16kB of RAM; per-connection memory usage starts at ~14kB and scales directly with your configured buffer sizes.
- Meticulously Tested: A comprehensive collection of tests and examples ensures correctness; there is no
unsafecode involved. - Complete Control: You dictate the application logic, and control every byte sent and received. Use slightly altered nodes to fuzz-test and stress-test your production nodes.
๐ Quick Start
Spin up a TCP node capable of receiving messages in 36 lines of code:
use ;
use ;
// Define your node
// Implement the Pea2Pea trait
// Specify how to read network messages
async
๐งฉ Architecture
pea2pea operates on a modular "hooks" system. You control the connection lifecycle by implementing specific traits, while the library handles the low-level async plumbing.
(For a visual representation, see the Connection Lifecycle Graph)
Simply implement the traits you need:
- Handshake: Secure your connections (tls, noise, etc.), configure the stream, or exchange metadata.
- Reading & Writing: Define framing (codecs), message processing, and backpressure handling.
- OnConnect / OnDisconnect: Trigger logic when a connection is fully established or severed (cleanup, recovery).
For full details, refer to the protocols documentation.
๐ Security
pea2pea is built to survive the hostile internet. Its architecture naturally mitigates common denial-of-service vectors without requiring complex configuration:
- Slowloris / Connection Exhaustion: The configurable timeouts ensure that "creeper" connections that fail to handshake or send data are aggressively pruned, freeing up slots for legitimate peers.
- SYN Floods / Rapid Churn: The library's internal state machine handles high-frequency connect/disconnect events (churn) without leaking file descriptors or memory.
- Malicious Payloads / Fuzzing: The strict separation of the
Readingprotocol means that malformed packets or garbage data are rejected at the codec level, instantly dropping the offender before application logic is touched. - Resource Limits: Hard caps on connection counts prevent bad actors from monopolizing your node's resources.
Challenge: We invite you to try and break a
pea2pea-powered node. Point your favorite stress-testing tool (likehping3or a custom fuzzer) at it; the node will hold its ground.
๐ Chaos Testing
pea2pea has been subjected to extensive adversarial stress testing: long
runs of maximally hostile concurrent churn, designed to surface
synchronization bugs, leaks, and lifecycle inconsistencies that simpler
tests can't reach.
A representative session: 24 worker tasks driving fully randomized operations against a pool of up to 32 concurrent nodes, with action delays of 0โ500ยตs, processing ~5 million paired connection lifecycles over a single 2-hour run. Every operation - node spawning, shutdown, connection establishment, disconnection, broadcast, unicast - is selected at random, without any coordination. Workers actively race each other on every shared structure the library exposes.
Across the run the library:
- Held all lifecycle invariants.
on_connectandon_disconnectcallback counts paired to within the live-connection count at any observation moment - no dropped callbacks across millions of events. - Maintained a bounded working set. Peak heap usage stayed well under 20 MiB regardless of run duration; the heap returns to baseline as connections close, with no growth proportional to total events processed.
- Recovered cleanly from every shutdown. Node teardown leaves no detectable residue - no leaked tasks, no leaked sockets, no leaked allocations.
The chaos test is included in the repository as
tests/chaos.rs and is fully reproducible; set
CHAOS_RUNTIME_SECS for a fixed deadline or run until interrupted.
๐ Benchmarking
pea2pea is designed to be as fast as the machine it runs on. To verify the throughput on your specific hardware, run the included benchmark suite:
cargo test --release --test benches -- --nocapture --ignored
Be sure to also check out the stress tests included in the examples.
๐ Examples
Check out the examples directory, which is organized by complexity and use case:
- ๐ฎ Fun & Visual (Tutorials): Gamified scenarios like the Telephone Game or Hot Potato that demonstrate core concepts like topology, message passing, and basic state synchronization.
- ๐ ๏ธ Practical & Patterns: Standard infrastructure patterns, including TLS, Noise Handshakes, Rate Limiting, and RPC.
- ๐ง Advanced & Stress Tests: High-load scenarios like Connection Churn or Dense Mesh that demonstrate the library's performance and libp2p interop.
๐ฆ Installation
Add this to your Cargo.toml:
[]
= "x.x.x" # replace with the latest version
= { = "1", = ["rt"] } # pick any other features you need
๐ง Project Status
Current State: Stable & Feature-Complete.
Despite the 0.x versioning, pea2pea is considered production-ready. The core architecture is finished and proven.
- API Stability: The public API is stable. We do not anticipate breaking changes unless there's a very good reason to do so.
- Scope: The library is effectively in "maintenance mode" regarding features. Future development is strictly limited to hardening internals to ensure maximum reliability. We are not adding new features to the core.
๐ค Contributing
Please see CONTRIBUTING.md for details on our strict scope policy.
๐ License
This project is dual-licensed under either:
- CC0 1.0 Universal (LICENSE-CC0 or https://creativecommons.org/publicdomain/zero/1.0/)
- MIT License (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.