onionwire/docs/PROTOCOL.md
rust-dev b8c52ca97d
All checks were successful
ci / test (pull_request) Successful in 19m52s
ci / sdk (pull_request) Successful in 2m16s
pay: domain-separate tip and gate legacy signature acceptance
`tip` was the one payment frame with no domain tag: sign_tip signed the
LF-joined fields, so its signature could be confused with any other
newline-joined preimage. Mirror inv/rcp: sign_tip now emits
"onionwire-tip-v1" || 0x00-separated txid/amount/address/memo/ts, and
verify_tip tries that form then the historical layout.

Legacy acceptance is now one switch instead of nine call sites:
`pay::LEGACY_SIGS` (default true) plus `pay::legacy_sigs()`. Every v1 /
concat fallback reads it — the `onionwire:v1` invite string and its two
historical signature forms, `loc`, `inv`, `rcp`, and `tip`. `prf` is not
gated here because src/profile.rs is outside this card's file scope; the
spec says so.

Tests: legacy-on keeps every untagged form verifying (incl. a new tip
case); legacy-off rejects each untagged form while the tagged form still
verifies (loc, inv, rcp, tip, invite); sign_tip is pinned to the tagged
layout.

docs/PROTOCOL.md gains the emitted/accepted table per signed frame and
the mixed-fleet consequence.
2026-10-22 22:23:44 -04:00

43 KiB
Raw Permalink Blame History

OnionWire protocol (v1)

This is the wire protocol. A second implementation should be able to interoperate from this document without reading the Rust.

It is not an IETF RFC. It describes what this repository speaks today (frame versions 1 and 2, invite schemes onionwire:v2 (emit) and onionwire:v1 (decode only)). There has been no public third-party audit. Arti onion services are experimental upstream.

Related: threat model, audit notes.

What this is not

OnionWire is not Tox, not Tox-over-Tor, not XMPP, and not “a messenger plus a SOCKS proxy.”

Tox (including ToT) OnionWire v1
Discovery DHT + bootstrap nodes Out-of-band invite only
After lookup Direct IP or TCP relay (SOCKS if you forced it) v3 onion ↔ v3 onion
Address Tox ID lives in the DHT ed25519 pubkey is identity; onion is a locator
Offline send Expected (relays / retry) Queued locally, retried peer-to-peer (no relay)
Mixed clearnet ToT can still talk to non-Tor Tox No clearnet peers

There is no directory, no name server, no introduction point of our own, and no UDP at the application layer.

Roles and keys

Each install holds:

  • Identity — ed25519 keypair. The 32-byte public key is the person. Roster primary key. Displayed as 64 lowercase hex chars (the fingerprint).
  • Prekey — x25519 keypair. This is the Noise IK static. It is long-lived — rotate it with F8, which hard-cuts every stored session. Rotating the onion (F4) does not rotate it.
  • KEM key — ML-KEM-768 (FIPS 203) keypair. The 1184-byte encapsulation key travels in a v2 invite as kem=; the 64-byte decapsulation seed lives in the SQLCipher store beside identity_sk. F8 rotates it together with the prekey, with the same hard cut (stored ratchet state is dropped and every friend re-pastes the invite).
  • Onion — Tor v3 address. Locator only. Disposable.

A friend is {identity_pk, current_onion, current_prekey_pk, kem_pk?}. Pasting the same identity k updates the locator, prekey and KEM key on that row. It never creates a second person. kem_pk is absent only for a friend added from a legacy onionwire:v1 invite; such a friend is classical (see No downgrade).

Petnames, chat history, and the optional Monero wallet RPC are local. They are not on the wire.

Transport

  1. Each peer publishes a Tor v3 onion service (in-process Arti in this tree).
  2. Application port is 80.
  3. The sender opens a Tor circuit to (friend.onion, 80), runs the handshake, sends one application frame, and drops the circuit.
  4. File transfer is N independent sessions (one handshake per chunk). There is no multiplexed long-lived stream in v1.

If the onion is down, a chat send is persisted to the local outbox and retried by a background worker with exponential backoff (30s, doubling, capped at 30 min; 8 attempts, then terminal Failed). There is no server and no store-and-forward relay: each attempt is a fresh handshake straight to (friend.onion, 80), exactly as above. Retries fire on a timer, on unlock/foreground, and whenever that peer is heard from (successful handshake or a connect to that onion). A protocol failure — signature mismatch, unknown frame, oversize — is not a transport failure and is never queued.

File transfer and payment frames stay fail-closed: they are one-shot and are not queued. The locator-push path retries for 180 seconds and then gives up.

Incoming rendezvous accepts are token-bucket limited: 30 per 60s, burst 10. Excess is dropped before handshake. That is availability, not anonymity.

Framing

Every Noise handshake message and every ciphertext is wrapped:

uint8  version     = 1 (normal) | 2 (PQ handshake prelude)
uint32 length      = big-endian body length
uint8  body[length]
  • version = 1 is Noise msg 1, msg 2, an identity proof, or one application ciphertext. It is unchanged from v1 of this document.
  • version = 2 is the PQ handshake prelude. Its body is uint16 ct_len (big-endian) followed by exactly ct_len bytes of ML-KEM-768 ciphertext. ct_len MUST be 1088. The prelude may only be the first frame of a session; the initiator sends exactly one, then Noise msg 1 with version = 1. read_frame (used after the opening frame) rejects version = 2.
  • length MUST be ≤ 65535. Check the length before allocating the body.
  • Other version values are a hard fail (close the stream).
  • Length that does not match the bytes on the wire is a hard fail.

