Skip to main content

Quick Start

Set up an encrypted P2P channel in 15 minutes. This guide walks through installing cairn, pairing two peers, establishing a session, and sending messages -- in all 5 supported languages.

Step 1: Create a Node

A Node is your local peer. Creating one generates an Ed25519 identity and starts the transport layer with zero-config defaults.

use cairn_p2p::{Node, CairnConfig, create};

let node = create(CairnConfig::default())?;
node.start().await?;
println!("Peer ID: {}", node.peer_id());

Step 2: Pair with a Peer

Pairing establishes mutual trust between two devices using a shared secret (PIN, QR code, or link). One peer initiates, the other responds.

PIN Pairing

Initiator -- generates a PIN and displays it:

let pairing_data = node.pair_generate_pin().await?;
println!("PIN: {}", pairing_data.pin); // e.g., "A1B2-C3D4"

Responder -- enters the PIN displayed by the initiator:

let peer_id = node.pair_enter_pin("A1B2-C3D4").await?;
println!("Paired with: {}", peer_id);

Step 3: Establish a Session

After pairing, open an encrypted session. Sessions use a Noise XX handshake followed by a double ratchet for forward secrecy.

let session = node.connect(&peer_id).await?;

Step 4: Send a Message

Send encrypted data over the session. Messages are delivered through the best available transport.

session.send("chat", b"hello from Rust").await?;

Step 5: Receive Messages

Register a handler to receive incoming messages on a channel.

let mut events = node.subscribe();
while let Some(event) = events.recv().await {
match event {
Event::MessageReceived { peer_id, channel, data } => {
println!("[{}] {}: {}", channel, peer_id, String::from_utf8_lossy(&data));
}
_ => {}
}
}

Step 6: Handle Reconnection

Sessions automatically reconnect after network disruptions. Listen for state changes to update your UI.

match event {
Event::StateChanged { peer_id, state } => {
println!("Peer {} state: {:?}", peer_id, state);
}
_ => {}
}

Connection states: connecting -> connected -> reconnecting -> connected (or disconnected).

Next Steps

  • First App -- Build a complete runnable P2P chat in under 50 lines
  • Guides -- Deep dive into pairing methods, sessions, and channels
  • Demo Applications -- Explore working example applications