* Consolidate duplicate BLE links after restore; suppress duplicate fragment streams; onChange coalescing
Field evidence (two-phone test after BLE state-restoration relaunches):
both phones held 2-3 simultaneous same-role connections to each other —
one side received every packet from three distinct centrals all bound to
the same peer — so every PTT voice frame arrived 3x, and a 41KB voice
file went out as TWO complete independent 89-fragment streams (different
assembly ids), both fully reassembled and the duplicate only dropped at
the very end by messageID dedup. 2-3x airtime/battery on all traffic
plus doubled reassembly memory.
Root causes and fixes:
- Duplicate links stayed unbound forever: announces (the only packet
that binds a link to a peer) went through the per-peer duplicate-link
collapse, so a peer's second/third link never received the announce it
needed to become bound — and unbound links pass the collapse untouched,
so every broadcast sprayed down all of them. Direct announces now
bypass the collapse and reach every live link (relayed announces keep
it); once bound, the existing collapse dedups all traffic.
- Same-role link retirement: a verified direct announce now consolidates
our central-role connections to that peer — keep the link the announce
arrived on (or the most recently bound one), cancel other connected
links bound to the same peer. One connection per role per peer is the
normal dual-role topology; only same-role duplicates are touched, only
links already announce-bound are retired (never pre-announce links),
at most one retirement per peer per rebind-cooldown window, and the
peer keeps a live link either way. Directness stays forgeable (TTL is
unsigned), so a replay could nominate the survivor — bounded by the
cooldown and by DM routing's existing canDeliverSecurely gate. A
rotation rebind now also cancels other stale links still bound to the
rotated-away ID, so the ghost identity retires promptly.
- Deterministic preferred-link collapse: when several bound links to one
peer are candidates, collapse now keeps the peer's most recently bound
link (the reverse-mapped one) instead of dictionary order; links
without a discovered characteristic are excluded from fanout (they
cannot be written to, and could silently eat a peer's collapsed copy).
links(to:) now reports all bound peripheral links, and removing one
duplicate no longer clobbers the reverse map of the survivor.
- Duplicate fragment streams: a transferId-less resend (gossip-sync
replay, spool) of file content already being fragmented out to a
covering audience is dropped at the outbound scheduler (broadcast
covers everyone; directed covers its recipient). App-initiated sends
carry an explicit transferId the progress UI tracks and always run.
A peer that asks after the stream completes still gets a resend.
- didUnsubscribeFrom no longer flaps a peer that is still live on other
links (the far side retiring its duplicate arrives as an unsubscribe);
didDisconnectPeripheral bookkeeping is skipped for self-retired links
by removing the store entry before cancelling.
Also: guard the DeliveryStatus onChange state write in TextMessageView/
MediaMessageView (unconditional per-row writes under a message storm
tripped SwiftUI's "tried to update multiple times per frame" warning).
The restore-path bgRemaining=∞ log was already fixed on main (#1425
review follow-up 07b5ac31: init-time seed + sampler-routed restore
captures); verified, no change needed.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Review fixes: multi-link disconnect guard, characteristic-aware retirement
Adversarial review of the duplicate-link PR (merge-with-nits):
- didDisconnectPeripheral gets the same multi-link guard as the
unsubscribe path: when a duplicate link drops naturally while the peer
stays live on another (dual-role central link, or a second bound link
during the post-restore consolidation window), peer-disconnect
bookkeeping (markDisconnected + disconnect notify) no longer runs — a
UI blip until the next announce re-marked the peer connected. The
reverse map was just repaired onto a connected survivor, so
directLinkState is the accurate probe. Scan restart and connect-slot
refill stay unguarded: they respond to the physical drop regardless of
remaining logical links. (No unit test: driving the CBCentralManager
delegate requires CBPeripheral instances, which cannot be constructed
in tests; the policy pieces backing the guard are covered.)
- Retirement is now characteristic-aware: the policy snapshot carries
characteristic presence, and keptPeripheralUUID selects anchors only
among writable links while any exist — consolidation must not keep a
link mid-service-rediscovery (didModifyServices cleared its
characteristic) and cancel the writable duplicate, stranding outbound
traffic on the central link until rediscovery finishes. When neither
anchor is writable but a writable duplicate exists, consolidation
defers to a later announce instead of guessing. The reverse-map
survivor repair in removePeripheral prefers writable links for the
same reason. Three new policy tests cover charless-vs-writable.
Deferred with code comments per review: central-side collapse keeps the
oldest subscription (no recency signal; remote consolidates within its
cooldown), and the extra preferred-bindings bleQueue hop in
sendOnAllLinks (fold into a combined snapshot if profiling flags it).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
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.
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 persistent identifiers
- Private Message End-to-End Encryption: Noise Protocol for mesh, NIP-17 for Nostr
- IRC-Style Commands: Familiar
/slap,/msg,/whostyle 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
- 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
- 290+ Relay Network: Distributed across the globe for reliability
- NIP-17 Encryption: Gift-wrapped private messages for internet privacy
- Ephemeral Keys: Fresh cryptographic identity per geohash area
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 levelneighborhood(6 chars): District/neighborhoodcity(5 chars): City levelprovince(4 chars): State/provinceregion(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:
-
Bluetooth First (preferred when available)
- Direct connection with established Noise session
- Fastest and most private option
-
Nostr Fallback (when Bluetooth unavailable)
- Uses recipient's Nostr public key
- NIP-17 gift-wrapping for privacy
- Routes through global relay network
-
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
cd bitchat
open bitchat.xcodeproj
To run on a device there're a few steps to prepare the code:
- Clone the local configs:
cp Configs/Local.xcconfig.example Configs/Local.xcconfig - Add your Developer Team ID into the newly created
Configs/Local.xcconfig- Bundle ID would be set to
chat.bitchat.<team_id>(unless you set to something else)
- Bundle ID would be set to
- Entitlements need to be updated manually (TODO: Automate):
- Search and replace
group.chat.bitchatwithgroup.<your_bundle_id>(e.g.group.chat.bitchat.ABC123)
- Search and replace
Option 2: Using just
brew install just
Want to try this on macos: just run will set it up and run from source.
Run just clean afterwards to restore things to original state for mobile app building and development.
Localization
- Base app resources live under
bitchat/Localization/Base.lproj/. Add new copy toLocalizable.stringsand plural rules toLocalizable.stringsdict. - Share extension strings are separate in
bitchatShareExtension/Localization/Base.lproj/Localizable.strings. - 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 buildto compile-check any localization updates.