length still reveals the exact ciphertext size. Chat hides it by padding the plaintext to a bucket before encryption (see Length buckets). Other frame types are not padded.

Length buckets

Normative for chat. A chat line is padded to one fixed ladder before the ratchet encrypts it, so the padding is inside ChaCha20-Poly1305, inside the Noise session, and authenticated by both. An observer sees a ciphertext whose length is one of the ladder values (plus constant overhead), never the body length.

Ladder — padded-plaintext sizes in bytes:

256, 512, 1024, 2048, 4096, 8192, 16384, 32768

Ratchet plaintext encoding:

uint16 pad_len       big-endian
uint8  body[..]      the chat line
uint8  fill[pad_len] random bytes, contents ignored
  • The padded plaintext MUST be exactly the smallest ladder value that is at least 2 + body_len. pad_len = bucket - 2 - body_len.
  • Empty and short bodies both pad to 256; a 254-byte body fits the 256 bucket with pad_len = 0.
  • fill is fresh random bytes. Its contents carry no meaning.
  • A body larger than 32766 bytes does not fit the ladder and MUST fail closed (it is a protocol error, never queued).

Receiver rules:

  • The total decrypted length is not required to be a ladder value. Only the header is normative, so a peer with a different ladder still interoperates.
  • pad_len is the only authority for the body length. A receiver MUST NOT trim trailing zeros, strip a repeated fill byte, or otherwise infer the boundary from content: a body that legitimately ends in the same byte as the fill round-trips unchanged.
  • A plaintext shorter than 2 bytes, or one whose pad_len exceeds len - 2, MUST be rejected as a hard failure before anything is appended, rendered, or persisted. The ratchet state is not advanced.
  • Unpadded frames are not accepted as if they were a bucket: if the first two bytes do not describe a consistent pad_len, the frame fails closed.
  • Padding is a plaintext-layer change and is independent of the rat frame version: a classical (0x01) and a hybrid (0x02) frame carry the same padded plaintext. See Ratchet (chat layer) for the header each version adds.

The ladder floor stays at 256 even though a hybrid frame's floor is over 2.6 KB. The ladder schedules the plaintext, and a hybrid step's size is dominated by its 2312-byte header — the 256 bucket is a rounding error there, so raising the floor would not conceal the header and would only inflate classical (0x01) chat, which is still the epoch-0 and legacy-friend path. A second, version-specific ladder would double the normative surface for no privacy gain; the bucket boundaries remain observable within each size class either way.

Minimum observable size depends on the rat header version:

  • Classical (0x01): rat 4 + version 1 + header 40 + nonce 12 + bucket 256
    • tag 16 = 329-byte rat frame; the Noise transport adds its 16-byte tag and the framing header adds 5 bytes, so the smallest classical chat frame on the wire is 350 bytes.
  • Hybrid (0x02): rat 4 + version 1 + header 2312 + nonce 12 + bucket 256
    • tag 16 = 2601-byte rat frame, i.e. 2622 bytes on the wire. The 2272 extra header bytes are the sender's ML-KEM-768 ratchet key and the ciphertext to the receiver's; the 256-byte bucket applies unchanged inside them.

Both floors hold whatever the body length. The 32768 bucket yields a 32862-byte classical frame and a 35113-byte hybrid frame, both under the 65535 Noise body cap.

The ML-KEM-768 ciphertext appears in two places: the one-shot handshake prelude (version = 2, 1095 bytes once per session), and every rat header after the first hybrid ratchet step (kem_pub[1184] || kem_ct[1088]). Epoch 0 of a chat is always classical, so the first rat frame of a friend relationship uses the 40-byte header.

fil chunks are deliberately not padded. They are raw file bytes paced through the accept token bucket, and padding them would either cut the usable chunk size or spend the 65535 frame cap on fill; the chunk size stays as specified under fil — file chunk.

This hides length, not timing: one Noise session per message, retry cadence and circuit timing are unchanged and remain accepted costs (see docs/THREAT_MODEL.md).

Handshake

Noise pattern: Noise_IK_25519_ChaChaPoly_BLAKE2s

Prologue (both sides, before the first Noise handshake message):

  • Classical (no PQ prelude, friend row has no kem_pk): onionwire-v1 (12 ASCII bytes, no NUL).

  • Hybrid (a PQ prelude was sent/received): the exact byte layout

    "onionwire-v2" || 0x00 || ct || 0x00 || ss_kem
    

    where onionwire-v2 is 12 ASCII bytes, ct is the 1088-byte ML-KEM-768 ciphertext from the prelude, and ss_kem is the 32-byte shared secret. Initiator: (ct, ss_kem) = ML-KEM-768.Encapsulate(friend.kem_pk). Responder: ss_kem = ML-KEM-768.Decapsulate(own_dk, ct). Both therefore commit to the ciphertext and to the PQ secret: a modified ct changes the prologue (and decapsulates to implicit-rejection garbage), so the Noise handshake fails before msg 2.

Handshake payloads are empty. A non-empty decrypted handshake payload is a hard fail.

Sequence

