The greeting comes after the handshake.
I wanted to send a friend request without HTTP. The first command was easy to name: WAVE. Getting a server to agree on what it meant took more work.
Quinn[1] could carry bytes across an encrypted QUIC[2] connection. But it could not tell the server that Emma was asking to be friends with Oliver. That agreement would be FRND/1. Campfire, the app above it, would still own the people, permissions, and database.
I wanted our first bytes to read 🤝FRND. Before sending them, QUIC has its own TLS[3] handshake to complete. During that handshake, ALPN[4] selects frnd/1. Only then do we send our greeting.
F0 9F A4 9D 46 52 4E 44🤝FRNDA protocol is an agreement between two programs: which bytes to send, what they mean, and what to do when something goes wrong. For FRND, our first goal is small: Emma sends a friend request to Oliver, and the server replies after saving it.
The ingredients for a protocol of your own.
| Component | What it is | How we use it |
|---|---|---|
| Client + server | The two programs talking to each other. | The client sends Emma’s WAVE. The server checks it, saves the request, and returns a result. |
| Rust + Cargo[5] | The language and its build tool. | Write both programs, share the message code, and run tests. |
| QUIC + Quinn | QUIC is the transport protocol. Quinn is the Rust library that implements it. | Open an encrypted connection and send bytes on streams. Later, use datagrams[6] for disposable updates. |
| Tokio[7] | The runtime that drives asynchronous Rust tasks. | Wait for network data while allowing other connections and requests to progress. |
| TLS + rustls[8] | TLS protects the connection; rustls implements it in our configuration. | The server presents a certificate. The client checks that it trusts the server. Configure the same ALPN name on both ends. |
| FRND codec[9] | Our encoder and decoder: values and bytes. | Encode WAVE as a header plus Oliver’s ID. Reject invalid fields before using the request. |
| Session rules | Rules for one connected conversation. | Finish setup, validate the shared credential, enforce limits, and decide which message types are allowed. |
| Application + storage | The friendship rules and saved state. | Check permission, save the pending request and its result together, and recognize retries. |
Download the Rust project, extract it, and run cargo test --locked. The embedded ZIP is the compact article snapshot. For the maintained terminal client, server, complete test suite, and two-computer walkthrough, use the FRND/1 repository. Read wave() first, then follow the request into receive_wave() and the transaction[11] fixture.
Why native Rust programs?
“Native” means these programs run directly on your computer or server. They can use UDP sockets and negotiate our own frnd/1 protocol over QUIC. Start with a small command-line client and a local server; a graphical app can come later.
Rust is our implementation choice, not a requirement of FRND. We can use one set of types and encoding functions on both sides, and its type system helps us keep valid messages separate from unchecked input. Another language can implement the same wire rules.
The browser’s WebTransport[12] API uses a different connection setup; it is not a direct client for this native FRND endpoint. Our in-page WASM[13] example runs only the Rust message decoder. It does not run the Quinn client or server. WebTransport specification
Why Quinn?
We want to build the friendship protocol, so we use a library for QUIC. Quinn provides asynchronous connections, streams and datagrams. Our code still decides what WAVE means and when a request counts as saved. Its Rust API fits this project’s Tokio runtime. Quinn’s components and examples
Start the server to create a certificate for frnd-lan. Its signing key remains in memory; only .frnd/server-cert.der is written. Copy that public certificate to the client checkout through an authenticated channel. The client pins it in an otherwise-empty root store. Configure frnd/1 as ALPN, the protocol name negotiated inside TLS. Once connected, send our preface[14] and HELLO on the setup stream[15]. HELLO carries the shared experiment credential and the app name. Wait for the server’s successful reply before sending WAVE.
Keep the checks separate: the pinned certificate identifies this server instance; the shared credential opens the experiment session but does not identify a person or account. Campfire would supply user identity and authorization above FRND. The friendly 🤝FRND marker only helps us recognize decrypted application bytes.
Wire rules and Rust Open reference
ALPN selects frnd/1 inside the TLS handshake. The pinned certificate authenticates the server instance. HELLO checks the shared experiment credential; this terminal profile does not authenticate Emma as a user. FRND reserves client bidirectional stream 0 for the 16-byte preface and HELLO, then waits for the setup result before opening operation streams.
Rust · Quinn 0.11.12 client setup View code
async fn connect(
endpoint: &mut quinn::Endpoint,
roots: rustls::RootCertStore,
server_addr: std::net::SocketAddr,
) -> Result<quinn::Connection, Error> {
use quinn::crypto::rustls::QuicClientConfig;
use std::sync::Arc;
// roots contains only the pinned .frnd/server-cert.der certificate.
let mut tls = rustls::ClientConfig::builder()
.with_root_certificates(roots)
.with_no_client_auth();
tls.alpn_protocols = vec![b"frnd/1".to_vec()];
let crypto = QuicClientConfig::try_from(tls)?;
endpoint.set_default_client_config(quinn::ClientConfig::new(Arc::new(crypto)));
let connection = endpoint.connect(server_addr, "frnd-lan")?.await?;
Ok(connection)
}The fixed preface is F0 9F A4 9D 46 52 4E 44 01 00 00 01 00 10 00 00: 🤝FRND, version 1.0, datagram capability bit 0, and a 1 MiB receive limit. That bit advertises support implemented by the session API: the native test harness sends a TYPING fixture with try_send_datagram() and rejects an oversized one. The terminal WAVE command itself uses only a reliable stream; Campfire TYPING and Pong paddle input remain the next application schemas.
Independent streams do not promise a global arrival order. FRND therefore reserves the first client bidirectional stream for setup and waits for its result. The greeting has one agreed location: an eight-byte marker followed by version, capabilities, and the receive limit.
A read is not a message.
The client writes a whole WAVE. The server’s first read might contain only three bytes. Nothing is broken: a stream carries bytes, and the receiver does not inherit the sender’s write boundaries.
A sixteen-byte header tells it how much more to expect. It carries the operation type, one response flag, a persistent operation ID[16], and the body length. The body of a WAVE is smaller than its header: eight bytes naming the recipient.
This is the request from the experiment: operation ID 7, recipient 42. The Bytebench models four uneven reads of the same 24-byte fixture, then runs the complete frame[17] through Rust/WASM.
The operation is a friend request. HIGH_FIVE will be a separate operation when Oliver accepts.
00 00 00 00 00 00 00 2AOliver = 42Watch one message become a command.
The trace models four stream reads: 3 + 5 + 8 + 8, followed by FIN[18]. Once the complete frame exists, the embedded Rust validates its header and WAVE fields before the application stage may run.
Press Play once, or advance one receiver decision at a time.
Rust decoder used at stage 2 Read code
fn decode_header(b: [u8; 16], limit: u32) -> Result<Header, &'static str> {
if u16::from_be_bytes([b[2], b[3]]) != 16 { return Err("unsupported header length"); }
if b[1] & !1 != 0 { return Err("reserved flags"); }
let body_len = u32::from_be_bytes([b[12], b[13], b[14], b[15]]);
if body_len > limit.min(1_048_576) { return Err("body too large"); }
Ok(Header { kind: b[0], response: b[1] & 1 != 0,
op_id: u64::from_be_bytes(b[4..12].try_into().unwrap()), body_len })
}Read boundaries and FIN are a deterministic trace. The header decoder and WAVE validator run as embedded Rust/WebAssembly on the complete 24-byte fixture. The state change visualizes the separately tested native transaction; browsers cannot open this Quinn endpoint directly.
A network read may return only part of a message. We therefore need a small label that tells the receiver what it is reading and how many bytes to expect. That label is our header. The data after it is the body.
For WAVE, the header is 16 bytes and the body is 8 bytes: Oliver’s user ID. The header carries the operation type, one response flag, a persistent operation ID, and the body length. Every other flag bit is reserved and must be zero. Multi-byte numbers use big-endian[19] order: the most significant byte goes first.
Write an encoder that turns WAVE(id: 7, recipient: 42) into 24 bytes. Write a decoder that reads the header, checks its fields and limits, then reads exactly the body it permits. A WAVE body must be eight bytes, regardless of the general size limit.
Read the complete frame and its FIN before changing application state. FIN means the sender has finished this direction of the stream. Reject a short body or extra bytes. The runnable example below checks the header and WAVE rules; it does not perform network reads or authorization.
Wire rules and Rust Open reference
| Offset | Field | FRND/1 rule |
|---|---|---|
| 0 | type · u8 | WAVE 0x10; OK 0x7E; OOPS 0x7F. |
| 1 | flags · u8 | Bit 0 is RESPONSE. Bits 7–1 are zero. |
| 2–3 | header length · u16 | Exactly 16, in big-endian order. |
| 4–11 | operation ID · u64 | Nonzero for operations and echoed by the reply. Setup uses zero. |
| 12–15 | body length · u32 | Excludes the header; validate before allocation. |
An OOPS body is one big-endian u16: 1 malformed, 2 forbidden, 3 operation conflict, 4 unsupported type, 5 resource limit, 6 stale target, or 7 invalid application state. Unknown codes remain errors; clients do not guess their meaning.
Rust · fixed header decoder View code
#[derive(Debug)]
struct Header {
kind: u8,
response: bool,
op_id: u64,
body_len: u32,
}
fn decode_header(b: [u8; 16], limit: u32) -> Result<Header, &'static str> {
if u16::from_be_bytes([b[2], b[3]]) != 16 {
return Err("unsupported header length");
}
if b[1] & !1 != 0 {
return Err("reserved flags");
}
let body_len = u32::from_be_bytes([b[12], b[13], b[14], b[15]]);
if body_len > limit.min(1_048_576) {
return Err("body too large");
}
Ok(Header {
kind: b[0],
response: b[1] & 1 != 0,
op_id: u64::from_be_bytes(b[4..12].try_into().unwrap()),
body_len,
})
}An early sketch repeated magic and version in every frame. ALPN and setup already establish those, so the repetition came out. The friendly greeting stays once, in the preface, where it helps identify decrypted traces; it supplies no security.
A missing sample should not always hold up the next one.
One long stream works until a history response gets in the way of a new request. FRND gives each reliable operation its own bidirectional stream: one request, one result, then FIN in each direction. That layout permits bounded concurrency; the current terminal server deliberately reads one operation stream at a time per connection.
A typing indicator makes a different demand. An old “typing” sample can be less useful than no sample. QUIC datagrams carry those short-lived updates without retransmission. They can disappear or arrive out of order, so FRND adds a sequence number and the app expires old state.
Reliable stream
A gap must be repaired.
Datagrams
The next sample can pass.
Nothing sent yet. Start a transmission with sample 2 selected for loss.
Schematic application delivery. Streams and datagrams share congestion control[20]; QUIC streams have independent ordering.
A bidirectional stream is a reliable byte channel with a sending direction for each side. We use one for each operation: Emma sends WAVE, then the server sends OK or OOPS on that same stream. Each side finishes its direction after one frame.
After setup, the client calls open_bi(), writes the WAVE bytes, then calls finish(). The terminal server validates the complete request, records the process-local effect, and replies. In a production Campfire service, the application adapter would also check Emma’s permission before committing durable state. The client checks the reply’s type and operation ID before showing success.
write_all() and finish() do not tell Emma that the friendship request was saved. Only the application result does. Add a deadline around the request; if the connection disappears, the outcome may be unknown.
Handle a bounded number of operation streams concurrently so a slow request does not stop every other request. Streams have independent ordering, but they still share the connection’s bandwidth and other limits.
A datagram is one message whose delivery and order are not guaranteed. Use it for “Emma is typing” or a paddle position, where newer data replaces older data. Include a sequence number, check permission first, and ignore duplicates or older samples. Invalid datagrams are discarded; they do not receive OOPS.
Wire rules and Rust Open reference
One bidirectional stream carries one request and one application result. The sender finishes after the frame. The receiver reads the fixed header, validates its declared body length before allocation, reads exactly that body, and requires FIN.
Rust · WAVE over one Quinn stream View code
async fn wave(
conn: &quinn::Connection,
op_id: u64,
recipient: u64,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let (mut send, mut recv) = conn.open_bi().await?;
send.set_priority(0)?;
let mut frame = [0u8; 24];
frame[0] = 0x10; // WAVE
frame[1] = 0; // request; every other flag bit is reserved
frame[2..4].copy_from_slice(&16u16.to_be_bytes());
frame[4..12].copy_from_slice(&op_id.to_be_bytes());
frame[12..16].copy_from_slice(&8u32.to_be_bytes());
frame[16..24].copy_from_slice(&recipient.to_be_bytes());
send.write_all(&frame).await?;
send.finish()?; // local send complete
let reply = recv.read_to_end(18).await?; // OK or 2-byte OOPS
// Session helper checks type, flags, length and echoed ID.
validate_wave_reply(&reply, op_id)?;
Ok(())
}Rust · bounded frame read View code
async fn receive_wave(
recv: &mut quinn::RecvStream,
local_limit: u32,
) -> Result<(Header, Vec<u8>), Error> {
// Read structural fields, then validate session rules:
let mut raw = [0u8; 16];
recv.read_exact(&mut raw).await?;
let header = decode_header(raw, local_limit)?;
validate_wave_request(&header)?; // before allocation
let mut body = vec![0u8; header.body_len as usize];
recv.read_exact(&mut body).await?;
let mut trailing = [0u8; 1];
if recv.read(&mut trailing).await?.is_some() {
return Err("extra bytes after one request".into());
}
Ok((header, body))
}The two paths still share bandwidth and congestion control. Independent streams remove an ordering dependency; they do not create separate internet connections. Try dropping sample 2: the stream waits for its gap, while the newest datagram remains useful.
The request is saved. Emma never gets the answer.
The server commits the request, then the connection dies before Emma sees OK. From her client’s point of view, the server might have done nothing.
Retrying on a fresh connection is reasonable. Creating another request is not. FRND carries an operation ID that survives reconnects. The terminal server keeps the recipient and outcome in memory under that operation ID. Repeating the same ID and recipient returns OK; reusing the ID for another recipient returns OOPS/3. A server restart clears this table. A production service should instead save the request’s exact content and its outcome under an authenticated principal[21] and that ID, in the same transaction as the domain change.
- From
- Emma
- To
- Oliver / 42
- Result
- OK · committed
Commit the request.
Emma never sees OK.
Replay the saved result.
A dropped packet alone is repaired by QUIC. This failure ends the connection after the domain transaction committed.
Imagine the server saves WAVE, then the connection breaks before Emma gets OK. She cannot tell whether it worked. Sending again must not create a second request.
The client keeps an operation ID before sending. For the production design, one database transaction checks that ID, changes the friendship state, and saves the outcome. A transaction commits all those changes together or none of them. A retry with the same authenticated user, ID, type and body gets the stored answer. The runnable terminal server demonstrates the replay rule with a bounded, process-local table; it does not provide user accounts or durable storage.
If that ID arrives with different content, return a conflict. Concurrent retries must share one atomic claim, usually a unique database constraint. Our test harness uses a lock and memory to demonstrate this; a real service needs durable storage that survives process failure.
Acceptance also needs a precise target. HIGH_FIVE carries the requester’s ID and the original WAVE operation ID. That prevents a delayed acceptance from accidentally accepting a newer request. An obsolete target returns OOPS/6. A retry of an already completed acceptance still gets its saved result.
For this worked profile, one durable writer allocates monotonically increasing operation IDs for each principal. A multi-device profile would need a different allocator because offline devices cannot coordinate one counter.
WAVE state transitions
The transport can deliver a valid WAVE into several application states. The server must define each result before it ships.
| Current state | Application action | Reply |
|---|---|---|
| No relationship | Create a pending request from Emma to Oliver | OK |
| Same request already pending | Keep the existing row; save this operation outcome | OK |
| Oliver has blocked Emma | Do not reveal relationship details | OOPS/2 · forbidden |
| Emma targets herself | No state change | OOPS/7 · invalid state |
| Oliver already waved at Emma | Require Emma to HIGH_FIVE that WAVE | OOPS/7 · invalid state |
| Already friends | No state change | OOPS/7 · invalid state |
| Command targets an old relationship revision | Do not touch the replacement relationship | OOPS/6 · stale |
Saved outcomes last for the account’s lifetime in this design. If you shorten that lifetime, define what happens to a retry that arrives too late. Deleting the record without another guard can make an old request look new.
Wire rules and Rust Open reference
In the terminal demo, the operation key is the operation ID within one server process, and the stored recipient detects conflicting reuse. In the production design, the key becomes authenticated principal plus operation ID, and the exact stored request prevents reuse for different content. The domain change and the replayable result belong in one durable transaction.
Rust test fixture · atomic claim and replay View code
fn commit(state: &mut State, h: &Header, body: Vec<u8>) -> Vec<u8> {
if let Some((old, result)) = state.outcomes.get(&h.op_id) {
return if *old == body {
result.clone()
} else {
frame(0x7f, true, h.op_id, &3u16.to_be_bytes())
};
}
let recipient = u64::from_be_bytes(body[..8].try_into().unwrap());
let relationship = if state.pending.contains_key(&recipient) {
RelationshipState::SamePending
} else {
RelationshipState::None
};
let result = match wave_transition(relationship) {
WaveDecision::CreatePending => {
state.pending.insert(recipient, h.op_id);
state.effects += 1;
frame(0x7e, true, h.op_id, &[])
}
WaveDecision::ReplayOk => frame(0x7e, true, h.op_id, &[]),
WaveDecision::Forbidden => frame(0x7f, true, h.op_id, &2u16.to_be_bytes()),
WaveDecision::Stale => frame(0x7f, true, h.op_id, &6u16.to_be_bytes()),
WaveDecision::InvalidState => frame(0x7f, true, h.op_id, &7u16.to_be_bytes()),
};
state.outcomes.insert(h.op_id, (body, result.clone()));
result
}This embedded fixture, like the terminal demo, uses a mutex and memory. A deployed server needs an authenticated principal, a unique database constraint, and storage that survives process failure.
A delayed acceptance must also target the right request. HIGH_FIVE names Emma and the original WAVE ID, so an obsolete target returns “stale” instead of changing a newer relationship. Concurrent retries need a unique transactional claim. A flag labelled “idempotent[22]” would not perform any of this work.
The congestion window is shared. Which stream uses it next?
By this point, FRND can have several reliable streams ready at once. Imagine a 2 MB history download already buffered when a 120-byte chat message appears. QUIC congestion control decides how much the connection may put on the network. It does not know which application work is latency-sensitive.
The sender therefore needs a small scheduling policy. Quinn transmits locally buffered data from higher-priority streams before lower-priority streams. Mark the chat stream interactive and the history stream background, and the short message can use the next available send opportunity instead of waiting behind bulk data.
This reduces queueing delay inside our sender when the connection is busy. It does not shorten the path RTT, enlarge the congestion window, bypass flow control, or guarantee when the peer processes the message.
What runs today: the terminal client sends one WAVE at priority 0, and the terminal server processes one WAVE at a time per connection. The two-class queue below is the next scheduling step for an application that has interactive and background work buffered together.
Before · no latency-aware scheduling: the connection can send again, but the 2 MB history stream gets the next opportunity. The 120-byte message remains in the local queue.
The congestion controller sets the connection’s send budget. Priority only chooses which locally buffered stream uses that budget next.
Independent streams remove cross-stream ordering, but they still compete for one connection’s sending capacity. Without a policy, a bulk transfer can add avoidable queueing delay before a small interactive message.
Congestion control decides how much the connection may send. Flow control decides how much the receiver will accept. Stream priority decides which locally buffered stream supplies bytes when sending is possible.
Use a few local classes such as interactive and background. Measure queueing time and tail latency, and include an ageing or fairness rule so a long-running background stream still moves. FRND/1 keeps this out of the wire header because each endpoint schedules its own outgoing work.
Priority is a local implementation policy, so FRND does not put it in the wire header. Set it before buffering data, keep the number of classes small, and let background work make progress so it cannot starve. Quinn notes that changing a stream with pending data may take effect only after that data is sent. See Quinn’s set_priority() contract.
let (mut send, recv) = connection.open_bi().await?;
let priority = match work {
Work::Interactive => 10,
Work::Background => -10,
};
send.set_priority(priority)?;
// Both classes still share QUIC congestion and flow control.Pong should not need another transport stack.
Campfire is a useful first app, but a second one reveals what we accidentally baked into the protocol. Pong has no chat-history screen. It does have durable match results and rapidly ageing paddle positions.
A new adapter gives those operations their own schemas. Scores use reliable operations and can only be submitted by an authorized match authority. Paddle input uses datagrams with sequence numbers. The server validates that input and computes the game state.
The adapter turns conversations into FRND messages. Select Pong to reuse the same transport for match state.
Keep the code in three pieces: the codec knows bytes; the session knows connection rules; the application adapter knows what a command should do in your app.
After validation, translate a WAVE frame into a command such as Wave { operation_id, recipient }. A production adapter passes it to the friendship service with the authenticated user. The terminal demo stops at the shared credential gate. The service returns the saved outcome; the protocol code turns that outcome into reply bytes.
Campfire can add CHAT and TYPING. Pong can define paddle input and authorized score updates. Both reuse the connection and framing code, but each needs its own message schemas and permission checks. Select one app profile during HELLO so both ends agree on the vocabulary.
Build WAVE first. The additional app messages here are design sketches; they are not a finished chat or game implementation.
Wire rules and Rust Open reference
The codec returns typed commands only after structural validation. In a production service, the adapter receives that command with an authenticated principal and owns application permissions and state transitions. The current terminal profile has no per-user principal.
Rust · protocol/application boundary View code
enum Command {
Wave {
operation_id: u64,
recipient: u64,
},
HighFive {
operation_id: u64,
requester: u64,
wave_operation_id: u64,
},
}
// Called only after frame and session validation.
// Outcome is returned after the application's atomic transaction.
trait Adapter {
async fn apply(&self, principal: u64, command: Command) -> Result<Outcome, DomainError>;
}The shared codec understands frames. The session layer understands setup, deadlines, and retries. Campfire understands conversations; Pong understands matches. Select either app above and the reason for streams versus datagrams stays the same.
The same stream carries the request and its answer.
Setup has already accepted the shared experiment credential. Emma’s client opens one bidirectional QUIC stream for operation 7. Her sending direction carries a 24-byte WAVE naming user 42, Oliver, and then ends with FIN.
The server does not reply merely because bytes arrived. It waits for the complete frame, validates it, saves one pending request, and only then sends OK on the stream’s other direction. Emma can show “request sent” after that OK arrives.
Press Run exchange to follow one WAVE and its result.
Start with one local client, one local server, and WAVE. You do not need Campfire’s UI, friend categories, or Pong to prove the protocol works.
- Trace setup. Check the pinned
frnd-lancertificate, matching ALPN, preface, shared-credential HELLO, and setup reply. - Trace one WAVE. Follow
wave()into the server decoder, state transition, transaction, and reply. - Break the reply. Commit, interrupt the connection, reconnect, and verify the retry produces one effect.
- Replace in-memory storage. Add durable transactions, real application identity, authorization, and service-wide resource limits.
The native harness passed 12 tests with Rust 1.98.1 and Quinn 0.11.12. The embedded browser module proves the same frame validation runs as Rust/WASM; it does not open QUIC or write a database row.