Peer-to-peer, kept simple.
A minimal libp2p implementation in Rust that connects applications over QUIC and TCP, from Rust, Node.js, React Native, or the browser.
cargo add minip2p-rsnpm install @minip2p/nodenpm install @minip2p/react-nativenpm install @minip2p/webNothing runs behind your back
minip2p is a minimal libp2p implementation in Rust. It connects applications over authenticated QUIC and TCP, negotiates custom protocol streams, and adds pubsub, discovery, relays, and NAT traversal only when you ask for them.
There is no async runtime: the protocols are deterministic sans-I/O state machines that move only when you call wait. Sockets, clocks, and timers live in adapters, and unsafe is forbidden across the workspace, apart from one scoped call that enables Apple’s fast UDP datapath and napi-rs’s generated code in the Node binding.
The core builds as no_std + alloc for microcontrollers. Node.js, React Native, and the browser drive the same endpoint through bindings, with Promises and typed events.
Your code
loop { node.wait(deadline)? }Event(e) => handle(e)
Endpoint core
sans-I/O · no sockets · no clock
Transport adapter
UDP socket · clock
01You call wait(deadline). Nothing runs until you do. The call drives the endpoint.
02The adapter waits. It sleeps on its socket and the core's next timer. A datagram lands.
03Bytes and the time go in. The core is plain state machines: no sockets, no clock. Same input, same output.
04One event comes out. wait returns a single event: here, the path upgrade.
05Your match arm runs. Handle it and go around again. Connections, streams, NAT, Gossipsub and discovery all arrive this way.
Many routes, one outcome
Call connect once. Every route races inside one attempt, and your loop hears how it ends exactly once. See Traverse NAT.
- connect(peer) → ConnectId
- wait → ConnectionEstablishedcircuit
- wait → Nat(PathEstablished)Relayed
- wait → ConnectionReplacedcircuit → direct
- wait → Nat(PathUpgraded)→ Punched
- wait → ConnectSettledConnected
01connect dials every candidate. QUIC and TCP candidates race at once. The peer's NAT drops both, and the failures stay inside the attempt.
02A relay leg starts 200 ms later. The circuit through the relay is usable right away, but provisional.
03DCUtR punches a direct path. One peer dials while the other fires timed UDP packets back, so both NATs open for the same path. The direct connection replaces the circuit.
04The attempt settles, once. One ConnectSettled ends the attempt.
Cargo features
Each feature of minip2p-rs adds a capability without changing the endpoint interface.
- quicQUIC over quinn-proto with libp2p TLS. On by default; needs std.
- tcpTCP upgraded with Noise XX and Yamux, beside or instead of QUIC.
- autonatAutoNAT probes and reachability state.
- relayRelay reservations and races, plus DCUtR hole punching with quic.
- pubsubSigned gossipsub publish and subscribe.
- discoverySigned beacons, a shared peer book, and optional auto-dial.
- mdnsLocal-link discovery over multicast DNS.
- relay-serverHost a Circuit Relay v2 server.
- smoltcpTCP and mDNS over a host-owned smoltcp stack, for no_std devices.
Example
Dial a peer, wait until it is ready, and ping it. Both programs are compiled in CI exactly as shown.
use std::time::{Duration, Instant};
use minip2p::{ConnectOutcome, Endpoint, EndpointEvent, EndpointWaitOutcome, PeerAddr};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// A complete peer address, e.g. /ip4/127.0.0.1/udp/4001/quic-v1/p2p/12D3KooW...
let target: PeerAddr = std::env::args()
.nth(1)
.ok_or("usage: dialer <peer-address>")?
.parse()?;
let peer = target.peer_id().clone();
let mut node = Endpoint::builder()
.agent_version("minip2p-hello/dialer")
.listen_default()?
.bind()?;
// One Connection attempt, one Connect ID, one terminal event.
let connect_id = node.connect(target)?;
let mut deadline = Instant::now() + Duration::from_secs(10);
loop {
let event = match node.wait(deadline)? {
EndpointWaitOutcome::Event(event) => event,
// Another thread woke the wait; nothing to service here.
EndpointWaitOutcome::Deadline => {
return Err("peer did not answer in time".into());
}
_ => continue, // interrupted by a WaitHandle
};
match event {
EndpointEvent::ConnectSettled {
connect_id: id,
outcome,
..
} if id == connect_id => {
if !matches!(outcome, ConnectOutcome::Connected { .. }) {
return Err(format!("connect failed: {outcome:?}").into());
}
}
EndpointEvent::PeerReady { peer_id, .. } if peer_id == peer => {
node.ping(&peer)?;
// The ping gets its own budget, however long setup took.
deadline = Instant::now() + Duration::from_secs(5);
}
EndpointEvent::PingRttMeasured { peer_id, rtt_ms, .. } if peer_id == peer => {
println!("peer={peer} rtt={rtt_ms}ms");
return Ok(());
}
// Everything else is unrelated to this exchange.
_ => {}
}
}
}import { generateSecretKey, Minip2p } from "@minip2p/node";
const address = process.argv.at(2);
if (!address || process.argv.length !== 3) {
throw new Error(
"Usage: pnpm run ping <multiaddress printed by the listener>"
);
}
const endpoint = Minip2p.create({
agentVersion: "minip2p-nodejs-example/0.1.0",
// Bind both transports so either printed listener address can be dialed.
listen: ["/ip4/127.0.0.1/udp/0/quic-v1", "/ip4/127.0.0.1/tcp/0"],
secretKey: generateSecretKey(),
});
try {
const connected = await endpoint.connect(address, { timeoutMs: 10_000 });
// The default timeout allows for the full Identify deadline.
await endpoint.waitPeerReady(connected.peerId);
const rttMs = await endpoint.ping(connected.peerId, { timeoutMs: 5000 });
console.log(`Connected to ${connected.peerId} over ${connected.path.kind}`);
console.log(`Ping: ${rttMs} ms`);
} finally {
endpoint.close();
}