Initiator knows the responder’s identity pubkey (pinned), x25519 prekey and (if kem_pk is present) ML-KEM key from the invite (or roster).

  1. PQ prelude — only when the responder’s roster row has kem_pk: initiator → responder, one version = 2 frame carrying the ML-KEM ciphertext. If the row has no kem_pk, no prelude is sent and the prologue is onionwire-v1.
  2. IK msg 1 — initiator → responder (framed, version = 1). Responder’s Noise static is the invite spk.
  3. Responder looks up the remote static in the roster by prekey. Unknown prekey → close. This is how the answerer learns who is calling. It then compares the friend row with how the session opened (see No downgrade) and only then sends msg 2.
  4. IK msg 2 — responder → initiator (framed).
  5. Both sides enter transport mode. Handshake hash h is 32 bytes (BLAKE2s).
  6. Identity proof, initiator first — transport-encrypt a 96-byte proof, send as one frame.
  7. Identity proof, responder — same, one frame.

Proof encoding (96 bytes):

bytes[32]  identity_pk     // ed25519
bytes[64]  ed25519_sign(identity_sk, h)

Verify:

  • proof length is exactly 96
  • identity_pk equals the pinned identity (initiator: invite/roster k; responder: roster row found via prekey)
  • ed25519_verify(identity_pk, h, sig) succeeds

Any mismatch is a fingerprint failure. Do not send application data. Do not retry with a different key.

After proofs, the initiator sends one transport frame of application ciphertext and closes. The responder decrypts that one frame and closes.

Compromise of the long-term x25519 prekey does not decrypt past transport (IK + ephemeral). It does allow future impersonation at the Noise layer until the peer notices the identity proof failing — so the proof is not optional. With a PQ prelude, the transport secrets also mix ss_kem; a later cryptographically relevant quantum adversary that recorded the session still needs ML-KEM-768 broken to recover the Noise transport keys.

No downgrade

The rule comes from the roster row, never from what arrives on the wire:

  • friend row has kem_pk → always send the prelude; the responder requires one. A version = 1 opening from that peer is rejected with prelude required before msg 2, the identity proofs, and any application frame.
  • friend row has no kem_pk (added from a legacy v1 invite) → classical session with the onionwire-v1 prologue. The UI labels the friend as lacking PQ protection.
  • A prelude is not accepted for a friend row with no kem_pk: the responder rejects it with unexpected prelude before msg 2, so the wire cannot upgrade a classical row. kem_pk only enters a row from a signed v2 invite.

A v1-only build dialling a v2 install cannot parse version = 2 as an opening frame and hard-fails, and a v2 build will not send a prelude to a v1 peer. That mixed-fleet break is accepted; there is no fallback path.

Application plaintext

After decrypt, classify the plaintext:

Prefix (4 bytes) Kind If unknown / invalid
rat Double Ratchet chat frame (see Ratchet) drop
loc locator update drop
prf profile drop
inv Monero invoice drop
rcp Monero receipt claim drop
tip Monero tip (receipt + memo) drop
png ping (reserved; classify and drop) drop
fil file chunk drop
[a-z][a-z][a-z] unknown typed frame drop (not chat)
anything else chat store as a chat line

rat is classified before the [a-z]{3} catch-all, so a peer that does not implement the ratchet drops a chat frame instead of rendering ciphertext as a chat line. Older builds that stored rat -prefixed bytes as chat are obsolete; upgrade both sides.

A peer that does not implement a typed prefix MUST still drop [a-z]{3}<space>… rather than render it as chat.

Chat MUST NOT begin with three lowercase ASCII letters and a space. (Inside a rat frame the plaintext is a chat line and is not re-classified.)

Hex on the wire is lowercase on encode; decode accepts either case. No 0x prefix.

Application-frame signatures

loc, prf, inv, rcp, and tip each carry an ed25519 signature over the fields, not the 4-byte typed prefix. Encode MUST sign the domain-separated form (type tag, then each field, 0x00 separators). Verify MUST accept that form and, for mixed-version peers, the legacy untagged LF-joined layout. Anything else fails closed. Do not emit the legacy layout.

The invite string is separate and uses onionwire-invite-v2 (see Invite).

Legacy acceptance is one switch, LEGACY_SIGS, default on. Every fallback listed below reads it; with it off, verification accepts only the emitted (tagged) form. It is a local capability constant, not a wire field: it is never sent, and a peer cannot negotiate it.

frame emitted accepted inbound
invite onionwire-invite-v2, 0x00-separated over k, o, spk, kem same; onionwire:v1 over onionwire-invite-v1 0x00-separated k,o,spk, or over k || o || spk (legacy only)
loc "onionwire-loc-v1" 0x00 onion 0x00 ts same; onion || LF || ts (legacy only)
prf "onionwire-prf-v1" 0x00 name 0x00 bio 0x00 xmr_addr 0x00 ts same; the four fields joined by LF (not yet gated — see below)
inv "onionwire-inv-v1" 0x00 amount_atomic 0x00 address 0x00 memo 0x00 ts same; the four fields joined by LF (legacy only)
rcp "onionwire-rcp-v1" 0x00 txid 0x00 amount_atomic 0x00 address 0x00 ts same; the four fields joined by LF (legacy only)
tip "onionwire-tip-v1" 0x00 txid 0x00 amount_atomic 0x00 address 0x00 memo 0x00 ts same; the five fields joined by LF (legacy only)

The tag suffixes do say -v1; that is the tag's own version, not the invite string version.

prf is the one frame whose legacy fallback is not yet gated: it is accepted unconditionally in this revision and moving it under LEGACY_SIGS is a separate change.

