From 9717e7513f210acaee4e28fdd7bcba7325b7bf0f Mon Sep 17 00:00:00 2001 From: jack <212554440+jackjackbits@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:36:08 -1000 Subject: [PATCH] perf: Keychain/identity caching, ephemeral Nostr dedup, fragment routing guard, media & row cache quick wins (#1882) --- bitchat/Nostr/NostrIdentity.swift | 28 ++- bitchat/Nostr/NostrIdentityBridge.swift | 99 +++++++--- bitchat/Protocols/BitchatFilePacket.swift | 33 +++- .../BLE/BLESourceRouteOriginationPolicy.swift | 2 + bitchat/Services/CashuTokenDecoder.swift | 34 ++++ .../Services/Courier/MessageOutboxStore.swift | 12 +- bitchat/Services/Groups/GroupStore.swift | 15 +- bitchat/Services/KeychainManager.swift | 186 ++++++++++-------- .../MessageDeduplicationService.swift | 10 +- .../Services/NostrProcessedEventStore.swift | 131 ++++++++++-- bitchat/Utils/Color+Peer.swift | 7 +- bitchat/ViewModels/ChatMediaPreparation.swift | 10 +- .../ChatMediaTransferCoordinator.swift | 115 +++++------ .../GeohashSubscriptionManager.swift | 4 +- bitchat/ViewModels/NostrInboundPipeline.swift | 11 +- .../Views/Media/BlockRevealImageView.swift | 52 +++-- .../ChatNostrCoordinatorContextTests.swift | 4 + .../MessageDeduplicationServiceTests.swift | 74 +++++++ bitchatTests/Mocks/MockKeychain.swift | 13 +- .../PerformanceBaselineTests.swift | 1 + ...BLESourceRouteOriginationPolicyTests.swift | 45 +++++ bitchatTests/Services/GroupStoreTests.swift | 12 ++ localPackages/Arti/arti-bitchat/src/socks.rs | 4 + 23 files changed, 665 insertions(+), 237 deletions(-) diff --git a/bitchat/Nostr/NostrIdentity.swift b/bitchat/Nostr/NostrIdentity.swift index 9d41ca54..29bf74d2 100644 --- a/bitchat/Nostr/NostrIdentity.swift +++ b/bitchat/Nostr/NostrIdentity.swift @@ -7,12 +7,33 @@ struct NostrIdentity: Codable { let privateKey: Data let publicKey: Data let npub: String // Bech32-encoded public key + /// Precomputed lowercase hex representation of `publicKey` (32-byte x-only), + /// stored once at construction instead of re-encoding on every render/lookup. + let publicKeyHex: String + + private enum CodingKeys: String, CodingKey { + case privateKey + case publicKey + case npub + } /// Memberwise initializer init(privateKey: Data, publicKey: Data, npub: String, createdAt _: Date) { self.privateKey = privateKey self.publicKey = publicKey self.npub = npub + self.publicKeyHex = publicKey.hexEncodedString() + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let privateKey = try container.decode(Data.self, forKey: .privateKey) + let publicKey = try container.decode(Data.self, forKey: .publicKey) + let npub = try container.decode(String.self, forKey: .npub) + self.privateKey = privateKey + self.publicKey = publicKey + self.npub = npub + self.publicKeyHex = publicKey.hexEncodedString() } /// Generate a new Nostr identity @@ -38,16 +59,11 @@ struct NostrIdentity: Codable { self.privateKey = privateKeyData self.publicKey = xOnlyPubkey self.npub = try Bech32.encode(hrp: "npub", data: xOnlyPubkey) + self.publicKeyHex = xOnlyPubkey.hexEncodedString() } /// Get Schnorr signing key for Nostr event signatures func schnorrSigningKey() throws -> P256K.Schnorr.PrivateKey { try P256K.Schnorr.PrivateKey(dataRepresentation: privateKey) } - - /// Get hex-encoded public key (for Nostr events) - var publicKeyHex: String { - // Public key is already stored as x-only (32 bytes) - return publicKey.hexEncodedString() - } } diff --git a/bitchat/Nostr/NostrIdentityBridge.swift b/bitchat/Nostr/NostrIdentityBridge.swift index 52cb4876..066289fb 100644 --- a/bitchat/Nostr/NostrIdentityBridge.swift +++ b/bitchat/Nostr/NostrIdentityBridge.swift @@ -8,6 +8,7 @@ final class NostrIdentityBridge { private let currentIdentityKey = "nostr-current-identity" private let deviceSeedKey = "nostr-device-seed" // In-memory cache to avoid transient keychain access issues + private var currentIdentityCache: NostrIdentity? private var deviceSeedCache: Data? // Cache derived identities to avoid repeated crypto during view rendering private var derivedIdentityCache: [String: NostrIdentity] = [:] @@ -21,19 +22,43 @@ final class NostrIdentityBridge { /// Get or create the current Nostr identity func getCurrentNostrIdentity() throws -> NostrIdentity? { - // Check if we already have a Nostr identity - if let existingData = keychain.load(key: currentIdentityKey, service: keychainService), - let identity = try? JSONDecoder().decode(NostrIdentity.self, from: existingData) { - return identity + cacheLock.lock() + if let cached = currentIdentityCache { + cacheLock.unlock() + return cached } - + cacheLock.unlock() + + // Distinguish missing vs transiently unavailable Keychain so a locked-device + // read neither overwrites an existing identity nor caches a throwaway key. + switch keychain.loadWithResult(key: currentIdentityKey, service: keychainService) { + case .success(let existingData): + if let identity = try? JSONDecoder().decode(NostrIdentity.self, from: existingData) { + cacheLock.lock() + currentIdentityCache = identity + cacheLock.unlock() + return identity + } + case .itemNotFound: + break + case .deviceLocked, .accessDenied, .authenticationFailed, .otherError: + return nil + } + // Generate new Nostr identity let nostrIdentity = try NostrIdentity.generate() - - // Store it + + // Store it and confirm retention before caching, since save is void-returning let data = try JSONEncoder().encode(nostrIdentity) keychain.save(key: currentIdentityKey, data: data, service: keychainService, accessible: nil) - + + if case .success(let stored) = keychain.loadWithResult(key: currentIdentityKey, service: keychainService), + stored == data { + cacheLock.lock() + currentIdentityCache = nostrIdentity + cacheLock.unlock() + } + return nostrIdentity } @@ -52,6 +77,7 @@ final class NostrIdentityBridge { /// cannot keep signing with pre-panic keys cached in memory. func clearInMemoryCaches() { cacheLock.lock() + currentIdentityCache = nil deviceSeedCache = nil derivedIdentityCache.removeAll() cacheLock.unlock() @@ -73,33 +99,46 @@ final class NostrIdentityBridge { // MARK: - Per-Geohash Identities (Location Channels) - /// Returns a stable device seed used to derive unlinkable per-geohash identities. - /// Stored only on device keychain. - private func getOrCreateDeviceSeed() -> Data { + /// Returns a stable device seed used to derive unlinkable per-geohash identities, + /// along with whether the seed is durably backed by Keychain and safe to cache. + private func getOrCreateDeviceSeed() -> (seed: Data, durable: Bool) { cacheLock.lock() if let cached = deviceSeedCache { cacheLock.unlock() - return cached + return (cached, true) } cacheLock.unlock() - if let existing = keychain.load(key: deviceSeedKey, service: keychainService) { - // Migrate to AfterFirstUnlockThisDeviceOnly for stability during lock - keychain.save(key: deviceSeedKey, data: existing, service: keychainService, accessible: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) + switch keychain.loadWithResult(key: deviceSeedKey, service: keychainService) { + case .success(let existing): cacheLock.lock() deviceSeedCache = existing cacheLock.unlock() - return existing + return (existing, true) + case .itemNotFound: + break + case .deviceLocked, .accessDenied, .authenticationFailed, .otherError: + // Preserve the retry path without overwriting or caching a temporary seed. + let ephemeralSeed = SymmetricKey(size: .bits256).withUnsafeBytes { Data($0) } + return (ephemeralSeed, false) } + // CryptoKit key generation cannot fail, unlike SecRandomCopyBytes — // a discarded failure here would persist an all-zero identity seed. let seed = SymmetricKey(size: .bits256).withUnsafeBytes { Data($0) } // Ensure availability after first unlock to prevent unintended rotation when locked keychain.save(key: deviceSeedKey, data: seed, service: keychainService, accessible: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) - cacheLock.lock() - deviceSeedCache = seed - cacheLock.unlock() - return seed + let persisted: Bool + if case .success(let stored) = keychain.loadWithResult(key: deviceSeedKey, service: keychainService), + stored == seed { + cacheLock.lock() + deviceSeedCache = seed + cacheLock.unlock() + persisted = true + } else { + persisted = false + } + return (seed, persisted) } /// Derive a deterministic, unlinkable Nostr identity for a mesh-bridge @@ -121,7 +160,7 @@ final class NostrIdentityBridge { } cacheLock.unlock() - let seed = getOrCreateDeviceSeed() + let (seed, durable) = getOrCreateDeviceSeed() guard let msg = geohash.data(using: .utf8) else { throw NSError(domain: "NostrIdentity", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid geohash string"]) } @@ -140,10 +179,11 @@ final class NostrIdentityBridge { for i in 0..<10 { let keyData = candidateKey(iteration: UInt32(i)) if let identity = try? NostrIdentity(privateKeyData: keyData) { - // Cache the result - cacheLock.lock() - derivedIdentityCache[geohash] = identity - cacheLock.unlock() + if durable { + cacheLock.lock() + derivedIdentityCache[geohash] = identity + cacheLock.unlock() + } return identity } } @@ -151,10 +191,11 @@ final class NostrIdentityBridge { let fallback = (seed + msg).sha256Hash() let identity = try NostrIdentity(privateKeyData: fallback) - // Cache the result - cacheLock.lock() - derivedIdentityCache[geohash] = identity - cacheLock.unlock() + if durable { + cacheLock.lock() + derivedIdentityCache[geohash] = identity + cacheLock.unlock() + } return identity } diff --git a/bitchat/Protocols/BitchatFilePacket.swift b/bitchat/Protocols/BitchatFilePacket.swift index 7745b6c4..4a5c6ba5 100644 --- a/bitchat/Protocols/BitchatFilePacket.swift +++ b/bitchat/Protocols/BitchatFilePacket.swift @@ -26,23 +26,42 @@ struct BitchatFilePacket { case content = 0x04 } + /// Zero-allocation preflight check matching `encode()` validation rules. + var canEncode: Bool { + let resolvedSize = fileSize ?? UInt64(content.count) + guard resolvedSize <= UInt64(UInt32.max) else { return false } + guard resolvedSize <= UInt64(FileTransferLimits.maxPayloadBytes) else { return false } + guard content.count <= Int(UInt32.max) else { return false } + return FileTransferLimits.isValidPayload(content.count) + } + /// Encodes the packet using v2 canonical TLVs (4-byte FILE_SIZE, 4-byte CONTENT length). /// Returns `nil` when fields exceed protocol limits (e.g., content > UInt32.max). func encode() -> Data? { + guard canEncode else { return nil } let resolvedSize = fileSize ?? UInt64(content.count) - guard resolvedSize <= UInt64(UInt32.max) else { return nil } - guard resolvedSize <= UInt64(FileTransferLimits.maxPayloadBytes) else { return nil } - guard content.count <= Int(UInt32.max) else { return nil } - guard FileTransferLimits.isValidPayload(content.count) else { return nil } func appendBE(_ value: T, into data: inout Data) { var big = value.bigEndian withUnsafeBytes(of: &big) { data.append(contentsOf: $0) } } - var encoded = Data() + let nameData: Data? = { + guard let name = fileName, let d = name.data(using: .utf8), d.count <= Int(UInt16.max) else { return nil } + return d + }() + let mimeData: Data? = { + guard let mime = mimeType, let d = mime.data(using: .utf8), d.count <= Int(UInt16.max) else { return nil } + return d + }() - if let name = fileName, let nameData = name.data(using: .utf8), nameData.count <= Int(UInt16.max) { + let capacity = (nameData.map { 3 + $0.count } ?? 0) + + 7 + + (mimeData.map { 3 + $0.count } ?? 0) + + 5 + content.count + var encoded = Data(capacity: capacity) + + if let nameData { encoded.append(TLVType.fileName.rawValue) appendBE(UInt16(nameData.count), into: &encoded) encoded.append(nameData) @@ -52,7 +71,7 @@ struct BitchatFilePacket { appendBE(UInt16(4), into: &encoded) appendBE(UInt32(resolvedSize), into: &encoded) - if let mime = mimeType, let mimeData = mime.data(using: .utf8), mimeData.count <= Int(UInt16.max) { + if let mimeData { encoded.append(TLVType.mimeType.rawValue) appendBE(UInt16(mimeData.count), into: &encoded) encoded.append(mimeData) diff --git a/bitchat/Services/BLE/BLESourceRouteOriginationPolicy.swift b/bitchat/Services/BLE/BLESourceRouteOriginationPolicy.swift index 5cc8bf9c..a5a02275 100644 --- a/bitchat/Services/BLE/BLESourceRouteOriginationPolicy.swift +++ b/bitchat/Services/BLE/BLESourceRouteOriginationPolicy.swift @@ -27,6 +27,8 @@ enum BLESourceRouteOriginationPolicy { shouldAttemptRoute: (PeerID) -> Bool, computeRoute: (PeerID) -> [Data]? ) -> [Data]? { + guard packet.route == nil, + packet.type != MessageType.fragment.rawValue else { return nil } guard packet.senderID == localPeerIDData else { return nil } guard let recipientData = packet.recipientID, recipientData.count == 8, diff --git a/bitchat/Services/CashuTokenDecoder.swift b/bitchat/Services/CashuTokenDecoder.swift index 87dfee02..06b9a95e 100644 --- a/bitchat/Services/CashuTokenDecoder.swift +++ b/bitchat/Services/CashuTokenDecoder.swift @@ -78,7 +78,41 @@ enum CashuTokenDecoder { /// fallback: the token must cleanly decode to a known version *and* carry /// a positive amount, otherwise this returns nil. This stops base64 junk /// and truncated V4 tokens from being relayed as if they were valid money. + private final class DecodeCacheEntry: NSObject { + let info: TokenInfo? + init(_ info: TokenInfo?) { self.info = info } + } + + private final class PermissiveDecodeCache: @unchecked Sendable { + private let cache: NSCache = { + let c = NSCache() + c.countLimit = 256 + return c + }() + + func entry(for key: String) -> DecodeCacheEntry? { + cache.object(forKey: key as NSString) + } + + func store(_ info: TokenInfo?, for key: String) { + cache.setObject(DecodeCacheEntry(info), forKey: key as NSString) + } + } + + private static let permissiveCache = PermissiveDecodeCache() + static func decode(_ raw: String, strict: Bool = false) -> TokenInfo? { + if !strict, let cached = permissiveCache.entry(for: raw) { + return cached.info + } + let decoded = decodeUncached(raw, strict: strict) + if !strict { + permissiveCache.store(decoded, for: raw) + } + return decoded + } + + private static func decodeUncached(_ raw: String, strict: Bool) -> TokenInfo? { guard let token = bareToken(from: raw) else { return nil } let version = String(token[token.index(token.startIndex, offsetBy: 5)]) guard let payload = base64URLDecode(String(token.dropFirst(6))), !payload.isEmpty else { diff --git a/bitchat/Services/Courier/MessageOutboxStore.swift b/bitchat/Services/Courier/MessageOutboxStore.swift index 9bb07be9..6b175c38 100644 --- a/bitchat/Services/Courier/MessageOutboxStore.swift +++ b/bitchat/Services/Courier/MessageOutboxStore.swift @@ -608,6 +608,7 @@ final class MessageOutboxStore { recoveryRouterSnapshot = [:] unreportedRecoveredSnapshot = nil lifecycleGeneration &+= 1 + cachedEncryptionKey = nil if let fileURL { try? FileManager.default.removeItem(at: fileURL) } @@ -617,6 +618,8 @@ final class MessageOutboxStore { // MARK: - Internals + private var cachedEncryptionKey: SymmetricKey? + private func encryptionKey(createIfMissing: Bool) -> SymmetricKey? { switch readEncryptionKey() { case .available(let key): @@ -625,6 +628,7 @@ final class MessageOutboxStore { break case .invalid: guard createIfMissing else { return nil } + cachedEncryptionKey = nil keychain.delete(key: Self.keychainKey, service: Self.keychainService) case .unavailable: return nil @@ -651,14 +655,20 @@ final class MessageOutboxStore { SecureLogger.error("Outbox encryption key was not retained by Keychain", category: .session) return nil } + cachedEncryptionKey = key return key } private func readEncryptionKey() -> EncryptionKeyReadResult { + if let cachedEncryptionKey { + return .available(cachedEncryptionKey) + } switch keychain.loadWithResult(key: Self.keychainKey, service: Self.keychainService) { case .success(let data): guard data.count == 32 else { return .invalid } - return .available(SymmetricKey(data: data)) + let key = SymmetricKey(data: data) + cachedEncryptionKey = key + return .available(key) case .itemNotFound: return .missing case .deviceLocked, .authenticationFailed: diff --git a/bitchat/Services/Groups/GroupStore.swift b/bitchat/Services/Groups/GroupStore.swift index ce7f443f..33c97f9a 100644 --- a/bitchat/Services/Groups/GroupStore.swift +++ b/bitchat/Services/Groups/GroupStore.swift @@ -23,6 +23,7 @@ final class GroupStore: ObservableObject { private let keychain: KeychainManagerProtocol private let fileURL: URL? + private var keyCache: [Data: Data] = [:] /// - Parameter fileURL: Overrides the on-disk location (tests). Ignored /// when `persistsToDisk` is false. @@ -43,9 +44,16 @@ final class GroupStore: ObservableObject { return group(withID: groupID) } - /// Current-epoch symmetric key for the group, from the keychain. + /// Current-epoch symmetric key for the group, cached in memory after first keychain read. func key(forGroupID groupID: Data) -> Data? { - keychain.getIdentityKey(forKey: Self.keychainKey(for: groupID)) + if let cached = keyCache[groupID] { + return cached + } + guard let fetched = keychain.getIdentityKey(forKey: Self.keychainKey(for: groupID)) else { + return nil + } + keyCache[groupID] = fetched + return fetched } // MARK: - Mutations @@ -86,6 +94,7 @@ final class GroupStore: ObservableObject { SecureLogger.error("Failed to store group key in keychain", category: .security) return false } + keyCache[group.groupID] = key if let index = groups.firstIndex(where: { $0.groupID == group.groupID }) { groups[index] = group } else { @@ -123,6 +132,7 @@ final class GroupStore: ObservableObject { func removeGroup(withID groupID: Data) { groups.removeAll { $0.groupID == groupID } + keyCache.removeValue(forKey: groupID) _ = keychain.deleteIdentityKey(forKey: Self.keychainKey(for: groupID)) persist() } @@ -135,6 +145,7 @@ final class GroupStore: ObservableObject { _ = keychain.deleteIdentityKey(forKey: Self.keychainKey(for: group.groupID)) } groups.removeAll() + keyCache.removeAll() if let fileURL { try? FileManager.default.removeItem(at: fileURL) } diff --git a/bitchat/Services/KeychainManager.swift b/bitchat/Services/KeychainManager.swift index abc86b10..bc83c029 100644 --- a/bitchat/Services/KeychainManager.swift +++ b/bitchat/Services/KeychainManager.swift @@ -74,9 +74,11 @@ final class KeychainManager: KeychainManagerProtocol { #if DEBUG if TestEnvironment.isRunningTests { return sharedTestKeychain } #endif - return KeychainManager() + return shared } + private static let shared = KeychainManager() + #if DEBUG /// One store per process, mirroring the real keychain: separate /// default-constructed components (e.g. two NostrIdentityBridge @@ -91,7 +93,39 @@ final class KeychainManager: KeychainManagerProtocol { private let appGroup = "group.\(BitchatApp.bundleID)" #if os(iOS) private let installAccessGate = KeychainInstallAccessGate() + /// Caches whether the app has a keychain-access-group entitlement matching + /// `appGroup`. Once a SecItem call returns -34018 (errSecMissingEntitlement), + /// subsequent reads/writes/deletes skip the doomed access-group XPC roundtrip. + private let accessGroupLock = NSLock() + private var accessGroupAvailable = true + + private func shouldUseAccessGroup() -> Bool { + accessGroupLock.lock() + defer { accessGroupLock.unlock() } + return accessGroupAvailable + } + + private func markAccessGroupUnavailable() { + accessGroupLock.lock() + accessGroupAvailable = false + accessGroupLock.unlock() + } #endif + + private func performSecItemWithAccessGroupFallback(_ body: (_ addAccessGroup: Bool) -> OSStatus) -> OSStatus { + #if os(iOS) + if shouldUseAccessGroup() { + let status = body(true) + if status != -34018 { + return status + } + markAccessGroupUnavailable() + } + return body(false) + #else + return body(false) + #endif + } /// Every generic-password service owned by this app, including names used /// by older releases. Keep custom services here so one-time security /// migrations and panic deletion cannot silently miss them. @@ -405,36 +439,45 @@ final class KeychainManager: KeychainManagerProtocol { /// Internal method to save data with detailed result and retry for transient errors private func saveDataWithResult(_ data: Data, forKey key: String, retryCount: Int = 2) -> KeychainSaveResult { - // Delete any existing item first to ensure clean state - _ = delete(forKey: key) - - // Build base query - var base: [String: Any] = [ + let matchBase: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: key, + kSecAttrService as String: service + ] + let attributesToUpdate: [String: Any] = [ kSecValueData as String: data, - kSecAttrService as String: service, kSecAttrAccessible as String: Self.itemAccessibility, kSecAttrLabel as String: "bitchat-\(key)" ] + var addBase = matchBase + addBase[kSecValueData as String] = data + addBase[kSecAttrAccessible as String] = Self.itemAccessibility + addBase[kSecAttrLabel as String] = "bitchat-\(key)" #if os(macOS) - base[kSecAttrSynchronizable as String] = false + addBase[kSecAttrSynchronizable as String] = false #endif - func attempt(addAccessGroup: Bool) -> OSStatus { - var query = base + func update(addAccessGroup: Bool) -> OSStatus { + var query = matchBase + if addAccessGroup { query[kSecAttrAccessGroup as String] = appGroup } + return SecItemUpdate(query as CFDictionary, attributesToUpdate as CFDictionary) + } + + func add(addAccessGroup: Bool) -> OSStatus { + var query = addBase if addAccessGroup { query[kSecAttrAccessGroup as String] = appGroup } return SecItemAdd(query as CFDictionary, nil) } - #if os(iOS) - var status = attempt(addAccessGroup: true) - if status == -34018 { // Missing entitlement, retry without access group - status = attempt(addAccessGroup: false) + // Prefer atomic SecItemUpdate (1 XPC) over delete+add (2-4 XPCs), falling + // back to SecItemAdd only when the item does not yet exist. + var status = performSecItemWithAccessGroupFallback(update(addAccessGroup:)) + if status == errSecItemNotFound { + status = performSecItemWithAccessGroupFallback(add(addAccessGroup:)) + if status == errSecDuplicateItem { + status = performSecItemWithAccessGroupFallback(update(addAccessGroup:)) + } } - #else - let status = attempt(addAccessGroup: false) - #endif // Classify the result let result = classifySaveStatus(status) @@ -480,19 +523,12 @@ final class KeychainManager: KeychainManagerProtocol { ] var result: AnyObject? - func attempt(withAccessGroup: Bool) -> OSStatus { + let status = performSecItemWithAccessGroupFallback { withAccessGroup in var q = base if withAccessGroup { q[kSecAttrAccessGroup as String] = appGroup } return SecItemCopyMatching(q as CFDictionary, &result) } - #if os(iOS) - var status = attempt(withAccessGroup: true) - if status == -34018 { status = attempt(withAccessGroup: false) } - #else - let status = attempt(withAccessGroup: false) - #endif - // Classify the result let readResult = classifyReadStatus(status, data: result as? Data) @@ -565,43 +601,46 @@ final class KeychainManager: KeychainManagerProtocol { // MARK: - Generic Operations private func saveData(_ data: Data, forKey key: String) -> Bool { - // Delete any existing item first to ensure clean state - _ = delete(forKey: key) - - // Build base query - var base: [String: Any] = [ + let matchBase: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: key, + kSecAttrService as String: service + ] + let attributesToUpdate: [String: Any] = [ kSecValueData as String: data, - kSecAttrService as String: service, kSecAttrAccessible as String: Self.itemAccessibility, kSecAttrLabel as String: "bitchat-\(key)" ] + var addBase = matchBase + addBase[kSecValueData as String] = data + addBase[kSecAttrAccessible as String] = Self.itemAccessibility + addBase[kSecAttrLabel as String] = "bitchat-\(key)" #if os(macOS) - base[kSecAttrSynchronizable as String] = false + addBase[kSecAttrSynchronizable as String] = false #endif - // Try with access group where it is expected to work (iOS app builds) - var triedWithoutGroup = false - func attempt(addAccessGroup: Bool) -> OSStatus { - var query = base + func update(addAccessGroup: Bool) -> OSStatus { + var query = matchBase + if addAccessGroup { query[kSecAttrAccessGroup as String] = appGroup } + return SecItemUpdate(query as CFDictionary, attributesToUpdate as CFDictionary) + } + + func add(addAccessGroup: Bool) -> OSStatus { + var query = addBase if addAccessGroup { query[kSecAttrAccessGroup as String] = appGroup } return SecItemAdd(query as CFDictionary, nil) } - #if os(iOS) - var status = attempt(addAccessGroup: true) - if status == -34018 { // Missing entitlement, retry without access group - triedWithoutGroup = true - status = attempt(addAccessGroup: false) + var status = performSecItemWithAccessGroupFallback(update(addAccessGroup:)) + if status == errSecItemNotFound { + status = performSecItemWithAccessGroupFallback(add(addAccessGroup:)) + if status == errSecDuplicateItem { + status = performSecItemWithAccessGroupFallback(update(addAccessGroup:)) + } } - #else - // On macOS dev/simulator default to no access group to avoid -34018 - let status = attempt(addAccessGroup: false) - #endif if status == errSecSuccess { return true } - if status == -34018 && !triedWithoutGroup { + if status == -34018 { SecureLogger.error(NSError(domain: "Keychain", code: -34018), context: "Missing keychain entitlement", category: .keychain) } else if status != errSecDuplicateItem { SecureLogger.error(NSError(domain: "Keychain", code: Int(status)), context: "Error saving to keychain", category: .keychain) @@ -620,19 +659,12 @@ final class KeychainManager: KeychainManagerProtocol { ] var result: AnyObject? - func attempt(withAccessGroup: Bool) -> OSStatus { + let status = performSecItemWithAccessGroupFallback { withAccessGroup in var q = base if withAccessGroup { q[kSecAttrAccessGroup as String] = appGroup } return SecItemCopyMatching(q as CFDictionary, &result) } - #if os(iOS) - var status = attempt(withAccessGroup: true) - if status == -34018 { status = attempt(withAccessGroup: false) } - #else - let status = attempt(withAccessGroup: false) - #endif - if status == errSecSuccess { return result as? Data } if status == -34018 { SecureLogger.error(NSError(domain: "Keychain", code: -34018), context: "Missing keychain entitlement", category: .keychain) @@ -648,18 +680,11 @@ final class KeychainManager: KeychainManagerProtocol { kSecAttrService as String: service ] - func attempt(withAccessGroup: Bool) -> OSStatus { + let status = performSecItemWithAccessGroupFallback { withAccessGroup in var q = base if withAccessGroup { q[kSecAttrAccessGroup as String] = appGroup } return SecItemDelete(q as CFDictionary) } - - #if os(iOS) - var status = attempt(withAccessGroup: true) - if status == -34018 { status = attempt(withAccessGroup: false) } - #else - let status = attempt(withAccessGroup: false) - #endif return status == errSecSuccess || status == errSecItemNotFound } @@ -867,30 +892,27 @@ final class KeychainManager: KeychainManagerProtocol { kSecAttrService as String: customService, kSecAttrAccount as String: key ] - var addQuery = primaryKeyQuery - addQuery.merge([ + let attributesToUpdate: [String: Any] = [ kSecValueData as String: data, - kSecAttrAccessible as String: accessible ?? Self.itemAccessibility, - kSecAttrSynchronizable as String: false - ]) { _, new in new } + kSecAttrAccessible as String: accessible ?? Self.itemAccessibility + ] - // Delete by the item's primary key only. Value/accessibility fields - // are add attributes, not valid selectors for replacing an existing - // item; including them can leave the old item in place and make the - // subsequent add fail as a duplicate. - let deleteStatus = SecItemDelete(primaryKeyQuery as CFDictionary) - guard deleteStatus == errSecSuccess || deleteStatus == errSecItemNotFound else { - SecureLogger.error( - NSError(domain: "Keychain", code: Int(deleteStatus)), - context: "Unable to replace custom-service keychain item", - category: .keychain - ) - return + var status = SecItemUpdate(primaryKeyQuery as CFDictionary, attributesToUpdate as CFDictionary) + if status == errSecItemNotFound { + var addQuery = primaryKeyQuery + addQuery.merge([ + kSecValueData as String: data, + kSecAttrAccessible as String: accessible ?? Self.itemAccessibility, + kSecAttrSynchronizable as String: false + ]) { _, new in new } + status = SecItemAdd(addQuery as CFDictionary, nil) + if status == errSecDuplicateItem { + status = SecItemUpdate(primaryKeyQuery as CFDictionary, attributesToUpdate as CFDictionary) + } } - let addStatus = SecItemAdd(addQuery as CFDictionary, nil) - if addStatus != errSecSuccess { + if status != errSecSuccess { SecureLogger.error( - NSError(domain: "Keychain", code: Int(addStatus)), + NSError(domain: "Keychain", code: Int(status)), context: "Unable to save custom-service keychain item", category: .keychain ) diff --git a/bitchat/Services/MessageDeduplicationService.swift b/bitchat/Services/MessageDeduplicationService.swift index a31c05a5..8575c710 100644 --- a/bitchat/Services/MessageDeduplicationService.swift +++ b/bitchat/Services/MessageDeduplicationService.swift @@ -308,10 +308,14 @@ final class MessageDeduplicationService { } /// Records a Nostr event as processed. - /// - Parameter eventId: The event ID - func recordNostrEvent(_ eventId: String) { + /// - Parameters: + /// - eventId: The event ID + /// - persist: Whether to persist the ID across launches (true for + /// private-envelope kind 1059 DMs; false for ephemeral geohash + /// chat/presence kinds 20000/20001). + func recordNostrEvent(_ eventId: String, persist: Bool = true) { nostrEventCache.record(eventId, value: true) - if nostrEventStore != nil { + if persist, nostrEventStore != nil { pendingPersistIDs.append(eventId) schedulePersistIfNeeded() } diff --git a/bitchat/Services/NostrProcessedEventStore.swift b/bitchat/Services/NostrProcessedEventStore.swift index a1312f38..760f887c 100644 --- a/bitchat/Services/NostrProcessedEventStore.swift +++ b/bitchat/Services/NostrProcessedEventStore.swift @@ -21,18 +21,40 @@ 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 enum LoadResult { + case loaded([String]) + case transientError + } + private let fileURL: URL? + private let readData: (URL) throws -> Data // 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) - init(fileURL: URL? = nil) { + private var cachedIDs: [String]? + private var cachedKnown: Set = [] + private var deferredIDs: [String] = [] + private var directoryCreated = false + + init( + fileURL: URL? = nil, + readData: @escaping (URL) throws -> Data = { try Data(contentsOf: $0) } + ) { self.fileURL = fileURL ?? Self.defaultFileURL() + self.readData = readData } /// Processed event IDs, oldest first (insertion order). func load() -> [String] { - ioQueue.sync { loadLocked() } + ioQueue.sync { + switch loadLocked() { + case .loaded(let ids): + return ids + case .transientError: + return [] + } + } } /// Merge new IDs onto the persisted record, oldest-first, trimming from @@ -42,33 +64,96 @@ final class NostrProcessedEventStore { func append(_ newIDs: [String], cap: Int) { guard !newIDs.isEmpty else { return } ioQueue.async { [self] in - var merged = loadLocked() - var known = Set(merged) - for id in newIDs where !known.contains(id) { - merged.append(id) - known.insert(id) + switch loadLocked() { + case .transientError: + // Never overwrite an unreadable durable file with an empty + // baseline; hold new IDs until the file becomes readable. + deferredIDs.append(contentsOf: newIDs) + if deferredIDs.count > cap { + deferredIDs.removeFirst(deferredIDs.count - cap) + } + case .loaded(var merged): + let pending = deferredIDs + newIDs + deferredIDs.removeAll() + var didAdd = false + for id in pending where cachedKnown.insert(id).inserted { + merged.append(id) + didAdd = true + } + guard didAdd else { return } + if merged.count > cap { + let overflow = merged.count - cap + for evicted in merged.prefix(overflow) { + cachedKnown.remove(evicted) + } + merged.removeFirst(overflow) + } + cachedIDs = merged + saveLocked(merged) } - if merged.count > cap { - merged.removeFirst(merged.count - cap) - } - saveLocked(merged) } } func wipe() { ioQueue.sync { + cachedIDs = [] + cachedKnown.removeAll() + deferredIDs.removeAll() + directoryCreated = false guard let fileURL else { return } try? FileManager.default.removeItem(at: fileURL) } } - private func loadLocked() -> [String] { - guard let fileURL, - let data = try? Data(contentsOf: fileURL), - let ids = try? JSONDecoder().decode([String].self, from: data) else { - return [] + private func loadLocked() -> LoadResult { + if let cachedIDs { + return .loaded(cachedIDs) } - return ids + guard let fileURL else { + cachedIDs = [] + cachedKnown = [] + return .loaded([]) + } + guard FileManager.default.fileExists(atPath: fileURL.path) else { + cachedIDs = [] + cachedKnown = [] + return .loaded([]) + } + let data: Data + do { + data = try readData(fileURL) + } catch { + if Self.isMissingFileError(error) { + cachedIDs = [] + cachedKnown = [] + return .loaded([]) + } + // Leave cache uninitialized so later loads/appends recover the + // durable record once file protection or transient I/O clears. + return .transientError + } + guard let ids = try? JSONDecoder().decode([String].self, from: data) else { + cachedIDs = [] + cachedKnown = [] + return .loaded([]) + } + cachedIDs = ids + cachedKnown = Set(ids) + return .loaded(ids) + } + + private static func isMissingFileError(_ error: Error) -> Bool { + let nsError = error as NSError + if nsError.domain == NSCocoaErrorDomain && nsError.code == NSFileReadNoSuchFileError { + return true + } + if nsError.domain == NSPOSIXErrorDomain && nsError.code == Int(ENOENT) { + return true + } + if let underlying = nsError.userInfo[NSUnderlyingErrorKey] as? Error { + return isMissingFileError(underlying) + } + return false } private func saveLocked(_ eventIDs: [String]) { @@ -78,10 +163,13 @@ final class NostrProcessedEventStore { return } do { - try FileManager.default.createDirectory( - at: fileURL.deletingLastPathComponent(), - withIntermediateDirectories: true - ) + if !directoryCreated { + try FileManager.default.createDirectory( + at: fileURL.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + directoryCreated = true + } let data = try JSONEncoder().encode(eventIDs) var options: Data.WritingOptions = [.atomic] #if os(iOS) @@ -89,6 +177,7 @@ final class NostrProcessedEventStore { #endif try data.write(to: fileURL, options: options) } catch { + directoryCreated = false SecureLogger.error("Failed to persist processed Nostr events: \(error)", category: .session) } } diff --git a/bitchat/Utils/Color+Peer.swift b/bitchat/Utils/Color+Peer.swift index e2ab3a15..ad77ee45 100644 --- a/bitchat/Utils/Color+Peer.swift +++ b/bitchat/Utils/Color+Peer.swift @@ -9,12 +9,14 @@ import SwiftUI extension Color { + private static let maxPeerColorCacheEntries = 512 private static var peerColorCache: [String: Color] = [:] - + init(peerSeed: String, isDark: Bool) { let cacheKey = peerSeed + (isDark ? "|dark" : "|light") if let cached = Self.peerColorCache[cacheKey] { self = cached + return } let h = peerSeed.djb2() var hue = Double(h % 1000) / 1000.0 @@ -31,6 +33,9 @@ extension Color { let saturation = min(1.0, max(0.50, sBase + (sRand - 0.5) * sRange)) let brightness = min(1.0, max(0.35, bBase + (bRand - 0.5) * bRange)) let c = Color(hue: hue, saturation: saturation, brightness: brightness) + if Self.peerColorCache.count >= Self.maxPeerColorCacheEntries { + Self.peerColorCache.removeAll(keepingCapacity: true) + } Self.peerColorCache[cacheKey] = c self = c } diff --git a/bitchat/ViewModels/ChatMediaPreparation.swift b/bitchat/ViewModels/ChatMediaPreparation.swift index 6852d397..3a606b43 100644 --- a/bitchat/ViewModels/ChatMediaPreparation.swift +++ b/bitchat/ViewModels/ChatMediaPreparation.swift @@ -29,12 +29,18 @@ enum ChatMediaPreparation { mimeType: "audio/mp4", content: data ) - guard packet.encode() != nil else { throw ChatMediaPreparationError.encodingFailed } + guard packet.canEncode else { throw ChatMediaPreparationError.encodingFailed } return packet } static func prepareImagePacket(from sourceURL: URL) throws -> ChatPreparedImage { let outputURL = try ImageUtils.processImage(at: sourceURL) + return try prepareProcessedImagePacket(at: outputURL) + } + + /// Packages an image file already processed by `ImageUtils.processImage` + /// without decoding and re-encoding JPEG a second time. + static func prepareProcessedImagePacket(at outputURL: URL) throws -> ChatPreparedImage { do { let data = try Data(contentsOf: outputURL) guard data.count <= FileTransferLimits.maxImageBytes else { @@ -47,7 +53,7 @@ enum ChatMediaPreparation { mimeType: "image/jpeg", content: data ) - guard packet.encode() != nil else { throw ChatMediaPreparationError.encodingFailed } + guard packet.canEncode else { throw ChatMediaPreparationError.encodingFailed } return ChatPreparedImage(outputURL: outputURL, packet: packet) } catch { try? FileManager.default.removeItem(at: outputURL) diff --git a/bitchat/ViewModels/ChatMediaTransferCoordinator.swift b/bitchat/ViewModels/ChatMediaTransferCoordinator.swift index 548e48b0..b762a400 100644 --- a/bitchat/ViewModels/ChatMediaTransferCoordinator.swift +++ b/bitchat/ViewModels/ChatMediaTransferCoordinator.swift @@ -629,64 +629,61 @@ final class ChatMediaTransferCoordinator { #if os(iOS) func processThenSendImage(_ image: UIImage?) { guard let image else { return } + guard context.canSendMediaInCurrentContext else { + SecureLogger.info("Image send blocked outside mesh/private context", category: .session) + context.addSystemMessage(String(localized: "Images are only available in mesh chats.", comment: "System message when an image send is attempted outside mesh chats")) + return + } + let targetPeer = context.selectedPrivateChatPeer let generation = imagePreparationBarrier.currentGeneration let barrier = imagePreparationBarrier Task.detached(priority: .userInitiated) { [weak self, barrier] in do { - let processedURL = try await runBlockingMediaPreparation { + let prepared = try await runBlockingMediaPreparation { try barrier.performIfCurrent( generation: generation, operation: { - try ImageUtils.processImage(image) + let processedURL = try ImageUtils.processImage(image) + return try ChatMediaPreparation.prepareProcessedImagePacket(at: processedURL) } ) } - guard let processedURL else { + guard let prepared else { return } await MainActor.run { [weak self, barrier] in guard let self, barrier.isCurrent(generation) else { - try? FileManager.default.removeItem(at: processedURL) + try? FileManager.default.removeItem(at: prepared.outputURL) return } - self.sendImage(from: processedURL) + self.enqueuePreparedImage(prepared, targetPeer: targetPeer) + } + } catch ChatMediaPreparationError.imageTooLarge(let size) { + SecureLogger.warning("Processed image exceeds size limit (\(size) bytes)", category: .session) + await MainActor.run { [weak self, barrier] in + guard let self, + barrier.isCurrent(generation) else { + return + } + self.context.addSystemMessage("Image is too large to send.") } } catch { SecureLogger.error("Image processing failed: \(error)", category: .session) + await MainActor.run { [weak self, barrier] in + guard let self, + barrier.isCurrent(generation) else { + return + } + self.context.addSystemMessage("Failed to prepare image for sending.") + } } } } #elseif os(macOS) func processThenSendImage(from url: URL?) { guard let url else { return } - let generation = imagePreparationBarrier.currentGeneration - let barrier = imagePreparationBarrier - Task.detached(priority: .userInitiated) { [weak self, barrier] in - do { - let processedURL = try await runBlockingMediaPreparation { - try barrier.performIfCurrent( - generation: generation, - operation: { - try ImageUtils.processImage(at: url) - } - ) - } - guard let processedURL else { - return - } - await MainActor.run { [weak self, barrier] in - guard let self, - barrier.isCurrent(generation) else { - try? FileManager.default.removeItem(at: processedURL) - return - } - self.sendImage(from: processedURL) - } - } catch { - SecureLogger.error("Image processing failed: \(error)", category: .session) - } - } + sendImage(from: url) } #endif @@ -731,31 +728,7 @@ final class ChatMediaTransferCoordinator { try? FileManager.default.removeItem(at: prepared.outputURL) return } - let privateMessageID = targetPeer.flatMap { peerID in - PrivateMediaMessageIdentity.stableID( - for: prepared.packet, - senderPeerID: self.context.myPeerID, - recipientPeerID: peerID - ) - } - let message = self.enqueueMediaMessage( - content: "\(MimeType.Category.image.messagePrefix)\(prepared.outputURL.lastPathComponent)", - targetPeer: targetPeer, - messageID: privateMessageID - ) - let messageID = message.id - let transferId = self.makeTransferID(messageID: messageID) - self.registerTransfer(transferId: transferId, messageID: messageID) - if let peerID = targetPeer { - self.beginPrivateMediaSend( - prepared.packet, - to: peerID, - transferId: transferId, - messageID: messageID - ) - } else { - self.context.sendFileBroadcast(prepared.packet, transferId: transferId) - } + self.enqueuePreparedImage(prepared, targetPeer: targetPeer) } } catch ChatMediaPreparationError.imageTooLarge(let size) { SecureLogger.warning("Processed image exceeds size limit (\(size) bytes)", category: .session) @@ -779,6 +752,34 @@ final class ChatMediaTransferCoordinator { } } + private func enqueuePreparedImage(_ prepared: ChatPreparedImage, targetPeer: PeerID?) { + let privateMessageID = targetPeer.flatMap { peerID in + PrivateMediaMessageIdentity.stableID( + for: prepared.packet, + senderPeerID: context.myPeerID, + recipientPeerID: peerID + ) + } + let message = enqueueMediaMessage( + content: "\(MimeType.Category.image.messagePrefix)\(prepared.outputURL.lastPathComponent)", + targetPeer: targetPeer, + messageID: privateMessageID + ) + let messageID = message.id + let transferId = makeTransferID(messageID: messageID) + registerTransfer(transferId: transferId, messageID: messageID) + if let peerID = targetPeer { + beginPrivateMediaSend( + prepared.packet, + to: peerID, + transferId: transferId, + messageID: messageID + ) + } else { + context.sendFileBroadcast(prepared.packet, transferId: transferId) + } + } + func enqueueMediaMessage( content: String, targetPeer: PeerID?, diff --git a/bitchat/ViewModels/GeohashSubscriptionManager.swift b/bitchat/ViewModels/GeohashSubscriptionManager.swift index 930cc549..e07e8932 100644 --- a/bitchat/ViewModels/GeohashSubscriptionManager.swift +++ b/bitchat/ViewModels/GeohashSubscriptionManager.swift @@ -37,7 +37,7 @@ protocol GeohashSubscriptionContext: AnyObject { // MARK: Nostr identity & dedup func deriveNostrIdentity(forGeohash geohash: String) throws -> NostrIdentity func currentNostrIdentity() -> NostrIdentity? - func recordProcessedNostrEvent(_ eventID: String) + func recordProcessedEphemeralNostrEvent(_ eventID: String) func clearProcessedNostrEvents() /// Records the Nostr pubkey behind a (possibly virtual) peer ID. func registerNostrKeyMapping(_ pubkey: String, for peerID: PeerID) @@ -341,7 +341,7 @@ final class GeohashSubscriptionManager { ) } - context.recordProcessedNostrEvent(event.id) + context.recordProcessedEphemeralNostrEvent(event.id) } @MainActor diff --git a/bitchat/ViewModels/NostrInboundPipeline.swift b/bitchat/ViewModels/NostrInboundPipeline.swift index 535f1ae5..e067d86f 100644 --- a/bitchat/ViewModels/NostrInboundPipeline.swift +++ b/bitchat/ViewModels/NostrInboundPipeline.swift @@ -13,6 +13,7 @@ protocol NostrInboundPipelineContext: AnyObject { // MARK: Event dedup func hasProcessedNostrEvent(_ eventID: String) -> Bool func recordProcessedNostrEvent(_ eventID: String) + func recordProcessedEphemeralNostrEvent(_ eventID: String) // MARK: Nostr identity & blocking func deriveNostrIdentity(forGeohash geohash: String) throws -> NostrIdentity @@ -69,7 +70,11 @@ extension ChatViewModel: NostrInboundPipelineContext { } func recordProcessedNostrEvent(_ eventID: String) { - deduplicationService.recordNostrEvent(eventID) + deduplicationService.recordNostrEvent(eventID, persist: true) + } + + func recordProcessedEphemeralNostrEvent(_ eventID: String) { + deduplicationService.recordNostrEvent(eventID, persist: false) } func setGeoNickname(_ nickname: String, forPubkey pubkeyHex: String) { @@ -138,7 +143,7 @@ final class NostrInboundPipeline { return } - context.recordProcessedNostrEvent(event.id) + context.recordProcessedEphemeralNostrEvent(event.id) if let gh = context.currentGeohash, let myGeoIdentity = try? context.deriveNostrIdentity(forGeohash: gh), @@ -223,7 +228,7 @@ final class NostrInboundPipeline { return } if context.hasProcessedNostrEvent(event.id) { return } - context.recordProcessedNostrEvent(event.id) + context.recordProcessedEphemeralNostrEvent(event.id) let powBits = NostrPoW.validatedDifficulty(idHex: event.id, tags: event.tags) diff --git a/bitchat/Views/Media/BlockRevealImageView.swift b/bitchat/Views/Media/BlockRevealImageView.swift index 7caa4066..683a7956 100644 --- a/bitchat/Views/Media/BlockRevealImageView.swift +++ b/bitchat/Views/Media/BlockRevealImageView.swift @@ -145,7 +145,7 @@ struct BlockRevealImageView: View { @ViewBuilder private var imageContent: some View { if let image = platformImage { - Image(platformImage: image) + let baseImage = Image(platformImage: image) .resizable() .aspectRatio(aspectRatio, contentMode: .fit) .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous)) @@ -153,15 +153,22 @@ struct BlockRevealImageView: View { RoundedRectangle(cornerRadius: 16, style: .continuous) .stroke(Color.gray.opacity(0.2), lineWidth: 1) ) - .mask( - BlockRevealMask( - fraction: fraction, - columns: 24, - rows: 16 - ) - .animation(.easeOut(duration: 0.2), value: fraction) - ) - .blur(radius: isBlurred ? 20 : 0) + Group { + if fraction < 1 { + baseImage + .mask( + BlockRevealMask( + fraction: fraction, + columns: 24, + rows: 16 + ) + .animation(.easeOut(duration: 0.2), value: fraction) + ) + } else { + baseImage + } + } + .blur(radius: isBlurred ? 20 : 0) .overlay { if isBlurred { RoundedRectangle(cornerRadius: 16, style: .continuous) @@ -299,17 +306,24 @@ private struct BlockRevealMask: Shape { let totalBlocks = columns * rows let revealCount = max(0, min(totalBlocks, Int(ceil(fraction * Double(totalBlocks))))) guard revealCount > 0 else { return path } + if revealCount >= totalBlocks { + path.addRect(rect) + return path + } let blockWidth = rect.width / CGFloat(columns) let blockHeight = rect.height / CGFloat(rows) - var remaining = revealCount - for row in 0.. 0 { + path.addRect(CGRect(x: 0, y: 0, width: rect.width, height: CGFloat(fullRows) * blockHeight)) + } + if partialColumns > 0 { + path.addRect(CGRect( + x: 0, + y: CGFloat(fullRows) * blockHeight, + width: CGFloat(partialColumns) * blockWidth, + height: blockHeight + )) } return path } diff --git a/bitchatTests/ChatNostrCoordinatorContextTests.swift b/bitchatTests/ChatNostrCoordinatorContextTests.swift index ffe22d9f..3f75d4af 100644 --- a/bitchatTests/ChatNostrCoordinatorContextTests.swift +++ b/bitchatTests/ChatNostrCoordinatorContextTests.swift @@ -139,6 +139,10 @@ private final class MockChatNostrContext: ChatNostrContext { recordedNostrEventIDs.append(eventID) } + func recordProcessedEphemeralNostrEvent(_ eventID: String) { + recordProcessedNostrEvent(eventID) + } + func clearProcessedNostrEvents() { processedNostrEventIDs.removeAll() clearProcessedNostrEventsCount += 1 diff --git a/bitchatTests/MessageDeduplicationServiceTests.swift b/bitchatTests/MessageDeduplicationServiceTests.swift index 2726e698..1436d340 100644 --- a/bitchatTests/MessageDeduplicationServiceTests.swift +++ b/bitchatTests/MessageDeduplicationServiceTests.swift @@ -377,6 +377,80 @@ struct MessageDeduplicationServiceTests { #expect(service.hasProcessedNostrEvent("event123")) } + @Test func recordNostrEvent_ephemeralDoesNotPersistToDisk() { + let fileURL = FileManager.default.temporaryDirectory + .appendingPathComponent("nostr-ephemeral-\(UUID().uuidString).json") + defer { try? FileManager.default.removeItem(at: fileURL) } + + let store = NostrProcessedEventStore(fileURL: fileURL) + let service = MessageDeduplicationService( + contentCapacity: 100, + nostrEventCapacity: 100, + nostrEventStore: store + ) + + service.recordNostrEvent("ephemeral-geo-event", persist: false) + + #expect(service.hasProcessedNostrEvent("ephemeral-geo-event")) + #expect(!FileManager.default.fileExists(atPath: fileURL.path)) + #expect(store.load().isEmpty) + } + + @Test func nostrProcessedEventStore_recoversAfterTransientReadFailure() throws { + let fileURL = FileManager.default.temporaryDirectory + .appendingPathComponent("nostr-transient-\(UUID().uuidString).json") + defer { try? FileManager.default.removeItem(at: fileURL) } + + let initial = try JSONEncoder().encode(["old1", "old2"]) + try initial.write(to: fileURL, options: [.atomic]) + + let lock = NSLock() + var failReads = true + let store = NostrProcessedEventStore(fileURL: fileURL) { url in + lock.lock() + let shouldFail = failReads + lock.unlock() + if shouldFail { + throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadNoPermissionError) + } + return try Data(contentsOf: url) + } + + // Transient failure during initial load must not poison the cache. + #expect(store.load().isEmpty) + store.append(["while-locked"], cap: 100) + + lock.lock() + failReads = false + lock.unlock() + + store.append(["after-unlock"], cap: 100) + // `load()` runs on `ioQueue.sync`, draining prior async appends. + #expect(store.load() == ["old1", "old2", "while-locked", "after-unlock"]) + + let reopened = NostrProcessedEventStore(fileURL: fileURL) + #expect(reopened.load() == ["old1", "old2", "while-locked", "after-unlock"]) + } + + @Test func nostrIdentityBridge_retriesAfterTransientKeychainFailure() throws { + let keychain = MockKeychain() + let firstBridge = NostrIdentityBridge(keychain: keychain) + let original = try #require(try firstBridge.getCurrentNostrIdentity()) + + let secondBridge = NostrIdentityBridge(keychain: keychain) + keychain.simulatedGenericReadError = .deviceLocked + #expect(try secondBridge.getCurrentNostrIdentity() == nil) + + keychain.simulatedGenericReadError = nil + let recovered = try #require(try secondBridge.getCurrentNostrIdentity()) + #expect(recovered.publicKeyHex == original.publicKeyHex) + + let loadsAfterRecovery = keychain.loadCallCount + let cached = try #require(try secondBridge.getCurrentNostrIdentity()) + #expect(cached.publicKeyHex == original.publicKeyHex) + #expect(keychain.loadCallCount == loadsAfterRecovery) + } + @Test func hasProcessedNostrEvent_falseForUnseen() { let service = MessageDeduplicationService(contentCapacity: 100, nostrEventCapacity: 100) diff --git a/bitchatTests/Mocks/MockKeychain.swift b/bitchatTests/Mocks/MockKeychain.swift index d5e99f1d..f5e7bad1 100644 --- a/bitchatTests/Mocks/MockKeychain.swift +++ b/bitchatTests/Mocks/MockKeychain.swift @@ -20,14 +20,19 @@ final class MockKeychain: KeychainManagerProtocol { var simulatedGenericReadError: KeychainReadResult? var simulatedDeleteAllResult = true private(set) var deleteAllCallCount = 0 + private(set) var saveIdentityKeyCallCount = 0 + private(set) var getIdentityKeyCallCount = 0 + private(set) var loadCallCount = 0 func saveIdentityKey(_ keyData: Data, forKey key: String) -> Bool { + saveIdentityKeyCallCount += 1 storage[key] = keyData return true } func getIdentityKey(forKey key: String) -> Data? { - storage[key] + getIdentityKeyCallCount += 1 + return storage[key] } func deleteIdentityKey(forKey key: String) -> Bool { @@ -57,6 +62,7 @@ final class MockKeychain: KeychainManagerProtocol { // BCH-01-009: New methods with proper error classification func getIdentityKeyWithResult(forKey key: String) -> KeychainReadResult { + getIdentityKeyCallCount += 1 if let simulated = simulatedReadError { return simulated } @@ -67,6 +73,7 @@ final class MockKeychain: KeychainManagerProtocol { } func saveIdentityKeyWithResult(_ keyData: Data, forKey key: String) -> KeychainSaveResult { + saveIdentityKeyCallCount += 1 if let simulated = simulatedSaveError { return simulated } @@ -84,10 +91,12 @@ final class MockKeychain: KeychainManagerProtocol { } func load(key: String, service: String) -> Data? { - serviceStorage[service]?[key] + loadCallCount += 1 + return serviceStorage[service]?[key] } func loadWithResult(key: String, service: String) -> KeychainReadResult { + loadCallCount += 1 if let simulatedGenericReadError { return simulatedGenericReadError } diff --git a/bitchatTests/Performance/PerformanceBaselineTests.swift b/bitchatTests/Performance/PerformanceBaselineTests.swift index 6eda1e09..ef3fa0a5 100644 --- a/bitchatTests/Performance/PerformanceBaselineTests.swift +++ b/bitchatTests/Performance/PerformanceBaselineTests.swift @@ -704,6 +704,7 @@ private final class PerfNostrContext: ChatNostrContext { var processedEventCount: Int { processedNostrEventIDs.count } func hasProcessedNostrEvent(_ eventID: String) -> Bool { processedNostrEventIDs.contains(eventID) } func recordProcessedNostrEvent(_ eventID: String) { processedNostrEventIDs.insert(eventID) } + func recordProcessedEphemeralNostrEvent(_ eventID: String) { processedNostrEventIDs.insert(eventID) } func clearProcessedNostrEvents() { processedNostrEventIDs.removeAll() } var geoNicknames: [String: String] = [:] diff --git a/bitchatTests/Services/BLESourceRouteOriginationPolicyTests.swift b/bitchatTests/Services/BLESourceRouteOriginationPolicyTests.swift index c762a0c7..8f6dfaa0 100644 --- a/bitchatTests/Services/BLESourceRouteOriginationPolicyTests.swift +++ b/bitchatTests/Services/BLESourceRouteOriginationPolicyTests.swift @@ -95,4 +95,49 @@ struct BLESourceRouteOriginationPolicyTests { #expect(sawComputeRoute) #expect(route(packet: makePacket(), computedRoute: []) == nil) } + + @Test func fragmentPacketNeverGetsRoute() { + var sawComputeRoute = false + let fragment = BitchatPacket( + type: MessageType.fragment.rawValue, + senderID: localPeerIDData, + recipientID: Data(hexString: "1112131415161718"), + timestamp: UInt64(Date().timeIntervalSince1970 * 1000), + payload: Data(repeating: 0xAB, count: 32), + signature: nil, + ttl: 7 + ) + let result = BLESourceRouteOriginationPolicy.route( + for: fragment, + to: recipient, + localPeerIDData: localPeerIDData, + isRecipientConnected: { _ in false }, + shouldAttemptRoute: { _ in true }, + computeRoute: { _ in + sawComputeRoute = true + return [self.hop] + } + ) + #expect(result == nil) + #expect(!sawComputeRoute) + } + + @Test func alreadyRoutedPacketNeverGetsRoute() { + var sawComputeRoute = false + var routed = makePacket() + routed.route = [hop] + let result = BLESourceRouteOriginationPolicy.route( + for: routed, + to: recipient, + localPeerIDData: localPeerIDData, + isRecipientConnected: { _ in false }, + shouldAttemptRoute: { _ in true }, + computeRoute: { _ in + sawComputeRoute = true + return [self.hop] + } + ) + #expect(result == nil) + #expect(!sawComputeRoute) + } } diff --git a/bitchatTests/Services/GroupStoreTests.swift b/bitchatTests/Services/GroupStoreTests.swift index a5130bff..0546dcb4 100644 --- a/bitchatTests/Services/GroupStoreTests.swift +++ b/bitchatTests/Services/GroupStoreTests.swift @@ -170,6 +170,18 @@ struct GroupStoreTests { #expect(reloaded.key(forGroupID: group.groupID) != nil) } + @Test func cachedKeyReadsDoNotRequeryKeychain() throws { + let keychain = MockKeychain() + let store = GroupStore(keychain: keychain, persistsToDisk: false) + let group = try #require(store.createGroup(named: "cached", creator: makeMember(seed: 0xC1))) + let readsAfterCreate = keychain.getIdentityKeyCallCount + + for _ in 0..<10 { + #expect(store.key(forGroupID: group.groupID) != nil) + } + #expect(keychain.getIdentityKeyCallCount == readsAfterCreate) + } + @Test func groupsWithoutKeysAreDroppedOnLoad() throws { let keychain = MockKeychain() let fileURL = tempFileURL() diff --git a/localPackages/Arti/arti-bitchat/src/socks.rs b/localPackages/Arti/arti-bitchat/src/socks.rs index 4795a7d9..a6d2549b 100644 --- a/localPackages/Arti/arti-bitchat/src/socks.rs +++ b/localPackages/Arti/arti-bitchat/src/socks.rs @@ -28,6 +28,10 @@ pub async fn handle_socks_connection( peer_addr: SocketAddr, client: Arc>, ) -> io::Result<()> { + // Disable Nagle on the local loopback socket to avoid delayed-ACK stalls on + // small SOCKS5 handshake replies and WebSocket control/event frames. + let _ = stream.set_nodelay(true); + // --- Greeting --- // Client sends: VER | NMETHODS | METHODS let mut greeting = [0u8; 2];