Friend Exchange Protocol
A peer-to-peer friend request and profile exchange system built with Iroh, featuring automatic peer discovery via mDNS and secure bidirectional communication.
Overview
This protocol enables two peers on the same local network to:
- Discover each other automatically
- Exchange friend requests
- Share profile information upon acceptance
All communication happens peer-to-peer without any central server.
Protocol Specification
ALPN Identifier
Communication Flow
The protocol uses two bidirectional streams for a complete exchange:
Stream 1: Friend Request/Response
A ── FriendRequest ──▶ B
◀── FriendResponse ──
Stream 2: Profile Exchange (only if accepted)
A ── Profile(A) ──▶ B
◀── Profile(B) ──
Message Formats
All messages are JSON-encoded.
1. FriendRequest
Sent by the initiator (A) to request friendship.
{
"from": "UUID_string",
"name": "Display Name"
}
Fields:
from: Unique identifier of the requester
name: Display name of the requester
2. FriendResponse
Sent by the acceptor (B) in response to the friend request.
Fields:
accepted: Boolean indicating acceptance (true) or rejection (false)
3. Profile
Exchanged by both peers after acceptance.
{
"user_id": "UUID_string",
"bio": "User biography",
"avatar": "avatar_filename.png"
}
Fields:
user_id: Unique identifier of the user
bio: Short biography or description
avatar: Avatar/profile picture filename or identifier
Protocol Steps
Step 1: Peer Discovery (mDNS)
Both peers advertise their presence on the local network using mDNS. When a peer is discovered:
- The discoverer becomes the initiator (A)
- The discovered peer becomes the acceptor (B)
Step 2: Connection Establishment
A establishes a QUIC connection to B using the Iroh endpoint and the ALPN iroh/friend/0.
Step 3: Friend Request Exchange (Stream 1)
- A opens a bidirectional stream
- A sends
FriendRequest with their name and UUID
- A finishes sending and waits for response
- B receives the request
- B decides whether to accept or reject
- B sends
FriendResponse with acceptance status
- B finishes sending
If rejected: Connection closes, protocol ends.
If accepted: Continue to Step 4.
Step 4: Profile Exchange (Stream 2)
- A opens a new bidirectional stream
- A sends their
Profile data
- A finishes sending and waits for B's profile
- B receives A's profile
- B sends their
Profile data
- B finishes sending
- A receives B's profile
- Protocol complete!
Implementation Details
Connection Management
- Transport: QUIC via Iroh
- Discovery: mDNS for automatic local network discovery
- Streams: Uses QUIC bidirectional streams
- Serialization: JSON with serde
Stream Ordering
The protocol uses two separate bidirectional streams to maintain clear boundaries between:
- Request/response handshake
- Profile data exchange
This prevents message ordering issues and makes the protocol state machine clear.
Error Handling
- Connection failures are logged and the program exits gracefully
- Rejection is handled by closing the connection after sending the response
- All I/O operations use proper error propagation
Building and Running
Prerequisites
- Rust 1.70+ (or latest stable)
- Two devices on the same local network (or two terminals on the same machine)
Build
Run
Terminal 1 (Peer B - Acceptor):
Terminal 2 (Peer A - Initiator):
Start both instances - they will discover each other automatically. The first peer to discover the other will initiate the friend request.
Cancel Search
Press Ctrl+C at any time to cancel peer discovery and exit.
Example Output
Successful Exchange
Peer A (Initiator):
Your Endpoint ID: 42cce99541
Searching for peers... (Press Ctrl+C to cancel)
Discovered: eedd6e5bc6
Found peer! Connecting to eedd6e5bc6
Sent friend request
Friend request accepted!
Sent my profile to B
Received B's profile: Profile { user_id: "B_UUID", bio: "Hello! I'm B, nice to meet you!", avatar: "avatar_b.png" }
Profile exchange complete!
Peer B (Acceptor):
Your Endpoint ID: eedd6e5bc6
Searching for peers... (Press Ctrl+C to cancel)
Incoming connection from 42cce99541
Friend request from: Preetham (A_UUID)
Sent response: accepted=true
Received A's profile: Profile { user_id: "A_UUID", bio: "Hi, I'm Preetham!", avatar: "avatar_a.png" }
Sent my profile to A
Profile exchange complete!
Rejected Request
Peer A:
Your Endpoint ID: 42cce99541
Searching for peers... (Press Ctrl+C to cancel)
Discovered: eedd6e5bc6
Found peer! Connecting to eedd6e5bc6
Sent friend request
Friend request was rejected.
Peer B:
Your Endpoint ID: eedd6e5bc6
Searching for peers... (Press Ctrl+C to cancel)
Incoming connection from 42cce99541
Friend request from: Preetham (A_UUID)
Sent response: accepted=false
Security Considerations
Current Implementation
- All communication is encrypted via QUIC/TLS
- Peer identities are verified using Iroh's public key infrastructure
- Only works on local network (mDNS discovery)
Production Recommendations
- Authentication: Add signature verification for friend requests
- Rate Limiting: Implement rate limits on connection attempts
- User Confirmation: Add actual user interaction for accept/reject decisions
- Profile Validation: Validate profile data size and content
- Privacy: Consider what information to expose in profiles
- Persistence: Store accepted friends and their profiles
- Relay Support: Add relay servers for NAT traversal and internet-wide discovery
Customization
Changing Accept/Reject Logic
In FriendProtocol::accept(), modify this line:
let accept = true; // Change to false to reject, or add actual user input
For production, replace with actual user interaction:
let accept = prompt_user_for_acceptance(&request).await?;
Modifying Profile Data
Edit the Profile struct to include additional fields:
#[derive(Debug, Serialize, Deserialize)]
struct Profile {
user_id: String,
bio: String,
avatar: String,
// Add more fields:
display_name: String,
age: u32,
interests: Vec<String>,
}
Changing Discovery Timeout
Discovery now runs indefinitely. To add a timeout back:
let discovered = tokio::select! {
result = rx => Some(result),
_ = tokio::time::sleep(Duration::from_secs(30)) => {
println!("⏱️ Search timed out");
None
}
_ = tokio::signal::ctrl_c() => {
println!("\nSearch cancelled by user");
None
}
};
Architecture
Components
- Endpoint: The Iroh QUIC endpoint that manages connections
- MdnsDiscovery: Automatic peer discovery on the local network
- Router: Routes incoming connections to the appropriate protocol handler
- FriendProtocol: The protocol handler for friend requests
Threading Model
- Main task: Discovery and connection initiation
- Router task: Accepts incoming connections
- Each connection is handled in its own async task
Troubleshooting
"aborted by peer: the server refused to accept a new connection"
Cause: ALPN mismatch between peers.
Tip
Solution: Ensure both peers are running the exact same code with matching ALPN.
"No peers found" / Peers don't discover each other
Cause: Firewall blocking mDNS or UDP traffic.
Tip
Solution:
- Ensure both devices are on the same network
- Check firewall settings (allow UDP port 5353 for mDNS)
- Try disabling firewall temporarily for testing
Connection hangs on "Connecting to..."
Cause: Network connectivity issues or NAT traversal problems.
Tip
Solution:
- Check that devices can ping each other
- Ensure no VPN is interfering
- For internet-wide connections, configure relay servers
Acknowledgments
Built with Iroh - a next-generation networking library for Rust.