Mixed-fleet consequence. Older builds verify only the untagged bytes, so they reject every tagged signature from a new sender — including tip , which older builds emitted and verified untagged. That direction needs the peer updated before tips flow. The reverse works while LEGACY_SIGS is on: a new build verifies an old sender's untagged loc/prf/inv/rcp/tip and an onionwire:v1 invite. Turning the switch off is a fleet-wide cutover, not a per-peer choice.

loc — locator update

Sent when the sender rotated their onion and the receiver is reachable.

loc <onion>\n<ts>\n<sig_hex>
  • onion — v3 onion (56 base32 a-z2-7 chars + .onion)
  • ts — unix seconds, decimal ASCII
  • sig_hex — 64-byte ed25519, 128 hex chars
  • the loc prefix is not signed

Current signature (encode this):

ed25519_sign(identity_sk,
  "onionwire-loc-v1" || 0x00 || onion || 0x00 || ascii(ts))

Legacy accept: a signature over onion || LF || ascii(ts) is still accepted on verify while LEGACY_SIGS is on, so old loc frames verify. New loc frames MUST use the domain-separated form. Do not emit legacy.

Apply only if all of:

  • the Noise session’s peer identity is already in the roster
  • signature verifies under that identity
  • ts is strictly greater than the stored onion_updated_at

Otherwise drop. Unknown pubkeys are not inserted from loc. There is no directory: if you rotated while they were offline, they cannot find you until they paste a new invite.

prf — profile

prf <display_name>\n<bio>\n<xmr_addr>\n<ts>\n<sig_hex>

Limits: name ≤ 64 bytes, bio ≤ 512 bytes. No newlines in those fields. xmr_addr may be empty; if non-empty it MUST be a checksummed Monero address (see invoices). The prf prefix is not signed.

Current signature (encode this):

ed25519_sign(identity_sk,
  "onionwire-prf-v1" || 0x00 || name || 0x00 || bio || 0x00 || xmr_addr || 0x00 || ascii(ts))

Legacy accept: a signature over the four fields joined by LF is still accepted on verify. New profile frames MUST use the domain-separated form. Do not emit legacy. This fallback is not yet read through LEGACY_SIGS.

Apply only for an existing friend, valid signature, newer ts. Not a public profile. Not a directory.

inv — invoice (we want to receive)

inv <amount_atomic>\n<address>\n<memo>\n<ts>\n<sig_hex>

amount_atomic is decimal piconero (integer string, > 0). address is a Monero mainnet/stagenet standard, subaddress, or integrated address with a valid Keccak checksum. The inv prefix is not signed.

Current signature (encode this):

ed25519_sign(identity_sk,
  "onionwire-inv-v1" || 0x00 || amount_atomic || 0x00 || address || 0x00 || memo || 0x00 || ascii(ts))

Legacy accept: a signature over the four fields joined by LF is still accepted on verify while LEGACY_SIGS is on. New invoices MUST use the domain-separated form. Do not emit legacy.

The frame is a signed claim, not a payment. It is one-shot: if the peer onion is down, the send fails. There is no queued invoice.

rcp — receipt claim (we paid)

rcp <txid>\n<amount_atomic>\n<address>\n<ts>\n<sig_hex>

The rcp prefix is not signed.

Current signature (encode this):

ed25519_sign(identity_sk,
  "onionwire-rcp-v1" || 0x00 || txid || 0x00 || amount_atomic || 0x00 || address || 0x00 || ascii(ts))

Legacy accept: a signature over the four fields joined by LF is still accepted on verify while LEGACY_SIGS is on. New receipts MUST use the domain-separated form. Do not emit legacy.

Signature proves which friend sent the claim. It does not prove money moved. Local verified=1 only if a user-hosted monero-wallet-rpc returns one transfer row with the same non-empty txid, amount, and address (conjunction, not OR). RPC down or an unsynced daemon → stay unverified. Wallet RPC is loopback HTTP Digest; it is not this protocol.

tip — tip (we paid, with memo)

Sent after a chain transfer, together with rcp . One-shot.

tip <txid>\n<amount_atomic>\n<address>\n<memo>\n<ts>\n<sig_hex>

The tip prefix is not signed.

Current signature (encode this):

ed25519_sign(identity_sk,
  "onionwire-tip-v1" || 0x00 || txid || 0x00 || amount_atomic || 0x00 ||
  address || 0x00 || memo || 0x00 || ascii(ts))

Legacy accept: a signature over the five fields joined by LF is still accepted on verify while LEGACY_SIGS is on. New tips MUST use the domain-separated form. Do not emit legacy.

memo MUST NOT contain newlines. Same address and amount rules as invoices. A peer that does not implement tip MUST drop it as an unknown typed prefix, not render it as chat.

png — ping (reserved)

Classified as ping and dropped. No ping body is defined in v1. Implementations MUST NOT emit png and MUST drop it inbound.

fil — file chunk

Cap: 1 MiB reconstructed file. No resume. One Noise session per chunk.

The sender is responsible for fitting the receiver's documented rendezvous budget (30 accepts / 60s, burst 10). Chunks MUST be paced so the average interval between send attempts stays at least 3s. A sender MAY retry an individual chunk a bounded number of times (this tree: 3). Exhausting retries fails the transfer. No outbox, no resume, no continuation under a new xfer_id.

