mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-25 02:05:19 +00:00
v1.7.0
28
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
020de96519 |
Mesh bridging: stitch nearby mesh islands over the internet, courier drops, unified settings (#1412)
* Mesh bridging: stitch nearby mesh islands over Nostr, courier drops, settings surface Three features plus a UI consolidation, all opt-in behind a new Bridge toggle: Channel bridge: while bridging, outgoing public mesh messages are also signed (with a derived, unlinkable per-cell Nostr identity) as kind-20000 events tagged #r with the local geohash-6 cell and published to the cell's deterministic geo relays; mesh-only peers deposit via new toBridge/fromBridge carrier directions through a bridge gateway (bridge + gateway toggles). Remote islands' events render into the mesh timeline marked with a network glyph. Events carry the original mesh message ID so the store's insert-by-ID absorbs radio/bridge duplicates in either order. Loop prevention mirrors GatewayService (three BoundedIDSet caches + skip-if-seen-locally + budgets). Nothing crosses a bridge unless its author signed it for the bridge; a per-message "nearby only" composer toggle keeps a message radio-only. Courier over the bridge: sealed courier envelopes park on default relays as kind-1401 drops tagged #x with their day-rotating recipient tag (NIP-40 expiry), signed by per-drop throwaway keys. Recipients subscribe for their own candidate tags; bridge gateways watch verified local peers' tags and hand matching drops over as directed courier packets. DM delivery to known peers stops requiring a physical courier encounter; the Noise-X seal never opens in transit. Presence: kind-20001 heartbeats on the rendezvous feed a "people across the bridge" count in the header (approximate: local participants subtracted by radio-copy attribution). Settings/Info: AppInfoView is now a segmented Settings/Info sheet. Settings hosts appearance, voice (fixes the duplicated Voice section), a Connectivity section (bridge + gateway + Tor toggles, the latter two moved out of the location sheet), and a confirmed panic-wipe button. New announce TLV 0x06 advertises the gateway's rendezvous cell; PeerCapabilities gains .bridge. i18n: 23 new keys across all 29 locales; coverage tests green. Tests: 50 new app tests + 3 BitFoundation tests; full suite 1445 green. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Settings polish: one toggle style, sticky Info-first tab, location access in Settings - The live-voice toggle now uses the same settings card + IRC pill as the connectivity toggles (settingToggle, renamed from connectivityToggle). - Segmented control orders Info first; the selected pane persists across opens (AppStorage), so first-ever open lands on Info and afterwards the sheet reopens where it was left. - "remove location access" moved from the channels sheet into the Settings Connectivity section (same key, still deep-links to system settings). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Location UX + copy: state-aware access control, honest empty state, clearer bridge/gateway text - Settings' location control now covers all three permission states: grant (real prompt, only possible while never-asked), open-system-settings when denied, remove-access when granted. The channels sheet keeps its own grant path for people who start there. - The channels list no longer spins forever without permission; it shows "grant location access to find nearby channels" instead (new key, 29 locales). - Bridge and gateway subtitles rewritten for clarity; the gateway subtitle moved to a new key since it now carries bridge traffic, and the old geohash-only key is deleted. The word "user" is banned from copy in every locale ("this person is blocked"). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Field-test fixes: dedupe relay-connectivity triggers, throttle presence, log bridge decisions First on-device run confirmed publishes accepted and the subscription delivering, but exposed trigger spam: NostrRelayManager's isConnected re-emits per relay recompute, so presence published 5x/second and the courier-drop subscription rebuilt 6x in 300ms. removeDuplicates() on the sinks + a 30s presence throttle (same-second heartbeats are byte-identical events anyway). Also: injection/skip/downlink now log under 🌉 so field verification is observable — the first test looked silent precisely because dedup correctly suppressed same-island bridged copies. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Fix restart self-echo: recognize own rendezvous events by derived pubkey Second field run proved bidirectional bridging live (~1-2s Mac<->iPhone via Tor) but caught a bug: relay backfill after an app relaunch re-delivered the device's own pre-restart events, and with the in-memory published-ID cache wiped they rendered as bridged copies of your own messages. The rendezvous identity is deterministically derived per cell, so self-recognition by pubkey needs no cache and survives restarts; own events are also marked never-downlink. Regression test simulates the fresh-launch state. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * People sheet: mesh, bridge, and groups in one list The header's bridged count had no matching faces anywhere — the people sheet only knew mesh peers. BridgeService now publishes named participants (nickname from message tags, geohash-style #last4 disambiguation, presence keeps a known name alive) and the mesh people sheet gains an "across the bridge" section between mesh peers and groups. Display-only rows in v1 (bridged identities have no DM route yet). Two new catalog keys x29 locales; also normalizes one out-of-sort-order entry inherited from a hand-edited key on main. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Header: one people icon, one count, one sheet Fold the bridged-people count into the main person.2.fill count instead of a second network-glyph counter; the merged people sheet (mesh / across the bridge / groups) is the breakdown. VoiceOver still announces how many of the total are across the bridge. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * People sheet symmetry: #mesh section header, no active count Every section now gets the same glyph+label header shape (shared PeopleSectionHeader): #mesh over the peer list, across-the-bridge over bridged people. The "N active" line is gone (mesh); location channels keep their geohash subtitle. Dead subtitle/count helpers removed. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * One switch: the bridge toggle drives all internet sharing Field feedback: two toggles (bridge + gateway) with an invisible dependency was a trap — bridged messages silently never reached mesh-only neighbors unless a second lever was found and flipped. Collapsed to a single switch that does the right thing for your situation: - Bridge ON + internet: your messages cross, you see the bridge, AND your device serves its island — accepts toBridge deposits, carries remote messages onto the radio, watches courier drops for verified local peers, advertises the cell, and runs the geohash-channel gateway. - Bridge ON, no internet: you ride whoever nearby is serving. - Bridge OFF: nothing of yours crosses; radio reception of bridged traffic stays passive and free. With every online bridger serving, downlink gets a 0.2-1.5s jittered holdoff + send-time suppression recheck so co-located gateways don't burn duplicate airtime (two-gateway test included). The internet-gateway card is gone from Settings (GatewayService now follows the bridge switch, with launch-time migration); its orphaned catalog keys deleted and the bridge subtitle broadened across all 29 locales. Also: MeshPeerList's empty state ("nobody around...") aligned to the section row rhythm. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Bridge pumps its own location; fix centered people sheet; stop drop-subscription churn Field session 3 found the bridge silently cell-less: it read availableChannels passively, which only flow while some other feature (channels sheet, location notes, geo sampling) happens to pump location — turn those off and the bridge never gets a rendezvous. BridgeService now requests a one-shot fix whenever it's enabled without a cell (and piggybacks one on the presence timer so moving devices migrate cells). Also from the session: the people sheet's scroll content hugged its widest child and got centered on iPhone when the list was empty — pinned to full width, leading. And the courier-drop subscription rebuilt every ~60s on verified announces despite an unchanged tag set — now resubscribes only when the tags actually change. (Also merges origin/main: keychain test isolation #1413.) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Fix launch race: bridge reacts to the permission callback, retries cell-less Field session 4: the launch-time location request ran before the CoreLocation authorization callback delivered, so refreshChannels() silently no-opped (it requires .authorized) and nothing ever retried — the bridge stayed cell-less all session. Three layers now close it: - a $permissionState sink re-enters refreshRendezvous the moment authorization resolves (the fast path), - the maintenance timer arms even without a cell and retries the full rendezvous refresh (the backstop; it previously required a cell, which made it useless for exactly this failure), - flipping the bridge switch while never-asked triggers the location prompt — that's the user-initiated moment for it. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * People sheet: one header style for every section; bridged people visible while own bridge is off GroupChatList's header now uses the shared PeopleSectionHeader (glyph + label, same size/padding as #mesh and across-the-bridge; keeps its key and header trait). Bridge section and the header count are no longer gated on this device's own toggle: bridged people arrive over passive radio from a serving neighbor, and whoever is visible in the timeline belongs in the sheet and the count. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * People sheet: equalize the first section's gap MeshPeerList's first row kept a legacy 10pt top bump from when nothing sat above it, and the outer VStack's 6pt inter-child spacing applied between the #mesh header and the list but not inside the other sections. Both gone: sections own their rhythm (header 12/4, rows 4), spacing 0 outside. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * People sheet: rows drop their leading glyphs — the section header carries the type Mesh rows lose the per-state transport icon (connected/relayed/nostr/ offline), bridge rows the network glyph, group rows the person.3 icon. Trailing state badges (star, lock, verified, unread, blocked, crown) stay, and the row accessibility description still announces connection state, so VoiceOver loses nothing. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Remove dead code left behind by the Settings|Info consolidation Periphery (--strict) flagged five leftovers on this branch: - LocationChannelsModel.setGatewayEnabled: the standalone internet-gateway toggle is gone (the bridge switch drives internet sharing), so nothing calls it; the gatewayEnabled published property stays for the header dot. - AppInfoView Strings.Location title/enable/openSettings: the old Location section's header and permission buttons no longer exist. Their orphaned Localizable.xcstrings entries go with them (the gateway-toggle keys were already pruned). - BridgePeopleList's appTheme environment value was never read. The sixth CI finding (PrekeyBundleStore.StoredBundle.noiseKey assign-only) is a Periphery flake: the property is read in loadFromDisk, the finding didn't reproduce locally or on the next CI run of unchanged code. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * People sheet: mesh rows get their transport glyph back The mesh section is the one heterogeneous list — the leading icon encodes HOW a peer is reachable (radio / relayed / nostr-only / offline), which the header can't say. Bridge and group rows stay glyph-free. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Fix courier drop skipped by stale BLE reachability; periodic deposit sweep Field test: a DM sent seconds after the recipient's radio vanished still saw them as "reachable" (60s verified retention), so canDeliverPromptly held, every deposit was skipped, and the message sat spooled with no retry path. MessageRouter now sweeps its outbox every 2 minutes and publishes bridge drops for messages whose recipient no transport can promptly reach; the drop layer's message-ID dedup makes the sweep idempotent. Regression test reproduces the exact field sequence. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Show "carried" when a message ships as a bridge drop Field feedback: dropped DMs delivered but the sender saw nothing — the drop path never fired onMessageCarried, and the recipient's delivery ack has no radio route back until the peers next share a transport. depositDrop now reports whether a fresh drop was sealed and the router marks the message carried (📦) on both the send path and the sweep; the ack still upgrades it to delivered whenever a route exists. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Fix locale word order: offline tag after name in DM header; localized "ago" The private-chat header rendered the localized offline word in the availability-glyph slot, before the name — "sin conexión bob". Offline now shows the same dimmed person glyph the mesh list uses, with the word as a small trailing tag after the name and lock, so it reads correctly in every locale. Full sweep of views found one more composition bug: notice timestamps glued English "ago" onto a localized duration; now the whole phrase comes from RelativeDateTimeFormatter (same as the "fades" label). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * DM header offline state: icon only The availability slot now reads uniformly as a glyph (radio / relayed / globe / dimmed person), matching the mesh list; the text tag is gone. VoiceOver still announces "offline" via the glyph's accessibility label. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Offline glyph: slashed antenna instead of dimmed person Offline is now the visual negation of connected (same antenna glyph, slashed) in both the DM header and mesh list rows; a generic person icon didn't say "unreachable". 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> |
||
|
|
ef848857b7 |
Remove dead code found by full Periphery audit; add scan config + advisory CI (#1410)
Periphery 3.7.4 audit of both schemes (macOS + iOS, intersected so platform-specific code is never touched), with test targets indexed and the share extension built. 277 dead declarations removed or demoted: dead forwarding wrappers (ChatViewModel+Nostr/+PrivateChat), removed- feature remnants (autocomplete command suggestions, back-swipe tuning, MediaSendError, GeohashParticipantTracker), unused Tor dormancy bindings, assign-only properties, unused parameters (renamed to _), and redundant public accessibility. 13 orphaned localization keys deleted across all 29 locales (old pre-#1392 location-notes UI, app_info warnings). Two real tests were flagged as unused because they never ran: Swift Testing methods missing @Test (NostrProtocolTests. testAckRoundTripNIP44V2_Delivered, NotificationStreamAssemblerTests. testAssemblesCompressedLargeFrame). Re-armed both; they pass. Deliberately kept, now recorded in .periphery.baseline.json: iOS-only code invisible to the CI macOS scan, C FFI signatures, keep-alive NWPathMonitor reference, InboundEventKey.eventID (dedup semantics), wifiBulk capability bit (reserved for Wi-Fi bulk work, used by BitFoundation package tests), and the String secureClear cluster (exercised by package tests). New: .periphery.yml config and an advisory Dead Code CI job (mirrors the SwiftLint precedent from #1361) that fails on findings not in the committed baseline. Verified: full macOS app suite, BitFoundation (119) and BitLogger (13) package tests green; periphery scan --strict exits clean. Co-authored-by: jack <jackjackbits@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
87910541ef |
Prekey bundles: forward-secret async first contact for courier mail (#1381)
* Add capability bits to announce TLV Announces now carry an optional capabilities TLV (0x05): a little-endian bitfield with named bits for upcoming features (prekeys, wifiBulk, gateway, groups, board, vouch, meshDiagnostics). Old clients skip the unknown TLV; peers without it decode as nil so features can distinguish "legacy peer" from "advertises nothing". PeerCapabilities lives in BitFoundation with a minimal-length encoding that preserves unknown bits for forward compatibility. Peer capabilities are stored in the BLE peer registry on verified announce and exposed via BLEService.peerCapabilities(_:). The local advertisement set is empty until each feature ships its bit. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Prekey bundles: forward-secret async first contact for courier mail Courier envelopes were sealed with one-way Noise X to the recipient's long-lived static key, so a later compromise of that key exposed every envelope captured in transit. This adds one-time prekey bundles: - PrekeyBundle (MessageType 0x24): 8 one-time Curve25519 public prekeys bound to the owner's Noise static key by an Ed25519 signature over "bitchat-prekey-bundle-v1" canonical bytes; gossiped mesh-wide on its own 60s sync round (SyncTypeFlags bit 9, 200-peer cap, 24h freshness) and verified against the announce-bound signing key before caching. - Sealed envelope v2: Noise X where the responder static is the one-time prekey, prologue "bitchat-prekey-v1" || prekeyID. Sender identity rides encrypted inside and is authenticated exactly like v1 (blocked-sender check included). CourierEnvelope gains an optional prekeyID TLV that v1 decoders skip as unknown. - Local prekeys live in the Keychain; consumed privates survive a 48h grace window for spray-and-wait redeliveries, then are deleted (the forward-secrecy clock starts at deletion). The batch tops back up and re-gossips when unconsumed count drops below 3, and everything is wiped in panic mode. - Routing: courier sealing picks a cached verified bundle when one exists (one prekey per message, reused across deposit retries), with the advertised .prekeys capability as a veto for on-mesh peers, and falls back to static sealing otherwise. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Prekeys: authenticate bundle packets, fix consume-republish, deflake CI Fixes the prekey-bundle PR review + CI failure: - CI root cause: the receive queue (mesh.message) is concurrent, so a gossiped prekey bundle can be processed before the announce that binds its owner's signing key. The old handler dropped such bundles outright, so under CI parallel load the bundle was permanently lost and the cache/gossip tests flaked (verifiedBundleEntersGossipStore, prekeySealedMailTravelsViaCourierAndOpens). Bundles that arrive before their binding are now retained per-owner (bounded) and re-attempted when the verified announce lands, atomically to avoid a check-then-act race. - Authenticate the OUTER prekey-bundle packet (Codex P2 / review MEDIUM): require senderID == PeerID(bundle.noiseStaticPublicKey) and verify the packet's Ed25519 signature (covers senderID + timestamp) against the owner's bound signing key, in addition to the inner bundle signature. Stops replay under a fresh timestamp / fake senderID. - Key the gossip prekey-bundle store/dedup by the bundle's authenticated identity (noiseStaticPublicKey), not the unauthenticated packet senderID, so one valid bundle sprayed under many fabricated sender IDs can't multiply entries and exhaust the 200-owner cap. - Bump published-bundle generatedAt strictly on consume (Codex P1): consuming a prekey shrinks the published bundle, so it now republishes with a strictly newer generatedAt and re-gossips, so peers replace the cached copy and stop assigning the consumed ID before its 48h grace. - Guard the panic/clear detached Application Support tree-deletes behind TestEnvironment.isRunningTests: the SPM test process shares that tree, so the wipe could land mid-test and flake file-dependent tests. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Update sync tests for prekeyBundle as bit 9 / default sync round Prekeys makes bit 9 (prekeyBundle) a known SyncTypeFlags bit and enables a prekey sync round by default. That broke tests authored by other PRs that assumed bit 9 was phantom or that only their own sync round fires: - SyncTypeFlags(Board)Tests: move the "unknown bits" probes to bits 10+ (0xFE -> 0xFC / 0xFD), since bit 9 is now assigned. - GossipSync(Board)Tests + GossipSyncManagerTests: disable the prekey sync round in configs that run maintenance (as they already do for message/ fragment/fileTransfer), so they isolate the behavior under test. Full app suite (1301 tests) green locally via SPM. 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> |
||
|
|
7341696280 |
Expand store-and-forward: open couriers, spray-and-wait, persistent outbox, 6h public history (#1372)
Store-and-forward previously delivered to an out-of-range peer only if a
mutual favorite happened to be connected at send time and later met the
recipient directly, and everything except courier envelopes died with the
app process. This closes those gaps end to end:
- Persist the MessageRouter outbox to disk, sealed with a ChaChaPoly key
held only in the Keychain (no plaintext at rest); queued private
messages now survive an app kill and flush on next launch.
- Deposit retry: queued messages are re-deposited whenever a new eligible
courier connects, tracked per message so the same courier is never
double-burned, until 3 distinct couriers carry it or it expires.
- Tiered open couriering: signature-verified strangers can now carry mail
(2 envelopes/depositor into a 20-slot pool) alongside mutual favorites
(5 each); overflow evicts verified-tier mail before favorites'.
- Spray-and-wait: envelopes carry a copy budget (4, capped 8, new TLV,
wire-compatible with old clients); couriers split half their remaining
budget with each newly encountered courier so mail diffuses through a
moving crowd.
- Remote handover: a verified relayed announce now floods a copy toward
the multi-hop recipient (directed-relay treatment, 10-min per-envelope
cooldown) while the carried original stays put for a direct encounter.
- Public history: gossip-sync window for whole public messages widened
from 15 min to 6 h, matched on the receive-acceptance side, and the
message store persists to disk so devices bridge partitions and
restarts ("town crier").
- Privacy-safe local delivery counters (bare tallies, log-only) so the
store-and-forward stack is measurable on-device.
- Panic wipe now also clears the sealed outbox, gossip archive, and
counters.
- Rewrite WHITEPAPER.md to describe the app as implemented (Noise XX/X,
actual flood control, courier system, gossip sync, Nostr path); the old
document described a bloom filter, three fragment types, and a
MessageRetryService that don't exist.
1037 macOS tests pass (17 new); iOS builds.
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
|
||
|
|
a66c591f8e |
Courier: deposit in parallel when the only route is a send queue (#1368)
* Deposit with couriers in parallel when the only route is a send queue The courier path was nearly unreachable: NostrTransport claims any favorite with a known npub as "reachable" regardless of connectivity, and the mesh favorite exchange shares npubs, so for essentially every courier-eligible recipient the router picked Nostr's reachable branch. With no internet the message just sat in the relay send queue — in the flagship scenario (internet shutdown, mutual friend standing right there) the courier walked away carrying nothing. Add Transport.canDeliverPromptly(to:), defaulting to reachability for radio-backed transports; NostrTransport answers honestly by mirroring the relay manager's connection state (fail-closed behind Tor). When the chosen transport can't hand the message off promptly, the router now also deposits a sealed copy with connected couriers. Double delivery is harmless: receivers dedup by message ID, and delivered/read acks never downgrade the carried status. When relays are up, sends are trusted and no courier quota is spent. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Track DM-relay connectivity, not any-relay, for prompt delivery Codex review: NostrRelayManager.isConnected is true when any relay is up, including geohash/custom relays — but private messages target the default (gift-wrap-capable) relay set and queue when none of those are connected. A lone geohash relay would have suppressed the parallel courier deposit while the DM sat in the queue. Publish a DM-scoped connectivity flag and drive canDeliverPromptly from 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> |
||
|
|
75da63c9d7 |
Fix favorites end-to-end: peer-list duplicates, Nostr sync, /fav key corruption (v1.5.4) (#1367)
* Friend-courier store-and-forward: mutual favorites carry sealed messages to offline peers When a private message has no reachable transport, the router now seals it to the recipient's Noise static key (new one-way Noise X pattern) and hands the envelope to up to three connected mutual favorites. Couriers store the opaque ciphertext under strict quotas (20 total, 5 per depositor, 16 KiB, 24 h) and hand it over when the recipient's announce matches a rotating HMAC recipient tag; the recipient opens it and the message flows through the normal private-message pipeline, so dedup and delivery acks just work. - CourierEnvelope TLV + courierEnvelope (0x04) message type in BitFoundation - Noise X one-way pattern reusing the existing handshake machinery, domain-separated by a courier prologue; sender identity authenticated via the ss DH (no forward secrecy - documented tradeoff) - CourierStore with eviction, file persistence, and panic-wipe integration - Rotating recipient tags (HMAC over epoch day) so carried envelopes don't correlate for observers who don't already know the recipient's key - New "carried" delivery status with figure.walk glyph; header indicator while carrying mail for others - Three-node end-to-end test ferrying packets through real BLEService instances, plus codec/crypto/store/router suites (986 tests green) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Fix courier handoff verification and directed sends * Authenticate courier deposits by ingress peer * Gate courier handover on direct announces and isolate store test Envelopes are removed from the courier store optimistically, so releasing them on a relayed (multi-hop) announce risks losing carried mail to a speculative flood that never reaches the recipient. Handover now also requires the announce to have arrived directly (full TTL), i.e. an actual encounter with a live link; regression test builds a relayed copy of a genuinely signed announce (TTL is excluded from announce signatures). Also make CourierStore's on-disk location injectable so the persistence test round-trips through a temp directory instead of wiping the real Application Support store, and reattach BLEAnnounceHandler's doc comment to the class it describes. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Use Xcode-bundled Swift in CI instead of a standalone toolchain The unpinned setup-swift action installs Swift 6.1, which refuses the SDK on runner images that have rolled to Xcode 26.5 ("this SDK is not supported by the compiler"). Jobs passed or failed depending on which image they landed on. The Xcode-bundled toolchain always matches the image's SDK, and matches local development. Cache keys now include the toolchain version so artifacts from one compiler are never restored into builds with another. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Drop couriered mail from blocked senders at envelope open The UI-layer block check (isPeerBlocked in the transport event coordinator) resolves a fingerprint from the live session or peer list, but a couriered message arrives precisely when its sender is absent — no session, no registry entry — so the check failed open and a blocked identity's mail was delivered anyway. Gate in openCourierEnvelope, where the sealed sender's full static key is in hand. End-to-end test ferries a full deposit→carry→handover round and verifies the envelope from a blocked sender never reaches the delegate (confirmed failing without the gate). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Fix favorites end-to-end: peer-list dedup, Nostr sync, /fav key corruption - UnifiedPeerService: dedup offline favorites against mesh peers by noise key. Phase 2 compared a 64-hex noise-key PeerID against 16-hex mesh IDs (never equal), leaving only a nickname+isConnected heuristic — a mutual favorite that was reachable-but-not-connected or renamed rendered twice, and a same-nick stranger could suppress a favorite entirely. - Nostr inbound: intercept [FAVORITED]/[UNFAVORITED] markers in the live PM handler so they update theyFavoritedUs instead of rendering as chat text; mutual favorites can now form over Nostr. Delete the dead favorite-aware PM variant and ChatNostrCoordinator.handleFavoriteNotification (unwired, parsed a stale FAVORITE:TRUE|… format no sender emits). - NostrTransport.isPeerReachable: match short form regardless of incoming ID width — toggling an offline favorite (addressed by 64-hex noise key) was silently dropped with no reachable transport. - BLEService.sendPrivateMessage: normalize recipient to the short ID like sendFilePrivate, so a 64-hex target hits the existing Noise session instead of initiating a handshake with a 32-byte wire recipient ID. - /fav, /unfav: stop writing Data(hexString: peerID.id) — the 8-byte routing ID for mesh peers — into the favorites store as a "noise key", and stop double-sending the favorite notification; delegate to toggleFavorite with a proper state check. - FavoritesPersistenceService.updatePeerFavoritedUs: keep the stored nickname when the caller passes the "Unknown" placeholder. - Bump marketing version to 1.5.4. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Route DMs to mutual favorites via Nostr when a mesh-keyed peer goes offline Field-tested on device: with a DM window opened while the peer was on mesh (conversation keyed by the short 16-hex ID), walking out of range and sending failed instantly with "peer not reachable" even though the header showed the peer as Nostr-reachable (mutual favorite, npub known). sendPrivateMessage derived the favorites key as Data(hexString: peerID.id) — for a short mesh ID that is the 8-byte routing ID, never the noise key — so the mutual-favorite/Nostr-key checks always came up empty and the send failed before reaching MessageRouter. Conversations keyed by the full 64-hex noise-key ID (opened from the offline favorite row) were unaffected, which is why later tests appeared to work. Resolve the noise key properly (peerID.noiseKey, then the unified peer row, then the favorites store by derived short ID) and add a regression test for the mesh-keyed-peer-goes-offline case. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Label Nostr DMs from favorites with their stored nickname Field-tested: a DM delivered over the Nostr fallback rendered as "anon#678e" instead of the sender's name. The inbound handler named the sender via displayNameForNostrPubkey, which only knows geohash-scoped names — even though the pipeline had already resolved the sender's noise key (the conversation is keyed by it). When the conversation key carries a noise key, prefer the favorite's stored nickname; geohash DMs (nostr_ keys) keep the anon geo name. This also stops an inbound Nostr [FAVORITED] from overwriting the stored nickname with the anon fallback, since the same name feeds updatePeerFavoritedUs. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Fix courier path for offline favorites addressed by noise-key IDs Two Codex review findings, both the same ID-width confusion this PR targets, in the courier flow: - CourierDirectory.favoritesBacked resolved recipients only via getFavoriteStatus(forPeerID:), which requires a short 16-hex ID — offline favorites are addressed by the full 64-hex noise-key ID, so attemptCourierDeposit silently bailed for exactly the peers couriers exist to serve. The 64-hex ID now yields its own key directly. - openCourierEnvelope emitted the derived short mesh ID even when the sender has no live mesh identity, landing couriered mail in an unresolvable short-ID thread labeled "Unknown". Absent senders now emit the full noise-key ID so the message joins the stable favorite conversation; present senders keep the live short-ID thread. 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> |
||
|
|
c60eff2c11 | Move additional files/tests to BitFoundation (#1102) | ||
|
|
4cfcefcda6 |
BitFoundation module to centralize shared components (#1089)
* Run local packages’ tests as well on CI * BitFoundation module to centralize shared components |
||
|
|
b839ce5f6c |
PeerID 31/n: Remove String interop to be explicit (#840)
* PeerID 28/n: `ChatViewModel.getShortIDForNoiseKey` * PeerID 29/n: `BLEService` + remove dupe funcs from #823 * `handleFileTransfer` to use PeerID * `sendMessage` and `sendPrivateMessage` * PeerID 30/n: Update some leftovers * `lowercased()` inside PeerID for normalization * PeerID 31/n: Remove String interop to be explicit * MockBLEService: Remove direct target delivery This causes a delivery even if the sender and receiver are not connected --------- Co-authored-by: jack <jackjackbits@users.noreply.github.com> |
||
|
|
3d914dcf46 |
Convert the remaining tests to Swift Testing (#781)
* SwiftTesting: NoiseProtocolTests + BinaryProtocolPaddingTests * SwiftTesting: `NotificationStreamAssemblerTests` * SwiftTesting: `NostrProtocolTests` * SwiftTesting: `BinaryProtocolTests` * SwiftTesting: `PeerIDTests` * SwiftTesting: `BLEServiceTests` * SwiftTesting: `CommandProcessorTests` * SwiftTesting: `GCSFilterTests` * SwiftTesting: `GeohashBookmarksStoreTests` * Remove `peerID` test constants * Remove PeerID + String interop from tests * Refactor IntegrationTests to extract state management * Refactor global state management of MockBLEService * NoiseProtocolSwiftTests: `actor` -> `struct` * Remove measurement tests w/ no benchmark * `NoiseProtocolSwiftTests` -> `NoiseProtocolTests` * SwiftTesting: `LocationChannelsTests` * SwiftTesting: `GossipSyncManagerTests` * SwiftTesting: `LocationNotesManagerTests` * Global `sleep` function for tests * SwiftTesting: `IntegrationTests` --------- Co-authored-by: jack <jackjackbits@users.noreply.github.com> |
||
|
|
551a843691 |
PeerID 18/n: BitchatDelegate + Tests (#769)
|
||
|
|
fbc15ea08f | SwiftTesting: Enable in GitHubActions + peer uuids (#767) | ||
|
|
af6703cf24 |
Fix test suite peer ID collisions (#764)
Use unique peer IDs for each test suite to prevent global registry collisions when Swift Testing runs suites in parallel. - PrivateChatE2ETests: PRIV_* prefix - PublicChatE2ETests: PUB_* prefix - Update all peer ID references to use actual instance IDs This fixes the race condition where simplePublicMessage() was receiving duplicate deliveries due to registry contamination. Co-authored-by: jack <jackjackbits@users.noreply.github.com> |
||
|
|
eb13eec4c5 |
Swift Testing (#748)
* Swift Testing: `PrivateChatE2ETests` + minor refactor * Swift Testing: `PublicChatE2ETests` * Swift Testing: `FragmentationTests` * Fix MockBLEService init to accept PeerID and remove _testRegister call * Add peerID property to MockBLEService and fix ttlDecrement test * Remove duplicate peerID property and fix type comparisons --------- Co-authored-by: jack <jackjackbits@users.noreply.github.com> |
||
|
|
5f44c56a90 | PeerID 15/n: Bitchat Message & Packet accept in init (#754) | ||
|
|
03c357f048 |
PeerID 11/n: Noise types use PeerID + create separate files (#750)
* Noise types use PeerID * Fix tests * Extract `NoiseSessionManager` into a separate file * Extract `NoiseSessionState` into a separate file * Remove `failed` state from `NoiseSessionState` * Extract `NoiseSessionError` into a separate file |
||
|
|
bdc31d3be3 | Don’t auto-register mock BLE services on creation (#746) | ||
|
|
90273cee2d |
PeerID 4/n: BitchatMessage.senderPeerID + String equality (#739)
|
||
|
|
3183703a63 |
Fix broken build + uncover localization tests (#702)
* Move LocalizationCatalogTests out of Localization/ SPM is treating all the files under Localization as a resource as per the Package.swift, hence it’s not even building it * Use a class object vs struct to fix build issue * Explicitly check that the output is not a l10n key * Remove skipped test |
||
|
|
ea8d51a36b |
Refactor: BitchatMessage (#610)
* Extract BitchatMessage into a separate file * Convert `fromBinaryPayload` to `convenience init?` * Extract message dedup into an extension * Remove dead `formatMessageContent` * Minor refactor of timestamp and username formatting * Remove dead `getSenderColor` |
||
|
|
920dc31795 |
Refactor: Testable Keychain and Identity Manager (#584)
* Make static functions instance functions to be testable * Injectable KeychainManager + Mock + updated tests * Remove `pendingActions` from identity manager (dead code) * Remove `getHandshakeState` from identity manager (dead code) * Remove `getAllSocialIdentities` from identity manager (dead code) * Remove `getCryptographicIdentity` from identity manager (dead code) * Remove `resolveIdentity` from identity manager (dead code) * Identity Manager: minor clean up * Put Identity Manager behind a protocol * Remove Keychain and Identity Manager singletons * Tests: include MockKeychain/MockIdentityManager in project; init identityManager in CommandProcessorTests --------- Co-authored-by: jack <jackjackbits@users.noreply.github.com> |
||
|
|
a30b73dd99 |
Feature/fragmentation fixes (#453)
* Fix fragmentation + BLE long-write + padding - Accumulate CBATTRequest long writes by offset and decode once per central - Decode original packet after fragment reassembly (preserve flags/compression) - Switch MessagePadding to strict PKCS#7 and validate before unpadding - Make BinaryProtocol.decode robust: try raw first, then unpad fallback - Unpad frames before BLE notify; fragment when exceeding centrals' max update length - Skip notify path when max update length < 21 bytes (protocol minimum) Verified large PMs and announces route without decode errors and peers show reliably. * Tests: fix weak delegate lifetime, legacy constants, and unused vars; fragment unpadded frames - BLEServiceTests: hold strong reference to MockBitchatDelegate - IntegrationTests: fix inline comment braces; replace removed types with test-safe values; use numeric 0x06 for legacy handshake resp checks - BinaryProtocolTests: remove unused minResult variable - BLEService: fragment the unpadded frame so fragments are efficient * tests: add Noise rehandshake recovery test; document in-memory test bus and autoFlood; stabilize large-network broadcast * tests: align suite with current behavior (compression, padding, routing, nonce); deflake and stabilize --------- Co-authored-by: jack <jackjackbits@users.noreply.github.com> |
||
|
|
6fbf7eee25 |
Refactor/ble nostr boundaries (#449)
* Refactor: move Nostr embedding and TLVs out of BLE; add NostrEmbeddedBitChat, Packets, PeerIDUtils; centralize MessageDeduplicator; update ChatViewModel to use new helpers; remove AI_CONTEXT.md and CLAUDE.md * Rename class to BLEService with compatibility alias; move mention parsing out of BLE; emit low-level BLE events to delegate; unify hex helpers; accept 64-hex in isPeerConnected; add PeerIDResolver * Project: rename file to BLEService.swift and update Xcode project; keep typealias SimplifiedBluetoothService = BLEService for compatibility * Remove SimplifiedBluetoothService alias; update app code to use BLEService explicitly * Tests: rename MockSimplifiedBluetoothService to MockBLEService; update typealiases and Xcode project * Docs: update comments to refer to BLEService (tests, protocol, noise service) * Tests: rename SimplifiedBluetoothServiceTests to BLEServiceTests; update project references and class names * Introduce Transport protocol; BLEService conforms; document delegate-only event pattern in BLEService; keep publishers internal for UnifiedPeerService * Adopt Transport end-to-end: add TransportPeerSnapshot + publishers; BLEService maps to Transport snapshots; UnifiedPeerService consumes Transport; ChatViewModel holds Transport * Fix Transport integration: replace getPeerFingerprint with getFingerprint(for:); update PrivateChatManager and CommandProcessor to use Transport; add BLEService.getFingerprint(for:); update PeerManager to use Transport * Refactor transport and BLE/Nostr layers; unify UI events; fix MainActor isolation - Rename SimplifiedBluetoothService to BLEService and slim responsibilities - Introduce Transport protocol and peerEventsDelegate for UI updates - Add NostrTransport and MessageRouter to route PM/read/favorite via BLE or Nostr - Centralize TLVs, PeerID utils, and MessageDeduplicator outside BLE - Update UnifiedPeerService and ChatViewModel to use Transport and delegate events - Fix MainActor isolation: route delegate calls via Task on MainActor; update notifyUI helper - Adjust related files and tests accordingly * BLEService: remove internal publishers; switch to delegate-only events - Drop legacy messages/peers/fullPeers publishers - Provide lightweight peerSnapshotSubject only to satisfy Transport - Rework publishFullPeerData to build snapshots from internal state and notify delegate + subject - Remove all peersPublisher.send call sites - Keep UnifiedPeerService on delegate updates exclusively * Remove inlined Nostr send helpers from ChatViewModel; route via MessageRouter - Replace direct Nostr sends (PM, ACKs, favorites) with MessageRouter - Add router method for delivery ACKs and implement NostrTransport.sendDeliveryAck - Simplify ChatViewModel favorite notification path to use router - Keep Nostr receive handling intact; reduce duplication * Fix ReadReceipt initializer usage in ChatViewModel (readerID + readerNickname) * Fix unused variable warning: replace shadowed 'nostrPubkey' bind with boolean check in ChatViewModel * Fix queued PM format: use TLV for pending messages after Noise handshake - Pending messages (including first-time favorite notifications) now use the same TLV encoding as normal sends - Ensures ChatViewModel can decode on first send, even if handshake completes after queuing --------- Co-authored-by: jack <jackjackbits@users.noreply.github.com> |
||
|
|
845ffc601b |
Refactor/robustness (#446)
* Refactor BitChat for improved robustness and performance Major refactoring to simplify architecture and fix critical issues: Architecture Improvements: - Replace complex BluetoothMeshService with simplified SimplifiedBluetoothService - Consolidate message routing and peer management into unified services - Remove redundant caching layers and optimize performance Bug Fixes: - Fix critical BLE peer mapping corruption in mesh networks - Fix encrypted message routing failures in multi-peer scenarios - Fix app freezes and Main Thread Checker warnings - Fix BLE message delivery in dual-role connections - Fix favorite toggle UI not updating instantly - Fix Nostr offline messaging with 24-hour message filtering Features: - Add command processor for chat commands - Add autocomplete service for mentions and commands - Improve private chat management with dedicated service - Add unified peer service for consistent state management Performance: - Optimize BLE reconnection speed - Reduce excessive logging throughout codebase - Improve message deduplication efficiency - Optimize UI updates and state management * Improvements refactor robust (#441) * remove unused code * remove more * TLV for announcement * restore * restore * restore? * messages tlv too (#442) * Fix Nostr notification and read receipt issues, add TLV encoding, cleanup unused code ## Notification & Read Receipt Fixes - Fixed toolbar notification icon appearing incorrectly on app restart for already-read messages - Fixed read receipts being incorrectly deleted on startup when privateChats was empty - Fixed messages not being marked as read when opening chat for first time - Fixed senderPeerID not being updated during message consolidation - Added startup phase logic to block old messages (>30s) while allowing recent ones - Fixed unread status checking across all storage locations (ephemeral, stable Noise keys, temporary Nostr IDs) ## TLV Encoding Implementation - Implemented Type-Length-Value encoding for private message payloads - Added PrivateMessagePacket struct with TLV encode/decode methods - Enhanced message structure for better extensibility and robustness ## Code Cleanup - Removed unused PeerStateManager class and related dependencies - Removed dead protocol types (DeliveryAck, ProtocolAck/Nack, NoiseIdentityAnnouncement) - Cleaned up BitchatDelegate by removing unused methods - Removed excessive debug logging throughout ChatViewModel - Added test-only ProtocolNack helper for integration tests ## Technical Details - Messages stored under three ID types: ephemeral peer IDs, stable Noise key hexes, temporary Nostr IDs - Fixed cleanupOldReadReceipts() to skip when privateChats is empty or during startup - Updated message consolidation to properly update senderPeerID - Restored NIP-17 timestamp randomization (±15 minutes) for privacy --------- Co-authored-by: jack <jackjackbits@users.noreply.github.com> Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com> |
||
|
|
a97d5c2d5e |
Implement Nostr NIP-17 for offline messaging and performance optimizations (#358)
* Implement Nostr NIP-17 integration for offline mutual favorite messaging - Add Nostr relay connectivity and NIP-17 gift-wrapped private messages - Implement dual transport system: Bluetooth mesh + Nostr relays - Add favorites persistence with mutual detection and Nostr key exchange - Support offline messaging for mutual favorites via Nostr relays - Handle peer identity rotation with automatic favorite key updates - Fix UI to show all favorites (online and offline) in peer list - Add proper message routing based on peer availability - Update peer list icons: 📶 for mesh, 🌐 for Nostr, 🌙 for one-sided - Fix toolbar display for offline peers in private chat view - Add network entitlements for macOS and iOS - Implement automatic noise key updates when peers reconnect * Implement Nostr NIP-17 for private messaging between mutual favorites - Add support for NIP-17 gift-wrapped private messages with double encryption - Enable private messaging via Nostr when mutual favorites are offline - Fix peer reconnection issues: users now stay in private chat when peer reconnects - Fix read receipt delivery: send pending receipts when peer comes back online - Add message ID tracking through Nostr transport for proper delivery acknowledgments - Update peer noise key mapping when peers reconnect with different IDs - Check for Nostr messages when app becomes active - Implement 7-day message retrieval window for better reliability * Fix private message UI refresh and adjust PEOPLE header spacing - Fix UI not updating when receiving private messages on mesh - Add immediate batch processing for messages in active chat - Force UI update when viewing current chat peer - Ensure real-time message display without navigation - Reduce PEOPLE header spacing from 16 to 12 points for tighter UI * Fix build errors and unused value warnings in Nostr favorites integration * Implement read receipts via Nostr - Added sendReadReceipt method to MessageRouter to send receipts via mesh or Nostr - Added handleReadReceipt to process incoming read receipts from Nostr - Made ReadReceipt.readerID mutable to allow updates - Added missing notification names and error cases - Uncommented and enabled read receipt handling in ChatViewModel - Read receipts now work seamlessly via both mesh and Nostr transports * Fix ReadReceipt initialization - use correct constructor * Implement persistent message deduplication for Nostr - Added ProcessedMessagesService to track messages across app restarts - Store processed message IDs and last timestamp in UserDefaults - Skip already processed messages when receiving from Nostr - Adjust subscription filter to use smart timestamp (last processed or 24h) - Prevents duplicate messages when reconnecting to Nostr relays * Fix peer list UI not updating to Nostr mode on disconnect - Remove peer from peerNicknames when connection state changes to disconnected - Ensures UI properly reflects peer disconnection state - Peer list now correctly shows Nostr mode (🌐) when peer walks out of range * Update peer count to include Nostr peers and improve UI indicators - Peer count now shows total peers including those available via Nostr - Count appears purple when only Nostr peers are connected - Private message header shows purple globe icon for Nostr transport - Consistent visual language for Nostr connectivity across the app * Improve RSSI real-time updates and fix UI flashing - Reduce RSSI update timer from 10s to 5s and per-peripheral from 5s to 3s - Add RSSI change detection with 2 dBm threshold for responsive updates - Always update previous RSSI values to fix gradual change detection bug - Trigger RSSI read on peer authentication for immediate status - Fix UI flashing 'nobody around' by removing array clearing on updates - Add proper cleanup of RSSI tracking on disconnect and peer rotation * Fix favorite nickname updates and peer list filtering - Add updateNickname method to FavoritesPersistenceService to update nicknames while preserving favorite status - Update announce handler to check for existing favorites and update their nicknames - Remove dead BluetoothMeshService+PublicAPI.swift file - Move sendFavoriteNotification to main BluetoothMeshService - Fix peer list to only show connected peers and user's favorites (not peers who favorite the user) - Remove UI logic for showing peers who favorite us but we don't favorite back * Remove dead code and fix ghost connections Phase 1 - Remove abandoned peer ID rotation code: - Remove previousPeerID property and rotationGracePeriod constant - Remove grace period logic from isPeerIDOurs() - Remove previousPeerID handling from announce packets - Pass nil for previousPeerID in identity announcements Phase 2 - Fix ghost connections from relayed packets: - CRITICAL FIX: Only add peers to activePeers if they have a peripheral connection - Check for peripheral connection before marking peer as active - Prevents ghost connections when announce packets are relayed - Log warning when rejecting relayed announce without peripheral Phase 3 - Begin consolidating redundant peer tracking: - Create new PeerSession class to unify peer data in one place - Add helper methods for PeerSession management - Integrate PeerSession into announce packet handling - Update authentication state changes to use PeerSession - Update peripheral mapping and RSSI to sync with PeerSession - Update disconnect and leave handling to update PeerSession - Add consolidated getter methods for peer info This fixes the issue where peers appeared connected without actually having a Bluetooth connection, and begins the migration to a cleaner single-source-of-truth peer tracking system. * Fix multiple connect messages on peer restart - Move hasPeripheralConnection check outside sync block to fix scope issue - Add debug logging to track connect message conditions - Ensure connect messages only show on first connection or reconnection with peripheral * Optimize RSSI updates for better battery life - Add app state tracking to BluetoothMeshService - Only update RSSI when app is in foreground and peer list is visible - Add setPeerListVisible method to control RSSI updates - Remove individual periodic RSSI updates in favor of centralized timer - Update ContentView to notify mesh service of peer list visibility changes - Improve battery efficiency by avoiding unnecessary RSSI reads * Initialize peer list visibility state on view appear - Ensure RSSI timer state is properly initialized when view loads - Call setPeerListVisible with initial showSidebar value * Fix duplicate peers and multiple disconnect messages - Fixed duplicate peer entries when relay-connected by adding relay-connected peers to connectedNicknames set - Added deduplication logic for disconnect messages with 2-second window to prevent multiple disconnect notifications for same peer - Added cleanup for old disconnect notification tracking to prevent memory growth * Fix peer count indicator color logic - Show green for any mesh peer (direct Bluetooth or relay connected) - Show purple only for Nostr-only peers (no mesh connections) - Show red only when no peers are reachable at all - Fixed to use meshPeerCount instead of viewModel.isConnected which only checked direct connections * Fix relay connection issues and peripheral mapping cleanup - Fixed relay-connected peers being marked as directly connected when receiving identity announce - Added proper cleanup of temp peripheral mappings when discovering real peer ID - Fixed disconnect notification deduplication cleanup - Improved debug logging to show actual connection state (direct/relay/nostr/offline) - Added debug logging for relay connection detection - Fixed compiler warning about unused variable * Fix Unknown peer disconnect notifications and disable faulty relay detection - Add check to prevent disconnect notifications for Unknown peers that never announced - Disable relay connection detection until proper relay tracking is implemented - In a 2-peer network, peers should never show as relay-connected * Fix RSSI updates and peer visibility after reconnection - Add updatePeers() call in didUpdatePeerList to refresh RSSI values in UI - Track version hello times to better detect direct connections - Allow peers to be marked active if recent version hello received - Fix thread safety for version hello tracking - Clean up old version hello times to prevent memory leaks * Remove RSSI tracking completely and replace with radio icon for mesh connections * Fix build errors after RSSI removal - Add missing peripheralID declaration in didDiscover delegate method - Remove obsolete setPeerListVisible calls from ContentView * Center private message header elements using ZStack layout - Replace HStack with ZStack for perfect centering - Globe/nick/lock cluster now always centered regardless of button sizes - Back and favorite buttons positioned in overlay HStack * Fix private chat view showing Unknown when peer reconnects with new ID - Update FavoritesPersistenceService to notify with both old and new keys - Handle peer ID changes in ChatViewModel to migrate private chat data - Update selectedPrivateChatPeer when favorite's noise key changes - Maintain chat history and unread status across peer ID changes * Fix read receipts after peer reconnection and replace nos.lol relay - Updated sendReadReceipt to resolve current peer ID when peers reconnect with new IDs - Enhanced MessageRouter to check favorites for current noise keys - Replaced nos.lol relay with relay.snort.social to avoid PoW requirements * Fix message routing to use Nostr when peers are disconnected Changed message routing logic to check actual peer connection status using isPeerConnected() instead of just checking if peer exists in nickname list. This ensures that offline mutual favorites correctly route messages through Nostr instead of attempting Bluetooth handshakes. Also added safety check to prevent starting private chat with ourselves. * Add debug logging for Nostr timestamp randomization Added logging to track the random offset being applied to Nostr event timestamps to debug why messages appear 8-9 minutes in the future. * Fix Nostr timestamp issue by reducing randomization range Temporarily reduced the timestamp randomization from +/-15 minutes to +/-1 minute to address messages appearing 8-9 minutes in the future. Added detailed UTC/local time logging to help debug the issue. The random offset should have been evenly distributed but was consistently showing positive offsets. This change mitigates the issue while we investigate the root cause. * Fix message routing for offline favorites and reduce Nostr timestamp randomization - Fix transport selection to properly detect disconnected peers using isPeerConnected() - Change from checking peer nicknames to checking actual connection status - Reduce Nostr timestamp randomization from ±15 minutes to ±1 minute - Add detailed timestamp logging for debugging * Improve PM header UI and encryption status display - Show transport icons (radio/link/globe) in PM header matching peer list - Always show lock icon if noise session ever established (no handshake icon) - Change verified icon from shield to checkmark seal - Use consistent green color (textColor) for PM header and encryption icons * Update AI_CONTEXT.md with comprehensive Nostr implementation details - Add Nostr and MessageRouter to architecture diagram - Document NIP-17 gift wrap implementation - Explain favorites integration and mutual requirement - Detail message routing logic and transport selection - Add security considerations and debugging tips - Update common tasks with Nostr-specific guidance * Fix data consistency issues in favorites, chat migration, and bloom filter - Fix favorites deduplication to use public key instead of nickname Prevents losing favorites when multiple peers use same nickname - Fix private chat migration to use fingerprints instead of nicknames Prevents merging unrelated conversations that share nicknames Fallback to nickname matching only for legacy data without fingerprints - Fix bloom filter reset to preserve messages from last 10 minutes Prevents duplicate message processing after bloom filter resets Keeps processedMessages for 10 minutes while bloom filter resets every 5 * Add mutual favorites internet messaging to app info * Remove excessive debug/info logging for production readiness - Removed ~140 debug/info level logs across core services - Preserved critical logs: errors, warnings, security events, state changes - Kept logs for: peer join/leave, favorite status, mutual relationships - Cleaned up verbose logging in: Bluetooth mesh, Nostr, message routing - Improved performance by reducing log I/O overhead 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * Implement performance optimizations and fix build warnings - Add UI update debouncing (50ms) to prevent excessive SwiftUI refreshes - Implement memory bounds for processedMessages with LRU eviction - Add encryption queue cleanup for disconnected peers - Optimize peer lookups from O(n) to O(1) with indexed dictionary - Fix multiple compiler warnings (unused variables, missing break statements) - Optimize peer counting with single-pass reduce operation - Fix ViewBuilder control flow issue in ContentView - Fix Dictionary initialization type mismatches with Array wrapper * Add TTL-based cleanup for Noise handshake sessions - Add session TTL (5 minutes) and max session limit (50) to NoiseHandshakeCoordinator - Clean up old established sessions to prevent unbounded memory growth - Move handshake cleanup timer out of DEBUG conditional for production use - Run cleanup every 60 seconds in production (vs 30s in debug) - Clean up crypto state immediately on peer disconnect - Prevents memory leaks from accumulating Noise sessions * Pre-compute and store fingerprints in PeerSession for O(1) lookups - Store fingerprint in PeerSession when peer authenticates - Update getPeerFingerprint() and getFingerprint() to check PeerSession first - Replace all noiseService.getPeerFingerprint() calls with optimized version - Eliminates repeated SHA256 calculations during message processing - Improves performance for favorite checks and encryption status updates * Implement exponential backoff for Nostr relay connections - Add reconnection tracking fields to Relay struct (attempts, timing) - Replace fixed 5-second delay with exponential backoff (1s → 2s → 4s... max 5min) - Stop reconnection attempts after 10 failures to prevent infinite retries - Reset attempt counter on successful connection - Add utility methods: retryConnection(), getRelayStatuses(), resetAllConnections() - DNS failures still bypass retry logic as before - Improves battery life and reduces server load from constant reconnection attempts --------- Co-authored-by: jack <jackjackbits@users.noreply.github.com> Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
492f90edd5 |
Optimize BLE mesh network for robustness and range (#314)
- Fixed relay probability calculation for 2-node networks (0% relay needed) - Added protocol ACKs to prevent unnecessary retransmissions - Implemented MessageState for enhanced duplicate detection - Added exponential backoff for collision avoidance - Fixed duplicate sends for bidirectional connections - Resolved packet ID generation issues using immutable fields only - Implemented smart rate limiting with progressive throttling - Removed unnecessary debug logging and fixed build warnings - Optimized message routing to prevent flooding in small networks Co-authored-by: jack <jackjackbits@users.noreply.github.com> |
||
|
|
847d333366 |
Fix all compilation errors and warnings in test suite
- Fixed mock service property overrides to match base class properties - Added missing CryptoKit imports where needed - Fixed immutable property assignments by creating new instances - Replaced XCTAssertThrows with XCTAssertThrowsError - Fixed DeliveryAck serialization method names (serialize -> encode) - Fixed unused variable warnings - Ensured all BitchatPacket modifications create new instances - Fixed BitchatMessage property mutations by creating new instances All test targets now build successfully for both iOS and macOS platforms. |
||
|
|
96136ec364 |
Add comprehensive test suite for bitchat
- Created test utilities and helpers for common test operations - Implemented Binary Protocol tests covering encoding/decoding, compression, and padding - Added Noise Protocol tests for handshake, encryption, and session management - Created Public Chat E2E tests for broadcasting, routing, TTL, and mesh topologies - Implemented Private Chat E2E tests for direct messaging, delivery ACKs, and retry logic - Added Integration tests for multi-peer scenarios, network resilience, and mixed traffic patterns - Created mock implementations for BluetoothMeshService and NoiseSession Test coverage includes: - Protocol layer (binary encoding, message serialization) - Security layer (Noise handshake, encryption/decryption) - Application layer (public/private messaging, delivery tracking) - Network scenarios (mesh topology, partitions, churn) - Performance and stress testing |