Eric Gang 49f388580f
Add golden test vectors for the courier wire format (#1472)
* Add golden test vectors for the courier wire format

The courier layer is only implementable from the Swift source today, and three
of the ways a second client gets it wrong fail silently — it builds, connects,
and delivers nothing, with no error at either end:

- `expiry` is milliseconds. Seconds makes every envelope read as long expired,
  so it is dropped at deposit with nothing logged.
- The signature does not cover the wire bytes. It covers a re-encoding with
  ttl zeroed, isRSR cleared and the signature omitted, which is then PKCS#7
  padded — a spray receipt is 46 bytes unsigned and unpadded, but 256 bytes
  signed. Signing the 46 produces a signature that never verifies.
- The signing key is Ed25519. CryptoKit spells it Curve25519.Signing, so
  reaching for a "Curve25519" primitive elsewhere yields X25519 key agreement.

Prose cannot defend against that class of bug; a fixture can. These vectors
pin the envelope TLV, the copies clamp, recipient-tag derivation, the
ciphertext hash, and the padded signing pre-image, and they are asserted from
the implementation so they cannot drift without a test failing.

Signature bytes are deliberately not pinned: CryptoKit's Ed25519 signing is
randomized rather than the deterministic RFC 8032 construction, so two
signatures over identical input differ and both verify. A second
implementation will not reproduce these bytes and does not need to — the
pre-image is what must match.

docs/courier-test-vectors.json carries the same values for implementers who
are not running Swift.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* Courier vectors: use a real deposit frame and pin every byte

Both changes address the Codex review on #1472.

The signing vector used type 0x2a, which is not a MessageType on main — it is
the spray-receipt opcode from a separate unmerged branch, so the frame decoded
to nothing and was misleading as an end-to-end courier vector. It now encodes
an actual courierEnvelope deposit: type 0x04 carrying the encoded envelope
from the TLV vector as its payload. 14 header + 8 sender + 8 recipient + 74
envelope = 104 unsigned and unpadded, 256 signed, 168 on the wire. The
envelope is under the 100-byte compression threshold, so the compressed path
stays out of it.

The pre-image assertions checked only length, the first three bytes, the flags
byte and the padding suffix. A change to timestamp encoding, payload length or
field layout could have left the test green while the JSON went stale — which
made the claim that these cannot drift without a test failing untrue as
written. Both the unpadded and padded sequences are now compared in full.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* Courier vectors: pin the pre-image in the signature test too

The signature test signed whatever pre-image it was handed and verified it,
which is self-consistent by construction — it would have passed over a wrong
canonicalization. Mutating an input (timestamp +1ms) proved it: the
comparison test failed and this one did not.

It now pins the pre-image before signing, so both tests fail on any change to
field layout, timestamp encoding or payload length.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* Courier vectors: drive the tests from the published JSON

Addresses both asks in the #1472 review.

The tests duplicated every vector as a Swift literal, so a format change that
updated only the Swift side would have left docs/courier-test-vectors.json
silently stale — the document was published as authoritative but nothing
checked it. Each test now reads the file and asserts against what it says.

The NoiseTestVectors.json precedent does not transfer directly: that fixture
lives inside its test target and loads from the test bundle, whereas this one
lives at repo-root docs/, outside the package, so SwiftPM cannot carry it as a
resource. It resolves the path from #filePath instead, the way
bitchatTests/LocalizationCoverageTests already reaches the repo root. CI runs
this package with the full tree checked out, and the target is not in the
xcodeproj, so there is no bundle-only run to break.

Two things beyond a mechanical swap:

- The published `label` for the tag HMAC is now load-bearing. The
  implementation's context string is private, so the test recomputes the tag
  from the label in the file and compares — otherwise the document could name
  the wrong label and nothing would notice.
- A dedicated test fails loudly if the file is missing or has lost a key,
  rather than letting a rename skip every assertion while the suite reports
  green.

Also fixes the stale prose. The review caught "the finished 110-byte wire
packet"; the same deleted spray-receipt example had left three more wrong
numbers in packetSigning._comment — the padding worked example read 46 + 16 =
62 with shortfall 210 = 0xd2, where the real frame is 104 + 16 = 120 with
shortfall 152 = 0x98.

Proven by mutation, not by green: flipping a byte in envelopeTLV.encoded, a
byte in signingPreimage, and the HMAC label each fail the matching test, and
removing the file fails all seven.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* Courier vectors: fail the length checks before indexing the bytes

Cross-model review (agy) on the previous commit.

The length assertions were #expect, so a frame of the wrong size reported the
mismatch and then kept going into `unpadded[2]` and the flags-offset reads.
Data subscripting past the end traps, so the process would die and take the
rest of the run's results with it — the failure mode where you learn least at
the moment you need to learn most. They are #require now.

Also marks the ciphertextHash vector as the weak one it is. Its derivation has
no consumer on main: the function that reads it arrives with the courier-spray
work, so the truncation is spelled out in the test rather than called, and a
future helper that truncates differently would not fail here. Said plainly in
the test rather than left for the next reader to discover.

Verified by mutation: declaring the wrong unsignedUnpaddedLength now fails both
signing tests with a reported expectation instead of a crash.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* Courier vectors: move the ciphertext-hash vector to where it can be checked

The remaining piece of the spray-receipt example this PR already removed once.

`ciphertextHash` documents the envelope identity a spray receipt carries, and
nothing on main carries one — `CourierStore.ciphertextHash` arrives with the
courier-spray branch. So the test could not call the function the vector
describes; it re-spelled the truncation instead, which would have passed just
as green against a helper that truncated differently. A vector nobody can check
is worse than no vector, because it reads as verified.

It moves to the spray PR, where the production function exists and the
assertion can go through it.

Everything left in the file is now asserted against code that runs on main.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* Courier vectors: decode the two keys nothing was reading

Cross-model review (codex) on the previous commits.

`packet.payloadIs` and `signature.verify` were the only non-comment keys the
Decodable shapes did not declare, so either could be renamed or deleted from the
published file and every test stayed green — the exact staleness this PR exists
to prevent, surviving in the two fields that tell a second implementer what to
feed the verifier.

Both are declared now, and `payloadIs` is checked rather than merely present:
it states a byte count, and that count is asserted against the real encoded
payload. Prose that states a number is a claim like any other.

Verified by mutation: renaming either key fails decoding, and stating 73 bytes
where the payload is 74 fails the length assertion alone.

Codex also read the pre-fix diff and re-reported the unchecked Data indexing
already fixed two commits ago, and claimed Ed25519 signing is deterministic so
the non-determinism assertion should fail. The latter is wrong for CryptoKit
specifically: `Curve25519.Signing` randomizes rather than following RFC 8032's
deterministic construction, which the test asserts and the suite confirms on
every run. No change.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 09:35:08 +02:00
2026-07-26 21:33:59 +02:00

icon_128x128@2x

bitchat

A decentralized peer-to-peer messaging app with dual transport architecture: local Bluetooth mesh networks for offline communication and internet-based Nostr protocol for global reach. No accounts, no phone numbers, no central servers. It's the side-groupchat.

bitchat.free

📲 App Store

📲 Play Store

Getting a copy you can trust

Install from the App Store, or build from source you have verified. A compiled build from anywhere else cannot be verified — see Verifying bitchat for how to check source against the per-release hash manifest, and for what to do if that is the only build you can get.

This matters more than it usually would: this repository has been the target of takedown demands, and when a repository or releases page disappears, mirrors appear that nobody can check.

License

This project is released into the public domain. See the LICENSE file for details.

Features

  • Dual Transport Architecture: Bluetooth mesh for offline + Nostr protocol for internet-based messaging
  • Location-Based Channels: Geographic chat rooms using geohash coordinates over global Nostr relays
  • Intelligent Message Routing: Automatically chooses best transport (Bluetooth → Nostr fallback)
  • Decentralized Mesh Network: Automatic peer discovery and multi-hop message relay over Bluetooth LE
  • Privacy First: No accounts, no phone numbers, no servers. Note that the mesh does use a persistent per-device identifier derived from your identity key — see the whitepaper on identity and metadata for what a nearby radio can observe
  • Private Message End-to-End Encryption: Noise Protocol for mesh, BitChat private envelopes for Nostr fallback
  • IRC-Style Commands: Familiar /slap, /msg, /who style interface
  • Universal App: Native support for iOS and macOS
  • Emergency Wipe: Triple-tap to instantly clear all data
  • Performance Optimizations: LZ4 message compression, adaptive battery modes, and optimized networking

Technical Architecture

BitChat uses a hybrid messaging architecture with two complementary transport layers:

Bluetooth Mesh Network (Offline)

  • Local Communication: Direct peer-to-peer within Bluetooth range
  • Multi-hop Relay: Messages route through nearby devices (max 7 hops)
  • No Internet Required: Works completely offline in disaster scenarios
  • Noise Protocol Encryption: End-to-end encryption, with forward secrecy for live sessions (store-and-forward mail is sealed without it — see the whitepaper)
  • Binary Protocol: Compact packet format optimized for Bluetooth LE constraints
  • Automatic Discovery: Peer discovery and connection management
  • Adaptive Power: Battery-optimized duty cycling

Nostr Protocol (Internet)

  • Global Reach: Connect with users worldwide via internet relays
  • Location Channels: Geographic chat rooms using geohash coordinates
  • 440+ Relay Network: Distributed across the globe for reliability
  • BitChat Private Envelopes: App-specific encrypted private messages over Nostr relays
  • Ephemeral Keys: Fresh cryptographic identity per geohash area

BitChat's private-envelope format is proprietary and is not NIP-17, NIP-44, or NIP-59 compatible. It uses Nostr as a relay transport but only interoperates with BitChat clients: private payloads travel inside kind-1059 events whose v2:-prefixed content is a BitChat-specific XChaCha20-Poly1305 construction, not NIP-44 encryption.

Channel Types

mesh #bluetooth

  • Transport: Bluetooth Low Energy mesh network
  • Scope: Local devices within multi-hop range
  • Internet: Not required
  • Use Case: Offline communication, protests, disasters, remote areas

Location Channels (block #dr5rsj7, neighborhood #dr5rs, country #dr)

  • Transport: Nostr protocol over internet
  • Scope: Geographic areas defined by geohash precision
    • block (7 chars): City block level
    • neighborhood (6 chars): District/neighborhood
    • city (5 chars): City level
    • province (4 chars): State/province
    • region (2 chars): Country/large region
  • Internet: Required (connects to Nostr relays)
  • Use Case: Location-based community chat, local events, regional discussions

Direct Message Routing

Private messages use intelligent transport selection:

  1. Bluetooth First (preferred when available)

    • Direct connection with established Noise session
    • Fastest and most private option
  2. Nostr Fallback (when Bluetooth unavailable)

    • Uses recipient's Nostr public key
    • BitChat's app-specific private-envelope encryption
    • Routes through global relay network
  3. Smart Queuing (when neither available)

    • Messages queued until transport becomes available
    • Automatic delivery when connection established

For detailed protocol documentation, see the Technical Whitepaper.

Setup

Option 1: Using Xcode

open bitchat.xcodeproj

For a signed device build, create your ignored local configuration and replace the example team ID with your Apple Developer Team ID:

cp Configs/Local.xcconfig.example Configs/Local.xcconfig

Local.xcconfig.example derives unique app and App Group identifiers from that team ID. The entitlement files already reference $(APP_GROUP_ID), so tracked project or entitlement files do not need to be edited.

Useful command-line checks from the repository root:

# macOS Debug build without signing
xcodebuild -project bitchat.xcodeproj -scheme "bitchat (macOS)" \
  -configuration Debug CODE_SIGNING_ALLOWED=NO build

# Full SwiftPM test suite
swift test

# iOS simulator tests
xcodebuild -project bitchat.xcodeproj -scheme "bitchat (iOS)" \
  -sdk iphonesimulator \
  -destination 'platform=iOS Simulator,name=iPhone 17' test

If iPhone 17 is unavailable, choose an installed simulator from:

xcodebuild -showdestinations -project bitchat.xcodeproj -scheme "bitchat (iOS)"

Option 2: Using just

brew install just
just check
just run

just build and just run use the current bitchat (macOS) scheme and keep Xcode output in the ignored .DerivedData/ directory. They never patch source, project, configuration, or entitlement files.

just clean removes only .DerivedData/ and .build/. It does not invoke Git or restore tracked files, so uncommitted work is preserved. just test runs the SwiftPM suite and just test-ios runs the iPhone 17 simulator suite.

Localization

  • App localizations live in bitchat/Localizable.xcstrings.
  • Share extension strings are separate in bitchatShareExtension/Localization/Localizable.xcstrings.
  • Prefer keys that describe intent (app_info.features.offline.title) and reuse existing ones where possible.
  • Run xcodebuild -project bitchat.xcodeproj -scheme "bitchat (macOS)" -configuration Debug CODE_SIGNING_ALLOWED=NO build to compile-check any localization updates.
Description
bluetooth mesh chat, IRC vibes
Readme Unlicense
Languages
Swift 99%
Python 0.4%
Shell 0.3%
Rust 0.2%