fil <xfer_id_hex>\n<filename>\n<sha256_hex>\n<idx>/<total>\n<raw bytes>
  • xfer_id — 16 random bytes (32 hex)
  • filename — 1–128 bytes, no /, NUL, newline, ., or ..; no C0/C1 controls or bidi/format marks (U+202A–U+202E, U+2066–U+2069, U+200E, U+200F, U+200B, U+200C)
  • sha256 — SHA-256 of the entire file (64 hex), repeated on every chunk
  • idx is 0-based; total ≥ 1; idx < total
  • last line is raw chunk bytes (not hex), length chosen so the framed Noise ciphertext stays ≤ 65535 (account for a 16-byte Poly1305 tag plus ASCII header)

Chunks MUST arrive in order for a given xfer_id. A bad chunk or hash mismatch deletes the partial. Empty files are one chunk. Successful receive is a chat line [file] name (N bytes), never the raw frame.

Chat

A chat send is ratcheted: the wire form of a chat message is a rat frame (see “Ratchet (chat layer)”), and the plaintext inside that frame is the chat line below, padded to a length bucket first (see Length buckets). A bare chat frame with no typed prefix is still accepted inbound as a chat line (older peers), but MUST NOT be emitted.

UTF-8 is not enforced for chat text: invalid bytes become U+FFFD (the implementation does not drop the row). Control and bidi formatting characters are stripped at ingest and at render: C0 0x00–0x1F except tab and newline, DEL (0x7F), C1 U+0080–U+009F, U+202A–U+202E, U+2066–U+2069, U+200E, U+200F, U+200B, U+200C. U+200D (ZWJ) is kept so emoji sequences stay intact. fil filenames must not contain those characters (tab and newline included). Displayed as a line. A chat line is at most 32766 bytes (the largest bucket minus the 2-byte pad_len header); a longer body is a protocol error, not a queued message. See Length buckets.

Ratchet (chat layer)

Chat is the only application payload that is ratcheted. A chat send is Double-Ratchet encrypted first, and the resulting rat frame is the application plaintext that a normal one-shot Noise session carries (handshake, one application frame, close — see Transport). Nothing else changes about the session.

The ratchet header is inside the Noise transport message, never in clear on the wire. A plaintext header (dh_pub || N || PN) would hand an observer per-message counters and ratchet-key changes for no benefit — the Noise session already hides the frame, so the header is authenticated as AEAD associated data instead.

Frame

"rat "       4 bytes   (0x72 0x61 0x74 0x20)
version      1 byte    0x01 (classical) or 0x02 (hybrid)
-- version 0x01: classical header, 40 bytes
header       40 bytes  dh_pub[32] || N uint32 BE || PN uint32 BE
nonce        12 bytes  random, per message
ciphertext   n+16      ChaCha20-Poly1305 ciphertext || tag

-- version 0x02: hybrid header, 2312 bytes
header      2312 bytes dh_pub[32] || N uint32 BE || PN uint32 BE
                       || kem_pub[1184] || kem_ct[1088]
nonce        12 bytes  random, per message
ciphertext   n+16      ChaCha20-Poly1305 ciphertext || tag
  • dh_pub — the sender's current X25519 ratchet public key (32 bytes).
  • N — the index of this message in the sender's current sending chain, counting from 0.
  • PN — how many messages the sender sent in its previous sending chain.
  • kem_pub — the sender's current ML-KEM-768 ratchet encapsulation key (1184 bytes).
  • kem_ct — an ML-KEM-768 ciphertext (1088 bytes) that the sender encapsulated to the receiver's current ratchet KEM key. It is repeated on every frame of a chain a hybrid step established, so a lost first frame does not wedge the chain.
  • Associated data is the whole header for the version in use, exactly as serialized above. A tampered dh_pub, N, PN, kem_pub or kem_ct therefore fails closed.
  • The ChaCha20-Poly1305 key is the message key from KDF_CK. The 12-byte nonce is random per message, not a chain counter.
  • A chat frame's minimum size depends on the header version, not the body: an empty chat line still pads to the 256-byte bucket. Version 0x01 is 329 bytes (5 + 40 + 12 + 256 + 16); version 0x02 is 2601 bytes (5 + 2312 + 12 + 256 + 16). A hybrid message therefore carries 2272 more header bytes than a classical one. See Length buckets.
  • On the wire those become 350 bytes for 0x01 (329 + the Noise 16-byte tag + the 5-byte framing header) and 2622 bytes for 0x02. The 350-byte floor is the classical case only.
  • A rat frame with no padding at all cannot occur for chat; the bare frame overhead (empty ciphertext plaintext) is 73 bytes for 0x01 (5 + 40 + 12 + 16) and 2345 bytes for 0x02 (5 + 2312 + 12 + 16).
  • A receiver MUST reject a frame without the rat prefix, a version other than 0x01/0x02, or a frame shorter than its version's minimum.
  • The frame must fit the Noise body cap (65535 bytes, including the 16-byte Poly1305 tag), so a rat frame is at most 65519 bytes. A maximal hybrid plaintext is therefore 63174 bytes, still far above the chat line limit.
  • A rat frame is one Noise body: the fil chunk-pacing rules do not apply, and the receive token bucket counts rendezvous accepts, not bytes, so the larger hybrid header changes neither.

Because the header rides inside Noise, an observer sees one opaque ciphertext per message: no message counts, no ratchet keys, and nothing that marks a first message of a chain versus a later one.

KDFs

Signal's constructions, with a second domain for hybrid steps:

