PROTOCOL.md gains a 'Ratchet (v1 chat layer)' section written so a second implementation can interoperate from the text alone: byte-exact frame layout (rat , 0x01, dh_pub||N||PN as header and AAD, 12-byte nonce, ChaCha20-Poly1305), the KDF_RK/KDF_CK constructions and the role-separated epoch rule, the derived bootstrap epoch, the receive and DH-step rules, the MAX_SKIP/MAX_SKIPPED_KEYS bounds with the replay rule, the SQLCipher ratchet_sessions row, and what stays unratcheted. THREAT_MODEL.md gains the corresponding gains (per-chain forward secrecy, PCS after a DH step, header not on the wire) and honest limits (skipped-key window, the prekey-bound bootstrap epoch, no deniability, no one-time prekeys, compromised endpoint out of scope, no metadata gain, the no-server- outbox lock untouched) plus the amended transport wording. README.md documents the operator-visible consequence: no reset command yet, prekey change / invite re-paste is the only recovery, /wipe keeps the state, and a desync is currently stderr-only.
585 lines
24 KiB
Markdown
585 lines
24 KiB
Markdown
# 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::VERSION` 1, invite scheme `onionwire:v1`). There has been no public
|
||
third-party audit. Arti onion services are experimental upstream.
|
||
|
||
Related: [threat model](THREAT_MODEL.md), [audit notes](SECURITY_AUDIT.md).
|
||
|
||
## 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
|
||
in v1. Rotating the onion (`F4`) does **not** rotate it.
|
||
- **Onion** — Tor v3 address. Locator only. Disposable.
|
||
|
||
A friend is `{identity_pk, current_onion, current_prekey_pk}`. Pasting the same
|
||
identity `k` updates the locator (and prekey) on that row. It never creates a
|
||
second person.
|
||
|
||
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** (`HS_PORT`).
|
||
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
|
||
`connect_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 still 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
|
||
uint32 length = big-endian body length
|
||
uint8 body[length]
|
||
```
|
||
|
||
- `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.
|
||
|
||
## Handshake
|
||
|
||
Noise pattern: `Noise_IK_25519_ChaChaPoly_BLAKE2s`
|
||
|
||
Prologue (both sides, before the first handshake message): `onionwire-v1`
|
||
(13 ASCII bytes, no NUL).
|
||
|
||
Handshake payloads are empty. A non-empty decrypted handshake payload is a
|
||
hard fail.
|
||
|
||
### Sequence
|
||
|
||
Initiator knows the responder’s identity pubkey (pinned) and x25519 prekey
|
||
from the invite (or roster).
|
||
|
||
1. **IK msg 1** — initiator → responder (framed). Responder’s Noise static is
|
||
the invite `spk`.
|
||
2. Responder looks up `get_remote_static()` in the roster **by prekey**.
|
||
Unknown prekey → close. This is how the answerer learns who is calling.
|
||
3. **IK msg 2** — responder → initiator (framed).
|
||
4. Both sides enter transport mode. Handshake hash `h` is 32 bytes (BLAKE2s).
|
||
5. **Identity proof, initiator first** — transport-encrypt a 96-byte proof,
|
||
send as one frame.
|
||
6. **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.
|
||
|
||
## Application plaintext
|
||
|
||
After decrypt, classify the plaintext:
|
||
|
||
| Prefix (4 bytes) | Kind | If unknown / invalid |
|
||
|---|---|---|
|
||
| `loc ` | locator update | drop |
|
||
| `prf ` | profile | drop |
|
||
| `inv ` | Monero invoice | drop |
|
||
| `rcp ` | Monero receipt claim | drop |
|
||
| `png ` | ping (reserved) | drop |
|
||
| `fil ` | file chunk | drop |
|
||
| `rat ` | Double Ratchet chat frame (see Ratchet) | 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. Mixed-version 0.1.2 clients
|
||
that stored those as chat are obsolete; upgrade both sides.
|
||
|
||
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`, and `rcp` 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 keeps `onionwire-invite-v1` (see Invite).
|
||
|
||
Older builds verify only the untagged bytes, so they reject tagged signatures
|
||
(fail closed, no downgrade). Mixed-version fleets break outbound application
|
||
frames from a new sender to an old receiver until both sides are updated.
|
||
|
||
### `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 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.
|
||
|
||
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. New invoices MUST use the domain-separated form. Do not
|
||
emit legacy.
|
||
|
||
The frame is a signed claim, not a payment.
|
||
|
||
### `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. 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 → stay unverified. Wallet RPC is loopback
|
||
HTTP Digest; it is not this protocol.
|
||
|
||
### `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 margin under the 0.5/s
|
||
refill; pacing at exactly 2s sits on the refill boundary and drains under
|
||
jitter. A sender MAY retry an individual chunk a bounded number of times.
|
||
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 (v1 chat layer)”), and the plaintext inside that frame is the chat
|
||
line below. A bare chat frame with no typed prefix is still accepted inbound as
|
||
a chat line (v0.2.1 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.
|
||
No length limit beyond the frame cap.
|
||
|
||
## Ratchet (v1 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. That is a deliberate divergence from the shape this layer came from:
|
||
the plan assumed a plaintext header (`dh_pub || N || PN`) ahead of the
|
||
ciphertext, which was rejected because a plaintext header 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
|
||
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
|
||
```
|
||
|
||
- `dh_pub` — the sender's current ratchet public key (X25519, 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.
|
||
- Associated data is the 40-byte header, exactly as serialized above
|
||
(`dh_pub || N as u32 BE || PN as u32 BE`). A tampered `dh_pub`, `N` or `PN`
|
||
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.
|
||
- Minimum frame (empty plaintext) is 73 bytes: 5 + 40 + 12 + 16.
|
||
- A receiver MUST reject a frame without the `rat ` prefix, a version other than
|
||
`0x01`, or less than 73 bytes.
|
||
- 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.
|
||
|
||
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, unchanged:
|
||
|
||
```
|
||
KDF_RK(root, dh_out):
|
||
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_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 (`hkdf` 0.12), `HMAC` is SHA-256 (`hmac`
|
||
0.12). Each side of an epoch derives its chains from one shared DH output with
|
||
`KDF_RK` called **twice**:
|
||
|
||
```
|
||
epoch_chains(root, shared) -> (new_root, ck_lo, ck_hi):
|
||
(root1, ck_lo) = KDF_RK(root, shared)
|
||
(root2, ck_hi) = KDF_RK(root1, shared)
|
||
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)
|
||
|
||
state = bootstrap(root_key, my_keypair(my_secret), X25519_pub(peer_secret))
|
||
```
|
||
|
||
`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. Then:
|
||
|
||
```
|
||
shared = DH(my_secret, remote_pub)
|
||
(new_root, ck_lo, ck_hi) = epoch_chains(root_key, shared)
|
||
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](THREAT_MODEL.md)).
|
||
|
||
**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 bad prefix, version or a frame under 73 bytes.
|
||
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 keypair; `epoch_chains(root, DH(new_secret, remote_pub))`; 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.
|
||
|
||
### 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)`,
|
||
`(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,
|
||
`shared = DH(new_secret, frame.dh_pub)`,
|
||
`(root, ck_lo, ck_hi) = epoch_chains(root_a, shared)`,
|
||
`send_ck = chain_for(new_pub, frame.dh_pub)`, `remote_pub = frame.dh_pub`,
|
||
`PN = old send_n`, `send_n = 0`, `established = true`.
|
||
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.
|
||
|
||
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 `0x01` followed by
|
||
the implementation's serialized `RatchetState` (root, keypairs, both chain keys
|
||
and counters, `established`, and the skipped-key store). 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.
|
||
|
||
### 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:v1:k=<64 hex>:o=<v3 onion>:spk=<64 hex>: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.
|
||
|
||
**Current signature (encode this):**
|
||
|
||
```
|
||
ed25519_sign(identity_sk,
|
||
"onionwire-invite-v1" || 0x00 || k_ascii || 0x00 || o_ascii || 0x00 || spk_ascii)
|
||
```
|
||
|
||
`k_ascii` / `spk_ascii` are the hex strings as they appear in the invite
|
||
(lowercase).
|
||
|
||
**Legacy accept:** a signature over the raw concatenation `k || o || spk`
|
||
(no domain tag, no separators) is still accepted on decode so old invites
|
||
verify. New invites MUST use the domain-separated form. Do not emit legacy.
|
||
|
||
Unknown `k`: prompt. Same `k`: update onion and prekey only.
|
||
|
||
## What v1 will not grow into
|
||
|
||
No DHT, no hosted server, no XMPP, no store-and-forward, no multi-device, no
|
||
A/V, no STUN/ICE/WebRTC, no SOCKS/C-tor fallback, no system DNS for friends.
|
||
|
||
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 and invite `onionwire:v1` are this document.
|
||
- A new handshake prologue or a new invite scheme is a breaking change.
|
||
- New typed prefixes (`xyz `) are backward compatible if old peers drop them.
|
||
- The `rat ` frame has its own version byte (`0x01`). 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.
|