# ChannelMessenger — Architecture & Implementation Specification

**Status:** authoritative. Supersedes the Swift-first framing of the original §40 assignment.
**Owner:** Don Elton. Written from his spec of 2026-09-01 plus his same-day revision.

---

## 0. What this is

A privacy-preserving **opportunistic MANET (mobile ad hoc network) with delay-tolerant fallback** —
not a chat app that happens to work offline.

Secure text messaging with **no Internet, no cellular, no infrastructure Wi-Fi, and no central server**.
A message may travel A→B, or A→relay→relay→B. **Relays learn essentially nothing.**

Don's framing, verbatim and load-bearing:

> "The next thing I would design before Claude writes production radio code is the exact wire protocol
> and route-discovery state machine, down to each packet type and field. That will prevent iOS, Android,
> macOS, and Windows implementations from gradually becoming incompatible."

**So the first deliverable is a wire protocol document, not code.**

---

## 1. THE REVISION — read this before the original spec

Don revised the architecture after the original spec was written. Where they conflict, **this section wins**.

### 1.1 Platform-neutral from day one
Android and possibly Windows are targets. The mesh protocol must be platform-neutral immediately.
Apple Wi-Fi Aware, Android Wi-Fi Aware / Wi-Fi Direct, BLE, Windows Wi-Fi Direct, LAN and Internet all
become **interchangeable transport adapters**.

### 1.2 Shared core in Rust — NOT parallel Swift and Kotlin implementations
> "I would not have Claude Code independently implement the cryptographic protocol and routing algorithm
> once in Swift and once in Kotlin. That invites subtle protocol divergence."

`mesh-core-rs` owns: crypto, envelopes, identities, route discovery, routing, duplicate suppression,
serialization, receipts, protocol state machine.

Compiled for iOS, macOS, Android, Windows. Bindings via **UniFFI** for Swift/Kotlin; C ABI or generated
bindings for Windows.

Platform apps own **only**: radio APIs, UI, lifecycle, notifications, permissions, secure key storage.

### 1.3 Wire format: canonical CBOR, not Swift Codable
Explicitly defined canonical serialization. Deterministic encoding rules must be written down, because
two implementations that disagree on map key ordering will silently fail authentication.

### 1.4 Routing: bounded route discovery FIRST, flooding only as fallback
Supersedes "controlled epidemic routing" in the original §16.

1. Direct discovery
2. Bounded route discovery, **default max 3 hops**
3. If a route is found, send by the best route
4. If no route exists, fall back to store-and-forward **courier mode**

Two distinct behaviours: **Live mesh** (Carol reachable now, message traverses immediately) and
**Courier mode** (Bob stores the packet, walks near Carol twenty minutes later, delivers).

### 1.5 Route discovery must not leak topology
Relays keep **short-lived opaque reverse-path state only**:

```
query AB12 · receivedFrom = PeerBob · hop = 2 · expires = now + 10s
token 7C91 reachable through peer E32F · cost 137 · expires 15s
```

They must NOT maintain global tables of the form "I can reach Alice / Bob / Carol". That leaks topology.

### 1.6 Presence beacons build a privacy-preserving routing table
Carol periodically emits `PresenceToken = HMAC(contactSecret, currentEpoch)`.
Alice knows Carol's expected token. **Bob does not.** But Bob can cache
`opaque-token-7C91 heard from radio-peer-X, 3s ago, quality 213` and answer or forward Alice's query fast.

### 1.7 Token rotation is mandatory
Otherwise an observer in an airport follows one unknown person across locations.
`token = HMAC(pairwiseRoutingSecret, floor(unixTime / 600))` — 10 minute epochs.
Receiver accepts **previous, current and next** epoch to tolerate clock skew.
Consecutive tokens must have no observable cryptographic relationship.

### 1.8 Link quality is an abstraction, and the cost is the WEAKEST link
Do **not** pick the strongest first hop. Don's example:

```
Route A:  Alice →(-42) Bob →(-88) Carol
Route B:  Alice →(-61) Dave →(-59) Carol      ← Route B should win
```

Define a generic **LinkQuality 0–255**. Each transport maps its own metric into it: BLE from RSSI,
Wi-Fi Aware from link metrics, LAN from latency/loss, Internet from latency/reachability.

```
RouteCost = hopPenalty + weakLinkPenalty + transportPenalty + congestionPenalty + batteryPenalty
```

### 1.9 Wi-Fi Aware is the preferred interoperable transport
It is a **Wi-Fi Alliance standard**, not an Apple-only mechanism — Android supports it natively on capable
devices. BLE is the universal denominator. Windows Wi-Fi Direct is a platform-specific adapter, and
Microsoft's older Wi-Fi Direct **Services** API is deprecated — do not depend on that service layer.

### 1.10 Layer diagram (Don's)
```
Messaging UI → Conversation Layer → Crypto Layer → Mesh Protocol
   → Routing Engine → Transport Manager
        ├── BLE   ├── Wi-Fi Aware   ├── Wi-Fi Direct   ├── LAN   └── Internet
```

---

## 2. Non-negotiables carried from the original spec

- **Envelopes, not sessions.** Do not design around TCP sessions between users. The encrypted Envelope is
  byte-identical regardless of the path it travels.
