mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-25 00:45:21 +00:00
The previous commit moved cryptographicIdentities into the persisted IdentityCache, which made the pre-existing off-queue cache access in the save path fatal instead of merely racy: forceSave() -> performSave() read and JSON-encoded `cache` on the caller's thread while a concurrent `queue.async(.barrier)` writer mutated the same dictionary. ThreadSanitizer flags this as a data race in saveIdentityCache(), and because JSONEncoder walks the dictionary storage, an interleaved mutation can spin forever — which is what hung the CI "Run Swift Tests (app)" job (killed at the watchdog timeout). The naive fix (snapshot `cache` under `queue.sync` in forceSave) instead introduced a deadlock: forceSave() is reachable from deinit, and the object's final release can run *on* the identity queue (the fire-and-forget barrier saves capture self), so queue.sync there is a re-entrant same-queue wait -> SIGTRAP. That matched the intermittent crash the hang investigation surfaced. Fix: - Split persistence into persist(snapshot:) which encodes/seals/writes a by-value IdentityCache snapshot, decoupled from reading `cache`. - saveIdentityCache() (only ever called inside a barrier writer) passes `cache` directly — already serialized, race-free. - forceSave() now snapshots + persists inside `queue.async(flags:.barrier)` (async, never sync): the read is on the barrier context so it never races an in-flight write, and being async it can't deadlock when invoked from deinit running on the queue. Durability is unaffected: every mutating API already persists inline within its own barrier, so forceSave is a belt-and-suspenders flush. Test: test_concurrentUpsertsAndForceSaveDoNotRaceOrHang hammers concurrent upserts interleaved with forceSave; it reproduces the data race under `--sanitize=thread` on the old code (SecureIdentityStateManager.swift:250) and passes cleanly with the fix. A lock-guarded LockedKeychain double is used so the test exercises the manager's own cache race rather than the non-thread-safe MockKeychain. Verified green over repeated `swift test --parallel` runs both with and without --enable-code-coverage. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Test Harness Guide
This test suite uses an in-memory networking harness to make end-to-end and integration tests deterministic, fast, and race-free without touching production code.
In-Memory Bus
- File:
bitchatTests/Mocks/MockBLEService.swift - Registry/Adjacency: Global
registrymapspeerIDto aMockBLEServiceinstance;adjacencyrecords simulated links between peers. - Setup: Call
MockBLEService.resetTestBus()insetUp()to clear state between tests. - Topology: Use
simulateConnectedPeer(_:)andsimulateDisconnectedPeer(_:)to add/remove links.connectFullMesh()helpers in tests build larger topologies. - Handlers: Tests can observe data via
messageDeliveryHandler(decodedBitchatMessage) andpacketDeliveryHandler(rawBitchatPacket). - De‑duplication: A thread-safe
seenMessageIDsprevents duplicate deliveries during flooding/relays.
Broadcast Flooding
- Flag:
MockBLEService.autoFloodEnabled - Intent: When
true, public broadcasts propagate across the entire connected component (ignores TTL for reach) while still de‑duping to prevent loops. - Usage: Enabled in Integration tests (
setUp) to simulate large-network broadcast; disabled in E2E tests to keep routing explicit and verify TTL behavior (seePublicChatE2ETests.testZeroTTLNotRelayed).
Rehandshake Flow (Noise)
- Why: The legacy NACK recovery path was removed; recovery now relies on Noise session rehandshake after decrypt failure or desync.
- Manager:
NoiseSessionManagermanages per-peer sessions. - Pattern: On decrypt failure, proactively clear the local session and re-initiate a handshake. The peer accepts and replaces their session.
- Test:
IntegrationTests.testRehandshakeAfterDecryptionFailure- Corrupts ciphertext to induce a decrypt error.
- Calls
removeSession(for:)on the initiator’s manager beforeinitiateHandshake(with:)to avoidalreadyEstablished. - Verifies encrypt/decrypt succeeds post-rehandshake.
Tips
- Determinism: Add small async delays only where handler installation/topology changes could race the first send.
- Scoping: Keep
autoFloodEnabledtoggled only within Integration tests; always reset intearDown()to avoid cross-test contamination. - Direct vs Relay: Private messages target a specific peer when adjacent; otherwise they are surfaced to neighbors for relay and, if known, also delivered to the target.
Quick Start
- Create nodes and connect them:
let svc = MockBLEService(); svc.myPeerID = "PEER1"svc.simulateConnectedPeer("PEER2")
- Observe messages:
svc.messageDeliveryHandler = { msg in /* asserts */ }
- Enable broadcast flooding for Integration suites only:
MockBLEService.autoFloodEnabled = true