KDF_RK(root, dh_out):                                  # v1: epoch 0, classical friends
    okm = HKDF-SHA256(salt = root, ikm = dh_out,
                      info = "onionwire-ratchet-v1-kdfrk", L = 64)
    new_root    = okm[0..32]
    chain_key   = okm[32..64]

KDF_RK_hybrid(root, dh_out, ss_kem):                   # v2: every hybrid ratchet step
    okm = HKDF-SHA256(salt = root, ikm = dh_out || ss_kem,
                      info = "onionwire-ratchet-v2-kdfrk", L = 64)
    new_root    = okm[0..32]
    chain_key   = okm[32..64]

KDF_CK(chain_key):
    message_key    = HMAC-SHA256(chain_key, 0x01)
    next_chain_key = HMAC-SHA256(chain_key, 0x02)

HKDF is RFC 5869 with SHA-256, HMAC is SHA-256. The two KDF_RK forms differ in both input shape and info string on purpose: ikm is 32 bytes for v1 and dh_out || ss_kem (64 bytes) for v2, and the domain strings are distinct. There is no way to derive a v2 chain without a real ss_kem, and a classical derivation can never be mistaken for a hybrid one.

Each side of an epoch derives its chains from one shared input with KDF_RK called twice:

epoch_chains(root, shared) -> (new_root, ck_lo, ck_hi):            # v1
    (root1, ck_lo) = KDF_RK(root, shared)
    (root2, ck_hi) = KDF_RK(root1, shared)
    new_root = root2

epoch_chains_hybrid(root, dh_out, ss_kem) -> (new_root, ck_lo, ck_hi):   # v2
    (root1, ck_lo) = KDF_RK_hybrid(root, dh_out, ss_kem)
    (root2, ck_hi) = KDF_RK_hybrid(root1, dh_out, ss_kem)
    new_root = root2

lo is the lexicographically lower of the pair's two ratchet public keys and hi the higher, comparing the 32 raw bytes. The chain a peer sends on is ck_lo if sender_pub <= receiver_pub, else ck_hi; the receiving chain is the other one. The epoch's chains are a pure function of the unordered pair, and the second KDF_RK call's root is the epoch's new root.

Bootstrap

The bootstrap epoch is derived, never exchanged: the Noise handshake is frozen and carries no payload, so there is no wire field to hand over an initial ratchet public key. Both peers instead derive it from key material they already have from the invite/roster (identity pubkey and signed prekey):

shared       = X25519(my_prekey_sk, peer_prekey_pk)      // 32 bytes
hk           = HKDF-SHA256(salt = "onionwire-ratchet-v1-bootstrap",
                           ikm = shared)
root_key     = hk.expand("root", 32)
my_secret    = hk.expand("ratchet-key" || my_identity_pk, 32)
peer_secret  = hk.expand("ratchet-key" || peer_identity_pk, 32)

my_ratchet   = keypair(my_secret)      // x25519 secret/public + ML-KEM-768
peer_ratchet = keypair(peer_secret)    // derived by both sides, same values

state = bootstrap(root_key, my_ratchet,
                  peer_ratchet.x25519_pub,
                  peer_ratchet.kem_pub if the friend row carries kem_pk else None)

HKDF.expand above is the RFC 5869 expand step (no second extract). The two identity public keys are public (invite/roster), so either peer computes its own secrets and the peer's, and both agree with no new wire field. The ML-KEM half of each initial ratchet keypair is derived from that keypair's X25519 secret, so the peer's KEM ratchet public key needs no wire field either:

kem_seed   = HKDF-SHA256(salt = "ratchet-kem", ikm = x25519_secret).expand("seed", 64)
kem_pub    = ML-KEM-768 encapsulation key from kem_seed

Then:

shared               = DH(my_secret, remote_pub)
(new_root, ck_lo, ck_hi) = epoch_chains(root_key, shared)      // v1: epoch 0 is classical
send_ck              = chain_for(my_pub, remote_pub)     // ck_lo or ck_hi
recv_ck              = chain_for(remote_pub, my_pub)
send_n = recv_n = 0, PN = 0, established = false

Fresh entropy enters at the first DH ratchet step; the bootstrap epoch itself is prekey-bound (see THREAT_MODEL.md).

Hybrid ratchet steps, and why epoch 0 stays classical

Every ratchet keypair is now {x25519, ML-KEM-768}. On a step the peer that rotates encapsulates to the receiver's current ratchet KEM key and puts kem_pub (its new key) and kem_ct (that ciphertext) in the header. The receiver decapsulates with the key it already holds, so both sides feed KDF_RK_hybrid the same (X25519 DH, ss_kem) pair and derive the same chains. No extra round trip is added: the KEM material rides on the rotation frame itself, and is repeated on every later frame of that chain so a lost first frame is harmless.

Epoch 0 cannot be per-session, so it stays classical. Epoch 0's root is derived from the two long-lived signed prekeys precisely so that neither side needs a wire field and both converge even when both send first. The hybrid Noise session does carry an ss_kem (see Transport), but each chat message is its own one-shot Noise session: a fresh encapsulation, therefore a different ss_kem for every dial, and different sessions for the two peers' first sends. Binding the epoch-0 root to that secret would make the root a function of which session carried which message, so:

  • two peers sending first would derive different epoch-0 roots and could not read each other at all, and
  • even a single direction would break at the second message, because message 2 would arrive on a different Noise session with a different ss_kem while the receiver still holds the root from message 1.