- **Identity is cryptographic and unrelated to the device.** Curve25519 signing + key agreement, generated
  locally, private keys in Keychain / platform secure storage. NEVER derive identity from phone number,
  email, Apple ID, serial, MAC, advertising ID, vendor ID, hostname or device name.
- **Routing identity ≠ human identity.** No permanent user IDs or public identity keys in relay packets.
  `routingSecret = HKDF(sharedSecret, "routing-v1")`, rotating destination tokens.
- **Sealed-sender property.** Sender info may live in the encrypted payload; never in the outer Envelope.
- **No device/OS advertising.** Never advertise "John's iPhone". Capabilities as protocol bits
  (`supportsTransportClass3`), never `deviceType = iPhone17`.
- **Pairing via QR first**, with a short authentication string (e.g. `742 983 125`) both sides compare.
  NFC is an identity/pairing mechanism only — **never a messaging transport** (Core NFC is for tags).
  AirDrop and cloud accounts are NOT trust mechanisms.
- **Standard crypto only.** HKDF derivation, ChaChaPoly or AES-GCM, unique nonce per message, protocol
  metadata as AAD. Double Ratchet after the basic system works. Never invent cryptography.
- **Abuse limits:** text only, ~32 KB max Envelope, ~24 h max relay lifetime, ~8 max hops, 25–100 MB
  configurable relay storage, per-encounter rate limits. Discard structurally/cryptographically invalid
  packets immediately.
- **Relay policy:** Relay Off / Contacts Only / Community Mesh.
- **Message states:** Queued, Nearby route available, Transferred, Relaying, Delivered, Read, Expired.
  Staying Queued for a long time is correct behaviour, not a bug.
- **Ordering:** monotonic per-sender sequence number **inside the encrypted payload**. Do not trust clocks.
- **Hostile input:** every parser treats network data as hostile. Strict length bounds before allocation.
  Never force-unwrap or `try!` network/crypto input.
- **Background reality:** iOS will not run an unrestricted permanent mesh. Promise *opportunistic delivery*,
  not a continuously running invisible router. Design every subsystem to be interrupted and resumed.
  Use an explicit foreground **Mesh Active / Flight Mesh** session model.

## 3. Honest claims

Claim: the protocol discloses **no device model, OS, telephone number, account identifier, or permanent
device identifier**.

Do NOT claim: complete metadata anonymity, or that an observer cannot tell a transmitter is an iPhone.
Radio fingerprinting and Apple's underlying P2P protocol behaviour may reveal platform information.
This is application-layer minimisation.

## 4. Threat model

Protect against: relays reading or modifying messages, observers reading plaintext, replay, forgery,
server compromise, server operators reading contents, permanent identifiers in discovery, stolen database
files revealing keys, duplicate packet injection.

Do NOT yet claim protection against: a compromised destination device, malware in decrypted memory,
global radio traffic analysis, OS compromise, physical extraction from an unlocked device, or perfect
sender/recipient anonymity against a global observer.

## 5. Acceptance test (Don's revised, stronger version)

```
iPhone A   Android B   iPhone C   Android D
A↔B  B↔C  C↔D     A cannot reach C or D.  B cannot reach D.
```
1. A issues route discovery for D's token, max 3 hops.
2. Discovery finds A→B→C→D. D returns a route response along the reverse path.
3. A sends the encrypted message; B and C relay.
4. **Neither B nor C can determine** sender identity, recipient identity, plaintext, conversation,
   device model, or OS.
5. D decrypts and returns an authenticated delivery receipt.
6. Break C↔D and prove routing **invalidates or expires** rather than retrying a stale path forever.
7. Enable courier mode: C retains the packet, reconnect C↔D later, verify delayed delivery.

No Internet or cellular at any point.

## 6. Open questions for Don — do not guess

1. **Repo/BOM:** private GitHub repo, or local-only? (affects how machines share it)
2. **Windows in scope for v1**, or design-for-but-defer?
3. **Rust core confirmed** for the MVP, accepting the toolchain cost (cargo-ndk, UniFFI, xcframework),
   or Swift-first for Stage 1 and port to Rust before Android?
4. Apple Developer / Play Console identifiers to use.
5. **What the pairing code carries.** `SPEC-ORIGINAL` §10 says the QR payload holds "key agreement
   public information" and a "pairing nonce"; `DECISIONS.md` E3 says the invite blob "carries public
   keys and a nonce". `PROTOCOL.md` §6.5 (Handshake v1, written 2 September 2026) requires each side's
   X25519 key and nonce half to be **fresh per pairing attempt**, which a value printed into a QR or
   left in a mailbox cannot be. What shipped — `PairingCode` on both platforms — carries the identity
   key alone, which is consistent with §6.5. `DECISIONS.md` outranks `PROTOCOL.md`, so E3's wording
   needs either an amendment or a note saying its "public keys" meant identity keys only. **Nothing is
   broken today**; this is a documentation conflict that will mislead the next reader of E3.

## 7. Verification note

This spec cites platform capabilities (Apple Wi-Fi Aware on iPhone 12+, Android Wi-Fi Aware and Wi-Fi
Direct, deprecated Windows Wi-Fi Direct Services). Don researched these. The implementing agent must
**verify current API surface against live Apple/Android/Microsoft documentation before writing radio code**
— do not treat any API detail in this document, or any model's training knowledge, as current.
