diff --git a/bitchat/App/AppChromeModel.swift b/bitchat/App/AppChromeModel.swift index 51cadfb0..cc2b3416 100644 --- a/bitchat/App/AppChromeModel.swift +++ b/bitchat/App/AppChromeModel.swift @@ -27,6 +27,8 @@ final class AppChromeModel: ObservableObject { /// that did not commit must be visible, not just logged — the person who /// triggered it needs to know data may remain on the device. @Published private(set) var panicWipeBlocked = false + @Published private(set) var panicInProgress = false + private(set) var panicTask: Task? private let chatViewModel: ChatViewModel private let onPanicWipe: () -> Void @@ -128,6 +130,8 @@ final class AppChromeModel: ObservableObject { } func panicClearAllData() { + guard !panicInProgress else { return } + panicInProgress = true // A wipe invalidates everything on screen, and its outcome must be // visible: the success message and the failed-wipe banner both live // on the root timeline, so a sheet left up (the App Info danger-zone @@ -140,7 +144,11 @@ final class AppChromeModel: ObservableObject { prepareForPanic?() onPanicWipe() - chatViewModel.panicClearAllData() + let cleanup = chatViewModel.beginPanicClearAllData() + panicTask = Task { @MainActor [self] in + _ = await cleanup?.value + panicInProgress = chatViewModel.isPanicResetting + } } private func bind(privateInboxModel: PrivateInboxModel) { @@ -175,6 +183,9 @@ final class AppChromeModel: ObservableObject { .receive(on: DispatchQueue.main) .assign(to: &$torBlocked) + chatViewModel.$isPanicResetting + .assign(to: &$panicInProgress) + chatViewModel.$panicRecoveryBlocked .receive(on: DispatchQueue.main) .assign(to: &$panicWipeBlocked) diff --git a/bitchat/App/AppRuntime.swift b/bitchat/App/AppRuntime.swift index 3d5bc5bc..a12ce64b 100644 --- a/bitchat/App/AppRuntime.swift +++ b/bitchat/App/AppRuntime.swift @@ -32,6 +32,7 @@ final class AppRuntime: ObservableObject { private let idBridge: NostrIdentityBridge private var cancellables = Set() private var started = false + private var startRequested = false private var lastNostrRelayConnectedState = false private var didHandleInitialNostrConnection = false @@ -127,6 +128,7 @@ final class AppRuntime: ObservableObject { } func start() { + startRequested = true guard chatViewModel.networkActivationAllowed else { return } guard !started else { checkForSharedContent() @@ -297,6 +299,16 @@ final class AppRuntime: ObservableObject { private extension AppRuntime { func bindRuntimeObservers() { + chatViewModel.$panicRecoveryBlocked + .removeDuplicates() + .dropFirst() + .receive(on: DispatchQueue.main) + .sink { [weak self] blocked in + guard !blocked, let self, self.startRequested else { return } + self.start() + } + .store(in: &cancellables) + NostrRelayManager.shared.$isConnected .receive(on: DispatchQueue.main) .sink { [weak self] isConnected in diff --git a/bitchat/Services/BLE/BLEService.swift b/bitchat/Services/BLE/BLEService.swift index a07e5d31..9a9f491e 100644 --- a/bitchat/Services/BLE/BLEService.swift +++ b/bitchat/Services/BLE/BLEService.swift @@ -724,7 +724,7 @@ final class BLEService: NSObject { func suspendForPanicReset() { setPanicSuspended(true) noisePacketHandler.resetForPanic() - gossipSyncManager?.stop() + gossipSyncManager?.stopForPanic() gossipSyncManager = nil // Stop the radio and drain CoreBluetooth's delegate queue first. A // callback may already have passed its initial suspension check; the @@ -742,6 +742,28 @@ final class BLEService: NSObject { clearEmergencySessionState() } + #if DEBUG + func _test_replaceGossipManager(_ manager: GossipSyncManager) { + gossipSyncManager?.stop() + gossipSyncManager = manager + } + #endif + + /// Close admission and stop radio activity before yielding for gossip retirement. + @MainActor + func beginPanicReset() -> Task { + setPanicSuspended(true) + let retiringGossip = gossipSyncManager + gossipSyncManager = nil + noisePacketHandler.resetForPanic() + stopServicesImmediatelyForPanic() + return Task { @MainActor [self] in + await retiringGossip?.stopForPanicAsync() + onEngine { noisePacketHandler.resetForPanic() } + clearEmergencySessionState() + } + } + /// Reopen the radio only after media deletion and recovery-marker commit. func completePanicReset(restartServices: Bool) { // The media wipe ran on the recovery operations' own file store; this @@ -760,7 +782,7 @@ final class BLEService: NSObject { currentNickname: String, restartServices: Bool = true ) { - gossipSyncManager?.stop() + gossipSyncManager?.stopForPanic() gossipSyncManager = nil // Discard deferred pre-panic ciphertext behind any in-flight receive // handlers so none can repopulate the handler's bounded queue. @@ -1040,7 +1062,7 @@ final class BLEService: NSObject { /// Panic cannot spend its security boundary sending a signed LEAVE or /// pumping the main run loop. Close the radio and timers immediately; - /// the identity/session cleanup follows synchronously. + /// the caller completes the remaining identity/session cleanup. private func stopServicesImmediatelyForPanic() { bleQueue.sync { pendingNotifications.removeAll() @@ -2929,12 +2951,9 @@ final class BLEService: NSObject { // MARK: - GossipSyncManager Delegate extension BLEService: GossipSyncManager.Delegate { - // Gossip calls arrive on the manager's own serial queue; sends read - // the engine-owned bindings, so they enter an engine slot. The sync - // hop is safe: mesh.sync sits above the engine in the sync order — - // production engine code only ever queue.async's into the manager - // (the queue.sync helpers are DEBUG test entry points that run on - // test threads), so no reverse edge exists. + // Gossip delegate calls synchronously enter the engine. Engine callers + // must enqueue manager work asynchronously to avoid reversing that order. + // Keep the synchronous panic-retirement drain outside the engine queue. func sendPacket(_ packet: BitchatPacket) { onEngine { broadcastPacket(packet) diff --git a/bitchat/Services/Board/BoardStore.swift b/bitchat/Services/Board/BoardStore.swift index db6a9605..15949f9b 100644 --- a/bitchat/Services/Board/BoardStore.swift +++ b/bitchat/Services/Board/BoardStore.swift @@ -91,14 +91,24 @@ final class BoardStore { private var posts: [StoredPost] = [] private var tombstones: [StoredTombstone] = [] private let queue = DispatchQueue(label: "chat.bitchat.board.store") - private let fileURL: URL? + private var fileURL: URL? + private let resolveDefaultFileURL: () -> URL? + private let persistsToDisk: Bool private let now: () -> Date /// - Parameter fileURL: Overrides the on-disk location (tests). Ignored /// when `persistsToDisk` is false. - init(persistsToDisk: Bool = true, fileURL: URL? = nil, now: @escaping () -> Date = Date.init) { + init( + persistsToDisk: Bool = true, + fileURL: URL? = nil, + now: @escaping () -> Date = Date.init, + resolveDefaultFileURL: (() -> URL?)? = nil + ) { self.now = now - self.fileURL = persistsToDisk ? (fileURL ?? Self.defaultFileURL()) : nil + let resolver = resolveDefaultFileURL ?? Self.defaultFileURL + self.resolveDefaultFileURL = resolver + self.persistsToDisk = persistsToDisk + self.fileURL = persistsToDisk ? (fileURL ?? resolver()) : nil loadFromDisk() } @@ -147,18 +157,19 @@ final class BoardStore { // MARK: - Maintenance /// Panic wipe: drop all board data from memory and disk. - func wipe() { - queue.sync { + @discardableResult + func wipe() -> Bool { + let removed = queue.sync { posts.removeAll() tombstones.removeAll() - if let fileURL { - try? FileManager.default.removeItem(at: fileURL) - } + let removed = !persistsToDisk || PanicFileDeletion.remove(&fileURL, resolvingWith: resolveDefaultFileURL) publishSnapshotLocked() + return removed } DispatchQueue.main.async { [weak self] in self?.didWipe.send() } + return removed } // MARK: - Internals (call only on `queue`) diff --git a/bitchat/Services/Courier/CourierStore.swift b/bitchat/Services/Courier/CourierStore.swift index 565eef17..a6e6cc8a 100644 --- a/bitchat/Services/Courier/CourierStore.swift +++ b/bitchat/Services/Courier/CourierStore.swift @@ -121,7 +121,9 @@ final class CourierStore { private var envelopes: [StoredEnvelope] = [] private let queue = DispatchQueue(label: "chat.bitchat.courier.store") - private let fileURL: URL? + private var fileURL: URL? + private let resolveDefaultFileURL: () -> URL? + private let persistsToDisk: Bool private let now: () -> Date private let readData: (URL) throws -> Data /// A protected file can be present but unreadable during an iOS @@ -139,10 +141,14 @@ final class CourierStore { persistsToDisk: Bool = true, fileURL: URL? = nil, now: @escaping () -> Date = Date.init, - readData: @escaping (URL) throws -> Data = { try Data(contentsOf: $0) } + readData: @escaping (URL) throws -> Data = { try Data(contentsOf: $0) }, + resolveDefaultFileURL: (() -> URL?)? = nil ) { self.now = now - self.fileURL = persistsToDisk ? (fileURL ?? Self.defaultFileURL()) : nil + let resolver = resolveDefaultFileURL ?? Self.defaultFileURL + self.resolveDefaultFileURL = resolver + self.persistsToDisk = persistsToDisk + self.fileURL = persistsToDisk ? (fileURL ?? resolver()) : nil self.readData = readData loadFromDisk() #if os(iOS) @@ -416,15 +422,16 @@ final class CourierStore { // MARK: - Maintenance /// Panic wipe: drop all carried mail from memory and disk. - func wipe() { - queue.sync { + @discardableResult + func wipe() -> Bool { + let removed = queue.sync { envelopes.removeAll() diskLoadDeferred = false - if let fileURL { - try? FileManager.default.removeItem(at: fileURL) - } + let removed = !persistsToDisk || PanicFileDeletion.remove(&fileURL, resolvingWith: resolveDefaultFileURL) publishCountLocked() + return removed } + return removed } /// Retries a protected-data read and merges any envelopes accepted while diff --git a/bitchat/Services/Gateway/BridgeCourierService.swift b/bitchat/Services/Gateway/BridgeCourierService.swift index 80a20a36..d222cc5c 100644 --- a/bitchat/Services/Gateway/BridgeCourierService.swift +++ b/bitchat/Services/Gateway/BridgeCourierService.swift @@ -202,7 +202,8 @@ final class BridgeCourierService: ObservableObject { } /// Panic wipe: forget queued drops and the persisted dedup record. - func wipe() { + @discardableResult + func wipe() -> Bool { cancelActivePublishes() rejectedDropKeys = ExpiringIDSet( capacity: Limits.maxTrackedIDs, @@ -210,7 +211,7 @@ final class BridgeCourierService: ObservableObject { ) publishedDropKeys = ExpiringIDSet(capacity: Limits.maxTrackedIDs, lifetime: CourierEnvelope.maxLifetimeSeconds) seenDropEventIDs = ExpiringIDSet(capacity: Limits.maxTrackedIDs, lifetime: CourierEnvelope.maxLifetimeSeconds) - dedupStore.wipe() + return dedupStore.wipe() } // MARK: - Sender role diff --git a/bitchat/Services/Gateway/BridgeDropDedupStore.swift b/bitchat/Services/Gateway/BridgeDropDedupStore.swift index 0e34a3bd..843fac37 100644 --- a/bitchat/Services/Gateway/BridgeDropDedupStore.swift +++ b/bitchat/Services/Gateway/BridgeDropDedupStore.swift @@ -78,12 +78,21 @@ final class BridgeDropDedupStore { var seenDropEventIDs: [String: Date] } - private let fileURL: URL? + private var fileURL: URL? + private let resolveDefaultFileURL: () -> URL? + private let persistsToDisk: Bool /// - Parameter fileURL: Overrides the on-disk location (tests). Ignored /// when `persistsToDisk` is false. - init(persistsToDisk: Bool = true, fileURL: URL? = nil) { - self.fileURL = persistsToDisk ? (fileURL ?? Self.defaultFileURL()) : nil + init( + persistsToDisk: Bool = true, + fileURL: URL? = nil, + resolveDefaultFileURL: (() -> URL?)? = nil + ) { + let resolver = resolveDefaultFileURL ?? Self.defaultFileURL + self.resolveDefaultFileURL = resolver + self.persistsToDisk = persistsToDisk + self.fileURL = persistsToDisk ? (fileURL ?? resolver()) : nil } func load() -> Snapshot { @@ -118,9 +127,9 @@ final class BridgeDropDedupStore { } /// Panic wipe: forget which drops we published or handled. - func wipe() { - guard let fileURL else { return } - try? FileManager.default.removeItem(at: fileURL) + @discardableResult + func wipe() -> Bool { + return !persistsToDisk || PanicFileDeletion.remove(&fileURL, resolvingWith: resolveDefaultFileURL) } private static func defaultFileURL() -> URL? { diff --git a/bitchat/Services/Groups/GroupStore.swift b/bitchat/Services/Groups/GroupStore.swift index ce7f443f..b00cf62c 100644 --- a/bitchat/Services/Groups/GroupStore.swift +++ b/bitchat/Services/Groups/GroupStore.swift @@ -22,13 +22,23 @@ final class GroupStore: ObservableObject { @Published private(set) var groups: [BitchatGroup] = [] private let keychain: KeychainManagerProtocol - private let fileURL: URL? + private var fileURL: URL? + private let resolveDefaultFileURL: () -> URL? + private let persistsToDisk: Bool /// - Parameter fileURL: Overrides the on-disk location (tests). Ignored /// when `persistsToDisk` is false. - init(keychain: KeychainManagerProtocol, persistsToDisk: Bool = true, fileURL: URL? = nil) { + init( + keychain: KeychainManagerProtocol, + persistsToDisk: Bool = true, + fileURL: URL? = nil, + resolveDefaultFileURL: (() -> URL?)? = nil + ) { self.keychain = keychain - self.fileURL = persistsToDisk ? (fileURL ?? Self.defaultFileURL()) : nil + let resolver = resolveDefaultFileURL ?? Self.defaultFileURL + self.resolveDefaultFileURL = resolver + self.persistsToDisk = persistsToDisk + self.fileURL = persistsToDisk ? (fileURL ?? resolver()) : nil loadFromDisk() } @@ -130,14 +140,13 @@ final class GroupStore: ObservableObject { /// Panic wipe: drop all group keys and metadata from memory and disk. /// (The panic flow also nukes the whole keychain; deleting per-group keys /// here keeps the store safe to wipe on its own.) - func wipe() { + @discardableResult + func wipe() -> Bool { for group in groups { _ = keychain.deleteIdentityKey(forKey: Self.keychainKey(for: group.groupID)) } groups.removeAll() - if let fileURL { - try? FileManager.default.removeItem(at: fileURL) - } + return !persistsToDisk || PanicFileDeletion.remove(&fileURL, resolvingWith: resolveDefaultFileURL) } // MARK: - Internals diff --git a/bitchat/Services/MeshTransportCapabilities.swift b/bitchat/Services/MeshTransportCapabilities.swift index fd2203ea..8fc802f6 100644 --- a/bitchat/Services/MeshTransportCapabilities.swift +++ b/bitchat/Services/MeshTransportCapabilities.swift @@ -21,12 +21,22 @@ protocol BluetoothStateReporting: AnyObject { protocol PanicResettingTransport: AnyObject { /// Quiesces the radio and drains in-flight work ahead of a panic wipe. func suspendForPanicReset() + @MainActor + func beginPanicReset() -> Task /// Finishes a panic wipe, optionally restarting services. func completePanicReset(restartServices: Bool) /// Rotates the transport identity as part of a panic reset. func resetIdentityForPanic(currentNickname: String, restartServices: Bool) } +extension PanicResettingTransport { + @MainActor + func beginPanicReset() -> Task { + suspendForPanicReset() + return Task {} + } +} + /// File and private-media transfer over a mesh transport, including the /// capability-proof policy that gates encrypted private media. protocol MeshFileTransferring: AnyObject { diff --git a/bitchat/Services/MessageDeduplicationService.swift b/bitchat/Services/MessageDeduplicationService.swift index 693365ca..d79871bd 100644 --- a/bitchat/Services/MessageDeduplicationService.swift +++ b/bitchat/Services/MessageDeduplicationService.swift @@ -313,12 +313,22 @@ final class MessageDeduplicationService { /// Clears all caches. This is the wipe/panic path: the persisted /// private-envelope record goes with everything else. - func clearAll() { + @discardableResult + func clearAll() -> Bool { contentCache.clear() nostrEventCache.clear() nostrAckCache.clear() pendingPersistIDs.removeAll() - nostrEventStore?.wipe() + return nostrEventStore?.wipe() ?? true + } + + @MainActor + func clearAllAsync() async -> Bool { + contentCache.clear() + nostrEventCache.clear() + nostrAckCache.clear() + pendingPersistIDs.removeAll() + return await nostrEventStore?.wipeAsync() ?? true } /// Clears only the in-memory Nostr caches (events and ACKs). Runs on diff --git a/bitchat/Services/NostrProcessedEventStore.swift b/bitchat/Services/NostrProcessedEventStore.swift index ee70f0e7..92103949 100644 --- a/bitchat/Services/NostrProcessedEventStore.swift +++ b/bitchat/Services/NostrProcessedEventStore.swift @@ -21,13 +21,22 @@ import Foundation /// file must also load during a locked-background restoration relaunch. /// Wiped on panic via the dedup service's clear paths. final class NostrProcessedEventStore { - private let fileURL: URL? + private var fileURL: URL? + private let resolveDefaultFileURL: () -> URL? // All file access is serialized here: appends are read-modify-write, and // overlapping debounced flushes would otherwise race and drop IDs. - private let ioQueue = DispatchQueue(label: "chat.bitchat.nostr-processed-events", qos: .utility) + private let ioQueue: DispatchQueue - init(fileURL: URL? = nil) { - self.fileURL = fileURL ?? Self.defaultFileURL() + /// The I/O queue must be serial to preserve append and wipe ordering. + init( + fileURL: URL? = nil, + ioQueue: DispatchQueue = DispatchQueue(label: "chat.bitchat.nostr-processed-events", qos: .utility), + resolveDefaultFileURL: (() -> URL?)? = nil + ) { + let resolver = resolveDefaultFileURL ?? Self.defaultFileURL + self.resolveDefaultFileURL = resolver + self.fileURL = fileURL ?? resolver() + self.ioQueue = ioQueue } /// Processed event IDs, oldest first (insertion order). @@ -55,10 +64,21 @@ final class NostrProcessedEventStore { } } - func wipe() { + @discardableResult + func wipe() -> Bool { + ioQueue.sync { PanicFileDeletion.remove(&fileURL, resolvingWith: resolveDefaultFileURL) } + } + + /// Completes in FIFO order without occupying the caller's executor. + func wipeAsync() async -> Bool { + await withCheckedContinuation { continuation in + enqueueWipe { continuation.resume(returning: $0) } + } + } + + private func enqueueWipe(_ completion: @escaping (Bool) -> Void) { ioQueue.async { [self] in - guard let fileURL else { return } - try? FileManager.default.removeItem(at: fileURL) + completion(PanicFileDeletion.remove(&fileURL, resolvingWith: resolveDefaultFileURL)) } } diff --git a/bitchat/Services/PanicFileDeletion.swift b/bitchat/Services/PanicFileDeletion.swift new file mode 100644 index 00000000..398db032 --- /dev/null +++ b/bitchat/Services/PanicFileDeletion.swift @@ -0,0 +1,33 @@ +// +// PanicFileDeletion.swift +// bitchat +// +// This is free and unencumbered software released into the public domain. +// For more information, see +// + +import BitLogger +import Foundation + +/// Missing files succeed; unresolved persistent locations and removal errors fail. +enum PanicFileDeletion { + static func remove(_ fileURL: inout URL?, resolvingWith resolve: () -> URL?) -> Bool { + // Retry a failed lookup and retain the recovered location for later persistence. + if fileURL == nil { fileURL = resolve() } + return remove(fileURL) + } + + static func remove(_ fileURL: URL?) -> Bool { + guard let fileURL else { return false } + do { + try FileManager.default.removeItem(at: fileURL) + return true + } catch let error as NSError { + if error.domain == NSCocoaErrorDomain && error.code == NSFileNoSuchFileError { + return true + } + SecureLogger.error("Panic metadata deletion failed: \(error)", category: .security) + return false + } + } +} diff --git a/bitchat/Services/PanicMetadataWipeOperations.swift b/bitchat/Services/PanicMetadataWipeOperations.swift new file mode 100644 index 00000000..9c55fa81 --- /dev/null +++ b/bitchat/Services/PanicMetadataWipeOperations.swift @@ -0,0 +1,17 @@ +// +// PanicMetadataWipeOperations.swift +// bitchat +// +// This is free and unencumbered software released into the public domain. +// For more information, see +// + +/// Metadata cleanup dependencies for the panic transaction. +struct PanicMetadataWipeOperations { + var wipeCourier: () -> Bool + var wipeBridge: () -> Bool + var wipeGossip: () -> Bool + var wipeGroups: () -> Bool + var wipeBoard: () -> Bool + var wipeEvents: @MainActor () async -> Bool +} diff --git a/bitchat/Sync/GossipMessageArchive.swift b/bitchat/Sync/GossipMessageArchive.swift index dd81983d..49cb616d 100644 --- a/bitchat/Sync/GossipMessageArchive.swift +++ b/bitchat/Sync/GossipMessageArchive.swift @@ -18,10 +18,13 @@ import Foundation /// range — so file protection (no additional sealing) is the right at-rest /// posture. Wiped on panic. final class GossipMessageArchive { - private let fileURL: URL? + private var fileURL: URL? + private let resolveDefaultFileURL: () -> URL? - init(fileURL: URL? = nil) { - self.fileURL = fileURL ?? Self.defaultFileURL() + init(fileURL: URL? = nil, resolveDefaultFileURL: (() -> URL?)? = nil) { + let resolver = resolveDefaultFileURL ?? Self.defaultFileURL + self.resolveDefaultFileURL = resolver + self.fileURL = fileURL ?? resolver() } /// Raw binary packets, decoded and freshness-filtered by the caller. @@ -56,14 +59,15 @@ final class GossipMessageArchive { } } - func wipe() { - guard let fileURL else { return } - try? FileManager.default.removeItem(at: fileURL) + @discardableResult + func wipe() -> Bool { + return PanicFileDeletion.remove(&fileURL, resolvingWith: resolveDefaultFileURL) } /// Panic-wipe hook for callers that don't hold the live instance. - static func wipeDefault() { - GossipMessageArchive().wipe() + @discardableResult + static func wipeDefault(resolveDefaultFileURL: (() -> URL?)? = nil) -> Bool { + GossipMessageArchive(resolveDefaultFileURL: resolveDefaultFileURL).wipe() } private static func defaultFileURL() -> URL? { diff --git a/bitchat/Sync/GossipSyncManager.swift b/bitchat/Sync/GossipSyncManager.swift index c54140f0..b108336d 100644 --- a/bitchat/Sync/GossipSyncManager.swift +++ b/bitchat/Sync/GossipSyncManager.swift @@ -135,15 +135,18 @@ final class GossipSyncManager { // sender while the owner is away. private var latestPrekeyBundleByPeer: [PeerID: (id: String, packet: BitchatPacket)] = [:] private var archiveDirty = false + private var stoppedForPanic = false // Timer private var periodicTimer: DispatchSourceTimer? - private let queue = DispatchQueue(label: "mesh.sync", qos: .utility) + private let queue: DispatchQueue private var lastStalePeerCleanup: Date = .distantPast private var syncSchedules: [SyncSchedule] = [] private var responseRateLimiter: SyncResponseRateLimiter - init(myPeerID: PeerID, config: Config = Config(), requestSyncManager: RequestSyncManager, archive: GossipMessageArchive? = nil) { + init(myPeerID: PeerID, config: Config = Config(), requestSyncManager: RequestSyncManager, archive: GossipMessageArchive? = nil, + queue: DispatchQueue = DispatchQueue(label: "mesh.sync", qos: .utility)) { + self.queue = queue self.myPeerID = myPeerID self.config = config self.requestSyncManager = requestSyncManager @@ -199,6 +202,31 @@ final class GossipSyncManager { periodicTimer?.cancel(); periodicTimer = nil } + /// Retire this owner after its earlier persistence finishes. + /// The panic controller deletes the archive after this method returns. + func stopForPanic() { + stop() + queue.sync { + stoppedForPanic = true + } + } + + /// Retires persistence in queue order without blocking the caller. + @MainActor + func stopForPanicAsync() async { + stop() + await withCheckedContinuation { continuation in + enqueuePanicRetirement { continuation.resume() } + } + } + + private func enqueuePanicRetirement(_ completion: @escaping () -> Void) { + queue.async { [self] in + stoppedForPanic = true + completion() + } + } + func scheduleInitialSyncToPeer(_ peerID: PeerID, delaySeconds: TimeInterval = 5.0) { queue.asyncAfter(deadline: .now() + delaySeconds) { [weak self] in guard let self = self else { return } @@ -685,6 +713,7 @@ final class GossipSyncManager { } private func persistArchiveIfDirty() { + guard !stoppedForPanic else { return } guard archiveDirty, let archive else { return } archiveDirty = false let packets = messages.allPackets(isFresh: isPacketFresh) diff --git a/bitchat/ViewModels/ChatOutgoingCoordinator.swift b/bitchat/ViewModels/ChatOutgoingCoordinator.swift index 1bb3e213..7c4110e0 100644 --- a/bitchat/ViewModels/ChatOutgoingCoordinator.swift +++ b/bitchat/ViewModels/ChatOutgoingCoordinator.swift @@ -83,9 +83,24 @@ final class ChatOutgoingCoordinator { /// the message still goes out at the difficulty already reached. /// (Read access is internal so tests can await the send's completion.) private(set) var geohashMiningTask: Task? + private var wipeGeneration: UInt64 = 0 - init(context: any ChatOutgoingContext) { + /// Panic abandons pending sends; ordinary cancellation still expedites mining. + func resetForPanic() { + wipeGeneration &+= 1 + geohashMiningTask?.cancel() + geohashMiningTask = nil + } + + typealias GeohashEventBuilder = (String, String, NostrIdentity, String, Bool) async throws -> NostrEvent + private let buildGeohashEvent: GeohashEventBuilder + + init(context: any ChatOutgoingContext, buildGeohashEvent: @escaping GeohashEventBuilder = { + try await NostrProtocol.createMinedEphemeralGeohashEvent( + content: $0, geohash: $1, senderIdentity: $2, nickname: $3, teleported: $4) + }) { self.context = context + self.buildGeohashEvent = buildGeohashEvent } /// Finish any in-flight geohash PoW mining early (the pending message @@ -98,7 +113,9 @@ final class ChatOutgoingCoordinator { guard let trimmed = content.trimmedOrNilIfEmpty else { return } if content.hasPrefix("/") { - Task { @MainActor [weak context = self.context] in + let generation = wipeGeneration + Task { @MainActor [weak self, weak context = self.context] in + guard let self, self.wipeGeneration == generation else { return } context?.handleCommand(content) } return @@ -184,26 +201,23 @@ private extension ChatOutgoingCoordinator { // delays or blocks a send beyond `NostrPoW.miningTimeCap`. let previousSend = geohashMiningTask previousSend?.cancel() - geohashMiningTask = Task { @MainActor [weak context = self.context] in + let generation = wipeGeneration + geohashMiningTask = Task { @MainActor [weak self, weak context = self.context] in await previousSend?.value + guard let self, self.wipeGeneration == generation else { return } let event: NostrEvent do { - event = try await NostrProtocol.createMinedEphemeralGeohashEvent( - content: trimmed, - geohash: channel.geohash, - senderIdentity: identity, - nickname: nickname, - teleported: teleported - ) + event = try await self.buildGeohashEvent(trimmed, channel.geohash, identity, nickname, teleported) } catch { + guard self.wipeGeneration == generation else { return } SecureLogger.error("❌ Failed to prepare geohash message: \(error)", category: .session) context?.addSystemMessage( String(localized: "system.location.send_failed", comment: "System message when a location channel send fails") ) return } - guard let context else { return } + guard self.wipeGeneration == generation, let context else { return } let message = BitchatMessage( id: event.id, diff --git a/bitchat/ViewModels/ChatTransportEventCoordinator.swift b/bitchat/ViewModels/ChatTransportEventCoordinator.swift index ee2d8b6c..d5d4fc2b 100644 --- a/bitchat/ViewModels/ChatTransportEventCoordinator.swift +++ b/bitchat/ViewModels/ChatTransportEventCoordinator.swift @@ -11,6 +11,7 @@ import Foundation /// true dependencies explicit. @MainActor protocol ChatTransportEventContext: AnyObject { + var networkActivationAllowed: Bool { get } // MARK: Connection & chat state var isConnected: Bool { get set } var nickname: String { get } @@ -86,6 +87,10 @@ protocol ChatTransportEventContext: AnyObject { func handleVouchPayload(from peerID: PeerID, payload: Data) } +extension ChatTransportEventContext { + var networkActivationAllowed: Bool { true } +} + extension ChatViewModel: ChatTransportEventContext { // `isConnected`, `nickname`, `myPeerID`, `privateMessages(for:)`, // `unreadPrivateMessages`, `selectedPrivateChatPeer`, `notifyUIChanged()`, @@ -268,6 +273,7 @@ final class ChatTransportEventCoordinator { @MainActor func didConnectToPeerSynchronously(_ peerID: PeerID) { + guard context.networkActivationAllowed else { return } SecureLogger.debug("🤝 Peer connected: \(peerID)", category: .session) context.isConnected = true @@ -291,6 +297,7 @@ final class ChatTransportEventCoordinator { @MainActor func didDisconnectFromPeerSynchronously(_ peerID: PeerID) { + guard context.networkActivationAllowed else { return } SecureLogger.debug("👋 Peer disconnected: \(peerID)", category: .session) context.removeEphemeralSession(peerID: peerID) @@ -332,6 +339,7 @@ private extension ChatTransportEventCoordinator { messageID: String?, in context: any ChatTransportEventContext ) { + guard context.networkActivationAllowed else { return } let normalized = content.trimmed let mentions = context.parseMentions(from: normalized) let message = BitchatMessage( @@ -358,6 +366,7 @@ private extension ChatTransportEventCoordinator { _ message: BitchatMessage, in context: any ChatTransportEventContext ) -> Bool { + guard context.networkActivationAllowed else { return false } guard !context.isMessageBlocked(message) else { return false } guard !message.content.trimmed.isEmpty || message.isPrivate else { return false } @@ -374,7 +383,7 @@ private extension ChatTransportEventCoordinator { func runOnMain(_ action: @escaping @MainActor (any ChatTransportEventContext) -> Void) { Task { @MainActor [weak context = self.context] in - guard let context else { return } + guard let context, context.networkActivationAllowed else { return } action(context) } } @@ -429,6 +438,7 @@ private extension ChatTransportEventCoordinator { timestamp: Date, in context: any ChatTransportEventContext ) { + guard context.networkActivationAllowed else { return } switch type { case .privateMessage: guard let packet = PrivateMessagePacket.decode(from: payload) else { return } diff --git a/bitchat/ViewModels/ChatViewModel.swift b/bitchat/ViewModels/ChatViewModel.swift index 36742d29..c6bfc43e 100644 --- a/bitchat/ViewModels/ChatViewModel.swift +++ b/bitchat/ViewModels/ChatViewModel.swift @@ -199,7 +199,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage let unifiedPeerService: UnifiedPeerService let autocompleteService: AutocompleteService let deduplicationService: MessageDeduplicationService // internal for test access - private lazy var outgoingCoordinator = ChatOutgoingCoordinator(context: self) + private(set) lazy var outgoingCoordinator = ChatOutgoingCoordinator(context: self) private lazy var lifecycleCoordinator = ChatLifecycleCoordinator(context: self) private lazy var transportEventCoordinator = ChatTransportEventCoordinator(context: self) private lazy var peerListCoordinator = ChatPeerListCoordinator(context: self) @@ -329,9 +329,12 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage var nostrRelayManager: NostrRelayManager? private let userDefaults = UserDefaults.standard let keychain: KeychainManagerProtocol + private let panicMetadataWipeOperations: PanicMetadataWipeOperations? private let panicRecoveryOperations: PanicRecoveryOperations private let panicNetworkLifecycle: PanicNetworkLifecycle - private var isPanicResetting = false + @Published private(set) var isPanicResetting = false + private(set) var startupPanicRecovery: Task? + private var bootstrapConfigured = false /// Private group membership: keys in the keychain, metadata on disk. let groupStore: GroupStore private let nicknameKey = "bitchat.nickname" @@ -1163,6 +1166,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage sfMetrics: StoreAndForwardMetrics? = nil, panicMediaWipe: (() throws -> Void)? = nil, panicRecoveryOperations: PanicRecoveryOperations? = nil, + panicMetadataWipeOperations: PanicMetadataWipeOperations? = nil, panicNetworkLifecycle: PanicNetworkLifecycle = .noop ) { let conversations = conversations ?? ConversationStore() @@ -1178,6 +1182,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage ) self.keychain = keychain + self.panicMetadataWipeOperations = panicMetadataWipeOperations self.panicRecoveryOperations = panicRecoveryOperations ?? .ephemeral(wipeMedia: panicMediaWipe ?? {}) self.panicNetworkLifecycle = panicNetworkLifecycle @@ -1235,14 +1240,20 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage "Pending panic recovery detected; wiping before runtime services start", category: .security ) - _ = panicClearAllData(restartServices: false) + startupPanicRecovery = beginPanicClearAllData(restartServices: false) } if networkActivationAllowed { - ChatViewModelBootstrapper(viewModel: self).configure() + configureAfterRecoveryIfNeeded() } } + private func configureAfterRecoveryIfNeeded() { + guard !bootstrapConfigured else { return } + bootstrapConfigured = true + ChatViewModelBootstrapper(viewModel: self).configure() + } + // MARK: - Deinitialization deinit { @@ -1312,12 +1323,14 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage /// Routes to private chat if one is selected, otherwise broadcasts @MainActor func sendMessage(_ content: String) { + guard networkActivationAllowed else { return } outgoingCoordinator.sendMessage(content) } /// Sends a 👋 to the mesh channel regardless of the active channel. @MainActor func sendMeshWave() { + guard networkActivationAllowed else { return } outgoingCoordinator.sendMeshWave() } @@ -1558,28 +1571,42 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage // PANIC: Emergency data clearing for activist safety @MainActor @discardableResult - func panicClearAllData(restartServices: Bool = true) -> Bool { + func panicClearAllData(restartServices: Bool = true) async -> Bool { + guard let task = beginPanicClearAllData(restartServices: restartServices) else { return false } + return await task.value + } + + /// Establish the recovery boundary synchronously at the confirmed UI action. + /// The returned task owns cleanup even if its caller stops awaiting it. + @MainActor + func beginPanicClearAllData(restartServices: Bool = true) -> Task? { + guard !isPanicResetting else { return nil } panicRecoveryBlocked = true isPanicResetting = true - defer { isPanicResetting = false } // Stop internet and location-presence work before clearing identity or // state. These services cancel their subscriptions and delayed tasks, // so old callbacks cannot reconnect during the transaction. panicNetworkLifecycle.stop() + // IMPORTANT: Clear Nostr-related state + // Drop relay subscriptions, handlers, pending sends, and replay state. + // Geohash DM handlers can capture pre-wipe Nostr identities, so a plain + // disconnect is not enough here. + NostrRelayManager.shared.resetForPanicWipe() + // Clearing relay handlers stops NEW events, but a detached gift-wrap + // decrypt spawned just before the wipe still holds a pre-wipe key and + // ciphertext; bump the pipeline's wipe generation so its result is + // dropped at the main-actor delivery hop instead of landing here. + nostrCoordinator.inbound.invalidateInFlightDecrypts() + outgoingCoordinator.resetForPanic() + nostrRelayManager = nil + + // Establish both independent durable intents before erasing anything. // `wipeMedia` will still attempt deletion if neither write succeeds. let recoveryIntent = panicRecoveryOperations.begin() - // Quiesce the mesh before clearing stores. Identity replacement below - // deliberately stays stopped until media deletion and marker commit. - if let panicTransport = meshService as? PanicResettingTransport { - panicTransport.suspendForPanicReset() - } else { - meshService.emergencyDisconnectAll() - } - // Invalidate detached media preparation and close live capture file // handles before clearing state or removing the media directory. mediaTransferCoordinator.resetForPanic() @@ -1595,9 +1622,31 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage // Clear all messages (public timelines and private chats live in the // single-writer ConversationStore; the derived `messages` view and // the legacy mirror empty with it) + publicMessagePipeline.resetForPanic() conversations.clearAll() pendingGeohashSystemMessages.removeAll() + // Quiesce the mesh before clearing stores. Identity replacement below + // deliberately stays stopped until media deletion and marker commit. + let retirement: Task? + if let panicTransport = meshService as? PanicResettingTransport { + retirement = panicTransport.beginPanicReset() + } else { + meshService.emergencyDisconnectAll() + retirement = nil + } + return Task { @MainActor [self] in + defer { isPanicResetting = false } + await retirement?.value + return await finishPanicClearAllData(recoveryIntent, restartServices: restartServices) + } + } + + @MainActor + private func finishPanicClearAllData( + _ recoveryIntent: PanicRecoveryIntent, + restartServices: Bool + ) async -> Bool { // Delete all keychain data (including Noise and Nostr keys) let keychainWipeCompleted = keychain.deleteAllKeychainData() if !keychainWipeCompleted { @@ -1636,10 +1685,10 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage // Drop courier mail carried for third parties (memory and disk), // our own queued outbox, the carried public history, and the // counters describing all of it - CourierStore.shared.wipe() - BridgeCourierService.shared.wipe() + var metadataWipeCompleted = (panicMetadataWipeOperations?.wipeCourier() ?? CourierStore.shared.wipe()) + metadataWipeCompleted = (panicMetadataWipeOperations?.wipeBridge() ?? BridgeCourierService.shared.wipe()) && metadataWipeCompleted messageRouter.wipeOutbox() - GossipMessageArchive.wipeDefault() + metadataWipeCompleted = (panicMetadataWipeOperations?.wipeGossip() ?? GossipMessageArchive.wipeDefault()) && metadataWipeCompleted StoreAndForwardMetrics.shared.reset() // Ambient-liveliness bookkeeping: sampled nearby-chat previews, the @@ -1654,14 +1703,14 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage NostrRelaySettings.reset() // Drop private group keys and rosters (keychain + disk) - groupStore.wipe() + metadataWipeCompleted = (panicMetadataWipeOperations?.wipeGroups() ?? groupStore.wipe()) && metadataWipeCompleted // Drop cached peers' prekey bundles (who we could write to is // metadata too). Our own prekey privates are keychain-backed and go // with deleteAllKeychainData above plus the identity reset below. PrekeyBundleStore.shared.wipe() // Drop bulletin-board posts and tombstones (memory and disk); board // posts are signed with our identity key and persist for days. - BoardStore.shared.wipe() + metadataWipeCompleted = (panicMetadataWipeOperations?.wipeBoard() ?? BoardStore.shared.wipe()) && metadataWipeCompleted // Drop any share-extension handoff staged in the app group. The normal // panic path clears this through AppChromeModel.onPanicWipe, but the @@ -1697,19 +1746,13 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage // Clear read receipt tracking sentReadReceipts.removeAll() - deduplicationService.clearAll() - - // IMPORTANT: Clear Nostr-related state - // Drop relay subscriptions, handlers, pending sends, and replay state. - // Geohash DM handlers can capture pre-wipe Nostr identities, so a plain - // disconnect is not enough here. - NostrRelayManager.shared.resetForPanicWipe() - // Clearing relay handlers stops NEW events, but a detached gift-wrap - // decrypt spawned just before the wipe still holds a pre-wipe key and - // ciphertext; bump the pipeline's wipe generation so its result is - // dropped at the main-actor delivery hop instead of landing here. - nostrCoordinator.inbound.invalidateInFlightDecrypts() - nostrRelayManager = nil + let eventCleanupCompleted: Bool + if let operations = panicMetadataWipeOperations { + eventCleanupCompleted = await operations.wipeEvents() + } else { + eventCleanupCompleted = await deduplicationService.clearAllAsync() + } + metadataWipeCompleted = eventCleanupCompleted && metadataWipeCompleted // Clear Nostr identity associations idBridge.clearAllAssociations() @@ -1725,13 +1768,12 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage meshService.setNickname(nickname) } - // The wipe must finish before this security action returns. A detached - // task could otherwise lose a race with a new capture or app exit and - // leave pre-panic media behind. + // Keep admission closed and recovery pending until file cleanup and + // the recovery-marker commit have both finished. let panicCompleted: Bool do { try panicRecoveryOperations.wipeMedia(recoveryIntent) - if keychainWipeCompleted { + if keychainWipeCompleted && metadataWipeCompleted { try panicRecoveryOperations.complete() panicCompleted = true SecureLogger.info( @@ -1763,18 +1805,23 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage guard panicCompleted else { return false } if let panicTransport = meshService as? PanicResettingTransport { - // Startup recovery reopens admission but leaves actual service - // start to the bootstrapper immediately after this method. + // Startup recovery reopens admission here; the bootstrapper below + // starts services if initialization has not finished yet. panicTransport.completePanicReset( - restartServices: restartServices + restartServices: restartServices && bootstrapConfigured ) } + // A failed startup attempt leaves the service graph unwired. The first + // successful retry must configure it before ordinary runtime work resumes. + let wasConfigured = bootstrapConfigured + configureAfterRecoveryIfNeeded() + if restartServices { // All persistent state and media are gone. Bring each service back // only now, under the new identity — a panic-resetting transport // owns its own restart sequencing above. - if !(meshService is PanicResettingTransport) { + if wasConfigured && !(meshService is PanicResettingTransport) { meshService.startServices() } @@ -2051,6 +2098,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage @MainActor func didReceiveTransportEvent(_ event: TransportEvent) { + guard networkActivationAllowed else { return } switch event { case .messageReceived(let message): _ = didReceiveTransportMessageSynchronously(message) @@ -2156,13 +2204,15 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage func didReceiveGroupMessage(payload: Data, timestamp: Date) { Task { @MainActor [weak self] in - self?.groupCoordinator.handleGroupMessagePayload(payload, timestamp: timestamp) + guard let self, self.networkActivationAllowed else { return } + self.groupCoordinator.handleGroupMessagePayload(payload, timestamp: timestamp) } } func didReceivePublicVoiceFrame(from peerID: PeerID, nickname: String, payload: Data, timestamp: Date) { Task { @MainActor [weak self] in - self?.liveVoiceCoordinator.handlePublicVoiceFramePayload( + guard let self, self.networkActivationAllowed else { return } + self.liveVoiceCoordinator.handlePublicVoiceFramePayload( from: peerID, nickname: nickname, payload: payload, @@ -2329,6 +2379,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage /// Handle incoming public message @MainActor func handlePublicMessage(_ message: BitchatMessage) { + guard networkActivationAllowed else { return } // Bridge hints are unauthenticated and may never suppress a genuine // BLE sender. Once the radio packet has passed BLE signature checks, // replace any earlier bridge alias before this row is enqueued. @@ -2347,6 +2398,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage /// difficulty; sufficient PoW relaxes the per-sender rate limit. @MainActor func handlePublicMessage(_ message: BitchatMessage, powBits: Int) { + guard networkActivationAllowed else { return } publicConversationCoordinator.handlePublicMessage(message, powBits: powBits) } diff --git a/bitchat/ViewModels/Extensions/ChatViewModel+PrivateChat.swift b/bitchat/ViewModels/Extensions/ChatViewModel+PrivateChat.swift index 9dad8030..eeae4eaa 100644 --- a/bitchat/ViewModels/Extensions/ChatViewModel+PrivateChat.swift +++ b/bitchat/ViewModels/Extensions/ChatViewModel+PrivateChat.swift @@ -36,6 +36,7 @@ extension ChatViewModel { id: NostrIdentity, messageTimestamp: Date ) { + guard networkActivationAllowed else { return } privateConversationCoordinator.handlePrivateMessage( payload, senderPubkey: senderPubkey, @@ -176,6 +177,7 @@ extension ChatViewModel { @MainActor func handlePrivateMessage(_ message: BitchatMessage) { + guard networkActivationAllowed else { return } // A finalized voice note whose burst already streamed in live swaps // into the existing bubble instead of appearing (and notifying) twice. if liveVoiceCoordinator.absorbFinalizedVoiceNote(message) { return } diff --git a/bitchat/ViewModels/GeohashSubscriptionManager.swift b/bitchat/ViewModels/GeohashSubscriptionManager.swift index 930cc549..fbbf521a 100644 --- a/bitchat/ViewModels/GeohashSubscriptionManager.swift +++ b/bitchat/ViewModels/GeohashSubscriptionManager.swift @@ -11,6 +11,7 @@ import Tor protocol GeohashSubscriptionContext: AnyObject { // MARK: Channel & subscription state var activeChannel: ChannelID { get set } + var networkActivationAllowed: Bool { get } var currentGeohash: String? { get set } var geoSubscriptionID: String? { get } var geoDmSubscriptionID: String? { get } @@ -132,6 +133,43 @@ final class GeohashSubscriptionManager { self.presence = presence } + #if DEBUG + /// Lets tests hold the outer callback before it enters the inbound pipeline. + @MainActor var relayCallbackScheduler: ((@escaping @MainActor () async -> Void) -> Void)? + #endif + + @MainActor + func giftWrapHandler(identity: NostrIdentity, resubscribing: Bool) -> (NostrEvent) -> Void { + relayEventHandler { manager, event in + if resubscribing { + await manager.inbound.subscribeGiftWrap(event, id: identity)?.value + } else { + await manager.inbound.handleGiftWrap(event, id: identity)?.value + } + } + } + + @MainActor + private func relayEventHandler( + _ receive: @escaping @MainActor (GeohashSubscriptionManager, NostrEvent) async -> Void + ) -> (NostrEvent) -> Void { + let generation = inbound.wipeGeneration + #if DEBUG + let scheduler = relayCallbackScheduler + #endif + return { [weak self] event in + let delivery: @MainActor () async -> Void = { [weak self] in + guard let self, self.inbound.wipeGeneration == generation, + self.context?.networkActivationAllowed == true else { return } + await receive(self, event) + } + #if DEBUG + if let scheduler { scheduler(delivery); return } + #endif + Task { @MainActor in await delivery() } + } + } + @MainActor func resubscribeCurrentGeohash() { guard let context else { return } @@ -153,17 +191,15 @@ final class GeohashSubscriptionManager { count: TransportConfig.nostrGeoRelayCount ) replayingGeoSubscriptionID = subID - NostrRelayManager.shared.subscribe(filter: filter, id: subID, relayUrls: subRelays, handler: { [weak self] event in - Task { @MainActor [weak self] in - guard let self else { return } - self.inbound.subscribeNostrEvent(event, isHistoryReplay: self.replayingGeoSubscriptionID == subID) - // Gateway downlink: rebroadcast relay events for the viewed - // channel onto the mesh (no-op unless gateway mode is on). - GatewayService.shared.rebroadcastRelayEvent(event, geohash: channel.geohash) - } + let generation = inbound.wipeGeneration + NostrRelayManager.shared.subscribe(filter: filter, id: subID, relayUrls: subRelays, handler: relayEventHandler { manager, event in + manager.inbound.subscribeNostrEvent(event, isHistoryReplay: manager.replayingGeoSubscriptionID == subID) + // Gateway downlink shares the callback's panic-generation check. + GatewayService.shared.rebroadcastRelayEvent(event, geohash: channel.geohash) }, onEOSE: { [weak self] in Task { @MainActor [weak self] in - self?.endHistoryReplay(for: subID) + guard let self, self.inbound.wipeGeneration == generation else { return } + self.endHistoryReplay(for: subID) } }) @@ -179,11 +215,8 @@ final class GeohashSubscriptionManager { pubkey: identity.publicKeyHex, since: Date().addingTimeInterval(-TransportConfig.nostrDMSubscribeLookbackSeconds) ) - NostrRelayManager.shared.subscribe(filter: dmFilter, id: dmSub) { [weak self] giftWrap in - Task { @MainActor [weak self] in - self?.inbound.subscribeGiftWrap(giftWrap, id: identity) - } - } + NostrRelayManager.shared.subscribe(filter: dmFilter, id: dmSub, + handler: giftWrapHandler(identity: identity, resubscribing: true)) } } @@ -252,17 +285,15 @@ final class GeohashSubscriptionManager { let filter = NostrFilter.geohashEphemeral(channel.geohash, since: ts, limit: TransportConfig.nostrGeohashInitialLimit) let subRelays = GeoRelayDirectory.shared.closestRelays(toGeohash: channel.geohash, count: 5) replayingGeoSubscriptionID = subID - NostrRelayManager.shared.subscribe(filter: filter, id: subID, relayUrls: subRelays, handler: { [weak self] event in - Task { @MainActor [weak self] in - guard let self else { return } - self.inbound.handleNostrEvent(event, isHistoryReplay: self.replayingGeoSubscriptionID == subID) - // Gateway downlink: rebroadcast relay events for the viewed - // channel onto the mesh (no-op unless gateway mode is on). - GatewayService.shared.rebroadcastRelayEvent(event, geohash: channel.geohash) - } + let generation = inbound.wipeGeneration + NostrRelayManager.shared.subscribe(filter: filter, id: subID, relayUrls: subRelays, handler: relayEventHandler { manager, event in + manager.inbound.handleNostrEvent(event, isHistoryReplay: manager.replayingGeoSubscriptionID == subID) + // Gateway downlink shares the callback's panic-generation check. + GatewayService.shared.rebroadcastRelayEvent(event, geohash: channel.geohash) }, onEOSE: { [weak self] in Task { @MainActor [weak self] in - self?.endHistoryReplay(for: subID) + guard let self, self.inbound.wipeGeneration == generation else { return } + self.endHistoryReplay(for: subID) } }) @@ -283,11 +314,8 @@ final class GeohashSubscriptionManager { pubkey: identity.publicKeyHex, since: Date().addingTimeInterval(-TransportConfig.nostrDMSubscribeLookbackSeconds) ) - NostrRelayManager.shared.subscribe(filter: dmFilter, id: dmSub) { [weak self] giftWrap in - Task { @MainActor [weak self] in - self?.inbound.handleGiftWrap(giftWrap, id: identity) - } - } + NostrRelayManager.shared.subscribe(filter: dmFilter, id: dmSub, + handler: giftWrapHandler(identity: identity, resubscribing: false)) } @MainActor @@ -384,11 +412,10 @@ final class GeohashSubscriptionManager { limit: TransportConfig.nostrGeohashSampleLimit ) let subRelays = GeoRelayDirectory.shared.closestRelays(toGeohash: gh, count: 5) - NostrRelayManager.shared.subscribe(filter: filter, id: subID, relayUrls: subRelays) { [weak self] event in - Task { @MainActor [weak self] in - self?.presence.subscribeNostrEvent(event, gh: gh) - } - } + NostrRelayManager.shared.subscribe(filter: filter, id: subID, relayUrls: subRelays, + handler: relayEventHandler { manager, event in + manager.presence.subscribeNostrEvent(event, gh: gh) + }) } @MainActor @@ -418,10 +445,9 @@ final class GeohashSubscriptionManager { since: Date().addingTimeInterval(-TransportConfig.nostrDMSubscribeLookbackSeconds) ) - context.nostrRelayManager?.subscribe(filter: filter, id: "chat-messages") { [weak self] event in - Task { @MainActor [weak self] in - self?.inbound.handleNostrMessage(event) - } - } + context.nostrRelayManager?.subscribe(filter: filter, id: "chat-messages", + handler: relayEventHandler { manager, event in + await manager.inbound.handleNostrMessage(event)?.value + }) } } diff --git a/bitchat/ViewModels/NostrInboundPipeline.swift b/bitchat/ViewModels/NostrInboundPipeline.swift index 535f1ae5..ce939cc7 100644 --- a/bitchat/ViewModels/NostrInboundPipeline.swift +++ b/bitchat/ViewModels/NostrInboundPipeline.swift @@ -9,6 +9,7 @@ import Foundation @MainActor protocol NostrInboundPipelineContext: AnyObject { var currentGeohash: String? { get } + var networkActivationAllowed: Bool { get } // MARK: Event dedup func hasProcessedNostrEvent(_ eventID: String) -> Bool @@ -127,7 +128,7 @@ final class NostrInboundPipeline { /// count when they arrive, which keeps senders with skewed clocks visible. @MainActor func subscribeNostrEvent(_ event: NostrEvent, isHistoryReplay: Bool = false) { - guard let context else { return } + guard let context, context.networkActivationAllowed else { return } // Cheap rejects (kind, dedup lookup) — duplicates dominate real // traffic. The signature was already verified (exactly once, off the // main actor) by NostrRelayManager before delivery. @@ -200,8 +201,10 @@ final class NostrInboundPipeline { mentions: mentions.isEmpty ? nil : mentions ) - Task { @MainActor [weak context] in - guard let context else { return } + let generation = wipeGeneration + Task { @MainActor [weak self, weak context] in + guard let self, let context, context.networkActivationAllowed, + self.wipeGeneration == generation else { return } let isBlocked = context.isNostrBlocked(pubkeyHexLowercased: event.pubkey.lowercased()) context.handlePublicMessage(message, powBits: powBits) if !isBlocked { @@ -214,7 +217,7 @@ final class NostrInboundPipeline { /// See `subscribeNostrEvent(_:isHistoryReplay:)` for `isHistoryReplay`. @MainActor func handleNostrEvent(_ event: NostrEvent, isHistoryReplay: Bool = false) { - guard let context else { return } + guard let context, context.networkActivationAllowed else { return } // Cheap rejects (kind, dedup lookup) — the signature was already // verified (exactly once, off the main actor) by NostrRelayManager. guard (event.kind == NostrProtocol.EventKind.ephemeralEvent.rawValue @@ -298,45 +301,51 @@ final class NostrInboundPipeline { mentions: mentions.isEmpty ? nil : mentions ) - Task { @MainActor [weak context] in - guard let context else { return } + let generation = wipeGeneration + Task { @MainActor [weak self, weak context] in + guard let self, let context, context.networkActivationAllowed, + self.wipeGeneration == generation else { return } context.handlePublicMessage(message, powBits: powBits) context.checkForMentions(message) context.sendHapticFeedback(for: message) } } + @discardableResult @MainActor - func subscribeGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) { - guard let context else { return } + func subscribeGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) -> Task? { + guard let context, context.networkActivationAllowed else { return nil } // Cheap dedup pre-check only; processGeohashGiftWrap does the // authoritative main-actor check-and-record before the off-main // NIP-17 unwrap. The outer signature was already verified (exactly // once, off the main actor) by NostrRelayManager. - guard !context.hasProcessedNostrEvent(giftWrap.id) else { return } + guard !context.hasProcessedNostrEvent(giftWrap.id) else { return nil } // Capture the wipe generation at spawn, alongside the per-geohash // identity (private key) the detached task strongly captures. A panic // wipe between spawn and delivery bumps the generation, and the task // drops its result instead of delivering plaintext post-wipe. let wipeGeneration = self.wipeGeneration - Task.detached(priority: .userInitiated) { [weak self] in - await self?.processGeohashGiftWrap(giftWrap, id: id, verbose: false, wipeGeneration: wipeGeneration) + return Task.detached(priority: .userInitiated) { [weak self] in + guard let self else { return } + await self.processGeohashGiftWrap(giftWrap, id: id, verbose: false, wipeGeneration: wipeGeneration) } } + @discardableResult @MainActor - func handleGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) { - guard let context else { return } + func handleGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) -> Task? { + guard let context, context.networkActivationAllowed else { return nil } // Cheap dedup pre-check only; see subscribeGiftWrap. if context.hasProcessedNostrEvent(giftWrap.id) { - return + return nil } // Spawn-time wipe-generation capture; see subscribeGiftWrap. let wipeGeneration = self.wipeGeneration - Task.detached(priority: .userInitiated) { [weak self] in - await self?.processGeohashGiftWrap(giftWrap, id: id, verbose: true, wipeGeneration: wipeGeneration) + return Task.detached(priority: .userInitiated) { [weak self] in + guard let self else { return } + await self.processGeohashGiftWrap(giftWrap, id: id, verbose: true, wipeGeneration: wipeGeneration) } } @@ -361,7 +370,7 @@ final class NostrInboundPipeline { // Authoritative check-and-record, atomic on the main actor so two // concurrent detached tasks can't both process the same event. let alreadyProcessed: Bool = await MainActor.run { - guard self.wipeGeneration == wipeGeneration else { return true } + guard context.networkActivationAllowed, self.wipeGeneration == wipeGeneration else { return true } if context.hasProcessedNostrEvent(giftWrap.id) { return true } context.recordProcessedNostrEvent(giftWrap.id) return false @@ -396,7 +405,7 @@ final class NostrInboundPipeline { // A panic wipe during the off-main decrypt must not let the // pre-wipe plaintext reach post-wipe state; drop it here, atomic // with the wipe on the main actor. - guard self.wipeGeneration == wipeGeneration else { return } + guard context.networkActivationAllowed, self.wipeGeneration == wipeGeneration else { return } guard let packet = Self.decodeEmbeddedBitChatPacket(from: content), packet.type == MessageType.noiseEncrypted.rawValue, let payload = NoisePayload.decode(packet.payload) @@ -432,38 +441,35 @@ final class NostrInboundPipeline { } @MainActor - func handleNostrMessage(_ giftWrap: NostrEvent) { - guard let context else { return } + @discardableResult + func handleNostrMessage(_ giftWrap: NostrEvent) -> Task? { + guard let context, context.networkActivationAllowed else { return nil } // Cheap dedup pre-check only; processNostrMessage does the // authoritative check-and-record before the off-main NIP-17 unwrap. // The outer signature was already verified (exactly once, off the // main actor) by NostrRelayManager, and only verified events are // recorded, so a forged-signature copy can never poison the dedup // set and suppress the genuine event. - if context.hasProcessedNostrEvent(giftWrap.id) { return } + if context.hasProcessedNostrEvent(giftWrap.id) { return nil } - Task.detached(priority: .userInitiated) { [weak self] in - await self?.processNostrMessage(giftWrap) + let generation = wipeGeneration + return Task.detached(priority: .userInitiated) { [weak self] in + guard let self else { return } + await self.processNostrMessage(giftWrap, wipeGeneration: generation) } } - func processNostrMessage(_ giftWrap: NostrEvent) async { + func processNostrMessage(_ giftWrap: NostrEvent, wipeGeneration: UInt64) async { guard let context else { return } - // Authoritative check-and-record, atomic on the main actor so two - // concurrent detached tasks can't both process the same event. - let alreadyProcessed: Bool = await MainActor.run { - if context.hasProcessedNostrEvent(giftWrap.id) { return true } + // Admission, dedup and identity acquisition share one main-actor hop. + // A task admitted before panic must not acquire the old identity under + // the new generation while asynchronous cleanup is still pending. + let currentIdentity: NostrIdentity? = await MainActor.run { + guard context.networkActivationAllowed, + self.wipeGeneration == wipeGeneration, + !context.hasProcessedNostrEvent(giftWrap.id) else { return nil } context.recordProcessedNostrEvent(giftWrap.id) - return false - } - if alreadyProcessed { return } - // Fetch the identity and the wipe generation in ONE main-actor hop: - // the generation then vouches for exactly this identity. A wipe after - // this point bumps the generation and the delivery hop below drops - // the decrypted result (same guard as processGeohashGiftWrap; this - // account-mailbox path had the identical hazard). - let (currentIdentity, wipeGeneration): (NostrIdentity?, UInt64) = await MainActor.run { - (context.currentNostrIdentity(), self.wipeGeneration) + return context.currentNostrIdentity() } guard let currentIdentity else { return } @@ -502,7 +508,7 @@ final class NostrInboundPipeline { await MainActor.run { // Drop pre-wipe plaintext if a panic wipe landed // during the off-main decrypt (see above). - guard self.wipeGeneration == wipeGeneration else { return } + guard context.networkActivationAllowed, self.wipeGeneration == wipeGeneration else { return } context.registerNostrKeyMapping(senderPubkey, for: targetPeerID) switch payload.type { diff --git a/bitchat/ViewModels/PublicMessagePipeline.swift b/bitchat/ViewModels/PublicMessagePipeline.swift index 92dd0412..1fb52726 100644 --- a/bitchat/ViewModels/PublicMessagePipeline.swift +++ b/bitchat/ViewModels/PublicMessagePipeline.swift @@ -74,6 +74,14 @@ final class PublicMessagePipeline { buffer.contains { $0.message.id == messageID } } + func resetForPanic() { + timer?.invalidate() + timer = nil + buffer.removeAll(keepingCapacity: false) + recentBatchSizes.removeAll(keepingCapacity: false) + dynamicFlushInterval = baseFlushInterval + } + func flushIfNeeded() { flushBuffer() } diff --git a/bitchat/Views/ContentView.swift b/bitchat/Views/ContentView.swift index 9b09c73d..f66ed2cb 100644 --- a/bitchat/Views/ContentView.swift +++ b/bitchat/Views/ContentView.swift @@ -228,6 +228,7 @@ struct ContentView: View { var body: some View { mainContent + .disabled(appChromeModel.panicInProgress) .onAppear { [conversationUIModel, voiceRecordingVM] in conversationUIModel.setCurrentColorScheme(colorScheme) conversationUIModel.setCurrentTheme(appTheme) diff --git a/bitchatTests/AppArchitectureTests.swift b/bitchatTests/AppArchitectureTests.swift index ef5dfb92..618a11f5 100644 --- a/bitchatTests/AppArchitectureTests.swift +++ b/bitchatTests/AppArchitectureTests.swift @@ -485,7 +485,7 @@ struct AppArchitectureTests { @Test("Panic wipe dismisses chrome sheets so its outcome is visible") @MainActor - func panicWipeDismissesChromePresentation() { + func panicWipeDismissesChromePresentation() async { let viewModel = makeArchitectureViewModel() let privateInboxModel = PrivateInboxModel(conversations: ConversationStore()) let chromeModel = AppChromeModel(chatViewModel: viewModel, privateInboxModel: privateInboxModel) @@ -500,6 +500,9 @@ struct AppArchitectureTests { chromeModel.showFingerprint(for: PeerID(str: "peer-3")) chromeModel.panicClearAllData() + #expect(viewModel.isPanicResetting) + #expect(!viewModel.networkActivationAllowed) + await chromeModel.panicTask?.value #expect(!chromeModel.isAppInfoPresented) #expect(!chromeModel.isLocationChannelsSheetPresented) diff --git a/bitchatTests/ChatNostrCoordinatorContextTests.swift b/bitchatTests/ChatNostrCoordinatorContextTests.swift index ffe22d9f..6e2c99f3 100644 --- a/bitchatTests/ChatNostrCoordinatorContextTests.swift +++ b/bitchatTests/ChatNostrCoordinatorContextTests.swift @@ -106,6 +106,7 @@ private final class MockChatNostrContext: ChatNostrContext { // Nostr identity & blocking var geohashIdentities: [String: NostrIdentity] = [:] + var networkActivationAllowed = true var nostrIdentity: NostrIdentity? var blockedNostrPubkeys: Set = [] var displayNamesByPubkey: [String: String] = [:] @@ -117,7 +118,13 @@ private final class MockChatNostrContext: ChatNostrContext { return identity } - func currentNostrIdentity() -> NostrIdentity? { nostrIdentity } + var identityReads = 0 + var onIdentityRead: (() -> Void)? + func currentNostrIdentity() -> NostrIdentity? { + identityReads += 1 + onIdentityRead?() + return nostrIdentity + } func isNostrBlocked(pubkeyHexLowercased: String) -> Bool { blockedNostrPubkeys.contains(pubkeyHexLowercased.lowercased()) @@ -275,6 +282,23 @@ private func teleportedGeohashEvent(from sender: NostrIdentity, sentAt: Date) th /// the full view-model tests. struct ChatNostrCoordinatorContextTests { + @Test(arguments: [false, true]) @MainActor + func queuedPublicNostrDeliveryRespectsPanicBoundary(_ sampled: Bool) async throws { + let context = MockChatNostrContext() + let coordinator = ChatNostrCoordinator(context: context) + let sender = try NostrIdentity.generate() + let event = try NostrProtocol.createEphemeralGeohashEvent( + content: "pre-panic public message", geohash: "u4pruyd", + senderIdentity: sender, nickname: "synthetic") + if sampled { coordinator.inbound.subscribeNostrEvent(event) } + else { coordinator.inbound.handleNostrEvent(event) } + coordinator.inbound.invalidateInFlightDecrypts() + await drainMainQueue() + #expect(context.handledPublicMessages.isEmpty) + #expect(context.mentionCheckedMessageIDs.isEmpty) + #expect(context.hapticMessageIDs.isEmpty) + } + @Test @MainActor func handleNostrEvent_ingestsPublicMessageOnceAndDeduplicates() async throws { let context = MockChatNostrContext() @@ -543,6 +567,51 @@ struct ChatNostrCoordinatorContextTests { // `test_receiveGiftWrap_tamperedSignatureIsDroppedAndDoesNotPoisonDedup`. // The inbound pipeline only ever sees verified events. + @Test(arguments: [false, true]) @MainActor + func mailboxRejectsIdentityAcquisitionAcrossPanic(_ blocked: Bool) async throws { + let context = MockChatNostrContext() + let coordinator = ChatNostrCoordinator(context: context) + let recipient = try NostrIdentity.generate() + let sender = try NostrIdentity.generate() + context.nostrIdentity = recipient + let embedded = try #require(NostrEmbeddedBitChat.encodePMForNostrNoRecipient( + content: "old mailbox plaintext", messageID: "mailbox-boundary")) + let giftWrap = try NostrProtocol.createPrivateMessage(content: embedded, + recipientPubkey: recipient.publicKeyHex, senderIdentity: sender) + let generation = coordinator.inbound.wipeGeneration + if blocked { context.networkActivationAllowed = false } + else { coordinator.inbound.invalidateInFlightDecrypts() } + await coordinator.inbound.processNostrMessage(giftWrap, wipeGeneration: generation) + #expect(context.identityReads == 0) + #expect(context.recordedNostrEventIDs.isEmpty) + #expect(context.handledPrivateMessages.isEmpty) + + context.networkActivationAllowed = true + await coordinator.inbound.processNostrMessage(giftWrap, + wipeGeneration: coordinator.inbound.wipeGeneration) + #expect(context.identityReads == 1) + #expect(context.handledPrivateMessages.count == 1) + } + + @Test @MainActor + func mailboxDropsDeliveryIfPanicFollowsIdentityAcquisition() async throws { + let context = MockChatNostrContext() + let coordinator = ChatNostrCoordinator(context: context) + let recipient = try NostrIdentity.generate() + let sender = try NostrIdentity.generate() + context.nostrIdentity = recipient + let embedded = try #require(NostrEmbeddedBitChat.encodePMForNostrNoRecipient( + content: "old mailbox plaintext", messageID: "mailbox-delivery")) + let giftWrap = try NostrProtocol.createPrivateMessage(content: embedded, + recipientPubkey: recipient.publicKeyHex, senderIdentity: sender) + context.onIdentityRead = { coordinator.inbound.invalidateInFlightDecrypts() } + await coordinator.inbound.processNostrMessage(giftWrap, + wipeGeneration: coordinator.inbound.wipeGeneration) + #expect(context.identityReads == 1) + #expect(context.handledPrivateMessages.isEmpty) + #expect(context.nostrKeyMapping.isEmpty) + } + @Test @MainActor func processNostrMessage_duplicateDeliveryProcessesOnce() async throws { let context = MockChatNostrContext() @@ -559,10 +628,10 @@ struct ChatNostrCoordinatorContextTests { // Fan-in of the same (already verified) gift wrap from several relays // records and processes exactly once. - await coordinator.inbound.processNostrMessage(giftWrap) + await coordinator.inbound.processNostrMessage(giftWrap, wipeGeneration: coordinator.inbound.wipeGeneration) #expect(context.recordedNostrEventIDs == [giftWrap.id]) - await coordinator.inbound.processNostrMessage(giftWrap) + await coordinator.inbound.processNostrMessage(giftWrap, wipeGeneration: coordinator.inbound.wipeGeneration) #expect(context.recordedNostrEventIDs == [giftWrap.id]) } diff --git a/bitchatTests/ChatOutgoingCoordinatorContextTests.swift b/bitchatTests/ChatOutgoingCoordinatorContextTests.swift index 174f2da5..d7e24963 100644 --- a/bitchatTests/ChatOutgoingCoordinatorContextTests.swift +++ b/bitchatTests/ChatOutgoingCoordinatorContextTests.swift @@ -257,3 +257,43 @@ struct ChatOutgoingCoordinatorContextTests { == context.appendedPublicMessages.map(\.message.id)) } } + + +struct OutgoingPanicBoundaryTests { + @Test(arguments: [false, true]) @MainActor + func completionFromOldMiningCannotEchoSendOrReportError(_ failMining: Bool) async throws { + let context = MockChatOutgoingContext() + context.activeChannel = .location(GeohashChannel(level: .city, geohash: "u4pruydq")) + var release: CheckedContinuation? + let coordinator = ChatOutgoingCoordinator(context: context, buildGeohashEvent: { content, geohash, identity, nickname, teleported in + let event = try await NostrProtocol.createMinedEphemeralGeohashEvent( + content: content, geohash: geohash, senderIdentity: identity, + nickname: nickname, teleported: teleported) + await withCheckedContinuation { release = $0 } + if failMining { throw MockChatOutgoingContext.IdentityUnavailable() } + return event + }) + coordinator.sendMessage("old mining") + let task = try #require(coordinator.geohashMiningTask) + for _ in 0..<100 where release == nil { try await Task.sleep(nanoseconds: 10_000_000) } + let resume = try #require(release) + coordinator.resetForPanic() + resume.resume() + await task.value + #expect(context.appendedPublicMessages.isEmpty) + #expect(context.sentGeohashContexts.isEmpty) + #expect(context.recordedActivityKeys.isEmpty) + #expect(context.systemMessages.isEmpty) + } + + @Test @MainActor + func panicInvalidatesDeferredCommandsButAllowsFreshCommands() async { + let context = MockChatOutgoingContext() + let coordinator = ChatOutgoingCoordinator(context: context) + coordinator.sendMessage("/who old") + coordinator.resetForPanic() + coordinator.sendMessage("/who fresh") + await drainMainActorTasks() + #expect(context.handledCommands == ["/who fresh"]) + } +} diff --git a/bitchatTests/ChatViewModelTests.swift b/bitchatTests/ChatViewModelTests.swift index 9306c606..a1aa29e8 100644 --- a/bitchatTests/ChatViewModelTests.swift +++ b/bitchatTests/ChatViewModelTests.swift @@ -20,6 +20,7 @@ private func makeTestableViewModel( panicMediaWipe: (() throws -> Void)? = nil, panicRecoveryOperations: PanicRecoveryOperations? = nil, panicNetworkLifecycle: PanicNetworkLifecycle = .noop, + panicMetadataWipeOperations: PanicMetadataWipeOperations? = nil, locationManager: LocationChannelManager = .shared ) -> (viewModel: ChatViewModel, transport: MockTransport) { let keychain = injectedKeychain ?? MockKeychain() @@ -36,6 +37,7 @@ private func makeTestableViewModel( locationManager: locationManager, panicMediaWipe: panicMediaWipe, panicRecoveryOperations: panicRecoveryOperations, + panicMetadataWipeOperations: panicMetadataWipeOperations, panicNetworkLifecycle: panicNetworkLifecycle ) @@ -2065,7 +2067,7 @@ struct ChatViewModelPrivateMediaDeletionTests { } @Test @MainActor - func panicInvalidatesActiveAndQueuedPrivateChatClears() { + func panicInvalidatesActiveAndQueuedPrivateChatClears() async { let (viewModel, transport) = makeTestableViewModel() transport.deferDeletedPrivateMediaPersistence = true let firstPeerID = PeerID(str: String(repeating: "4", count: 64)) @@ -2097,7 +2099,7 @@ struct ChatViewModelPrivateMediaDeletionTests { transport.deletedPrivateMediaMessageIDBatches == [[firstID]] ) - _ = viewModel.panicClearAllData(restartServices: false) + _ = await viewModel.panicClearAllData(restartServices: false) viewModel.seedPrivateChat([ privateMediaMessage( id: firstID, @@ -2150,20 +2152,257 @@ struct ChatViewModelPrivateMediaDeletionTests { struct ChatViewModelPanicTests { + @Test(arguments: 0...6) @MainActor + func metadataFailureAttemptsRemainingCleanupAndRetryCommits(_ failedStore: Int) async { + let names = ["courier", "bridge", "gossip", "groups", "board", "events"] + var attempts: [String] = [] + var denyDeletion = true + var pending = false + var commits = 0 + var mediaAttempts = 0 + var restarts = 0 + func wipe(_ index: Int) -> Bool { + attempts.append(names[index]) + return !denyDeletion || (failedStore != index && failedStore != 6) + } + let metadata = PanicMetadataWipeOperations( + wipeCourier: { wipe(0) }, + wipeBridge: { wipe(1) }, + wipeGossip: { wipe(2) }, + wipeGroups: { wipe(3) }, + wipeBoard: { wipe(4) }, + wipeEvents: { wipe(5) } + ) + let recovery = PanicRecoveryOperations( + isPending: { pending }, + begin: { + pending = true + return PanicRecoveryIntent(fileMarkerEstablished: true, externalMarkerEstablished: true) + }, + wipeMedia: { _ in mediaAttempts += 1 }, + complete: { commits += 1; pending = false } + ) + let keychain = MockKeychain() + let (viewModel, transport) = makeTestableViewModel( + keychain: keychain, + panicRecoveryOperations: recovery, + panicNetworkLifecycle: PanicNetworkLifecycle(stop: {}, restart: { restarts += 1 }), + panicMetadataWipeOperations: metadata + ) + let starts = transport.startServicesCallCount + + #expect(!(await viewModel.panicClearAllData()), "A denied metadata store must keep panic incomplete") + #expect(attempts == names, "A denied store must not skip the later metadata stores") + #expect(keychain.deleteAllCallCount == 1) + #expect(mediaAttempts == 1, "Metadata failure must not skip media cleanup") + #expect(pending) + #expect(commits == 0) + #expect(restarts == 0) + #expect(transport.startServicesCallCount == starts) + #expect(!viewModel.networkActivationAllowed) + + denyDeletion = false + attempts.removeAll() + #expect(await viewModel.panicClearAllData()) + #expect(attempts == names, "Retry must attempt the full metadata cleanup again") + #expect(keychain.deleteAllCallCount == 2) + #expect(mediaAttempts == 2) + #expect(!pending) + #expect(commits == 1) + #expect(restarts == 1) + #expect(transport.startServicesCallCount == starts + 1) + #expect(viewModel.networkActivationAllowed) + } + + @Test(arguments: 0..<6) @MainActor + func unresolvedMetadataLocationKeepsPanicPendingUntilRetry(_ failedStore: Int) async throws { + let names = ["courier", "bridge", "gossip", "groups", "board", "events"] + let fm = FileManager.default + let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try fm.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? fm.removeItem(at: root) } + let files = names.map { root.appendingPathComponent("\($0).json") } + let sibling = root.appendingPathComponent("keep.txt") + let bytes = Data("SYNTHETIC_UNRESOLVED_METADATA".utf8) + let siblingBytes = Data("KEEP".utf8) + var denyLookup = true + var lookups = Array(repeating: 0, count: names.count) + func resolve(_ index: Int) -> URL? { + lookups[index] += 1 + return denyLookup && index == failedStore ? nil : files[index] + } + let keychain = MockKeychain() + let courier = CourierStore(resolveDefaultFileURL: { resolve(0) }) + let bridge = BridgeDropDedupStore(resolveDefaultFileURL: { resolve(1) }) + let gossip = GossipMessageArchive(resolveDefaultFileURL: { resolve(2) }) + let groups = GroupStore(keychain: keychain, resolveDefaultFileURL: { resolve(3) }) + let board = BoardStore(resolveDefaultFileURL: { resolve(4) }) + let events = NostrProcessedEventStore(resolveDefaultFileURL: { resolve(5) }) + let bridgeService = BridgeCourierService(dedupStore: bridge) + let deduplicationService = MessageDeduplicationService(nostrEventStore: events) + let wipes: [() -> Bool] = [ + { courier.wipe() }, { bridgeService.wipe() }, { gossip.wipe() }, + { groups.wipe() }, { board.wipe() }, { deduplicationService.clearAll() } + ] + // File removal does not depend on decoding; seed after constructing the stores. + for file in files { try bytes.write(to: file) } + try siblingBytes.write(to: sibling) + var attempts: [String] = [] + func wipe(_ index: Int) -> Bool { + attempts.append(names[index]) + return wipes[index]() + } + let metadata = PanicMetadataWipeOperations( + wipeCourier: { wipe(0) }, wipeBridge: { wipe(1) }, + wipeGossip: { wipe(2) }, wipeGroups: { wipe(3) }, + wipeBoard: { wipe(4) }, wipeEvents: { wipe(5) } + ) + var pending = false + var mediaAttempts = 0 + var completionOrder: [String] = [] + let recovery = PanicRecoveryOperations( + isPending: { pending }, + begin: { + pending = true + return PanicRecoveryIntent(fileMarkerEstablished: true, externalMarkerEstablished: true) + }, + wipeMedia: { _ in mediaAttempts += 1 }, + complete: { completionOrder.append("complete"); pending = false } + ) + let lifecycle = PanicNetworkLifecycle(stop: {}, restart: { + #expect(!pending, "Recovery must complete before service restart") + completionOrder.append("restart") + }) + let (viewModel, transport) = makeTestableViewModel( + keychain: keychain, + panicRecoveryOperations: recovery, + panicNetworkLifecycle: lifecycle, + panicMetadataWipeOperations: metadata + ) + let starts = transport.startServicesCallCount + #expect(keychain.saveIdentityKey(Data("SYNTHETIC_KEY".utf8), forKey: "panic-url-resolution-test")) + + #expect(!(await viewModel.panicClearAllData()), "An unresolved persistent location must keep panic incomplete") + #expect(attempts == names, "A failed lookup must not skip other metadata stores") + #expect(keychain.deleteAllCallCount == 1) + #expect(keychain.getIdentityKey(forKey: "panic-url-resolution-test") == nil) + #expect(mediaAttempts == 1) + #expect(pending) + #expect(completionOrder.isEmpty, "An unresolved store must not complete recovery or restart services") + #expect(transport.startServicesCallCount == starts) + #expect(!viewModel.networkActivationAllowed) + #expect(try Data(contentsOf: files[failedStore]) == bytes) + for index in names.indices where index != failedStore { + #expect(!fm.fileExists(atPath: files[index].path), "Other metadata stores must still be deleted") + } + #expect(try Data(contentsOf: sibling) == siblingBytes) + + let failedLookups = lookups[failedStore] + denyLookup = false + attempts.removeAll() + #expect(await viewModel.panicClearAllData(), "Retry must resolve the location and finish cleanup") + #expect(lookups[failedStore] > failedLookups, "Retry must attempt the failed lookup again") + #expect(attempts == names) + #expect(keychain.deleteAllCallCount == 2) + #expect(mediaAttempts == 2) + #expect(!pending) + #expect(completionOrder == ["complete", "restart"]) + #expect(transport.startServicesCallCount == starts + 1) + #expect(viewModel.networkActivationAllowed) + for file in files { #expect(!fm.fileExists(atPath: file.path)) } + #expect(try Data(contentsOf: sibling) == siblingBytes) + } + @Test @MainActor - func panicClearAllData_finishesMediaWipeBeforeReturning() { + func metadataFailureDuringBootstrapKeepsIntentForRetry() async throws { + let suiteName = "PanicBootstrapLocation." + UUID().uuidString + let storage = try #require(UserDefaults(suiteName: suiteName)) + defer { storage.removePersistentDomain(forName: suiteName) } + let locationManager = LocationChannelManager(storage: storage) + let names = ["courier", "bridge", "gossip", "groups", "board", "events"] + var attempts: [String] = [] + var denyBoardDeletion = true + var pending = true + var commits = 0 + var mediaAttempts = 0 + var restarts = 0 + func wipe(_ index: Int) -> Bool { + attempts.append(names[index]) + return index != 4 || !denyBoardDeletion + } + let metadata = PanicMetadataWipeOperations( + wipeCourier: { wipe(0) }, wipeBridge: { wipe(1) }, + wipeGossip: { wipe(2) }, wipeGroups: { wipe(3) }, + wipeBoard: { wipe(4) }, wipeEvents: { wipe(5) } + ) + let recovery = PanicRecoveryOperations( + isPending: { pending }, + begin: { + pending = true + return PanicRecoveryIntent(fileMarkerEstablished: true, externalMarkerEstablished: true) + }, + wipeMedia: { _ in mediaAttempts += 1 }, + complete: { commits += 1; pending = false } + ) + let keychain = MockKeychain() + let (viewModel, transport) = makeTestableViewModel( + keychain: keychain, + panicRecoveryOperations: recovery, + panicNetworkLifecycle: PanicNetworkLifecycle(stop: {}, restart: { restarts += 1 }), + panicMetadataWipeOperations: metadata, + locationManager: locationManager + ) + + _ = await viewModel.startupPanicRecovery?.value + + #expect(attempts == names, "Bootstrap recovery must attempt each metadata operation") + #expect(keychain.deleteAllCallCount == 1) + #expect(mediaAttempts == 1) + #expect(pending) + #expect(commits == 0) + #expect(restarts == 0) + #expect(transport.startServicesCallCount == 0) + #expect(!viewModel.networkActivationAllowed) + + #expect(transport.delegate == nil) + #expect(viewModel.publicMessagePipeline.delegate == nil) + denyBoardDeletion = false + attempts.removeAll() + #expect(await viewModel.panicClearAllData()) + #expect(attempts == names) + #expect(keychain.deleteAllCallCount == 2) + #expect(mediaAttempts == 2) + #expect(!pending) + #expect(commits == 1) + #expect(restarts == 1) + #expect(transport.startServicesCallCount == 1) + #expect(viewModel.networkActivationAllowed) + #expect(transport.delegate === viewModel) + #expect(transport.eventDelegate === viewModel) + #expect(viewModel.publicMessagePipeline.delegate != nil) + let fresh = BitchatMessage(sender: "synthetic", content: "after startup retry", timestamp: Date(), isRelay: false) + viewModel.handlePublicMessage(fresh) + viewModel.publicMessagePipeline.flushIfNeeded() + #expect(viewModel.messages.contains(where: { $0.id == fresh.id })) + let bindings = viewModel.cancellables.count + #expect(await viewModel.panicClearAllData()) + #expect(viewModel.cancellables.count == bindings, "A later wipe must not bootstrap twice") + } + + @Test @MainActor + func panicClearAllData_finishesMediaWipeBeforeReturning() async { var wipeFinished = false let (viewModel, _) = makeTestableViewModel(panicMediaWipe: { wipeFinished = true }) - viewModel.panicClearAllData() + await viewModel.panicClearAllData() #expect(wipeFinished) } @Test @MainActor - func panicClearAllData_stopsNetworkBeforeWipeAndRestartsAfterCommit() { + func panicClearAllData_stopsNetworkBeforeWipeAndRestartsAfterCommit() async { var events: [String] = [] let lifecycle = PanicNetworkLifecycle( stop: { events.append("stop") }, @@ -2174,7 +2413,7 @@ struct ChatViewModelPanicTests { panicNetworkLifecycle: lifecycle ) - let completed = viewModel.panicClearAllData() + let completed = await viewModel.panicClearAllData() #expect(completed) #expect(events == ["stop", "wipe", "restart"]) @@ -2182,7 +2421,7 @@ struct ChatViewModelPanicTests { } @Test @MainActor - func panicKeychainFailureKeepsRecoveryPendingAndServicesStopped() { + func panicKeychainFailureKeepsRecoveryPendingAndServicesStopped() async { let keychain = MockKeychain() keychain.simulatedDeleteAllResult = false var events: [String] = [] @@ -2209,7 +2448,7 @@ struct ChatViewModelPanicTests { ) let startsBeforePanic = transport.startServicesCallCount - let completed = viewModel.panicClearAllData() + let completed = await viewModel.panicClearAllData() #expect(!completed) #expect(events == ["stop", "begin", "wipe"]) @@ -2219,7 +2458,7 @@ struct ChatViewModelPanicTests { } @Test @MainActor - func pendingPanicRecoveryCompletesBeforeTransportBootstrap() { + func pendingPanicRecoveryCompletesBeforeTransportBootstrap() async { var events: [String] = [] let operations = PanicRecoveryOperations( isPending: { @@ -2241,6 +2480,8 @@ struct ChatViewModelPanicTests { panicRecoveryOperations: operations ) + _ = await viewModel.startupPanicRecovery?.value + #expect(events == ["read", "begin", "wipe", "complete"]) #expect(transport.emergencyDisconnectCallCount == 1) #expect(transport.startServicesCallCount == 1) @@ -2248,7 +2489,7 @@ struct ChatViewModelPanicTests { } @Test @MainActor - func failedStartupRecoveryLeavesTransportAndNetworkBlocked() { + func failedStartupRecoveryLeavesTransportAndNetworkBlocked() async { enum WipeFailure: Error { case failed } var completedMarker = false let operations = PanicRecoveryOperations( @@ -2267,6 +2508,8 @@ struct ChatViewModelPanicTests { panicRecoveryOperations: operations ) + _ = await viewModel.startupPanicRecovery?.value + #expect(!completedMarker) #expect(transport.emergencyDisconnectCallCount == 1) #expect(transport.startServicesCallCount == 0) @@ -2274,7 +2517,7 @@ struct ChatViewModelPanicTests { } @Test @MainActor - func failedStartupKeychainRecoveryLeavesIntentAndTransportBlocked() { + func failedStartupKeychainRecoveryLeavesIntentAndTransportBlocked() async { let keychain = MockKeychain() keychain.simulatedDeleteAllResult = false var events: [String] = [] @@ -2296,6 +2539,8 @@ struct ChatViewModelPanicTests { panicRecoveryOperations: operations ) + _ = await viewModel.startupPanicRecovery?.value + #expect(events == ["begin", "wipe"]) #expect(keychain.deleteAllCallCount == 1) #expect(transport.emergencyDisconnectCallCount == 1) @@ -2332,7 +2577,7 @@ struct ChatViewModelPanicTests { ], for: PeerID(str: "PEER1")) viewModel.markPrivateChatUnread(PeerID(str: "PEER1")) - viewModel.panicClearAllData() + await viewModel.panicClearAllData() // After panic, emergency disconnect should be called #expect(transport.emergencyDisconnectCallCount == 1) @@ -2363,7 +2608,7 @@ struct ChatViewModelPanicTests { viewModel.geoNicknames = [pubkey: "alice"] viewModel.teleportedGeo = [pubkey] - viewModel.panicClearAllData() + await viewModel.panicClearAllData() #expect(viewModel.activeChannel == .mesh) #expect(viewModel.geoSubscriptionID == nil) @@ -2377,7 +2622,7 @@ struct ChatViewModelPanicTests { } @Test @MainActor - func panicClearAllData_wipesTheLocationStateOfItsOwnManager() throws { + func panicClearAllData_wipesTheLocationStateOfItsOwnManager() async throws { // Where the device has been, persisted the way the location manager // writes it: a teleport and a bookmark. let suiteName = "ChatViewModelPanicTests.\(UUID().uuidString)" @@ -2389,7 +2634,7 @@ struct ChatViewModelPanicTests { #expect(locationManager.bookmarks == ["u4pruy"]) let (viewModel, _) = makeTestableViewModel(locationManager: locationManager) - viewModel.panicClearAllData() + await viewModel.panicClearAllData() // The wipe lands on the manager the view model runs on: `.shared` in // the app, this test's own here, which leaves the process-wide one to @@ -2411,3 +2656,239 @@ struct ChatViewModelLifecycleTests { #expect(transport.startServicesCallCount == 1) } } + +// Private responsiveness regression: synthetic files and mocked lifecycle/recovery. +struct PanicResponsivenessTests { + @Test(arguments: [false, true]) @MainActor + func eventQueueWaitAllowsMainActorProgressBeforeCompletion(_ cancelCaller: Bool) async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let file = root.appendingPathComponent("events.json") + try Data("[]".utf8).write(to: file) + let queue = DispatchQueue(label: "panic.test.events") + let store = NostrProcessedEventStore(fileURL: file, ioQueue: queue) + let dedup = MessageDeduplicationService(nostrEventStore: store) + let release = DispatchSemaphore(value: 0) + queue.async { release.wait() } + // Bounded watchdog releases the synthetic slow operation even if main blocks. + var pending = false + var committed = false + var restarted = false + var heartbeatWhilePending = false + var duringWipe: () -> Void = {} + var heartbeat: Task? + var wipeTask: Task? + let recovery = PanicRecoveryOperations(isPending: { false }, begin: { + pending = true + duringWipe() + return PanicRecoveryIntent(fileMarkerEstablished: true, externalMarkerEstablished: true) + }, wipeMedia: { _ in }, complete: { committed = true; pending = false }) + let metadata = PanicMetadataWipeOperations(wipeCourier: { true }, wipeBridge: { true }, + wipeGossip: { true }, wipeGroups: { true }, wipeBoard: { true }, wipeEvents: { + DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) { release.signal() } + return await dedup.clearAllAsync() + }) + let (viewModel, _) = makeTestableViewModel(panicRecoveryOperations: recovery, + panicNetworkLifecycle: PanicNetworkLifecycle(stop: {}, restart: { restarted = true }), + panicMetadataWipeOperations: metadata) + duringWipe = { + heartbeat = Task { @MainActor in + try? await Task.sleep(nanoseconds: 50_000_000) + heartbeatWhilePending = pending && !committed && !restarted && !viewModel.networkActivationAllowed + if cancelCaller { wipeTask?.cancel() } + release.signal() + } + } + wipeTask = Task { @MainActor in await viewModel.panicClearAllData() } + let result = await wipeTask!.value + await heartbeat?.value + #expect(heartbeatWhilePending, "Main actor must run while queued deletion is pending") + #expect(result) + #expect(committed && restarted) + #expect(!FileManager.default.fileExists(atPath: file.path)) + } +} + +struct GossipPanicResponsivenessTests { + @Test(arguments: [false, true]) @MainActor + func pendingRetirementYieldsAndRejectsOverlappingPanic(_ denyEvents: Bool) async throws { + let suiteName = "PanicGossipLocation." + UUID().uuidString + let storage = try #require(UserDefaults(suiteName: suiteName)) + defer { storage.removePersistentDomain(forName: suiteName) } + let locationManager = LocationChannelManager(storage: storage) + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let file = root.appendingPathComponent("gossip.json") + let queue = DispatchQueue(label: "panic.test.gossip") + let archive = GossipMessageArchive(fileURL: file) + let manager = GossipSyncManager(myPeerID: PeerID(str: "1122334455667788"), + requestSyncManager: RequestSyncManager(), archive: archive, queue: queue) + let release = DispatchSemaphore(value: 0) + queue.async { release.wait(); archive.save([Data("synthetic queued save".utf8)]) } + let keychain = MockKeychain() + let idBridge = NostrIdentityBridge(keychain: MockKeychainHelper()) + let identityManager = MockIdentityManager(keychain) + let transport = BLEService(keychain: keychain, idBridge: idBridge, + identityManager: identityManager, initializeBluetoothManagers: false) + var pending = false + var begins = 0 + var commits = 0 + var mediaAttempts = 0 + var deny = denyEvents + let recovery = PanicRecoveryOperations(isPending: { false }, begin: { + begins += 1; pending = true + DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) { release.signal() } + return PanicRecoveryIntent(fileMarkerEstablished: true, externalMarkerEstablished: true) + }, wipeMedia: { _ in mediaAttempts += 1 }, complete: { commits += 1; pending = false }) + let metadata = PanicMetadataWipeOperations(wipeCourier: { true }, wipeBridge: { true }, + wipeGossip: { archive.wipe() }, wipeGroups: { true }, wipeBoard: { true }, wipeEvents: { !deny }) + let viewModel = ChatViewModel(keychain: keychain, idBridge: idBridge, + identityManager: identityManager, transport: transport, + locationManager: locationManager, + panicRecoveryOperations: recovery, panicMetadataWipeOperations: metadata) + transport._test_replaceGossipManager(manager) + defer { transport.suspendForPanicReset() } + let buffered = BitchatMessage(sender: "synthetic", content: "buffered before wipe", timestamp: Date(), isRelay: false) + viewModel.handlePublicMessage(buffered) + #expect(viewModel.publicMessagePipeline.containsMessage(withID: buffered.id)) + let chrome = AppChromeModel(chatViewModel: viewModel, + privateInboxModel: PrivateInboxModel(conversations: viewModel.conversations)) + let recipient = try NostrIdentity.generate() + let sender = try NostrIdentity.generate() + let embedded = try #require(NostrEmbeddedBitChat.encodePMForNostrNoRecipient( + content: "old mailbox plaintext", messageID: "old-mailbox")) + let giftWrap = try NostrProtocol.createPrivateMessage(content: embedded, + recipientPubkey: recipient.publicKeyHex, senderIdentity: sender) + let mailboxTask = viewModel.nostrCoordinator.inbound.handleNostrMessage(giftWrap) + let heartbeat = Task { @MainActor in + try? await Task.sleep(nanoseconds: 50_000_000) + #expect(pending && transport.radioIsPanicSuspended()) + #expect(!viewModel.networkActivationAllowed) + #expect(!(await viewModel.panicClearAllData()), "Overlapping panic must not begin another transaction") + #expect(begins == 1) + // The pre-panic task reaches identity acquisition while retirement + // remains pending. It must not add an event ID to the new generation. + await mailboxTask?.value + #expect(!viewModel.hasProcessedNostrEvent(giftWrap.id)) + release.signal() + #expect(!viewModel.publicMessagePipeline.containsMessage(withID: buffered.id)) + viewModel.publicMessagePipeline.flushIfNeeded() + #expect(!viewModel.messages.contains(where: { $0.id == buffered.id })) + let late = BitchatMessage(sender: "synthetic", content: "during wipe", timestamp: Date(), isRelay: false) + viewModel.handlePublicMessage(late) + #expect(!viewModel.publicMessagePipeline.containsMessage(withID: late.id)) + #expect(!viewModel.messages.contains(where: { $0.id == late.id }), "Pending wipe must reject inbound state") + viewModel.sendMessage("during wipe") + #expect(!viewModel.messages.contains(where: { $0.content == "during wipe" }), "Pending wipe must reject user sends") + } + chrome.panicClearAllData() + // No actor yield between confirmation and these boundary assertions. + #expect(pending && begins == 1) + #expect(transport.radioIsPanicSuspended()) + #expect(!viewModel.networkActivationAllowed && chrome.panicInProgress) + await chrome.panicTask?.value + await heartbeat.value + #expect(!chrome.panicInProgress) + #expect(mediaAttempts == 1) + #expect(!FileManager.default.fileExists(atPath: file.path), "Delete must follow queued save") + #expect(pending == denyEvents) + #expect(commits == (denyEvents ? 0 : 1)) + #expect(transport.radioIsPanicSuspended() == denyEvents) + manager.persistNow() + _ = manager._messageCount(for: PeerID(str: "1122334455667788")) + #expect(!FileManager.default.fileExists(atPath: file.path), "Retired owner must not recreate the archive") + if denyEvents { + deny = false + #expect(await viewModel.panicClearAllData()) + #expect(!pending && commits == 1 && !transport.radioIsPanicSuspended()) + } + let fresh = BitchatMessage(sender: "synthetic", content: "new after recovery", timestamp: Date(), isRelay: false) + viewModel.handlePublicMessage(fresh) + viewModel.publicMessagePipeline.flushIfNeeded() + #expect(viewModel.messages.contains(where: { $0.id == fresh.id })) + } +} + + +@Suite(.serialized) +struct PanicTaskBoundaryTests { + @Test(arguments: [false, true]) @MainActor + func queuedRelayCallbackCannotAdoptPostPanicGeneration(_ resubscribing: Bool) async throws { + let recovery = PanicRecoveryOperations(isPending: { false }, begin: { + PanicRecoveryIntent(fileMarkerEstablished: true, externalMarkerEstablished: true) + }, wipeMedia: { _ in }, complete: {}) + let metadata = PanicMetadataWipeOperations(wipeCourier: { true }, wipeBridge: { true }, + wipeGossip: { true }, wipeGroups: { true }, wipeBoard: { true }, wipeEvents: { true }) + let suiteName = "PanicTaskBoundaryTests.\(UUID().uuidString)" + let storage = try #require(UserDefaults(suiteName: suiteName)) + defer { storage.removePersistentDomain(forName: suiteName) } + let (viewModel, _) = makeTestableViewModel(panicRecoveryOperations: recovery, + panicMetadataWipeOperations: metadata, locationManager: LocationChannelManager(storage: storage)) + let recipient = try NostrIdentity.generate() + let sender = try NostrIdentity.generate() + let embedded = try #require(NostrEmbeddedBitChat.encodePMForNostrNoRecipient( + content: "synthetic old relay callback", messageID: "old-callback")) + let event = try NostrProtocol.createPrivateMessage(content: embedded, + recipientPubkey: recipient.publicKeyHex, senderIdentity: sender) + var callbacks: [@MainActor () async -> Void] = [] + let subscriptions = viewModel.nostrCoordinator.subscriptions + subscriptions.relayCallbackScheduler = { callbacks.append($0) } + let handler = subscriptions.giftWrapHandler(identity: recipient, resubscribing: resubscribing) + handler(event) + #expect(callbacks.count == 1) + #expect(await viewModel.panicClearAllData()) + // Model an already-enqueued outer callback not scheduled until after + // recovery. It must not acquire the pipeline's new wipe generation. + let oldCallback = callbacks.removeFirst() + await oldCallback() + #expect(!viewModel.hasProcessedNostrEvent(event.id)) + let oldMessages = viewModel.conversations.conversationsByID.values.flatMap(\.messages) + #expect(!oldMessages.contains { $0.content == "synthetic old relay callback" }) + // A new registration after recovery can deliver the same test event. + let freshHandler = subscriptions.giftWrapHandler(identity: recipient, resubscribing: resubscribing) + freshHandler(event) + await callbacks.removeFirst()() + let freshMessages = viewModel.conversations.conversationsByID.values.flatMap(\.messages) + #expect(freshMessages.contains { $0.content == "synthetic old relay callback" }) + } + + @Test @MainActor + func pendingGeohashSendCannotRestoreClearedConversation() async throws { + var releaseCleanup: CheckedContinuation? + let recovery = PanicRecoveryOperations(isPending: { false }, begin: { + PanicRecoveryIntent(fileMarkerEstablished: true, externalMarkerEstablished: true) + }, wipeMedia: { _ in }, complete: {}) + let metadata = PanicMetadataWipeOperations(wipeCourier: { true }, wipeBridge: { true }, + wipeGossip: { true }, wipeGroups: { true }, wipeBoard: { true }, wipeEvents: { + await withCheckedContinuation { releaseCleanup = $0 } + }) + let suiteName = "PanicTaskBoundaryTests.\(UUID().uuidString)" + let storage = try #require(UserDefaults(suiteName: suiteName)) + defer { storage.removePersistentDomain(forName: suiteName) } + let (viewModel, _) = makeTestableViewModel(panicRecoveryOperations: recovery, + panicMetadataWipeOperations: metadata, locationManager: LocationChannelManager(storage: storage)) + let channel = GeohashChannel(level: .city, geohash: "u4pruydq") + viewModel.activeChannel = .location(channel) + viewModel.sendMessage("synthetic pre-panic send") + let send = try #require(viewModel.outgoingCoordinator.geohashMiningTask) + // Begin panic without yielding to the outgoing task. Mining and its + // continuation then run while the controller waits for cleanup. + let wipe = try #require(viewModel.beginPanicClearAllData()) + await send.value + for _ in 0..<100 where releaseCleanup == nil { await Task.yield() } + let release = try #require(releaseCleanup) + let retained = viewModel.conversations.conversationsByID[.geohash(channel.geohash)]?.messages ?? [] + #expect(!retained.contains { $0.content == "synthetic pre-panic send" }) + #expect(!viewModel.networkActivationAllowed) + release.resume(returning: true) + #expect(await wipe.value) + // A fresh outgoing task after successful recovery must still work. + viewModel.activeChannel = .location(channel) + viewModel.sendMessage("synthetic fresh send") + await viewModel.outgoingCoordinator.geohashMiningTask?.value + let fresh = viewModel.conversations.conversationsByID[.geohash(channel.geohash)]?.messages ?? [] + #expect(fresh.contains { $0.content == "synthetic fresh send" }) + } +} diff --git a/bitchatTests/ConversationUIModelTests.swift b/bitchatTests/ConversationUIModelTests.swift index a4f90e6c..42adeece 100644 --- a/bitchatTests/ConversationUIModelTests.swift +++ b/bitchatTests/ConversationUIModelTests.swift @@ -334,7 +334,7 @@ struct ConversationUIModelTests { // The wipe reseeds every geohash identity and returns to the mesh, // which takes the retired key out of the memo too. - viewModel.panicClearAllData() + await viewModel.panicClearAllData() #expect(await TestHelpers.waitUntil({ uiModel.ownGeoChatSender == nil }, timeout: TestConstants.settleTimeout)) Self.show(geohash: Self.geohash, in: viewModel) let newHex = try Self.myGeoHex(viewModel) diff --git a/bitchatTests/Performance/PerformanceBaselineTests.swift b/bitchatTests/Performance/PerformanceBaselineTests.swift index 6eda1e09..08786e10 100644 --- a/bitchatTests/Performance/PerformanceBaselineTests.swift +++ b/bitchatTests/Performance/PerformanceBaselineTests.swift @@ -649,6 +649,7 @@ private struct SeededGenerator: RandomNumberGenerator { /// the coordinator's own pipeline. @MainActor private final class PerfNostrContext: ChatNostrContext { + var networkActivationAllowed: Bool { true } var activeChannel: ChannelID = .location(GeohashChannel(level: .neighborhood, geohash: "u4pruyd")) var currentGeohash: String? = "u4pruyd" var geoSubscriptionID: String? diff --git a/bitchatTests/Services/ComposerDraftStoreTests.swift b/bitchatTests/Services/ComposerDraftStoreTests.swift index d4f0a603..7ef444ee 100644 --- a/bitchatTests/Services/ComposerDraftStoreTests.swift +++ b/bitchatTests/Services/ComposerDraftStoreTests.swift @@ -3,7 +3,10 @@ import Testing @testable import bitchat import BitFoundation +// Keep synchronous store assertions on the same actor as panic reset. +// Suite serialization alone does not exclude panic tests in other suites. @Suite(.serialized) +@MainActor struct ComposerDraftStoreTests { /// Isolate each test from leftover in-memory drafts. private func withCleanStore(_ body: () -> Void) { diff --git a/bitchatTests/Services/NoiseEncryptionServiceTests.swift b/bitchatTests/Services/NoiseEncryptionServiceTests.swift index c0cd293f..c51fa7ad 100644 --- a/bitchatTests/Services/NoiseEncryptionServiceTests.swift +++ b/bitchatTests/Services/NoiseEncryptionServiceTests.swift @@ -667,42 +667,63 @@ struct NoiseEncryptionServiceTests { @Test("Claim gives an attempt a full on-wire timeout window") func handshakeClaimRearmsDeadline() async throws { let timeoutInterval: TimeInterval = 1 - let service = NoiseEncryptionService( - keychain: MockKeychain(), - ordinaryHandshakeTimeout: timeoutInterval - ) - let peerID = PeerID(str: "1021324354657687") - let recorder = HandshakeStartRecorder() - service.onHandshakeRecoveryRequired = { [weak service] request in - let firedAt = DispatchTime.now().uptimeNanoseconds - service?.cancelHandshakeRecovery(request) - recorder.recordTimeout(at: firedAt) - } - - let attempt = try #require( - try service.initiateHandshakeIfNeeded( - with: peerID, - retryOnTimeout: true + // Expired preparations do not satisfy this test: a claim must succeed. + for _ in 0..<5 { + let service = NoiseEncryptionService( + keychain: MockKeychain(), + ordinaryHandshakeTimeout: timeoutInterval ) - ) - try? await Task.sleep(nanoseconds: 500_000_000) - let claimed = service.claimHandshakeInitiation(attempt, for: peerID) - let claimedAt = DispatchTime.now().uptimeNanoseconds - #expect(claimed == attempt.payload) - let expired = await TestHelpers.waitUntil( - { recorder.timeoutCount == 1 }, - timeout: 5 - ) - #expect(expired) - let firedAt = try #require(recorder.firstTimeoutUptimeNanoseconds) - try #require(firedAt >= claimedAt) - let elapsed = TimeInterval(firedAt - claimedAt) / 1_000_000_000 - // A non-rearmed deadline would fire roughly 0.5 seconds after the - // claim. Measure on the timeout queue instead of relying on a task to - // resume inside a narrow pre-deadline window under parallel CI load. - #expect(elapsed >= timeoutInterval * 0.75) - #expect(!service.hasSession(with: peerID)) - #expect(recorder.timeoutCount == 1) + let peerID = PeerID(str: "1021324354657687") + let recorder = HandshakeStartRecorder() + service.onHandshakeRecoveryRequired = { [weak service] request in + let firedAt = DispatchTime.now().uptimeNanoseconds + service?.cancelHandshakeRecovery(request) + recorder.recordTimeout(at: firedAt) + } + + let preparedAt = DispatchTime.now().uptimeNanoseconds + let attempt = try #require( + try service.initiateHandshakeIfNeeded( + with: peerID, + retryOnTimeout: true + ) + ) + try? await Task.sleep(nanoseconds: 500_000_000) + let claimedAt = DispatchTime.now().uptimeNanoseconds + let claimed = service.claimHandshakeInitiation(attempt, for: peerID) + let claimReturnedAt = DispatchTime.now().uptimeNanoseconds + if claimed == nil { + // Waiting for recovery could hide a false nil while the session is live. + let missElapsed = TimeInterval(claimReturnedAt - preparedAt) / 1_000_000_000 + try #require(missElapsed >= timeoutInterval) + try #require(!service.hasSession(with: peerID)) + } + let expired = await TestHelpers.waitUntil( + { recorder.timeoutCount == 1 }, + timeout: 5 + ) + #expect(expired) + let firedAt = try #require(recorder.firstTimeoutUptimeNanoseconds) + if claimed == nil { + // A delayed test task can miss the preparation window. Verify + // expiry before retrying; an expired attempt does not test rearm. + try #require(firedAt >= preparedAt) + let preparationElapsed = TimeInterval(firedAt - preparedAt) / 1_000_000_000 + try #require(preparationElapsed >= timeoutInterval) + continue + } + #expect(claimed == attempt.payload) + try #require(firedAt >= claimedAt) + let elapsed = TimeInterval(firedAt - claimedAt) / 1_000_000_000 + // A non-rearmed deadline would fire roughly 0.5 seconds after the + // claim. The timestamp is captured in the recovery callback; callback + // delay can hide early expiry, so it is not an exact timer measurement. + #expect(elapsed >= timeoutInterval * 0.75) + #expect(!service.hasSession(with: peerID)) + #expect(recorder.timeoutCount == 1) + return + } + Issue.record("No claim succeeded before preparation expired in five attempts") } @Test("Duplicate spoofed message one cannot extend rollback or repause during cooldown") diff --git a/bitchatTests/Services/PanicMetadataCompletionTests.swift b/bitchatTests/Services/PanicMetadataCompletionTests.swift new file mode 100644 index 00000000..ae65839d --- /dev/null +++ b/bitchatTests/Services/PanicMetadataCompletionTests.swift @@ -0,0 +1,135 @@ +import Foundation +import BitFoundation +import XCTest +@testable import bitchat + +final class PanicMetadataCompletionTests: XCTestCase { + // Dispatch workers own the synchronous store calls. The lock protects the + // observation shared with the asynchronous XCTest method. + private final class Fixture: @unchecked Sendable { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + let queue = DispatchQueue(label: "test.processed-events.panic") + let release = DispatchSemaphore(value: 0) + private let lock = NSLock() + private var released = false + var file: URL { root.appendingPathComponent("events.json") } + lazy var store = NostrProcessedEventStore(fileURL: file, ioQueue: queue) + lazy var archive = GossipMessageArchive(fileURL: root.appendingPathComponent("gossip.json")) + lazy var gossip = GossipSyncManager( + myPeerID: PeerID(str: "0102030405060708"), + requestSyncManager: RequestSyncManager(), + archive: archive + ) + + func openQueue() { + lock.lock() + released = true + lock.unlock() + release.signal() + } + + var queueWasReleased: Bool { + lock.lock() + defer { lock.unlock() } + return released + } + } + + func testProcessedEventWipeWaitsForEarlierAppendAndAllowsFreshPersistence() async { + let fixture = Fixture() + let held = expectation(description: "serial file queue held after seed") + let entered = expectation(description: "worker about to wipe queued append") + let returnedEarly = expectation(description: "wipe returned while file queue held") + returnedEarly.isInverted = true + let completed = expectation(description: "wipe and fresh persistence completed") + defer { fixture.openQueue() } + + DispatchQueue.global().async { + fixture.store.append(["synthetic-seed"], cap: 10) + XCTAssertEqual(fixture.store.load(), ["synthetic-seed"]) + fixture.queue.async { + held.fulfill() + fixture.release.wait() + } + } + await fulfillment(of: [held], timeout: TestConstants.settleTimeout) + + DispatchQueue.global().async { + fixture.store.append(["synthetic-pre-panic"], cap: 10) + entered.fulfill() + let wiped = fixture.store.wipe() + if !fixture.queueWasReleased { returnedEarly.fulfill() } + XCTAssertTrue(wiped) + XCTAssertTrue(fixture.queueWasReleased, "Processed-event wipe must finish deletion before returning") + // Inspect before a load or another queue fence could hide an early return. + XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.file.path), + "Processed-event wipe must finish deletion before returning") + fixture.store.append(["synthetic-fresh"], cap: 10) + XCTAssertEqual(fixture.store.load(), ["synthetic-fresh"]) + let reopened = NostrProcessedEventStore(fileURL: fixture.file) + XCTAssertEqual(reopened.load(), ["synthetic-fresh"]) + try? FileManager.default.removeItem(at: fixture.root) + completed.fulfill() + } + await fulfillment(of: [entered], timeout: TestConstants.settleTimeout) + // This bounded observation is scheduling evidence; the intended removal + // control must reach the early-return assertion to establish sensitivity. + await fulfillment(of: [returnedEarly], timeout: TestConstants.negativeWaitWindow) + fixture.openQueue() + await fulfillment(of: [completed], timeout: TestConstants.settleTimeout) + } + + func testGossipPanicRetirementDrainsQueuedPersistenceBeforeArchiveDeletion() async { + let fixture = Fixture() + let held = expectation(description: "gossip queue held by packet collection") + let entered = expectation(description: "worker about to retire gossip owner") + let returnedEarly = expectation(description: "retirement returned while gossip queue held") + returnedEarly.isInverted = true + let completed = expectation(description: "retirement and archive deletion completed") + defer { fixture.openQueue() } + + DispatchQueue.global().async { + fixture.gossip.collectPublicMessagePackets { _ in + held.fulfill() + fixture.release.wait() + } + } + await fulfillment(of: [held], timeout: TestConstants.settleTimeout) + DispatchQueue.global().async { + let sender = PeerID(str: "1122334455667788") + let packet = BitchatPacket( + type: MessageType.message.rawValue, + senderID: Data([0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]), + recipientID: nil, + timestamp: UInt64(Date().timeIntervalSince1970 * 1000), + payload: Data("SYNTHETIC_QUEUED_GOSSIP".utf8), signature: nil, ttl: 1 + ) + fixture.gossip.onPublicPacketSeen(packet) + fixture.gossip.persistNow() + entered.fulfill() + fixture.gossip.stopForPanic() + XCTAssertTrue(fixture.queueWasReleased, "Gossip retirement must wait for queued persistence") + if !fixture.queueWasReleased { returnedEarly.fulfill() } + XCTAssertEqual(fixture.archive.load().count, 1, + "The queued pre-panic packet must reach persistence before retirement returns") + XCTAssertTrue(fixture.archive.wipe()) + let latePacket = BitchatPacket( + type: packet.type, senderID: packet.senderID, recipientID: nil, + timestamp: packet.timestamp, + payload: Data("SYNTHETIC_RETIRED_OWNER_CALLBACK".utf8), signature: nil, ttl: 1 + ) + fixture.gossip.onPublicPacketSeen(latePacket) + fixture.gossip.persistNow() + XCTAssertEqual(fixture.gossip._messageCount(for: sender), 2) + XCTAssertTrue(fixture.archive.load().isEmpty, + "The retired owner must not recreate its deleted archive") + fixture.gossip.stop() + try? FileManager.default.removeItem(at: fixture.root) + completed.fulfill() + } + await fulfillment(of: [entered], timeout: TestConstants.settleTimeout) + await fulfillment(of: [returnedEarly], timeout: TestConstants.negativeWaitWindow) + fixture.openQueue() + await fulfillment(of: [completed], timeout: TestConstants.settleTimeout) + } +} diff --git a/bitchatTests/Services/PanicMetadataStoreTests.swift b/bitchatTests/Services/PanicMetadataStoreTests.swift new file mode 100644 index 00000000..19773edf --- /dev/null +++ b/bitchatTests/Services/PanicMetadataStoreTests.swift @@ -0,0 +1,306 @@ +import BitFoundation +import Foundation +import CryptoKit +import Testing +#if canImport(Darwin) +import Darwin +#endif +@testable import bitchat + +@Suite(.serialized) +@MainActor +struct PanicMetadataStoreTests { + enum Store: CaseIterable { case groups, board, courier, gossip, bridge, events } + + @Test(arguments: Store.allCases) + func deletionFailureIsReportedAndRetryPreservesSibling(_ store: Store) throws { + let fm = FileManager.default + let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try fm.createDirectory(at: root, withIntermediateDirectories: true) + defer { _ = chmod(root.path, 0o700); try? fm.removeItem(at: root) } + let file = root.appendingPathComponent("metadata.json") + let sibling = root.appendingPathComponent("keep.txt") + let wipe: () -> Bool + switch store { + case .groups: + let owner = GroupStore(keychain: MockKeychain(), fileURL: file) + wipe = { owner.wipe() } + case .board: + let owner = BoardStore(fileURL: file) + wipe = { owner.wipe() } + case .courier: + let owner = CourierStore(fileURL: file) + wipe = { owner.wipe() } + case .gossip: + let owner = GossipMessageArchive(fileURL: file) + wipe = { owner.wipe() } + case .bridge: + let owner = BridgeDropDedupStore(fileURL: file) + wipe = { owner.wipe() } + case .events: + let owner = NostrProcessedEventStore(fileURL: file) + wipe = { owner.wipe() } + } + // Deletion is independent of record decoding; producer/reload coverage is separate. + let bytes = Data("SYNTHETIC_METADATA_DELETE_UNIT_FIXTURE".utf8) + try bytes.write(to: file) + try Data("KEEP".utf8).write(to: sibling) + #expect(chmod(root.path, 0o500) == 0) + #expect(!wipe(), "A denied metadata deletion must be reported") + #expect(try Data(contentsOf: file) == bytes) + #expect(chmod(root.path, 0o700) == 0) + #expect(wipe(), "Metadata deletion must succeed after access is restored") + #expect(!fm.fileExists(atPath: file.path)) + #expect(fm.fileExists(atPath: sibling.path), "Unrelated metadata sibling must survive") + if fm.fileExists(atPath: sibling.path) { + #expect(try Data(contentsOf: sibling) == Data("KEEP".utf8)) + } + #expect(wipe(), "An absent metadata file must be harmless") + } + + private func makeWipe( + _ store: Store, + fileURL: URL? = nil, + persistsToDisk: Bool = true, + resolve: @escaping () -> URL? + ) -> () -> Bool { + switch store { + case .groups: + let owner = GroupStore(keychain: MockKeychain(), persistsToDisk: persistsToDisk, + fileURL: fileURL, resolveDefaultFileURL: resolve) + return { owner.wipe() } + case .board: + let owner = BoardStore(persistsToDisk: persistsToDisk, fileURL: fileURL, + resolveDefaultFileURL: resolve) + return { owner.wipe() } + case .courier: + let owner = CourierStore(persistsToDisk: persistsToDisk, fileURL: fileURL, + resolveDefaultFileURL: resolve) + return { owner.wipe() } + case .gossip: + let owner = GossipMessageArchive(fileURL: fileURL, resolveDefaultFileURL: resolve) + return { owner.wipe() } + case .bridge: + let owner = BridgeDropDedupStore(persistsToDisk: persistsToDisk, fileURL: fileURL, + resolveDefaultFileURL: resolve) + return { owner.wipe() } + case .events: + let owner = NostrProcessedEventStore(fileURL: fileURL, resolveDefaultFileURL: resolve) + return { owner.wipe() } + } + } + + @Test(arguments: Store.allCases) + func unresolvedLocationFailsAndSameOwnerRetries(_ store: Store) throws { + let fm = FileManager.default + let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try fm.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? fm.removeItem(at: root) } + let file = root.appendingPathComponent("metadata.json") + let sibling = root.appendingPathComponent("keep.txt") + let bytes = Data("SYNTHETIC_UNRESOLVED_METADATA".utf8) + try bytes.write(to: file) + try Data("KEEP".utf8).write(to: sibling) + var resolvedURL: URL? + var lookups = 0 + let wipe = makeWipe(store) { lookups += 1; return resolvedURL } + #expect(!wipe(), "An unresolved persistent location must not count as deleted") + #expect(try Data(contentsOf: file) == bytes) + let failedLookups = lookups + resolvedURL = file + #expect(wipe(), "The same store must retry a failed location lookup") + #expect(lookups > failedLookups) + #expect(!fm.fileExists(atPath: file.path), "Recovered lookup must delete the retained metadata") + #expect(try Data(contentsOf: sibling) == Data("KEEP".utf8)) + let recoveredLookups = lookups + resolvedURL = nil + #expect(wipe(), "A recovered, now absent location must remain harmless") + #expect(lookups == recoveredLookups, "A recovered location must be retained") + } + + @Test(arguments: Store.allCases) + func explicitLocationBypassesDefaultLookup(_ store: Store) throws { + let fm = FileManager.default + let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try fm.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? fm.removeItem(at: root) } + let file = root.appendingPathComponent("metadata.json") + var lookups = 0 + let wipe = makeWipe(store, fileURL: file) { lookups += 1; return nil } + try Data("SYNTHETIC_EXPLICIT_METADATA".utf8).write(to: file) + #expect(wipe()) + #expect(!fm.fileExists(atPath: file.path)) + #expect(wipe(), "An explicitly located missing file must be harmless") + #expect(lookups == 0, "Explicit locations must bypass default lookup") + } + + @Test(arguments: [Store.groups, .board, .courier, .bridge]) + func memoryOnlyStoreNeitherResolvesNorDeletes(_ store: Store) throws { + let fm = FileManager.default + let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try fm.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? fm.removeItem(at: root) } + let file = root.appendingPathComponent("keep.json") + let bytes = Data("SYNTHETIC_UNOWNED_FILE".utf8) + try bytes.write(to: file) + var lookups = 0 + let wipe = makeWipe(store, fileURL: file, persistsToDisk: false) { lookups += 1; return file } + #expect(wipe(), "An intentionally memory-only store has no persistent cleanup") + #expect(fm.fileExists(atPath: file.path), "Memory-only cleanup must preserve supplied files") + if fm.fileExists(atPath: file.path) { #expect(try Data(contentsOf: file) == bytes) } + let wipeWithoutOverride = makeWipe(store, persistsToDisk: false) { lookups += 1; return file } + #expect(wipeWithoutOverride()) + #expect(lookups == 0, "Memory-only stores must not resolve a persistent location") + #expect(fm.fileExists(atPath: file.path)) + if fm.fileExists(atPath: file.path) { #expect(try Data(contentsOf: file) == bytes) } + } + + @Test + func defaultGossipWipeReportsUnresolvedLocationAndRetries() throws { + let fm = FileManager.default + let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try fm.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? fm.removeItem(at: root) } + let file = root.appendingPathComponent("archive.json") + let sibling = root.appendingPathComponent("keep.txt") + let bytes = Data("SYNTHETIC_DEFAULT_ARCHIVE".utf8) + try bytes.write(to: file) + try Data("KEEP".utf8).write(to: sibling) + #expect(!GossipMessageArchive.wipeDefault(resolveDefaultFileURL: { nil }), + "Default archive cleanup must report failed lookup") + #expect(try Data(contentsOf: file) == bytes) + #expect(GossipMessageArchive.wipeDefault(resolveDefaultFileURL: { file })) + #expect(!fm.fileExists(atPath: file.path)) + #expect(try Data(contentsOf: sibling) == Data("KEEP".utf8)) + #expect(GossipMessageArchive.wipeDefault(resolveDefaultFileURL: { file })) + } + + @Test(arguments: Store.allCases) + func recoveredLocationSupportsSameOwnerPersistence(_ store: Store) throws { + let fm = FileManager.default + let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try fm.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? fm.removeItem(at: root) } + let file = root.appendingPathComponent("metadata.json") + var resolvedURL: URL? + let resolve = { resolvedURL } + let wipe: () -> Bool + let saveAndReload: () throws -> Void + let now = Date(timeIntervalSince1970: 1_750_000_000) + switch store { + case .groups: + let keychain = MockKeychain() + let owner = GroupStore(keychain: keychain, resolveDefaultFileURL: resolve) + wipe = { owner.wipe() } + saveAndReload = { + let member = GroupMember(fingerprint: Data(repeating: 1, count: 32).hexEncodedString(), + signingKey: Data(repeating: 2, count: 32), nickname: "synthetic") + let group = try #require(owner.createGroup(named: "synthetic", creator: member)) + let reloaded = GroupStore(keychain: keychain, fileURL: file) + #expect(reloaded.group(withID: group.groupID) == group) + } + case .board: + let owner = BoardStore(now: { now }, resolveDefaultFileURL: resolve) + wipe = { owner.wipe() } + saveAndReload = { + let author = Curve25519.Signing.PrivateKey() + let postID = Data(repeating: 3, count: 16) + let created = UInt64(now.timeIntervalSince1970 * 1000) + let expires = created + 3_600_000 + let key = author.publicKey.rawRepresentation + let signingBytes = BoardPostPacket.signingBytes( + postID: postID, geohash: "9q8yy", content: "synthetic", authorSigningKey: key, + authorNickname: "synthetic", createdAt: created, expiresAt: expires, flags: 0) + let post = BoardPostPacket( + postID: postID, geohash: "9q8yy", content: "synthetic", authorSigningKey: key, + authorNickname: "synthetic", createdAt: created, expiresAt: expires, flags: 0, + signature: try author.signature(for: signingBytes)) + let wire = BoardWire.post(post) + let packet = BitchatPacket(type: MessageType.boardPost.rawValue, + senderID: Data(repeating: 4, count: 8), recipientID: nil, + timestamp: created, payload: wire.encode(), signature: nil, ttl: 1) + #expect(owner.ingest(wire, packet: packet) == .accepted) + let reloaded = BoardStore(fileURL: file, now: { now }) + #expect(reloaded.posts(forGeohash: "9q8yy").map(\.postID) == [postID]) + } + case .courier: + let owner = CourierStore(now: { now }, resolveDefaultFileURL: resolve) + wipe = { owner.wipe() } + saveAndReload = { + let recipient = Data(repeating: 5, count: 32) + let envelope = CourierEnvelope( + recipientTag: CourierEnvelope.recipientTag( + noiseStaticKey: recipient, epochDay: CourierEnvelope.epochDay(for: now)), + expiry: UInt64((now.timeIntervalSince1970 + 3600) * 1000), + ciphertext: Data(repeating: 6, count: 96)) + #expect(owner.deposit(envelope, from: Data(repeating: 7, count: 32))) + let reloaded = CourierStore(fileURL: file, now: { now }) + #expect(reloaded.takeEnvelopes(for: recipient) == [envelope]) + } + case .gossip: + let owner = GossipMessageArchive(resolveDefaultFileURL: resolve) + wipe = { owner.wipe() } + saveAndReload = { + let packet = BitchatPacket(type: MessageType.message.rawValue, + senderID: Data(repeating: 8, count: 8), recipientID: nil, + timestamp: UInt64(now.timeIntervalSince1970 * 1000), + payload: Data("SYNTHETIC_PUBLIC_PACKET".utf8), signature: nil, ttl: 1) + let encoded = try #require(packet.toBinaryData(padding: false)) + owner.save([encoded]) + #expect(GossipMessageArchive(fileURL: file).load() == [encoded]) + } + case .bridge: + let owner = BridgeDropDedupStore(resolveDefaultFileURL: resolve) + wipe = { owner.wipe() } + saveAndReload = { + owner.save(BridgeDropDedupStore.Snapshot( + publishedDropKeys: ["synthetic-drop": now], seenDropEventIDs: ["synthetic-event": now])) + let reloaded = BridgeDropDedupStore(fileURL: file).load() + #expect(reloaded.publishedDropKeys == ["synthetic-drop": now]) + #expect(reloaded.seenDropEventIDs == ["synthetic-event": now]) + } + case .events: + let owner = NostrProcessedEventStore(resolveDefaultFileURL: resolve) + wipe = { owner.wipe() } + saveAndReload = { + let eventID = String(repeating: "a", count: 64) + owner.append([eventID], cap: 10) + // load fences the serial append before a fresh owner reads the file. + #expect(owner.load() == [eventID]) + #expect(NostrProcessedEventStore(fileURL: file).load() == [eventID]) + } + } + #expect(!wipe()) + resolvedURL = file + #expect(wipe()) + resolvedURL = nil + try saveAndReload() + } + + @Test(arguments: [false, true]) + func panicRetirementPreventsPersistenceAndOrdinaryStopPreservesIt(_ retire: Bool) throws { + let fm = FileManager.default + let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try fm.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? fm.removeItem(at: root) } + let file = root.appendingPathComponent("archive.json") + let archive = GossipMessageArchive(fileURL: file) + let sender = PeerID(str: "1122334455667788") + let packet = BitchatPacket(type: MessageType.message.rawValue, + senderID: Data([0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]), + recipientID: nil, + timestamp: UInt64(Date().timeIntervalSince1970 * 1000), + payload: Data("SYNTHETIC_PUBLIC_PACKET".utf8), signature: nil, ttl: 1) + let encoded = try #require(packet.toBinaryData(padding: false)) + archive.save([encoded]) + let manager = GossipSyncManager(myPeerID: sender, requestSyncManager: RequestSyncManager(), archive: archive) + #expect(manager._messageCount(for: sender) == 1) + if retire { manager.stopForPanic() } else { manager.stop(); manager.start() } + defer { manager.stop() } + #expect(archive.wipe()) + manager.persistNow() + _ = manager._messageCount(for: sender) + #expect(fm.fileExists(atPath: file.path) == !retire, + "A retired owner must not save; ordinary stop/start must retain persistence") + } +}