There is no way to keep both "no wire field, both-send-first convergence" and a per-session secret in epoch 0 without replacing the one-shot session model, which is out of scope. Epoch 0 is therefore derived exactly as before, with the v1 KDF_RK, and the KEM secret enters at the first rotation after established. The first rotation is hybrid even for the bootstrap tie-break rotation: that is what closes the window two round trips in.

Consequences, stated exactly:

  • Every frame sent before the first hybrid step (the whole of epoch 0, in both directions, plus any outbox row encoded on it) is protected by X25519 only. A harvest-now adversary who later breaks X25519 can read those frames. This is the residual window and it does not shrink with more messages, only with the first rotation.
  • Every frame on a chain established by a hybrid step additionally requires the ML-KEM-768 secret. Breaking X25519 alone does not open it.
  • A frame that carries a new dh_pub but no KEM section is rejected (hybrid step required); a KEM section on a non-KEM friend is rejected too. There is no classical fallback once a session has KEM material.

Convergence when both peers send first. Either peer may send immediately on the bootstrap epoch, so two peers can each build a sending chain before either has received anything. Because the epoch's two chains come from the unordered pair, both derive both directions and each sends on its own, with no initiator/responder role. The only tie-break needed is for the first rotation: the peer whose ratchet public key is lexicographically lower rotates — but only after it has received a bootstrap-epoch frame (see established below); the other adopts that new key as a normal DH step and only then rotates. From the second epoch on, every rotation is a reply to an adopted key, so no tie-break is needed and the ratchet alternates.

Why it stays in lockstep. A DH ratchet step happens only on a frame whose dh_pub has not been adopted yet, and the side that steps is the side that receives. A peer cannot rotate twice without having received the other side's rotation first, so at most one rotation is ever in flight, and both peers feed KDF_RK the same (root, dh) pairs in the same causal order.

Receiving

On a decrypted rat frame (the outer Noise session has already been verified, so the peer identity is pinned):

  1. Parse; reject a bad prefix or version, and a frame shorter than its version's minimum (73 bytes for 0x01, 2345 for 0x02).
  2. If (dh_pub, N) is in the skipped-key store: open with that key, delete it from the store, deliver. A replay of the same frame then fails closed because the key is gone.
  3. Else if dh_pub equals the adopted remote ratchet public key, this is the current receiving chain:
    • N < recv_n → reject (message key already used).
    • N - recv_n > MAX_SKIP → reject.
    • Derive message keys for recv_n .. N into the skipped store, derive the key for N, open, set recv_n = N + 1.
    • On the first frame received in this state (established == false): set established, and if my_pub < remote_pub, rotate the sending chain — fresh {x25519, ml-kem} keypair; for a hybrid friend encapsulate to remote_kem_pub and derive with epoch_chains_hybrid(root, DH(new_secret, remote_pub), ss), for a classical friend epoch_chains(root, DH(...)); new sending chain for new_pub → remote_pub; PN = old send_n; send_n = 0. The receiving chain is untouched.
  4. Else it is a ratchet key not adopted yet: run a full DH ratchet step. A session that holds remote_kem_pub rejects a frame with no KEM section, and a session without KEM material rejects a frame that has one.

DH ratchet step

On a frame whose dh_pub differs from the adopted remote public key:

  1. Retire the current receiving chain. PN is how many messages the peer sent in it, so:
    • PN < recv_n → reject (used message key).
    • PN - recv_n > MAX_SKIP → reject.
    • Derive recv_n .. PN into the skipped store, tagged with the retired remote public key, so stragglers of the old chain still decrypt.
  2. Receiving half of the step, on the pair (my current secret, frame.dh_pub): shared = DH(my_secret, frame.dh_pub). For a hybrid step also ss_kem = ML-KEM.Decaps(my_current_ratchet_kem_secret, frame.kem_ct), then (root_a, ck_lo, ck_hi) = epoch_chains_hybrid(root, shared, ss_kem); otherwise (root_a, ck_lo, ck_hi) = epoch_chains(root, shared). recv_ck = chain_for(frame.dh_pub, my_pub), then open the frame with this chain exactly as in step 3 above (it must be within MAX_SKIP of index 0).
  3. Sending half: generate a fresh ratchet keypair {x25519, ml-kem}. For a hybrid step encapsulate to frame.kem_pub ((kem_ct, ss_kem) = ML-KEM.Encaps(frame.kem_pub)), derive (root, ck_lo, ck_hi) = epoch_chains_hybrid(root_a, DH(new_secret, frame.dh_pub), ss_kem) and keep kem_ct in the state so every frame of the new sending chain carries it; otherwise epoch_chains(root_a, DH(...)). send_ck = chain_for(new_pub, frame.dh_pub), remote_pub = frame.dh_pub, remote_kem_pub = frame.kem_pub, PN = old send_n, send_n = 0, established = true, recv_hybrid = frame has a KEM section.
  4. The frame is opened with the new receiving chain's message key. If the AEAD open fails, nothing is applied: the state must be byte-identical to before the frame. (A tampered kem_ct yields a different ss_kem through ML-KEM's implicit rejection, and the AEAD then fails; a tampered kem_pub is inside the AAD, so it fails the same way.)

The next frame this side sends therefore carries the new dh_pub, which is what lets the peer step too.

Bounds and replay

  • MAX_SKIP = 2000. Checked on both jumps: N - recv_n on the current chain and PN - recv_n while retiring one. jump == 2000 is accepted, jump == 2001 is rejected (MaxSkipExceeded) and leaves the state untouched.
  • MAX_SKIPPED_KEYS = 2000 stored message keys. When the store is at the cap, inserting a new key evicts the oldest-inserted entry first — insertion order, not N order.
  • A skipped key is removed the moment it decrypts a frame, so a replayed frame fails closed (UsedMessageKey or an AEAD failure).
  • Every bound is validated before any state mutation. A rejected or tampered frame must leave the state byte-identical.

State at rest

ratchet_sessions in the SQLCipher store: one row per friend (friend_id primary key, FOREIGN KEY → friends.id ON DELETE CASCADE, state BLOB NOT NULL, updated_at). The blob is version byte 0x02 followed by the implementation's serialized ratchet state:

0        version 0x02
1..211   fixed prefix: root, local secret/public, remote public,
         send_ck/send_n, recv_ck/recv_n, PN, established, flags,
         skipped-count
then     remote ratchet KEM public key (1184 bytes)  if flag 0x01
then     pending KEM ciphertext (1088 bytes)         if flag 0x02
         (flag 0x04 marks a receiving chain established hybrid)
then     skipped keys, dh_pub[32] || n u32 BE || message key[32]

The state is device-local: it is never transmitted, and its layout is not part of this wire protocol. The store is encrypted as a whole, so the blob is ciphertext on disk.

Hard cut. Version 0x01 is the pre-hybrid layout, which had no KEM ratchet key and no pending ciphertext. It is dropped, not migrated: on load, a v1 blob is deleted and the session re-bootstraps from the two prekeys, exactly the way an F8 prekey rotation drops state. Nothing is half-read, and epoch 0 comes back identical because its derivation did not change. A corrupt v2 blob or one written by a newer version is reported as an error instead — those are not an old format, and silently resetting them would be a downgrade. The same cut applies to any peer whose prekey or KEM key changes.

Not ratcheted

loc , prf , inv , rcp , tip , png and fil frames — and every file chunk — keep the one-shot Noise shape: one handshake per application frame, no ratchet, no persistent session. Only chat is ratcheted.

Prekey change resets the epoch

A peer whose prekey changes invalidates the bootstrap epoch on both sides, and the stale state is dropped locally, so the next chat frame starts a fresh bootstrap epoch. Frames sent under the dropped epoch are not readable afterwards. There is no key-confirmation exchange and no in-band reset command; the new invite is the signal.

Invite (out of band)

Not a QR graphic. A single ASCII string, max 4096 characters:

onionwire:v2:k=<64 hex>:o=<v3 onion>:spk=<64 hex>:kem=<base64url pk>:sig=<128 hex>

Field order in the string is not significant; duplicate or unknown fields are rejected. k is the identity pubkey, spk the x25519 prekey, o the current locator, and kem the ML-KEM-768 encapsulation key (1184 bytes) encoded as unpadded base64url (1579 characters). A v2 invite is about 1.9 KB, still well under the 4096-character cap.

Current signature (encode this):

ed25519_sign(identity_sk,
  "onionwire-invite-v2" || 0x00 || k_ascii || 0x00 || o_ascii || 0x00 ||
  spk_ascii || 0x00 || kem_ascii)

k_ascii / spk_ascii are the hex strings as they appear in the invite (lowercase); kem_ascii is the base64url field value after kem=. Because the signature covers kem_ascii, removing the field or substituting a different key fails verification — that is the anti-strip/anti-substitution property.

Legacy accept (onionwire:v1): a v1 invite has no kem field. Decode accepts it while LEGACY_SIGS is on and yields a friend with no kem_pk, i.e. a classical peer; with the switch off a v1 invite fails closed. A v1 signature is accepted in either historical form: the tagged "onionwire-invite-v1" || 0x00 || k || 0x00 || o || 0x00 || spk or the raw concatenation k || o || spk (no tag, no separators), so old invites keep verifying. onionwire:v2 MUST have kem= and MUST verify over the v2 domain; a v2 body relabelled v1 does not verify.

Encode MUST emit onionwire:v2 only. Unknown k: prompt. Same k: update locator, prekey and KEM key on that row (never a second friend), and drop the stored ratchet state if either key changed.

What v1 will not grow into

No DHT, no directory server, no hosted/server-side outbox, no XMPP/Prosody, no C-tor fallback, no multi-device, no A/V, no STUN/ICE/WebRTC, no system DNS for friends.

A local-only chat retry queue is in v1. It is not a mailbox and it never leaves the device. “No outbox” in this document means no server-side store-and-forward.

Those are how Tox-over-Tor leaks (UDP DHT, mixed clearnet, “just one direct path”). They are out of scope, not postponed.

Versioning

  • Frame version 1 (normal), frame version 2 (PQ prelude), invite onionwire:v2 (emit) and invite onionwire:v1 (decode only) are this document.
  • A new handshake prologue or a new invite scheme is a breaking change. The hybrid prologue and the prelude are exactly that: v1 peers cannot talk to a friend that has a kem_pk.
  • New typed prefixes (xyz ) are backward compatible if old peers drop them.
  • The rat frame has its own version byte (0x01 classical, 0x02 hybrid). A different ratchet frame layout or a different KDF is a breaking change for chat only: peers that disagree cannot read each other's chat, and every other frame keeps working. A 0x02 frame from a peer whose roster row says classical, or a 0x01 step from a hybrid peer, is rejected.